`;
document.body.appendChild(panel);
const submitBtn = document.getElementById('ai-helper-submit-btn');
const closeBtn = document.getElementById('ai-helper-close-btn');
const textarea = document.getElementById('ai-helper-textarea');
const resultDiv = document.getElementById('ai-helper-result');
const keyWarning = document.getElementById('ai-key-warning');
// Check if API Key is set
if (!CONFIG.AI_API_SETTINGS.API_KEY || CONFIG.AI_API_SETTINGS.API_KEY === '请在此处填入您自己的 DeepSeek API Key') {
keyWarning.style.display = 'block';
submitBtn.disabled = true;
submitBtn.innerText = '请先设置 API Key';
}
closeBtn.onclick = () => panel.remove();
submitBtn.onclick = async () => {
const question = textarea.value.trim();
if (!question) { resultDiv.innerText = '错误:问题不能为空!'; return; }
if (!CONFIG.AI_API_SETTINGS.API_KEY || CONFIG.AI_API_SETTINGS.API_KEY === '请在此处填入您自己的 DeepSeek API Key') {
resultDiv.innerText = '错误:请先设置您的 DeepSeek API Key!';
return;
}
submitBtn.disabled = true;
submitBtn.innerText = 'AI思考中...';
resultDiv.innerText = '正在向AI发送请求...';
try {
resultDiv.innerText = await askAiForAnswer(question);
} catch (error) {
resultDiv.innerText = `请求失败:${error}`;
} finally {
submitBtn.disabled = false;
submitBtn.innerText = '向AI提问';
}
};
makeDraggable(panel, document.getElementById('ai-helper-header'));
}
/**
* Make UI panel draggable
* @param {HTMLElement} panel - The panel element to be dragged.
* @param {HTMLElement} header - The header element that acts as the drag handle.
*/
function makeDraggable(panel, header) {
let isDragging = false, offsetX, offsetY;
header.addEventListener('mousedown', (e) => {
if (e.target.tagName === 'BUTTON' || e.target.tagName === 'INPUT') return;
isDragging = true;
if (panel.style.bottom || panel.style.right) {
const rect = panel.getBoundingClientRect();
panel.style.top = `${rect.top}px`;
panel.style.left = `${rect.left}px`;
panel.style.bottom = '';
panel.style.right = '';
}
offsetX = e.clientX - parseFloat(panel.style.left);
offsetY = e.clientY - parseFloat(panel.style.top);
header.style.cursor = 'grabbing';
document.body.style.userSelect = 'none';
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const newX = e.clientX - offsetX;
const newY = e.clientY - offsetY;
panel.style.left = `${newX}px`;
panel.style.top = `${newY}px`;
});
document.addEventListener('mouseup', () => {
if (isDragging) {
isDragging = false;
header.style.cursor = 'move';
document.body.style.userSelect = '';
}
});
}
// ===================================================================================
// --- AI 调用 (AI Invocation) ---
// ===================================================================================
/**
* Send request to DeepSeek AI and get answer
* @param {string} question - User's question
* @returns {Promise}
*/
function askAiForAnswer(question) {
return new Promise((resolve, reject) => {
if (!CONFIG.AI_API_SETTINGS.API_KEY || CONFIG.AI_API_SETTINGS.API_KEY === '请在此处填入您自己的 DeepSeek API Key') {
reject('API Key 未设置或不正确,请在控制面板中设置!');
return;
}
const payload = {
model: "deepseek-chat",
messages: [{
"role": "system",
"content": "你是一个乐于助人的问题回答助手。聚焦于执业药师相关的内容,请根据用户提出的问题,提供准确、清晰的解答。注意回答时仅仅包括答案,不允许其他额外任何解释,输出为一行一道题目的答案,答案只能是题目序号:字母选项,不能包含文字内容。单选输出示例:1.A。多选输出示例:1.ABC。"
}, {
"role": "user",
"content": question
}],
temperature: 0.2
};
GM_xmlhttpRequest({
method: 'POST',
url: CONFIG.AI_API_SETTINGS.DEEPSEEK_API_URL,
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${CONFIG.AI_API_SETTINGS.API_KEY}` },
data: JSON.stringify(payload),
timeout: 20000,
onload: (response) => { try { const result = JSON.parse(response.responseText); if (result.choices && result.choices.length > 0) { resolve(result.choices[0].message.content.trim()); } else { reject('AI响应格式不正确。'); } } catch (e) { reject(`解析AI响应失败: ${e.message}`); } }
,
onerror: (err) => reject(`请求AI API网络错误: ${err.statusText || '未知错误'}`),
ontimeout: () => reject('请求AI API超时')
});
});
}
// ===================================================================================
// --- 页面逻辑处理 (Page-Specific Logic) ---
// ===================================================================================
/**
* New helper function to encapsulate finding and clicking the first unfinished course
* @param {string} courseType - '专业课' or '公需课'.
*/
function attemptClickFirstUnfinishedCourse(courseType) {
let targetCourseElement = document.querySelector('.play-card:not(:has(.el-icon-success))');
if (!targetCourseElement) {
const allArticles = document.querySelectorAll('.information-card');
for (const article of allArticles) {
const statusTag = article.querySelector('.status');
if (statusTag && statusTag.innerText.trim() === '未完成') {
targetCourseElement = article;
break;
}
}
}
if (targetCourseElement) {
console.log(`[Script] ${courseType}: Found the first unfinished item, clicking to enter study...`);
const clickableElement = targetCourseElement.querySelector('.play-card-box-right-text') || targetCourseElement;
clickElement(clickableElement);
} else {
console.log(`[Script] ${courseType}: No unfinished items found on "unfinished" page.`);
// If no unfinished items, maybe navigate back to the main course list or indicate completion
// For now, let it loop in mainLoop, it will eventually re-check.
}
}
/**
* Handle course list page, compatible with video and article
* @param {string} courseType - '专业课' or '公需课'.
*/
function handleCourseListPage(courseType) {
if (!isServiceActive) return;
if (courseType === '公需课') {
const publicTarget = GM_getValue('sclpa_public_target', 'video');
const targetTabText = publicTarget === 'article' ? '文章资讯' : '视频课程';
const targetTab = findElementByText('.radioTab > .radio-tab-tag', targetTabText);
if (targetTab && !targetTab.classList.contains('radio-tab-tag-ed')) {
console.log(`[Script] Target is ${targetTabText}, switching tab...`);
clickElement(targetTab);
// After clicking the tab, give it more time to load content
setTimeout(() => {
attemptClickFirstUnfinishedCourse(courseType);
}, 3500); // Increased delay for tab content load
return;
}
}
const unfinishedTab = findElementByText('div.radio-tab-tag', '未完成');
if (unfinishedTab && !isUnfinishedTabActive(unfinishedTab) && !unfinishedTabClicked) {
console.log('[Script] Clicking "未完成" tab.');
clickElement(unfinishedTab);
unfinishedTabClicked = true;
// After clicking the tab, give it more time to load content
setTimeout(() => {
attemptClickFirstUnfinishedCourse(courseType);
}, 3500); // Increased delay for tab content load
return;
}
if (unfinishedTab && (isUnfinishedTabActive(unfinishedTab) || unfinishedTabClicked)) {
// If already on the unfinished tab or it was just clicked, proceed to find course
attemptClickFirstUnfinishedCourse(courseType);
}
}
/**
* Main handler for learning page
*/
function handleLearningPage() {
if (!isServiceActive) return;
if (!isTimeAccelerated) {
accelerateTime();
isTimeAccelerated = true;
}
const directoryItems = document.querySelectorAll('.catalogue-item');
if (directoryItems.length > 0) {
handleMultiChapterCourse(directoryItems);
} else {
const video = document.querySelector('video');
if (video) {
handleSingleMediaCourse(video);
} else {
handleArticleReadingPage();
}
}
}
/**
* Handle multi-chapter courses (professional courses)
* @param {NodeListOf} directoryItems
*/
function handleMultiChapterCourse(directoryItems) {
if (isChangingChapter) {
console.log('[Script] Multi-chapter course: Chapter change in progress, deferring actions.');
return;
}
const video = document.querySelector('video');
// Correctly identify the currently active chapter using the 'active' class
const currentActiveChapter = document.querySelector('.catalogue-item.active');
console.log('[Script] Current active chapter element:', currentActiveChapter ? currentActiveChapter.innerText.trim() : 'None');
let firstUncompletedChapter = null;
let allChaptersCompleted = true; // Assume all completed until proven otherwise
// Find the first uncompleted chapter (based on icon)
for (const item of directoryItems) {
if (!item.querySelector('.el-icon-success')) {
allChaptersCompleted = false;
firstUncompletedChapter = item; // This is the first chapter without a success icon
break;
}
}
// Scenario 1: All chapters are marked as completed by icon.
if (allChaptersCompleted) {
console.log('[Script] Multi-chapter course: All chapters marked as completed by icon. Navigating after course completion.');
safeNavigateAfterCourseCompletion();
return;
}
// Scenario 2: There are uncompleted chapters.
// If the first uncompleted chapter is NOT the currently active one, click it to navigate.
// Use classList.contains('active') for robust check.
if (firstUncompletedChapter && !firstUncompletedChapter.classList.contains('active')) {
console.log('[Script] Multi-chapter course: Detected first uncompleted chapter is not active. Clicking to navigate.');
clickElement(firstUncompletedChapter);
isChangingChapter = true; // Set flag to prevent rapid re-clicks
setTimeout(() => { isChangingChapter = false; }, 6000); // Give time for chapter and video to load
return;
}
// Scenario 3: The first uncompleted chapter IS the currently active one.
// Or, currentActiveChapter is null but firstUncompletedChapter exists (meaning we just landed on a chapter page).
// In this case, focus on playing the video for this active/target chapter.
// We proceed if firstUncompletedChapter exists AND it is the active one.
if (firstUncompletedChapter && firstUncompletedChapter.classList.contains('active')) {
console.log('[Script] Multi-chapter course: First uncompleted chapter is active. Focusing on video playback.');
if (!video) {
console.log('[Script] Multi-chapter course: Video element not found for active chapter. Waiting for video to load.');
return; // Wait for video element to appear
}
// Always attempt to set playback rate
if (video.playbackRate !== CONFIG.VIDEO_PLAYBACK_RATE) {
video.playbackRate = CONFIG.VIDEO_PLAYBACK_RATE;
console.log(`[Script] Multi-chapter course: Forcing video playbackRate to ${CONFIG.VIDEO_PLAYBACK_RATE}x.`);
}
video.muted = true; // Ensure video is muted
// Log video state for debugging
console.log(`[Script] Video State: paused=${video.paused}, ended=${video.ended}, currentTime=${video.currentTime.toFixed(2)}, duration=${video.duration.toFixed(2)}, readyState=${video.readyState}`);
const completionThreshold = 0.95; // Video must play 95%
// Check if video is ready and playing, or needs to be played
if (video.readyState >= 3) { // HAVE_FUTURE_DATA (3) or HAVE_ENOUGH_DATA (4)
if (video.paused || video.ended || video.currentTime === 0) {
console.log('[Script] Multi-chapter course: Video paused/ended/at start, attempting to play.');
video.play().catch(e => {
console.error("[Script] Failed to play video in current chapter (catch block):", e);
});
} else {
// Video is playing, check progress
if (video.duration > 0 && (video.currentTime / video.duration) >= completionThreshold) {
console.log('[Script] Multi-chapter course: Video reached completion threshold. Navigating to next step.');
safeNavigateAfterCourseCompletion(); // Current chapter video is done
} else {
console.log('[Script] Multi-chapter course: Video is playing, waiting for chapter completion.');
}
}
} else {
console.log('[Script] Multi-chapter course: Video not ready (readyState < 3). Waiting for more data.');
// Do not attempt to play if not ready, just wait for next loop iteration
}
} else {
console.warn('[Script] Multi-chapter course: Unexpected state. This should ideally not be reached if uncompleted chapters exist and are handled.');
}
}
/**
* Handle single media courses (public courses)
* @param {HTMLVideoElement} video
*/
function handleSingleMediaCourse(video) {
if (!video.dataset.singleVidControlled) {
video.addEventListener('ended', safeNavigateAfterCourseCompletion);
video.dataset.singleVidControlled = 'true';
console.log('[Script] Single media course: Added "ended" event listener.');
}
// Always attempt to set playback rate
if (video.playbackRate !== CONFIG.VIDEO_PLAYBACK_RATE) {
video.playbackRate = CONFIG.VIDEO_PLAYBACK_RATE;
console.log(`[Script] Single media course: Forcing video playbackRate to ${CONFIG.VIDEO_PLAYBACK_RATE}x.`);
}
video.muted = true; // Ensure video is muted
// Log video state for debugging
console.log(`[Script] Video State: paused=${video.paused}, ended=${video.ended}, currentTime=${video.currentTime.toFixed(2)}, duration=${video.duration.toFixed(2)}, readyState=${video.readyState}`);
const completionThreshold = 0.95; // 95% of the video played
// Check if video is ready and playing, or needs to be played
if (video.readyState >= 3) { // HAVE_FUTURE_DATA (3) or HAVE_ENOUGH_DATA (4)
if (video.paused || video.ended || video.currentTime === 0) {
console.log('[Script] Single media course: Video paused/ended/at start, attempting to play.');
video.play().catch(e => {
console.error("[Script] Failed to play video in single media course (catch block):", e);
});
} else {
// Video is playing, check progress
if (video.duration > 0 && (video.currentTime / video.duration) >= completionThreshold) {
console.log('[Script] Single media course: Video reached completion threshold. Navigating to next step.');
safeNavigateAfterCourseCompletion();
} else {
console.log('[Script] Single media course: Video is playing, waiting for completion.');
}
}
} else {
console.log('[Script] Single media course: Video not ready (readyState < 3). Waiting for more data.');
// Do not attempt to play if not ready, just wait for next loop iteration
}
}
/**
* Handle article reading page
*/
function handleArticleReadingPage() {
console.log('[Script] Detected article page, monitoring progress...');
const progressLabel = document.querySelector('.action-btn .label');
if (progressLabel && (progressLabel.innerText.includes('100') || progressLabel.innerText.includes('待考试'))) {
console.log('[Script] Article study completed, preparing to return to list.');
safeNavigateAfterCourseCompletion();
}
}
/**
* Handle exam page (where the actual questions are displayed)
* Automatically copies question to AI helper and processes the AI answer.
*/
function handleExamPage() {
if (!isServiceActive) return; // Only run if service is active
currentNavContext = GM_getValue('sclpa_nav_context', ''); // Ensure context is fresh
if (currentNavContext === 'course') {
console.log('[Script] Current navigation context is "course". Ignoring exam automation and navigating back to course list.');
safeNavigateBackToList();
return;
}
if (isSubmittingExam) {
console.log('[Script] Exam submission in progress, deferring AI processing.');
return;
}
if (!document.getElementById('ai-helper-panel')) {
createManualAiHelper();
setTimeout(() => {
triggerAiQuestionAndProcessAnswer();
}, 500);
} else {
triggerAiQuestionAndProcessAnswer();
}
}
/**
* Gathers all questions and options from the current exam page,
* sends them to AI, and waits for the response to select answers.
*/
async function triggerAiQuestionAndProcessAnswer() {
const examinationItems = document.querySelectorAll('.examination-body-item');
const aiHelperTextarea = document.getElementById('ai-helper-textarea');
const aiHelperSubmitBtn = document.getElementById('ai-helper-submit-btn');
const aiHelperResultDiv = document.getElementById('ai-helper-result');
if (examinationItems.length === 0 || !aiHelperTextarea || !aiHelperSubmitBtn || !aiHelperResultDiv) {
console.log('[Script] No examination items found or AI helper elements missing.');
return;
}
let fullQuestionBatchContent = '';
examinationItems.forEach(item => {
fullQuestionBatchContent += item.innerText.trim() + '\n\n'; // Concatenate all questions
});
// Only process if the batch of questions has changed and AI answer is not pending
if (fullQuestionBatchContent && fullQuestionBatchContent !== currentQuestionBatchText && !isAiAnswerPending) {
currentQuestionBatchText = fullQuestionBatchContent; // Update current batch text
aiHelperTextarea.value = fullQuestionBatchContent; // Set textarea value with all questions
aiHelperResultDiv.innerText = '正在向AI发送请求...';
console.log('[Script] New batch of exam questions copied to AI helper textarea, triggering AI query...');
isAiAnswerPending = true;
clickElement(aiHelperSubmitBtn);
let attempts = 0;
const maxAttempts = 300; // Max 300 attempts * 500ms = 60 seconds
const checkInterval = 500;
const checkAiResult = setInterval(() => {
if (aiHelperResultDiv.innerText.trim() && aiHelperResultDiv.innerText.trim() !== '正在向AI发送请求...' && aiHelperResultDiv.innerText.trim() !== '请先提问...') {
clearInterval(checkAiResult);
isAiAnswerPending = false;
console.log('[Script] AI response received:', aiHelperResultDiv.innerText.trim());
parseAndSelectAllAnswers(aiHelperResultDiv.innerText.trim()); // Call new function to handle all answers
setTimeout(() => {
handleNextQuestionOrSubmitExam(); // After all answers are selected, move to next step
}, 1000);
} else if (attempts >= maxAttempts) {
clearInterval(checkAiResult);
isAiAnswerPending = false;
console.log('[Script] Timeout waiting for AI response for question batch.');
aiHelperResultDiv.innerText = 'AI请求超时,请手动重试。';
setTimeout(() => {
handleNextQuestionOrSubmitExam();
}, 1000);
}
attempts++;
}, checkInterval);
} else if (isAiAnswerPending) {
console.log('[Script] AI answer already pending for current question batch, skipping new query.');
} else if (fullQuestionBatchContent === currentQuestionBatchText) {
console.log('[Script] Question batch content has not changed, skipping AI query.');
}
}
/**
* Parses the AI response and automatically selects the corresponding options for all questions on the exam page.
* @param {string} aiResponse - The raw response string from the AI (e.g., "1.A\n2.BC\n3.D").
*/
function parseAndSelectAllAnswers(aiResponse) {
const aiAnswerLines = aiResponse.split('\n').map(line => line.trim()).filter(line => line.length > 0);
const examinationItems = document.querySelectorAll('.examination-body-item');
const aiAnswersMap = new Map(); // Map to store {questionNumber: answerLetters}
aiAnswerLines.forEach(line => {
const parts = line.split('.');
if (parts.length >= 2) {
const qNum = parseInt(parts[0]);
const ansLetters = parts[1].toUpperCase();
if (!isNaN(qNum) && ansLetters) {
aiAnswersMap.set(qNum, ansLetters);
} else {
console.warn(`[Script] Invalid AI response line format or content: ${line}`);
}
} else {
console.warn(`[Script] Invalid AI response line format: ${line}`);
}
});
examinationItems.forEach(item => {
const questionTitleElement = item.querySelector('.examination-body-title');
if (questionTitleElement) {
const match = questionTitleElement.innerText.trim().match(/^(\d+)、/);
const questionNumber = match ? parseInt(match[1]) : null;
if (questionNumber !== null && aiAnswersMap.has(questionNumber)) {
const answerLetters = aiAnswersMap.get(questionNumber);
console.log(`[Script] Processing Q${questionNumber}: Selecting options ${answerLetters}`);
for (const letter of answerLetters) {
const optionText = `${letter}.`;
// Find options specific to this question item
const optionElement = Array.from(item.querySelectorAll('.examination-check-item')).find(el =>
el.innerText.trim().startsWith(optionText)
);
if (optionElement) {
console.log(`[Script] Selecting option: ${letter} for Q${questionNumber}`);
clickElement(optionElement);
} else {
console.warn(`[Script] Option '${letter}' not found for Q${questionNumber} using text '${optionText}'.`);
}
}
} else if (questionNumber === null) {
console.warn('[Script] Could not extract question number from item:', item.innerText.trim().substring(0, 50) + '...');
} else {
console.log(`[Script] No AI answer found for Q${questionNumber} in AI response. Skipping.`);
}
}
});
console.log('[Script] Finished parsing and selecting all answers on current page.');
}
/**
* Handles navigation after answering a question: either to the next question or submits the exam.
*/
function handleNextQuestionOrSubmitExam() {
if (!isServiceActive || isSubmittingExam) {
console.log('[Script] Service inactive or exam submission in progress, deferring next step.');
return;
}
// First, try to find the "下一题" button
const nextQuestionButton = findElementByText('button span', '下一题');
if (nextQuestionButton) {
console.log('[Script] Found "下一题" button, clicking it...');
clickElement(nextQuestionButton.closest('button'));
// After clicking "下一题", the page should load the next question batch.
// mainLoop will detect hash change and re-trigger handleExamPage,
// or if on the same hash but content changed, triggerAiQuestionAndProcessAnswer will detect new questions.
// Reset question batch text to ensure new questions are processed
currentQuestionBatchText = '';
} else {
// If "下一题" not found, try to find "提交试卷"
const submitExamButton = findElementByText('button.submit-btn span', '提交试卷');
if (submitExamButton) {
console.log('[Script] "下一题" not found. Found "提交试卷" button, clicking it...');
isSubmittingExam = true;
clickElement(submitExamButton.closest('button'));
setTimeout(() => {
console.log('[Script] Exam submitted. Navigating back to exam list page...');
const hash = window.location.hash.toLowerCase();
const returnUrl = hash.includes('openonlineexam')
? 'https://zyys.ihehang.com/#/openOnlineExam'
: 'https://zyys.ihehang.com/#/onlineExam';
window.location.href = returnUrl;
isSubmittingExam = false;
currentQuestionBatchText = ''; // Clear for next exam cycle
}, 3000);
} else {
console.log('[Script] Neither "下一题" nor "提交试卷" button found. Check page state or selectors.');
}
}
}
/**
* Handle exam list page (e.g., #/onlineExam or #/openOnlineExam)
* This function will find and click the "待考试" tab if it's not already active,
* then find and click the "开始考试" button for the first pending exam.
*/
function handleExamListPage() {
if (!isServiceActive) return;
currentNavContext = GM_getValue('sclpa_nav_context', '');
if (currentNavContext !== 'exam') {
console.log('[Script] Not in "exam" navigation context. Skipping exam list processing.');
return;
}
const pendingExamTab = findElementByText('div.radio-tab-tag', '待考试');
if (pendingExamTab && !isUnfinishedTabActive(pendingExamTab)) {
console.log('[Script] Found "待考试" tab, clicking it...');
clickElement(pendingExamTab);
setTimeout(() => {
attemptClickStartExamButton();
}, 2500);
} else if (pendingExamTab) {
console.log('[Script] "待考试" tab is already active. Attempting to find "开始考试" button...');
attemptClickStartExamButton();
} else {
console.log('[Script] No "待考试" tab or pending exam found. All exams might be completed.');
}
}
/**
* Attempts to find and click the "开始考试" button for the first available exam.
*/
function attemptClickStartExamButton() {
const startExamButton = findElementByText('button.el-button--danger span', '开始考试');
if (startExamButton) {
console.log('[Script] Found "开始考试" button, clicking it...');
clickElement(startExamButton.closest('button'));
} else {
console.log('[Script] "开始考试" button not found on the page.');
}
}
/**
* Handle generic popups, including the "前往考试" popup after course completion.
*/
function handleGenericPopups() {
if (!isServiceActive || isPopupBeingHandled) return;
const examCompletionPopupMessage = document.querySelector('.el-message-box__message p');
const goToExamBtnInPopup = findElementByText('button.el-button--primary span', '前往考试');
const cancelBtnInPopup = findElementByText('button.el-button--default span', '取消');
// Handle the specific "恭喜您已经完成所有课程学习" popup
if (examCompletionPopupMessage && examCompletionPopupMessage.innerText.includes('恭喜您已经完成所有课程学习')) {
console.log('[Script] Detected "恭喜您已经完成所有课程学习" popup.');
isPopupBeingHandled = true; // Set flag to prevent re-entry
if (goToExamBtnInPopup && cancelBtnInPopup) {
console.log('[Script] Clicking "取消" to dismiss completion popup and return to course list.');
clickElement(cancelBtnInPopup.closest('button'));
setTimeout(() => {
safeNavigateBackToList();
isPopupBeingHandled = false;
unfinishedTabClicked = false;
}, 1000);
return; // Handled this specific popup, exit
}
}
// IMPORTANT: Per user request, DO NOT click generic "确定" button.
// Only handle "进入下一节学习" if it's a specific button, not a generic "确定".
const nextChapterBtn = findElementByText('button span', '进入下一节学习');
if (nextChapterBtn) {
console.log(`[Script] Detected "进入下一节学习" button. Clicking it.`);
isPopupBeingHandled = true;
clickElement(nextChapterBtn.closest('button'));
setTimeout(() => { isPopupBeingHandled = false; }, 2500);
return; // Handled this specific button, exit
}
// If no specific popup or button is handled, do nothing.
// console.log('[Script] No relevant popups or buttons detected to handle.'); // Commented out to reduce log spam
}
// ===================================================================================
// --- 核心自动化 (Core Automation) ---
// ===================================================================================
/**
* [Time Engine] Global time acceleration, including setTimeout, setInterval, and requestAnimationFrame
*/
function accelerateTime() {
if (CONFIG.TIME_ACCELERATION_RATE <= 1) return;
console.log(`[Script] Time acceleration engine started, rate: ${CONFIG.TIME_ACCELERATION_RATE}x`);
const rate = CONFIG.TIME_ACCELERATION_RATE;
hook(window, 'setTimeout', (original) => (cb, delay, ...args) => original.call(window, cb, delay / rate, ...args));
hook(window, 'setInterval', (original) => (cb, delay, ...args) => original.call(window, cb, delay / rate, ...args));
hook(window, 'requestAnimationFrame', (original) => {
let firstTimestamp = -1;
return (callback) => {
return original.call(window, (timestamp) => {
if (firstTimestamp < 0) firstTimestamp = timestamp;
const acceleratedTimestamp = firstTimestamp + (timestamp - firstTimestamp) * rate;
callback(acceleratedTimestamp);
});
};
});
hook(Date, 'now', (original) => {
const scriptStartTime = original();
return () => scriptStartTime + (original() - scriptStartTime) * rate;
});
}
/**
* Initializes video playback fixes including rate anti-rollback and background playback prevention.
*/
function initializeVideoPlaybackFixes() {
console.log('[Script] Initializing video playback fixes (rate anti-rollback and background playback).');
// 1. Prevent webpage from resetting video playback rate
hook(Object, 'defineProperty', (original) => function(target, property, descriptor) {
if (target instanceof HTMLMediaElement && property === 'playbackRate') {
console.log('[Script] Detected website attempting to lock video playback rate, intercepted.');
// Do not return here, allow the original setter to be called but we will override it frequently.
}
return original.apply(this, arguments);
});
// 2. Prevent video pausing when tab is in background by faking visibility state
try {
Object.defineProperty(document, "hidden", {
get: function() {
return false;
},
configurable: true
});
Object.defineProperty(document, "visibilityState", {
get: function() {
return "visible";
},
configurable: true
});
} catch (e) {
console.warn('[Script] Failed to hook document visibility properties, background video playback might not work:', e);
}
}
/**
* Safely navigate back to the corresponding course list
*/
function safeNavigateBackToList() {
const hash = window.location.hash.toLowerCase();
const returnUrl = hash.includes('public') || hash.includes('openplayer') || hash.includes('imageandtext') || hash.includes('openonlineexam')
? 'https://zyys.ihehang.com/#/publicDemand'
: 'https://zyys.ihehang.com/#/specialized';
window.location.href = returnUrl;
}
/**
* Decide next action after a course (including all its chapters) is completed
*/
function safeNavigateAfterCourseCompletion() {
console.log('[Script] Course completed. Navigating back to course list.');
// Always navigate back to the appropriate list.
// The popup (if any) will be handled by handleGenericPopups in the main loop.
safeNavigateBackToList();
unfinishedTabClicked = false; // Reset for the next cycle
}
// ===================================================================================
// --- 主循环与启动器 (Main Loop & Initiator) ---
// ===================================================================================
/**
* Page router, determines which handler function to execute based on URL hash
*/
function router() {
const hash = window.location.hash.toLowerCase();
if (hash.includes('/specialized')) {
handleCourseListPage('专业课');
} else if (hash.includes('/publicdemand')) {
handleCourseListPage('公需课');
} else if (hash.includes('/examination')) {
handleExamPage();
} else if (hash.includes('/majorplayerpage') || hash.includes('/articleplayerpage') || hash.includes('/openplayer') || hash.includes('/imageandtext')) {
handleLearningPage();
} else if (hash.includes('/onlineexam') || hash.includes('/openonlineexam')) {
handleExamListPage();
}
}
/**
* Main script loop, executed every 2 seconds
*/
function mainLoop() {
if (window.location.hash !== currentPageHash) {
const oldHash = currentPageHash;
currentPageHash = window.location.hash;
if (oldHash.includes('/examination') && !currentPageHash.includes('/examination')) {
const aiPanel = document.getElementById('ai-helper-panel');
if (aiPanel) aiPanel.remove();
currentQuestionBatchText = ''; // Reset batch text on exam page exit
isAiAnswerPending = false;
isSubmittingExam = false;
}
if (currentPageHash.includes('/specialized') || currentPageHash.includes('/publicdemand') ||
currentPageHash.includes('/onlineexam') || currentPageHash.includes('/openonlineexam')) {
unfinishedTabClicked = false;
}
}
if (isServiceActive) {
handleGenericPopups();
}
router();
}
/**
* Start the script
*/
window.addEventListener('load', () => {
console.log(`[Script] Sichuan Licensed Pharmacist Continuing Education (v1.2.4) started.`);
console.log(`[Script] Service status: ${isServiceActive ? 'Running' : 'Paused'} | Current mode: ${scriptMode} | Current speed: ${currentPlaybackRate}x`);
currentPageHash = window.location.hash;
currentNavContext = GM_getValue('sclpa_nav_context', '');
initializeVideoPlaybackFixes();
createModeSwitcherPanel();
setInterval(mainLoop, 2000);
});
})();