All files queue-processor.ts

78.46% Statements 51/65
53.84% Branches 14/26
68.75% Functions 11/16
80.35% Lines 45/56

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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 1981x 1x 1x 1x     1x 1x 1x 1x 1x     1x   1x 1x 1x 1x       1x         1x       1x   1x                 1x     3x                 1x 3x 6x 3x       3x 1x           3x                       1x             1x         1x 2x         1x           1x 1x 1x           1x                     1x             5x   1x   5x     5x     1x 1x       5x                             1x                                                                          
import { BotDatabaseService } from '@baneverywhere/db';
import { InjectQueue, Process, Processor } from '@nestjs/bull';
import { Inject } from '@nestjs/common';
import { Action, BanEverywhereSettings } from '@prisma/client';
import { Job, Queue } from 'bull';
import { Actions } from '@prisma/client';
import { BOT_CONNECTION } from '@baneverywhere/namespaces';
import { ClientProxy } from '@nestjs/microservices';
import { BotPatterns } from '@baneverywhere/bot-interfaces';
import { logError } from '@baneverywhere/error-handler';
import { TwitchClientService } from '@baneverywhere/twitch-client';
 
@Processor('queue')
export class QueueProcessor {
  constructor(
    private readonly dbService: BotDatabaseService,
    @InjectQueue('queue') private readonly queue: Queue,
    @Inject(BOT_CONNECTION) private readonly botHandlerClient: ClientProxy,
    private readonly twitchService: TwitchClientService
  ) {}
 
  @logError()
  public async handleBanUnban(
    action: Action,
    job: Job<Omit<Actions, 'queueFor'> & { cursor?: number }>
  ) {
    const pattern =
      action === Action.BAN
        ? BotPatterns.BOT_BAN_USER
        : BotPatterns.BOT_UNBAN_USER;
 
    const { cursor, ...data } = job.data;
 
    const settings = await this.dbService.settings.findMany({
      where: {
        fromUsername: data.streamer.substr(1),
      },
      take: 50,
      skip: cursor ? 1 : 0,
      ...(cursor ? { cursor: { id: cursor } } : null),
    });
 
    const users = await this.dbService.user.findMany({
      where: {
        login: {
          in: settings.map((setting) => setting.toUsername),
        },
      },
      select: {
        login: true,
        machineUUID: true,
      },
    });
 
    await Promise.all(
      settings.map(async (setting) => {
        const user = users.find((u) => u.login === setting.toUsername);
        const preapproved = Boolean(
          setting.settings === BanEverywhereSettings.AUTOMATIC &&
            user?.machineUUID
        );
        if (preapproved) {
          this.botHandlerClient.emit(pattern, {
            queueFor: setting.toUsername,
            ...data,
          });
        }
 
        await this.dbService.actions.create({
          data: {
            ...data,
            queueFor: setting.toUsername,
            inQueue: BanEverywhereSettings.AUTOMATIC === setting.settings,
            approved: BanEverywhereSettings.AUTOMATIC === setting.settings,
            processed: preapproved,
          },
        });
      })
    );
 
    Iif (settings.length === 50) {
      this.queue.add(action, {
        ...job.data,
        cursor: settings[49].id,
      });
    }
 
    return;
  }
 
  @Process(Action.BAN)
  @logError()
  async handleBan(job: Job<Omit<Actions, 'queueFor'> & { cursor?: number }>) {
    return await this.handleBanUnban(Action.BAN, job);
  }
 
  @Process(Action.UNBAN)
  @logError()
  async handleUnban(job: Job<Omit<Actions, 'queueFor'> & { cursor?: number }>) {
    return await this.handleBanUnban(Action.UNBAN, job);
  }
 
  @Process('queue')
  @logError()
  async handleQueue(job: Job<{ username: string; cursor?: number }>) {
    const { username, cursor } = job.data;
    const user = await this.dbService.user.findUnique({
      where: {
        login: username,
      },
    });
 
    const actions = await this.dbService.actions.findMany({
      where: {
        queueFor: username,
        inQueue: true,
        processed: false,
      },
      take: 50,
      skip: cursor ? 1 : 0,
      ...(cursor ? { cursor: { id: cursor } } : null),
    });
 
    Iif (actions.length === 50) {
      this.queue.add('queue', {
        ...job.data,
        cursor: actions[49].id,
      });
    }
 
    const approved = actions.filter(action => action.approved);
 
    approved.forEach((action) => {
      const pattern =
        action.action === Action.BAN
          ? BotPatterns.BOT_BAN_USER
          : BotPatterns.BOT_UNBAN_USER;
      this.botHandlerClient.emit(pattern, action);
    });
 
    if (user.machineUUID) {
      return await this.dbService.actions
        .updateMany({
          where: {
            id: {
              in: actions.map((action) => action.id),
            },
          },
          data: {
            processed: true,
          },
        })
        .catch((err) => console.log(err));
    } else E{
      return;
    }
  }
 
  @Process('settings')
  @logError()
  async handleSettings(
    job: Job<{
      channelName: string;
      settings: BanEverywhereSettings;
      username: string;
    }>
  ) {
    const { channelName, settings, username } = job.data;
    const users = await this.twitchService.findUsernamesByLogin([
      channelName,
      username,
    ]);
 
    const user = users.find((u) => u.login.toLowerCase() === username.toLowerCase());
    const channel = users.find((u) => u.login.toLowerCase() === channelName.toLowerCase());
    Iif (!user || !channel) return;
 
    await this.dbService.settings.upsert({
      where: {
        fromId_toId: {
          fromId: user.id,
          toId: channel.id,
        },
      },
      create: {
        fromId: user.id,
        toId: channel.id,
        toUsername: channel.login,
        fromUsername: user.login,
        settings,
      },
      update: {
        settings,
      },
    });
  }
}