AdGuardHome/Filters/parser.py

47 lines
1.3 KiB
Python
Raw Normal View History

2016-07-06 15:02:14 +01:00
import urllib2
import datetime
def date_now():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def get_content(url):
r = urllib2.urlopen(url)
return r.read().split('\n')
def save_comment(comment, f):
idx = comment.find('%timestamp%')
if idx != -1:
comment = comment[:idx] + date_now() + '\n'
f.writelines(comment)
2016-07-07 08:28:04 +01:00
def save_url_rule(url, f):
url = line.replace('url', '').strip()
for rule in get_content(url):
# if rule.find('^') != -1:
# idx = rule.find('^')
# f.writelines(rule[:idx] + '\n')
# elif
if rule.find('$') != -1:
2016-07-07 08:28:04 +01:00
idx = rule.find('$');
f.writelines(rule[:idx] + '\n')
2016-07-06 15:02:14 +01:00
else:
f.writelines(rule + '\n')
2016-07-07 08:28:04 +01:00
def save_file_rule(line, f):
file_name = line.replace('file', '').strip()
with open(file_name, 'r') as rf:
for rule in rf:
2016-07-27 11:22:40 +01:00
f.writelines(rule)
2016-07-07 08:28:04 +01:00
2016-07-06 15:02:14 +01:00
with open('filter.template', 'r') as tmpl:
with open('filter.txt', 'w') as f:
for line in tmpl:
if line.startswith('!'):
save_comment(line, f)
2016-07-07 08:28:04 +01:00
if line.startswith('url'):
save_url_rule(line, f)
if line.startswith('file'):
save_file_rule(line, f)
2016-07-06 15:02:14 +01:00