-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageHandler.js
More file actions
242 lines (203 loc) ยท 7.75 KB
/
Copy pathImageHandler.js
File metadata and controls
242 lines (203 loc) ยท 7.75 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
const fs = require('fs');
const https = require('https');
const os = require('os');
const path = require('path');
/**
* Image Handler - Telegram image processing and management
* Handles image downloads, temp file management, and Claude integration
*/
class ImageHandler {
constructor(bot, sessionManager, activityIndicator, mainBot) {
this.bot = bot;
this.sessionManager = sessionManager;
this.activityIndicator = activityIndicator;
this.mainBot = mainBot; // Reference to main bot for concat mode access
}
/**
* Handle incoming photo message with optional caption
*/
async handlePhotoMessage(msg, processUserMessageCallback) {
const userId = msg.from.id;
const chatId = msg.chat.id;
const photos = msg.photo;
const caption = msg.caption || '';
console.log(`[User ${userId}] Photo message with caption: "${caption}"`);
let imagePath = null;
try {
// Get the largest photo (best quality)
const photo = photos[photos.length - 1];
console.log(`[User ${userId}] Selected photo: ${photo.file_id} (${photo.width}x${photo.height})`);
// Download the image to temp directory
imagePath = await this.downloadImage(photo.file_id, userId);
console.log(`[User ${userId}] Downloaded image to temp: ${imagePath}`);
// Create message for Claude with image path and caption
let message = '';
if (caption.trim()) {
message = `${caption.trim()}\n\nImage file: ${imagePath}`;
} else {
message = `Please analyze this image: ${imagePath}`;
}
console.log(`[User ${userId}] Sending to Claude: "${message}"`);
// Check if concat mode is enabled
if (this.mainBot && this.mainBot.getConcatModeStatus(userId)) {
// Add image to buffer
const bufferSize = await this.mainBot.addToMessageBuffer(userId, {
type: 'image',
content: caption,
imagePath: imagePath
});
await this.mainBot.safeSendMessage(chatId,
`๐ผ๏ธ **Image Added to Buffer**\n\n${caption ? `Caption: ${caption}` : 'No caption'}\n\nBuffer: ${bufferSize} message${bufferSize > 1 ? 's' : ''}`, {
reply_markup: this.mainBot.keyboardHandlers.createReplyKeyboard(userId)
}
);
return;
}
// Process message with temp file cleanup tracking
await this.processImageMessage(message, userId, chatId, imagePath, processUserMessageCallback);
} catch (error) {
console.error(`[User ${userId}] Error processing photo:`, error);
// Clean up temp file on error
if (imagePath && fs.existsSync(imagePath)) {
try {
fs.unlinkSync(imagePath);
console.log(`[User ${userId}] Cleaned up temp image on error: ${imagePath}`);
} catch (cleanupError) {
console.error(`[User ${userId}] Failed to cleanup temp image:`, cleanupError);
}
}
await this.sessionManager.sendError(chatId, error);
}
}
/**
* Download image from Telegram servers to temp directory
*/
async downloadImage(fileId, userId) {
try {
// Get file info from Telegram
const file = await this.bot.getFile(fileId);
const fileUrl = `https://api.telegram.org/file/bot${this.bot.token}/${file.file_path}`;
// Use system temp directory
const tempDir = os.tmpdir();
// Generate unique filename in temp directory
const timestamp = Date.now();
const extension = path.extname(file.file_path) || '.jpg';
const filename = `telegram_image_${userId}_${timestamp}${extension}`;
const imagePath = path.join(tempDir, filename);
console.log(`Downloading image from: ${fileUrl}`);
console.log(`Saving to temp file: ${imagePath}`);
// Download the file
await this.downloadFile(fileUrl, imagePath);
return imagePath;
} catch (error) {
console.error('Error downloading image:', error);
throw new Error(`Failed to download image: ${error.message}`);
}
}
/**
* Download file from URL to local path
*/
downloadFile(url, filePath) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(filePath);
https.get(url, (response) => {
if (response.statusCode !== 200) {
reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`));
return;
}
response.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
file.on('error', (error) => {
fs.unlink(filePath, () => {}); // Delete partial file
reject(error);
});
}).on('error', (error) => {
reject(error);
});
});
}
/**
* Process image message with temp file cleanup tracking
*/
async processImageMessage(text, userId, chatId, tempFilePath, processUserMessageCallback) {
// Get or create user session first
let session = this.sessionManager.getUserSession(userId);
if (!session) {
// First message - create new session
console.log(`[ImageHandler] Creating new session for user ${userId}`);
session = await this.sessionManager.createUserSession(userId, chatId);
// Send session init message
const sessionInitText = '๐ **New Session Started**\n\n' +
'Ready to process your requests with Claude CLI stream-json mode.\n\n' +
'๐ Session continuity with ID tracking\n' +
'๐ก๏ธ Auto-permissions enabled\n' +
'๐ Live TodoWrite updates active\n' +
'๐ธ Image analysis ready\n\n' +
'๐ก Use /end to close this session\n' +
'๐ Use /sessions to view history';
await this.sessionManager.safeSendMessage(chatId, sessionInitText);
}
// Store temp file path in session for cleanup after Claude completes
session.tempFilePath = tempFilePath;
console.log(`[User ${userId}] Stored temp file path in session: ${tempFilePath}`);
try {
// Use the callback to process the message
await processUserMessageCallback(text, userId, chatId);
// Note: Temp file will be cleaned up in SessionManager when Claude completes
} catch (error) {
// Clean up temp file immediately on error during setup
if (tempFilePath && fs.existsSync(tempFilePath)) {
try {
fs.unlinkSync(tempFilePath);
console.log(`[User ${userId}] Cleaned up temp image on setup error: ${tempFilePath}`);
} catch (cleanupError) {
console.error(`[User ${userId}] Failed to cleanup temp image:`, cleanupError);
}
}
// Clear temp file path from session
if (session) {
session.tempFilePath = null;
}
// Re-throw the error to maintain error handling flow
throw error;
}
}
/**
* Clean up temporary file (called by SessionManager)
*/
static cleanupTempFile(session, userId) {
if (session && session.tempFilePath) {
try {
if (fs.existsSync(session.tempFilePath)) {
fs.unlinkSync(session.tempFilePath);
console.log(`[User ${userId}] Cleaned up temp image after Claude completion: ${session.tempFilePath}`);
}
} catch (error) {
console.error(`[User ${userId}] Failed to cleanup temp image:`, error);
}
// Clear temp file path from session
session.tempFilePath = null;
}
}
/**
* Get handler statistics
*/
getStats() {
return {
// Could add statistics here like processed images count, etc.
handlerType: 'ImageHandler',
tempDirectory: os.tmpdir()
};
}
/**
* Cleanup resources
*/
cleanup() {
// Could clean up any pending temp files here if needed
console.log('๐งน ImageHandler cleanup completed');
}
}
module.exports = ImageHandler;