File size: 8,509 Bytes
9179e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import type { Page, Frame, Locator } from 'playwright';
import { logger } from '../../utils/logger';
import {
  readScopeDeepText,
  resolveAssignmentScope,
  SELECTORS,
} from '../selectors';
import { acceptEulaEverywhere } from './login';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface SimilarityResult {
  similarityPercent: number | null;
  viewerUrl: string | null;
  scope?: Page | Frame;
  locator?: Locator;
}

export interface WaitForSimilarityOptions {
  timeoutMs: number;
  pollMs: number;
  refreshAfterMs: number;
  inputFileName?: string;
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

function getSubmissionButtonLocator(scope: Page | Frame, inputTitle: string): Locator {
  const viewButtons = scope.locator(SELECTORS.similarity.viewSubmissionButton);
  if (inputTitle) {
    return viewButtons.filter({ hasText: inputTitle }).first();
  }
  return viewButtons.first();
}

/**
 * Poll for the similarity score to appear on the submission card.
 *
 * After `refreshAfterMs` with no result, refreshes the assignment launch URL
 * once. Returns the similarity percent (if readable) and viewer URL.
 */
export async function waitForSimilarity(
  page: Page,
  assignmentLaunchUrl: string,
  options: WaitForSimilarityOptions,
): Promise<SimilarityResult> {
  const { timeoutMs, pollMs, refreshAfterMs } = options;
  const inputTitle = options.inputFileName
    ? options.inputFileName.replace(/\.[^.]+$/, '').trim()
    : '';
  const started = Date.now();
  let lastText = '';
  // BUG-11 FIX: Allow multiple refreshes (every refreshAfterMs from first refresh)
  let refreshCount = 0;
  const MAX_REFRESHES = 2;
  let lastRefreshAt = 0;

  while (Date.now() - started < timeoutMs) {
    // ---- Deep text scan across all scopes ----
    const scopes: (Page | Frame)[] = [
      page,
      ...page.frames().filter((f) => !f.url().includes('cookie-shim')),
    ];

    for (const candidateScope of scopes) {
      const deepText = await readScopeDeepText(candidateScope);
      const percentMatch = deepText.match(
        /\b(?:Similarity:\s*)?(\d{1,3})%\b/i,
      );
      // BUG-4 FIX: Validate bounds — regex now matches 0-999 so we clamp to 0-100
      const percentRaw = percentMatch ? parseInt(percentMatch[1], 10) : NaN;
      const percent = Number.isFinite(percentRaw) && percentRaw >= 0 && percentRaw <= 100
        ? percentRaw : NaN;
      const percentOk = !isNaN(percent);
      const titleVisible =
        Boolean(inputTitle) &&
        deepText.toLowerCase().includes(inputTitle.toLowerCase());

      if (
        percentOk &&
        (titleVisible || /Submitted|Similarity|Your work/i.test(deepText))
      ) {
        const text = percentMatch![0].includes('Similarity')
          ? percentMatch![0]
          : `Similarity: ${percent}%`;
        logger.info('Similarity detected from deep text', {
          text,
          percent,
        });
        return {
          similarityPercent: percent,
          viewerUrl: null,
          scope: candidateScope,
          locator: getSubmissionButtonLocator(candidateScope, inputTitle),
        };
      }

      // After refresh, if submission row is visible even without percent, proceed
      if (
        refreshCount > 0 &&
        titleVisible &&
        /Your work/i.test(deepText)
      ) {
        logger.info(
          'Submission row visible after refresh; proceeding without similarity value',
        );
        return {
          similarityPercent: null,
          viewerUrl: null,
          scope: candidateScope,
          locator: getSubmissionButtonLocator(candidateScope, inputTitle),
        };
      }
    }

    // ---- Locator-based scan ----
    const scope = await resolveAssignmentScope(page);
    const candidates = [
      {
        kind: 'similarity',
        locator: scope
          .locator(
            'span[part="tii-grn-badge-label"]:has-text("Similarity:")',
          )
          .first(),
      },
      {
        kind: 'similarity',
        locator: scope.locator(SELECTORS.similarity.similaritySpan).first(),
      },
      {
        kind: 'similarity',
        locator: scope.locator(SELECTORS.similarity.similarityDisplay).first(),
      },
      {
        kind: 'title',
        locator: scope.locator(SELECTORS.similarity.viewSubmissionButton).first(),
      },
    ];

    for (const candidateEntry of candidates) {
      const candidate = candidateEntry.locator;
      if (
        await candidate.isVisible({ timeout: 1500 }).catch(() => false)
      ) {
        const text = (
          await candidate.innerText().catch(() => '')
        ).trim();
        const aria = (
          (await candidate
            .getAttribute('aria-label')
            .catch(() => '')) || ''
        ).trim();
        const visibleText = text || aria;

        if (visibleText && visibleText !== lastText) {
          lastText = visibleText;
          logger.info('Submission state', { visibleText });
        }

        if (
          candidateEntry.kind === 'title' &&
          visibleText &&
          refreshCount > 0
        ) {
          return {
            similarityPercent: null,
            viewerUrl: null,
            scope,
            locator: candidate,
          };
        }

        const simMatch = visibleText.match(
          /Similarity:\s*(\d+)%/i,
        );
        if (simMatch) {
          const percent = parseInt(simMatch[1], 10);
          logger.info('Similarity detected from locator', {
            visibleText,
            percent,
          });
          return {
            similarityPercent: percent,
            viewerUrl: null,
            scope,
            locator: getSubmissionButtonLocator(scope, inputTitle),
          };
        }
      }
    }

    // ---- Log body text for diagnostics ----
    const bodyText = await scope
      .locator('body')
      .innerText({ timeout: 3000 })
      .catch(() => '');
    const shortText = bodyText.replace(/\s+/g, ' ').trim().slice(0, 240);
    if (shortText && shortText !== lastText) {
      lastText = shortText;
      logger.debug('Waiting for submission/similarity', {
        bodySnippet: shortText,
      });
    }

    // ---- Refresh assignment launch URL periodically ----
    // BUG-11 FIX: Allow up to MAX_REFRESHES refreshes, each triggered after
    // refreshAfterMs has passed since the previous refresh (or since start).
    const elapsedSinceLastRefresh = lastRefreshAt === 0
      ? Date.now() - started
      : Date.now() - lastRefreshAt;
    const currentUrl = page.url();
    const urlSeemsFine =
      currentUrl.includes('turnitin.com') &&
      (currentUrl.includes('/assignment/') || currentUrl.includes('/class/'));
    const shouldRefresh =
      refreshCount < MAX_REFRESHES &&
      elapsedSinceLastRefresh >= refreshAfterMs &&
      (!urlSeemsFine || currentUrl.includes('/assignment/type/tool/launch'));

    if (shouldRefresh) {
      refreshCount++;
      lastRefreshAt = Date.now();
      logger.info(
        `Similarity not visible; refreshing assignment launch URL (refresh ${refreshCount}/${MAX_REFRESHES})`,
        { currentUrl },
      );
      await page
        .reload({ waitUntil: 'domcontentloaded', timeout: 60000 })
        .catch(() => {});
      await page.waitForTimeout(5000);

      // ── Handle 502/503/504 error pages after refresh ──
      for (let refreshRetry = 0; refreshRetry < 2; refreshRetry++) {
        const bodyAfterRefresh = await page
          .locator('body')
          .innerText({ timeout: 3000 })
          .catch(() => '');
        if (/502 Bad Gateway|503 Service|504 Gateway/i.test(bodyAfterRefresh)) {
          logger.warn(
            `Server error detected after refresh ${refreshCount} (attempt ${refreshRetry + 1}/2); retrying reload`,
            { bodySnippet: bodyAfterRefresh.slice(0, 200) },
          );
          await page.waitForTimeout(5000);
          await page
            .reload({ waitUntil: 'domcontentloaded', timeout: 60000 })
            .catch(() => {});
          await page.waitForTimeout(5000);
        } else {
          break;
        }
      }

      continue;
    }

    await page.waitForTimeout(pollMs);
  }

  throw new Error(
    `Submission card/similarity did not become ready within ${timeoutMs}ms`,
  );
}