-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathrednoteTools.ts
More file actions
305 lines (257 loc) · 9.79 KB
/
Copy pathrednoteTools.ts
File metadata and controls
305 lines (257 loc) · 9.79 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
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
import { AuthManager } from '../auth/authManager'
import { Browser, Page } from 'playwright'
import logger from '../utils/logger'
import { GetNoteDetail, NoteDetail } from './noteDetail'
export interface Note {
title: string
content: string
tags: string[]
url: string
author: string
likes?: number
collects?: number
comments?: number
}
export interface Comment {
author: string
content: string
likes: number
time: string
}
export class RedNoteTools {
private authManager: AuthManager
private browser: Browser | null = null
private page: Page | null = null
constructor() {
logger.info('Initializing RedNoteTools')
this.authManager = new AuthManager()
}
async initialize(): Promise<void> {
logger.info('Initializing browser and page')
this.browser = await this.authManager.getBrowser()
if (!this.browser) {
throw new Error('Failed to initialize browser')
}
try {
this.page = await this.browser.newPage()
// Load cookies if available
const cookies = await this.authManager.getCookies()
if (cookies.length > 0) {
logger.info(`Loading ${cookies.length} cookies`)
await this.page.context().addCookies(cookies)
}
// Check login status
logger.info('Checking login status')
await this.page.goto('https://www.rednote.com')
const isLoggedIn = await this.page.evaluate(() => {
const sidebarUser = document.querySelector('.user.side-bar-component .channel')
return sidebarUser?.textContent?.trim() === 'Me'
})
// If not logged in, perform login
if (!isLoggedIn) {
logger.error('Not logged in, please login first')
throw new Error('Not logged in')
}
logger.info('Login status verified')
} catch (error) {
// 初始化过程中出错,确保清理资源
await this.cleanup()
throw error
}
}
async cleanup(): Promise<void> {
logger.info('Cleaning up browser resources')
try {
if (this.page) {
await this.page.close().catch(err => logger.error('Error closing page:', err))
this.page = null
}
if (this.browser) {
await this.browser.close().catch(err => logger.error('Error closing browser:', err))
this.browser = null
}
} catch (error) {
logger.error('Error during cleanup:', error)
} finally {
this.page = null
this.browser = null
}
}
extractRedBookUrl(shareText: string): string {
// 匹配 http://xhslink.com/ 开头的链接
const xhslinkRegex = /(https?:\/\/xhslink\.com\/[a-zA-Z0-9\/]+)/i
const xhslinkMatch = shareText.match(xhslinkRegex)
if (xhslinkMatch && xhslinkMatch[1]) {
return xhslinkMatch[1]
}
// 匹配 https://www.rednote.com/ 开头的链接
const rednoteRegex = /(https?:\/\/(?:www\.)?rednote\.com\/[^,\s]+)/i
const rednoteMatch = shareText.match(rednoteRegex)
if (rednoteMatch && rednoteMatch[1]) {
return rednoteMatch[1]
}
return shareText
}
async searchNotes(keywords: string, limit: number = 10): Promise<Note[]> {
logger.info(`Searching notes with keywords: ${keywords}, limit: ${limit}`)
try {
await this.initialize()
if (!this.page) throw new Error('Page not initialized')
// Navigate to search page
logger.info('Navigating to search page')
await this.page.goto(`https://www.rednote.com/search_result?keyword=${encodeURIComponent(keywords)}`)
// Wait for search results to load
logger.info('Waiting for search results')
await this.page.waitForSelector('.feeds-container', {
timeout: 30000
})
// Get all note items
let noteItems = await this.page.$$('.feeds-container .note-item')
logger.info(`Found ${noteItems.length} note items`)
const notes: Note[] = []
// Process each note
for (let i = 0; i < Math.min(noteItems.length, limit); i++) {
logger.info(`Processing note ${i + 1}/${Math.min(noteItems.length, limit)}`)
try {
// Click on the note cover to open detail
await noteItems[i].$eval('a.cover.mask.ld', (el: HTMLElement) => el.click())
// Wait for the note page to load
logger.info('Waiting for note page to load')
await this.page.waitForSelector('#noteContainer', {
timeout: 30000
})
await this.randomDelay(0.5, 1.5)
// Extract note content
const note = await this.page.evaluate(() => {
const article = document.querySelector('#noteContainer')
if (!article) return null
// Get title
const titleElement = article.querySelector('#detail-title')
const title = titleElement?.textContent?.trim() || ''
// Get content
const contentElement = article.querySelector('#detail-desc .note-text')
const content = contentElement?.textContent?.trim() || ''
// Get author info
const authorElement = article.querySelector('.author-wrapper .username')
const author = authorElement?.textContent?.trim() || ''
// Get interaction counts from engage-bar
const engageBar = document.querySelector('.engage-bar-style')
const likesElement = engageBar?.querySelector('.like-wrapper .count')
const likes = parseInt(likesElement?.textContent?.replace(/[^\d]/g, '') || '0')
const collectElement = engageBar?.querySelector('.collect-wrapper .count')
const collects = parseInt(collectElement?.textContent?.replace(/[^\d]/g, '') || '0')
const commentsElement = engageBar?.querySelector('.chat-wrapper .count')
const comments = parseInt(commentsElement?.textContent?.replace(/[^\d]/g, '') || '0')
return {
title,
content,
url: window.location.href,
author,
likes,
collects,
comments
}
})
if (note) {
logger.info(`Extracted note: ${note.title}`)
notes.push(note as Note)
}
// Add random delay before closing
await this.randomDelay(0.5, 1)
// Close note by clicking the close button
const closeButton = await this.page.$('.close-circle')
if (closeButton) {
logger.info('Closing note dialog')
await closeButton.click()
// Wait for note dialog to disappear
await this.page.waitForSelector('#noteContainer', {
state: 'detached',
timeout: 30000
})
}
} catch (error) {
logger.error(`Error processing note ${i + 1}:`, error)
const closeButton = await this.page.$('.close-circle')
if (closeButton) {
logger.info('Attempting to close note dialog after error')
await closeButton.click()
// Wait for note dialog to disappear
await this.page.waitForSelector('#noteContainer', {
state: 'detached',
timeout: 30000
})
}
} finally {
// Add random delay before next note
await this.randomDelay(0.5, 1.5)
}
}
logger.info(`Successfully processed ${notes.length} notes`)
return notes
} catch (error) {
logger.error('Error searching notes:', error)
throw error
} finally {
await this.cleanup()
}
}
async getNoteContent(url: string): Promise<NoteDetail> {
logger.info(`Getting note content for URL: ${url}`)
try {
await this.initialize()
if (!this.page) throw new Error('Page not initialized')
const actualURL = this.extractRedBookUrl(url)
await this.page.goto(actualURL)
let note = await GetNoteDetail(this.page)
note.url = url
logger.info(`Successfully extracted note: ${note.title}`)
return note
} catch (error) {
logger.error('Error getting note content:', error)
throw error
} finally {
await this.cleanup()
}
}
async getNoteComments(url: string): Promise<Comment[]> {
logger.info(`Getting comments for URL: ${url}`)
try {
await this.initialize()
if (!this.page) throw new Error('Page not initialized')
await this.page.goto(url)
// Wait for comments to load
logger.info('Waiting for comments to load')
await this.page.waitForSelector('[role="dialog"] [role="list"]')
// Extract comments
const comments = await this.page.evaluate(() => {
const items = document.querySelectorAll('[role="dialog"] [role="list"] [role="listitem"]')
const results: Comment[] = []
items.forEach((item) => {
const author = item.querySelector('[data-testid="user-name"]')?.textContent?.trim() || ''
const content = item.querySelector('[data-testid="comment-content"]')?.textContent?.trim() || ''
const likes = parseInt(item.querySelector('[data-testid="likes-count"]')?.textContent || '0')
const time = item.querySelector('time')?.textContent?.trim() || ''
results.push({ author, content, likes, time })
})
return results
})
logger.info(`Successfully extracted ${comments.length} comments`)
return comments
} catch (error) {
logger.error('Error getting note comments:', error)
throw error
} finally {
await this.cleanup()
}
}
/**
* Wait for a random duration between min and max seconds
* @param min Minimum seconds to wait
* @param max Maximum seconds to wait
*/
private async randomDelay(min: number, max: number): Promise<void> {
const delay = Math.random() * (max - min) + min
logger.debug(`Adding random delay of ${delay.toFixed(2)} seconds`)
await new Promise((resolve) => setTimeout(resolve, delay * 1000))
}
}