diff --git a/lib/api-client/gmail-client.js b/lib/api-client/gmail-client.js index 0028dd0b..bcf4f496 100644 --- a/lib/api-client/gmail-client.js +++ b/lib/api-client/gmail-client.js @@ -521,6 +521,66 @@ class GmailClient { return result; } + + async getText(textId, options) { + options = options || {}; + await this.prepare(); + + const accessToken = await this.getToken(); + + const [messageId, textParts] = msgpack.decode(Buffer.from(textId, 'base64url')); + + const bodyParts = new Map(); + + textParts[0].forEach(p => { + bodyParts.set(p, 'text'); + }); + + textParts[1].forEach(p => { + bodyParts.set(p, 'html'); + }); + + const requestQuery = {}; + const messageData = await this.oAuth2Client.request( + accessToken, + `${GMAIL_API_BASE}/gmail/v1/users/me/messages/${messageId}?format=full`, + 'get', + requestQuery + ); + + const response = {}; + + if (options.textType && options.textType !== '*') { + response[options.textType] = ''; + } + + const textContent = {}; + const walkBodyParts = node => { + let textType = bodyParts.has(node.partId) ? bodyParts.get(node.partId) : false; + + if (textType && (options.textType === '*' || options.textType === textType) && node.body?.data) { + if (!textContent[textType]) { + textContent[textType] = []; + } + textContent[textType].push(Buffer.from(node.body.data, 'base64')); + } + + if (Array.isArray(node.parts)) { + for (let part of node.parts) { + walkBodyParts(part); + } + } + }; + walkBodyParts(messageData.payload); + + for (let key of Object.keys(textContent)) { + response[key] = textContent[key].map(buf => buf.toString()).join('\n'); + } + + response.hasMore = false; + + return response; + } } module.exports = { GmailClient }; @@ -539,6 +599,9 @@ let main = async () => { if (msg.attachments && msg.attachments.length) { await gmailClient.getMessage(msg.id, { textType: '*' }); + const textContent = await gmailClient.getText(msg.text.id, { textType: '*' }); + console.log('TEXT CONTENT', textContent); + let raw = await gmailClient.getRawMessage(msg.id); await fs.promises.writeFile(`/Users/andris/Desktop/${msg.id}.eml`, raw); for (let a of msg.attachments) {