io.github.apkcloud.devicedetector.parser.bot.BotParser Maven / Gradle / Ivy
Show all versions of DeviceDetector Show documentation
package io.github.apkcloud.devicedetector.parser.bot;
import io.github.apkcloud.devicedetector.parser.AbstractParser;
import io.github.apkcloud.devicedetector.entity.Bot;
import java.util.List;
/**
* 解析 UserAgent 以获取机器人信息
*
* 检测到的 bots 定义在 regexes/bots.yml
*/
public class BotParser extends AbstractBotParser {
protected String fixtureFile = "regexes/bots.yml";
protected String parserName = "bot";
protected boolean discardDetails = false;
/**
* 启用信息忽略
*/
public void discardDetails() {
this.discardDetails = true;
}
/**
* 解析当前 UA 并检查是否包含机器人信息
*
* bots.yml 检测到的机器人列表
*
* 步骤1:构建一个包含所有正则表达式的大正则表达式,并对 UA 进行匹配
* -> 如果没有找到匹配项:返回
* -> 否则:
* 步骤2:遍历 bots.yml 中的正则表达式列表,并尝试匹配每个正则表达式
* -> 返回匹配到的数据
*
* 如果 {@link #discardDetails} 设置为 TRUE,则跳过步骤2
* 将$bot设置为TRUE
*
* 注意:在匹配每个单独的正则表达式之前进行整体匹配可以加快检测速度
*
* @return Bot | null
*/
public Bot parse() throws Exception {
Bot result = null;
if (!AbstractParser.isNullOrEmpty(preMatchOverall(fixtureFile))) {
if (discardDetails) {
return null;
}
List regexes = getRegexes(fixtureFile, Bot.class);
for (Bot regex : regexes) {
List matches = matchUserAgent(regex.getRegex());
if (!AbstractParser.isNullOrEmpty(matches)) {
regex.setRegex(null);
result = regex;
break;
}
}
}
return result;
}
@Override
public String getName() {
return parserName;
}
}