-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatGPT Conversation Exporter Plus-2.0.user.js
408 lines (345 loc) · 14.6 KB
/
ChatGPT Conversation Exporter Plus-2.0.user.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// ==UserScript==
// @name ChatGPT Conversation Exporter Plus
// @namespace http://tampermonkey.net/
// @version 2.0
// @description 优雅导出 ChatGPT 对话记录,支持 JSON 和 Markdown 格式
// @author Gao Jiaxuan + GPT-4 + Claude
// @license Custom License
// @match https://chatgpt.com/c/*
// @match https://abcd.dwai.world/c/*
// @match https://ed.dawuai.buzz/c/*
// @match https://node.dawuai.buzz/c/*
// @match https://newnode.dawuai.buzz/c/*
// @match https://france.dwai.work/c/*
// @match https://dw.dwai.world/c/*
// @grant none
// ==/UserScript==
/*
您可以在个人设备上使用和修改该代码。
不得将该代码或其修改版本重新分发、再发布或用于其他公众渠道。
保留所有权利,未经授权不得用于商业用途。
*/
(function() {
'use strict';
// Python转换函数移植
function formatTimestamp(timestamp) {
if (!timestamp) return null;
const dt = new Date(timestamp * 1000);
return dt.toISOString().replace('T', ' ').replace(/\.\d+Z$/, ' UTC');
}
function getModelInfo(message) {
if (!message || !message.metadata) return "";
const { model_slug, default_model_slug } = message.metadata;
if (model_slug && default_model_slug && model_slug !== default_model_slug) {
return ` [使用模型: ${model_slug}]`;
}
return "";
}
function generateFootnotes(text, contentReferences) {
const footnotes = [];
let footnoteIndex = 1;
let updatedText = text;
for (const ref of contentReferences || []) {
if (ref.type === 'webpage' && ref.url) {
const title = ref.title || ref.url;
updatedText += ` [^${footnoteIndex}]`;
footnotes.push(`[^${footnoteIndex}]: [${title}](${ref.url})`);
footnoteIndex++;
}
}
return [footnotes, updatedText];
}
function extractMessageParts(message) {
if (!message || !message.message) return [null, null, []];
const msg = message.message;
const timestamp = formatTimestamp(msg.create_time);
const authorName = msg.author?.name;
if (authorName && (authorName.startsWith('canmore.') || authorName.startsWith('dalle.'))) {
return [null, null, []];
}
const parts = msg.content?.parts || [];
if (!parts.length) return [null, null, []];
let text = parts.join(' ');
if (!text) return [null, null, []];
if (parts[0] && typeof parts[0] === 'string' && parts[0].includes("DALL-E displayed")) {
return [null, null, []];
}
const cleanedText = text.replace(/citeturn0news\d+/g, '');
const contentReferences = msg.metadata?.content_references || [];
const [footnotes, updatedText] = generateFootnotes(cleanedText, contentReferences);
return [updatedText, timestamp, footnotes];
}
function isCanvasRelated(node) {
if (!node?.message) return false;
const message = node.message;
const authorName = message.author?.name;
const recipient = message.recipient;
if ((authorName && String(authorName).includes('canmore.')) ||
(recipient && String(recipient).includes('canmore.'))) {
return true;
}
const metadata = message.metadata || {};
return metadata.canvas || String(metadata.command || '').includes('canvas');
}
function adjustHeaderLevels(text, increaseBy = 2) {
return text.replace(/^(#+)(.*?)$/gm, (match, hashes, rest) => {
return '#'.repeat(hashes.length + increaseBy) + rest;
});
}
// 状态追踪
let state = {
largestResponse: null,
largestResponseSize: 0,
largestResponseUrl: null,
lastUpdateTime: null
};
// 日志函数
const log = {
info: (msg) => console.log(`[Conversation Saver] ${msg}`),
error: (msg, e) => console.error(`[Conversation Saver] ${msg}`, e)
};
// 对话转换为Markdown的核心函数
function buildConversationTree(mapping, nodeId, indent = 0) {
if (!mapping[nodeId]) return [];
const node = mapping[nodeId];
const conversation = [];
if (!isCanvasRelated(node)) {
const [messageContent, timestamp, footnotes] = extractMessageParts(node);
if (messageContent) {
const role = node.message?.author?.role;
if (role === 'user' || role === 'assistant') {
const modelInfo = getModelInfo(node.message);
const timestampInfo = timestamp ? `\n\n*${timestamp}*` : "";
const prefix = role === 'user' ?
`## Human${timestampInfo}\n\n` :
`## Assistant${modelInfo}${timestampInfo}\n\n`;
const adjustedContent = adjustHeaderLevels(messageContent);
conversation.push(prefix + adjustedContent);
if (footnotes.length) {
conversation.push("\n" + footnotes.join("\n"));
}
}
}
}
for (const childId of (node.children || [])) {
conversation.push(...buildConversationTree(mapping, childId, indent + 1));
}
return conversation;
}
// 移除特殊标记
function removeCiteTurnAndNavlistMarkers(data) {
if (typeof data === 'object' && data !== null) {
if (data.content && data.content.parts) {
data.content.parts = data.content.parts
.filter(part => typeof part === 'string' && !part.includes("video 袁娅维"));
}
for (let key in data) {
data[key] = removeCiteTurnAndNavlistMarkers(data[key]);
}
return data;
} else if (Array.isArray(data)) {
return data.map(item => removeCiteTurnAndNavlistMarkers(item));
} else if (typeof data === 'string') {
let result = data.replace(/(citeturn|turn)0(news|search)\d+/g, '')
.replace(/^video.*?《.*?》MV\s*/gm, '')
.replace(/navlist.*?(?=\n|$)/g, '')
.replace(/\n\s*\n/g, '\n\n');
return result.trim();
}
return data;
}
// 获取默认模型
function getDefaultModel(data) {
if (!data?.mapping) return 'unknown';
for (const node of Object.values(data.mapping)) {
if (node.message?.author?.role === 'assistant') {
return node.message.metadata?.default_model_slug || 'unknown';
}
}
return 'unknown';
}
// 转换JSON到Markdown
function convertJsonToMarkdown(jsonData) {
// 移除PUA字符
const cleanData = JSON.parse(JSON.stringify(jsonData).replace(/[\uE000-\uF8FF]/g, ''));
// 移除特定标记
const processedData = removeCiteTurnAndNavlistMarkers(cleanData);
// 获取标题和默认模型
const title = processedData.title || 'Conversation';
const defaultModel = getDefaultModel(processedData);
// 获取根节点
const mapping = processedData.mapping;
const rootId = Object.keys(mapping).find(nodeId => !mapping[nodeId].parent);
// 构建对话
const conversation = buildConversationTree(mapping, rootId);
// 生成最终的Markdown内容
let markdownContent = `# ${title}-${defaultModel}\n\n`;
markdownContent += conversation.join('\n\n').replace(/\n{3,}/g, '\n\n');
return markdownContent;
}
// 响应处理函数
function processResponse(text, url) {
try {
const responseSize = text.length;
if (responseSize > state.largestResponseSize) {
state.largestResponse = text;
state.largestResponseSize = responseSize;
state.largestResponseUrl = url;
state.lastUpdateTime = new Date().toLocaleTimeString();
updateButtonsStatus();
log.info(`发现更大的响应 (${responseSize} bytes) 来自: ${url}`);
}
} catch (e) {
log.error('处理响应时出错:', e);
}
}
// 监听 fetch 请求
const originalFetch = window.fetch;
window.fetch = async function(...args) {
const response = await originalFetch.apply(this, args);
const url = args[0];
if (url.includes('conversation/')) {
try {
const clonedResponse = response.clone();
clonedResponse.text().then(text => {
processResponse(text, url);
}).catch(e => {
log.error('解析fetch响应时出错:', e);
});
} catch (e) {
log.error('克隆fetch响应时出错:', e);
}
}
return response;
};
// 监听传统的 XHR 请求
const originalXhrOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
if (url.includes('conversation/')) {
this.addEventListener('load', function() {
try {
processResponse(this.responseText, url);
} catch (e) {
log.error('处理XHR响应时出错:', e);
}
});
}
return originalXhrOpen.apply(this, arguments);
};
// 更新按钮状态
function updateButtonsStatus() {
const jsonButton = document.getElementById('downloadJsonButton');
const mdButton = document.getElementById('downloadMdButton');
[jsonButton, mdButton].forEach(button => {
if (button) {
button.style.backgroundColor = state.largestResponse ? '#28a745' : '#007bff';
button.title = state.largestResponse
? `最后更新: ${state.lastUpdateTime}\n来源: ${state.largestResponseUrl}\n大小: ${(state.largestResponseSize / 1024).toFixed(2)}KB`
: '等待响应中...';
}
});
}
// 创建下载按钮
function createDownloadButtons() {
const buttonStyles = {
position: 'fixed',
top: '45%',
right: '0px',
zIndex: '9999',
padding: '10px',
backgroundColor: '#007bff',
color: '#ffffff',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
transition: 'all 0.3s ease',
fontFamily: 'Arial, sans-serif',
boxShadow: '0 2px 5px rgba(0,0,0,0.2)',
whiteSpace: 'nowrap'
};
// JSON下载按钮
const jsonButton = document.createElement('button');
jsonButton.id = 'downloadJsonButton';
jsonButton.innerText = '下载JSON';
Object.assign(jsonButton.style, buttonStyles);
// MD下载按钮
const mdButton = document.createElement('button');
mdButton.id = 'downloadMdButton';
mdButton.innerText = '下载MD';
Object.assign(mdButton.style, buttonStyles);
mdButton.style.right = '100px'; // 设置MD按钮在JSON按钮左边
// 鼠标悬停效果
[jsonButton, mdButton].forEach(button => {
button.onmouseover = () => {
button.style.transform = 'scale(1.05)';
button.style.boxShadow = '0 4px 8px rgba(0,0,0,0.3)';
};
button.onmouseout = () => {
button.style.transform = 'scale(1)';
button.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';
};
});
// 下载功能
jsonButton.onclick = function() {
if (!state.largestResponse) {
alert('还没有发现有效的会话记录。\n请等待页面加载完成或进行一些对话。');
return;
}
try {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const chatName = document.title.trim().replace(/[/\\?%*:|"<>]/g, '-');
const fileName = `${chatName}_${timestamp}.json`;
const blob = new Blob([state.largestResponse], { type: 'application/json' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
log.info(`成功下载JSON文件: ${fileName}`);
} catch (e) {
log.error('下载JSON过程中出错:', e);
alert('下载过程中发生错误,请查看控制台了解详情。');
}
};
mdButton.onclick = function() {
if (!state.largestResponse) {
alert('还没有发现有效的会话记录。\n请等待页面加载完成或进行一些对话。');
return;
}
try {
const jsonData = JSON.parse(state.largestResponse);
const markdownContent = convertJsonToMarkdown(jsonData);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const chatName = document.title.trim().replace(/[/\\?%*:|"<>]/g, '-');
const fileName = `${chatName}_${timestamp}.md`;
const blob = new Blob([markdownContent], { type: 'text/markdown' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
log.info(`成功下载MD文件: ${fileName}`);
} catch (e) {
log.error('下载MD过程中出错:', e);
alert('下载过程中发生错误,请查看控制台了解详情。');
}
};
document.body.appendChild(jsonButton);
document.body.appendChild(mdButton);
updateButtonsStatus();
}
// 页面加载完成后初始化
window.addEventListener('load', function() {
createDownloadButtons();
// 使用 MutationObserver 确保按钮始终存在
const observer = new MutationObserver(() => {
if (!document.getElementById('downloadJsonButton') || !document.getElementById('downloadMdButton')) {
log.info('检测到按钮丢失,正在重新创建...');
createDownloadButtons();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
log.info('增强版会话保存脚本已启动');
});
})();