All files / src/gmail/clients gmailApiClient.ts

85.91% Statements 61/71
67.64% Branches 23/34
100% Functions 16/16
85.07% Lines 57/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1788x 8x     8x   8x   8x     8x 5x 5x           5x           5x 5x 5x       5x 5x       6x   6x 62x           62x     3x 3x             23x 26x         22x   22x   22x       22x 22x           22x 22x   22x   22x       6x   6x 6x           6x 6x 6x   6x           6x       22x                           54x 54x   4x   4x     50x       4x 1x   1x     3x   3x               22x   22x       22x         22x         22x 22x             22x    
import { gmail_v1, google } from 'googleapis';
import { inject, injectable } from 'inversify';
import GmailMessageData from '../types/gmailMessageData';
import GoogleOAuth2ClientProvider from '../../googleOAuth2/providers/googleOAuth2ClientProvider';
import { injectables } from '../../core/types/injectables';
import GoogleOAuth2Identifiers from '../../googleOAuth2/types/googleOAuth2Identifiers';
import { DependencyInjector } from '../../dependencyInjector';
import IUsesGoogleOAuth2 from '../../googleOAuth2/contracts/IUsesGoogleOAuth2';
import ILogger from '../../core/contracts/ILogger';
 
@injectable()
export default class GmailApiClient implements IUsesGoogleOAuth2 {
    private readonly searchQuery: string = 'from:pb@unicreditgroup.bg subject: "Dvizhenie po smetka"';
    private readonly maxExponentialBackoffDepth: number = 2;
 
    private logger;
    private googleOAuth2ClientProvider: GoogleOAuth2ClientProvider;
    private gmail: gmail_v1.Gmail;
 
    private exponentialBackoffDepth = 0;
 
    public constructor(
        @inject(injectables.ILogger)
        logger: ILogger
    ) {
        this.logger = logger;
        this.googleOAuth2ClientProvider = null!;
        this.gmail = null!;
    }
 
    public async useOAuth2IdentifiersAsync(identifiers: GoogleOAuth2Identifiers) {
        this.googleOAuth2ClientProvider = await DependencyInjector.Singleton.generateGmailServiceAsync(injectables.GoogleOAuth2ClientProviderGenerator, identifiers);
        this.gmail = google.gmail({ version: 'v1', auth: this.googleOAuth2ClientProvider.client });
    }
 
    public async * generateMessageIdsAsync(pageToken?: string): AsyncGenerator<string, [], undefined> {
        const { messages, nextPageToken } = await this.fetchMessagesAsync(pageToken);
 
        for (const messageItem of messages) {
            Iif (messageItem.id === null || messageItem.id === undefined) {
                this.logger.warn('Empty message id. Skipping...', { messageItem: JSON.stringify(messageItem) });
 
                continue;
            }
            
            yield messageItem.id;
        }
 
        if (nextPageToken !== null && nextPageToken !== undefined) {
            yield * this.generateMessageIdsAsync(nextPageToken);
        }
 
        return [];
    }
    
    public async fetchMessageDataAsync(messageId: string) {
        const messageResponse = await this.makeApiCallAsync(async () =>
            await this.gmail.users.messages.get({
                userId: 'me',
                id: messageId
            }));
    
        const message = messageResponse.data;
 
        const messageData = this.constructMessageData(message);
    
        return messageData;
    }
    
    public async fetchAttachmentDataAsync(messageData: GmailMessageData) {
        const response = await this.makeApiCallAsync(async () => 
            await this.gmail.users.messages.attachments.get({
                userId: 'me',
                messageId: messageData.messageId,
                id: messageData.attachmentId
            }));
 
        const messagePartBody = response.data;
        const attachmentDataBase64 = String(messagePartBody.data);
 
        const attachmentData = this.decodeAttachmentData(attachmentDataBase64);
    
        return attachmentData;
    }
    
    private async fetchMessagesAsync(pageToken?: string) {
        this.logger.log(`Requesting messages...`);
 
        const response = await this.makeApiCallAsync(async () =>
            await this.gmail.users.messages.list({
                userId: 'me',
                q: this.searchQuery,
                pageToken: pageToken
            }));
 
        const messageList = response.data;
        const messages = messageList.messages;
        const nextPageToken = messageList.nextPageToken;
    
        Iif (messages === undefined) {
            this.logger.warn(`Failed to get messages`);
 
            return { messages: [], nextPageToken: null };
        }
    
        return { messages, nextPageToken };
    }
 
    private constructMessageData(message: gmail_v1.Schema$Message) {
        return {
            messageId: String(message.id),
            attachmentId: String(message
                .payload
               ?.parts
               ?.[1]
               ?.body
               ?.attachmentId)
        } as GmailMessageData
    }
 
    private async makeApiCallAsync<T>(apiCall: () => T): Promise<T> {
        let result;
 
        try {
            result = await apiCall();
        } catch(ex) {
            this.logger.warn(`Gmail API call failed (${(ex as Error).message ?? ex}). Reattempting after ${2 ** this.exponentialBackoffDepth}s...`);
            
            result = await this.tryExponentialBackoffAsync(ex, async () => await this.makeApiCallAsync(apiCall));
        }
 
        return result;
    }
 
    private async tryExponentialBackoffAsync<T>(ex: unknown, operation: () => Promise<T>): Promise<T> {
        if (this.exponentialBackoffDepth > this.maxExponentialBackoffDepth) {
            this.exponentialBackoffDepth = 0;
 
            throw ex;
        }
        
        await new Promise(res => setTimeout(res, 2 ** this.exponentialBackoffDepth++ * 1000));
 
        const result = await operation();
 
        this.exponentialBackoffDepth = 0;
 
        return result;
    }
    
    private decodeAttachmentData(attachmentDataBase64: string) {
        const base64Encoded = this.fromBase64Url(attachmentDataBase64);
    
        const utf16leEncoded = Buffer
            .from(base64Encoded, 'base64')
            .toString('utf16le');
    
        return utf16leEncoded;
    }
 
    private fromBase64Url(input: string) {
        // Replace non-url compatible chars with base64 standard chars
        let result = input
            .replace(/-/g, '+')
            .replace(/_/g, '/');
    
        // Pad out with standard base64 required padding characters
        const pad = result.length % 4;
        Iif (pad) {
            Iif (pad === 1) {
                throw new Error('InvalidLengthError: Input base64url string is the wrong length to determine padding');
            }
            result += new Array(5 - pad).join('=');
        }
    
        return result;
    }
}