summaryrefslogtreecommitdiff
path: root/src/handlers/index.js
blob: 0f0ab67ed4567bfb8f378413e723a28cb297f2f5 (plain)
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
const { Types } = require('mongoose');
const puppeteer = require('puppeteer');
const Bluebird = require('bluebird');
const UserModel = require('../services/users/user.model.js');
const launchUserSession = require('./launchUserSession.js');
const attendConference = require('./attendConference.js');
const { clickElementBySelector } = require('./utils.js');

const { EDUFPMI_URL, NODE_ENV, HEADFUL } = process.env;

// Always run headless in production, but allow configuring for development
const headless = NODE_ENV === 'production' || !HEADFUL;


const handleJobAsUser = async (job, browser, user) => {
  console.log(`Running job as ${user.username}`);

  const browserContext = await browser.createIncognitoBrowserContext();

  const { conferenceId } = job.attrs.data;
  const conferenceUrl = `${EDUFPMI_URL}/mod/bigbluebuttonbn/view.php?id=${conferenceId}`;

  const page = await launchUserSession(user, browserContext);
  await page.goto(conferenceUrl);

  // Launch the conference in a new tab
  const conferencePagePromise = new Promise(resolve => browserContext.on(
    'targetcreated',
    target => resolve(target.page())
  ));
  await clickElementBySelector(page, 'input#join_button_input');
  const conferencePage = await conferencePagePromise;
  await page.close();

  await attendConference(conferencePage, () => console.log(`Joined the conference at ${conferenceUrl}`));

  await browserContext.close();
};

const handleJob = async job => {
  const { data } = job.attrs;

  const participants = await UserModel.find({
    _id: {
      $in: data.participantIds.map(Types.ObjectId)
    }
  });

  console.log('Participants: ', participants.map(participant => participant.username));

  const browser = await puppeteer.launch({ headless, args: ['--no-sandbox', '--incognito'] });

  try {
    await Bluebird.map(participants, participant => handleJobAsUser(job, browser, participant));
  } catch (err) {
    console.error(err);
  } finally {
    await browser.close();
  }
};


module.exports = handleJob;