import { Page } from 'puppeteer' import { getQuizData, waitForQuizRefresh } from '../../browser/BrowserFunc' import { wait } from '../../util/Utils' import { log } from '../../util/Logger' export async function doQuiz(page: Page) { log('QUIZ', 'Trying to complete quiz') try { await page.waitForNetworkIdle({ timeout: 5000 }) await wait(2000) // Check if the quiz has been started or not const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { visible: true, timeout: 3000 }).then(() => true).catch(() => false) if (quizNotStarted) { await page.click('#rqStartQuiz') } else { log('QUIZ', 'Quiz has already been started, trying to finish it') } await wait(2000) let quizData = await getQuizData(page) const questionsRemaining = quizData.maxQuestions - quizData.CorrectlyAnsweredQuestionCount // Amount of questions remaining // All questions for (let question = 0; question < questionsRemaining; question++) { if (quizData.numberOfOptions === 8) { const answers: string[] = [] for (let i = 0; i < quizData.numberOfOptions; i++) { const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { visible: true, timeout: 5000 }) const answerAttribute = await answerSelector?.evaluate(el => el.getAttribute('iscorrectoption')) if (answerAttribute && answerAttribute.toLowerCase() === 'true') { answers.push(`#rqAnswerOption${i}`) } } // Click the answers for (const answer of answers) { await page.waitForSelector(answer, { visible: true, timeout: 2000 }) // Click the answer on page await page.click(answer) const refreshSuccess = await waitForQuizRefresh(page) if (!refreshSuccess) { await page.close() log('QUIZ', 'An error occurred, refresh was unsuccessful', 'error') return } } // Other type quiz } else if ([2, 3, 4].includes(quizData.numberOfOptions)) { quizData = await getQuizData(page) // Refresh Quiz Data const correctOption = quizData.correctAnswer for (let i = 0; i < quizData.numberOfOptions; i++) { const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { visible: true, timeout: 5000 }) const dataOption = await answerSelector?.evaluate(el => el.getAttribute('data-option')) if (dataOption === correctOption) { // Click the answer on page await page.click(`#rqAnswerOption${i}`) const refreshSuccess = await waitForQuizRefresh(page) if (!refreshSuccess) { await page.close() log('QUIZ', 'An error occurred, refresh was unsuccessful', 'error') return } } } await wait(2000) } } // Done with await wait(2000) await page.close() log('QUIZ', 'Completed the quiz successfully') } catch (error) { await page.close() log('QUIZ', 'An error occurred:' + error, 'error') } }