adblock-swift
用 Swift 编写的 AdBlockPlus 解析器和匹配器
此存储库是从 https://github.com/pmezard/adblock 中的 rules.go 端口移植的。
文档
func parseRules(ruleListString: String) -> ([Rule]?, Error?)
此函数期望以新行分隔的字符串作为输入并输出规则列表。
class AdBlockRequest {
init(url: String) {}
init() {}
// url is match against rule parts. Mandatory.
public var url: String
// domain is matched against optional domain or third-party rules
public var domain: String? = nil
// contentType is matched against optional content rules. This
// information is often available only in client responses. Filters
// may be applied twice, once at request time, once at response time.
public var contentType: String? = nil
// originDomain is matched against optional third-party rules.
public var originDomain: String? = nil
// We can use the header map to match various options such as xmlhttprequest
public var headers: [String: [String]]? = nil
// timeout is the maximum amount of time a single matching can take.
public var timeout: TimeInterval = 0.0
public var checkFreq: Int = 0
public var genericBlock: Bool? = nil
}
class RuleMatcher {
init() {} // RuleMatcher()
addRule(rule: Rule, ruleId: Int) -> Error?
match(req: AdBlockRequest) -> (Bool, Int, Error?) // matched, ruleId, error
}
RuleMatcher 是实现的要点。以下是如何使用的示例。
let ruleString = #"""
||badsite.com
@@||badsite.com/goodpart
"""#
let (rules, err) = parseRules(ruleListString: ruleString)
if let err = err {
return err
}
var matcher = RuleMatcher()
if let rules = rules {
for rule in rules {
// matcher has an auto-incrementing ruleId
// if you decide not to specify your own.
matcher.addRule(rule: rule, ruleId: 0)
}
}
var matched: Bool
var ruleId: Int
req = AdBlockRequest("https://badsite.com/badpart")
// Change the AdBlockRequest properties as you see fit.
req.originDomain = "goodsite.com"
(matched, ruleId, err) = matcher.match(req: req)
if matched {
print("adblock request matched!")
} else {
print("adblock request did not match")
}
注意
在 pmezard 的 Golang 版本上还有一些自定义扩展,例如 referer
选项和 AdBlockRequest.headers 字段。