Skip to content

Commit

Permalink
fix(core): 优化自动答题逻辑,修复有答案不选的BUG
Browse files Browse the repository at this point in the history
- 修复多选题只进行全匹配的BUG,导致有时候有答案但是不会选择
- 删除答题器的自定义重试,以及超时时间,而是写死,防止用户不清楚随意修改。
- 修复搜题结果不显示图片的BUG
  • Loading branch information
enncy committed Mar 19, 2023
1 parent baf6086 commit 23df64d
Show file tree
Hide file tree
Showing 13 changed files with 275 additions and 216 deletions.
22 changes: 11 additions & 11 deletions packages/core/src/core/answer-wrapper/answer.wrapper.handler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AnswererWrapper, SearchResult, Answer } from './interface';
import { AnswererWrapper, SearchInformation, Result } from './interface';
import { request } from '../utils/request';

/**
Expand Down Expand Up @@ -38,8 +38,8 @@ export async function defaultAnswerWrapperHandler(
answererWrappers: AnswererWrapper[],
// 上下文解析环境
env: any
): Promise<SearchResult[]> {
const searchResults: SearchResult[] = [];
): Promise<SearchInformation[]> {
const searchInfos: SearchInformation[] = [];
const temp: AnswererWrapper[] = JSON.parse(JSON.stringify(answererWrappers));
// 多线程请求
await Promise.all(
Expand All @@ -57,7 +57,7 @@ export async function defaultAnswerWrapperHandler(
} = wrapper;
try {
// 答案列表
let answers: Answer[] = [];
let results: Result[] = [];
// 构造请求数据
const data: Record<string, string> = Object.create({});
/** 构造一个请求数据 */
Expand Down Expand Up @@ -86,34 +86,34 @@ export async function defaultAnswerWrapperHandler(
if (info && Array.isArray(info)) {
/** 如果返回一个二维数组 */
if (info.every((item: any) => Array.isArray(item))) {
answers = answers.concat(
results = results.concat(
info.map((item: any) => ({
question: item[0],
answer: item[1]
}))
);
} else {
answers.push({
results.push({
question: info[0],
answer: info[1]
});
}
}

searchResults.push({
searchInfos.push({
url: wrapper.url,
name,
homepage,
answers,
results,
response: responseData,
data: requestData
});
} catch (error) {
searchResults.push({
searchInfos.push({
url: wrapper.url,
name,
homepage,
answers: [],
results: [],
response: undefined,
data: undefined,
error: error as any
Expand All @@ -136,5 +136,5 @@ export async function defaultAnswerWrapperHandler(
return str;
}

return searchResults;
return searchInfos;
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class AnswerWrapperParser {
/** 从 url 中解析 */
static async fromURL(url: string) {
const text = await request(url, {
contentType: 'text',
responseType: 'text',
method: 'get',
type: 'fetch'
});
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/core/answer-wrapper/interface.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
/** 题目答案 */
export interface Answer {
export interface Result {
question: string;
answer: string;
}

/** 题库查询结果 */
export interface SearchResult {
/** 题库查询信息 */
export interface SearchInformation {
url: string;
name: string;
/** 主页 */
homepage?: string;
/** 题目答案 */
answers: Answer[];
results: Result[];
/** 请求响应内容 */
response: any;
/** 请求发起内容 */
Expand Down
21 changes: 12 additions & 9 deletions packages/core/src/core/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ export function request<T extends 'json' | 'text'>(
opts: {
type: 'fetch' | 'GM_xmlhttpRequest';
method?: 'get' | 'post';
contentType?: T;
responseType?: T;
headers?: Record<string, string>;
data?: Record<string, string>;
}
): Promise<T extends 'json' ? any : string> {
return new Promise((resolve, reject) => {
try {
/** 默认参数 */
const { contentType = 'json', method = 'get', type = 'fetch', data = {}, headers = {} } = opts || {};
const { responseType = 'json', method = 'get', type = 'fetch', data = {}, headers = {} } = opts || {};
/** 环境变量 */
const env = $.isInBrowser() ? 'browser' : 'node';

Expand All @@ -29,12 +29,12 @@ export function request<T extends 'json' | 'text'>(
GM_xmlhttpRequest({
url,
method: method === 'get' ? 'GET' : 'POST',
data: new URLSearchParams(data).toString(),
headers: headers,
responseType: 'json',
data: Object.keys(data).length ? new URLSearchParams(data).toString() : undefined,
headers: Object.keys(headers).length ? headers : undefined,
responseType: responseType === 'json' ? 'json' : undefined,
onload: (response) => {
if (response.status === 200) {
if (contentType === 'json') {
if (responseType === 'json') {
try {
resolve(JSON.parse(response.responseText));
} catch (error) {
Expand All @@ -47,17 +47,20 @@ export function request<T extends 'json' | 'text'>(
reject(response.responseText);
}
},
onerror: reject
onerror: (err) => {
console.error('GM_xmlhttpRequest error', err);
reject(err);
}
});
} else {
reject(new Error('GM_xmlhttpRequest is not defined'));
}
} else {
const fet: (...args: any[]) => Promise<Response> = env === 'node' ? require('node-fetch').default : fetch;

fet(url, { contentType, body: method === 'post' ? JSON.stringify(data) : undefined, method, headers })
fet(url, { body: method === 'post' ? JSON.stringify(data) : undefined, method, headers })
.then((response) => {
if (contentType === 'json') {
if (responseType === 'json') {
response.json().then(resolve).catch(reject);
} else {
// @ts-ignore
Expand Down
14 changes: 7 additions & 7 deletions packages/core/src/core/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,21 @@ export function clearString(str: string, ...exclude: string[]) {
*
* ```js
*
* answerSimilar( ['3'], ['1+2','3','4','错误的例子'] ) // [0, 1, 0, 0]
* answerSimilar( ['3'], ['1+2','3','4','错误的选项'] ) // [0, 1, 0, 0]
*
* answerSimilar( ['hello world','console.log("hello world")'], ['console.log("hello world")','hello world','1','错误的例子'] ) // [1, 1, 0, 0]
* answerSimilar( ['hello world','console.log("hello world")'], ['console.log("hello world")','hello world','1','错误的选项'] ) // [1, 1, 0, 0]
*
* ```
*
*/
export function answerSimilar(answers: string[], options: string[]): Rating[] {
answers = answers.map(removeRedundant);
options = options.map(removeRedundant);
const _answers = answers.map(removeRedundant);
const _options = options.map(removeRedundant);

const similar =
answers.length !== 0
? options.map((option) => findBestMatch(option, answers).bestMatch)
: options.map((opt) => ({ rating: 0, target: '' } as Rating));
_answers.length !== 0
? _options.map((option) => findBestMatch(option, _answers).bestMatch)
: _options.map(() => ({ rating: 0, target: '' } as Rating));

return similar;
}
Expand Down
22 changes: 9 additions & 13 deletions packages/core/src/core/worker/interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SearchResult } from '../answer-wrapper/interface';
import { SearchInformation } from '../answer-wrapper/interface';

export type ElementResolver<R> = (root: HTMLElement | Document) => R;
export type RawElements = Record<
Expand All @@ -22,7 +22,7 @@ export type SearchedElements<E, T> = Record<keyof E, T> & {
export interface WorkContext<E> {
root: HTMLElement;
elements: SearchedElements<E, HTMLElement[]>;
searchResults: SearchResult[];
searchInfos: SearchInformation[];
}

/** 题目类型 */
Expand Down Expand Up @@ -62,12 +62,12 @@ export interface SimplifyWorkResult {
requesting: boolean;
/** 正在等待 答题 线程处理 */
resolving: boolean;
/** 搜索结果 */
searchResults: {
/** 查题信息 */
searchInfos: {
/** 题目名 */
name: SearchResult['name'];
name: SearchInformation['name'];
/** 题库链接 */
homepage?: SearchResult['homepage'];
homepage?: SearchInformation['homepage'];
/** 题库搜索错误信息 */
error?: string;
/** 搜索结果 [题目,答案] */
Expand All @@ -77,8 +77,8 @@ export interface SimplifyWorkResult {

/** 答案题目处理器 */
export type QuestionResolver<E> = (
/** 答案 */
searchResults: SearchResult[],
/** 查题信息 */
searchInfos: SearchInformation[],
/** 选项 */
options: HTMLElement[],
handler: (
Expand Down Expand Up @@ -177,7 +177,7 @@ export type AnswererType<E> = (
elements: SearchedElements<E, HTMLElement[]>,
type: string | undefined,
ctx: WorkContext<SearchedElements<E, HTMLElement[]>>
) => SearchResult[] | Promise<SearchResult[]>;
) => SearchInformation[] | Promise<SearchInformation[]>;

/**
* 答题器参数
Expand All @@ -195,10 +195,6 @@ export type WorkOptions<E extends RawElements> = {
requestPeriod?: number;
/** 答题间隔(秒), 如果过快可能导致保存答案失败啊,或者被检测到 */
resolvePeriod?: number;
/** 回答器请求超时时间(秒) */
timeout?: number;
/** 回答器请求重试次数 */
retry?: number;
/** 多线程数量(个) */
thread?: number;
/** 当元素被搜索到 */
Expand Down

0 comments on commit 23df64d

Please sign in to comment.