dnsmasq-china-list/updater.py

84 lines
2.5 KiB
Python
Raw Normal View History

2015-04-23 21:17:12 +08:00
#!/usr/bin/env python
from __future__ import unicode_literals
from argparse import ArgumentParser
2021-08-03 15:00:43 +08:00
import idna
2019-01-20 19:26:54 +08:00
import sys
import find_redundant
2015-04-23 21:17:12 +08:00
if __name__ == "__main__":
parser = ArgumentParser(description="dnsmasq-china-list updater")
parser.add_argument(
'-a', '--add',
metavar="DOMAIN",
nargs="+",
help='Add one or more new domain(s) (implies -s)',
2015-04-23 21:17:12 +08:00
)
2016-12-08 14:04:04 +08:00
parser.add_argument(
'-d', '--delete',
metavar="DOMAIN",
nargs="+",
default=[],
2016-12-08 14:07:07 +08:00
help='Remove one or more old domain(s) (implies -s)',
2016-12-08 14:04:04 +08:00
)
2015-04-23 21:17:12 +08:00
parser.add_argument(
'-s', '--sort',
action='store_true',
default=True,
help='Sort the list (default action)',
)
parser.add_argument(
'-f', '--file',
nargs=1,
default=["accelerated-domains.china.conf"],
help="Specify the file to update (accelerated-domains.china.conf by default)",
)
2015-04-23 21:17:12 +08:00
options = parser.parse_args()
with open(options.file[0]) as f:
2015-04-23 21:17:12 +08:00
lines = list(f)
2019-01-20 19:26:54 +08:00
changed = False
2015-04-23 21:17:12 +08:00
if options.add:
options.sort = True
for domain in options.add:
encoded_domain = idna.encode(domain).decode()
new_line = f"server=/{encoded_domain}/114.114.114.114\n"
disabled_line = f"#server=/{encoded_domain}/114.114.114.114"
if new_line in lines:
2021-08-03 15:00:43 +08:00
print(f"Domain already exists: {domain}")
else:
for line in lines:
if line.startswith(disabled_line):
print(f"Domain already disabled: {domain}")
break
else:
print(f"New domain added: {domain}")
lines.append(new_line)
changed = True
2015-04-23 21:17:12 +08:00
options.delete += find_redundant.find_redundant(lines)
2016-12-08 14:04:04 +08:00
if options.delete:
options.sort = True
for domain in options.delete:
2021-08-03 15:00:43 +08:00
target_line = f"server=/{idna.encode(domain).decode()}/114.114.114.114\n"
2016-12-08 14:04:04 +08:00
if target_line not in lines:
2021-08-03 15:00:43 +08:00
print(f"Failed to remove domain {domain}: not found.")
2016-12-08 14:04:04 +08:00
else:
2021-08-03 15:00:43 +08:00
print(f"Domain removed: {domain}")
2016-12-08 14:04:04 +08:00
lines.remove(target_line)
2019-01-20 19:26:54 +08:00
changed = True
if (options.add or options.delete) and not changed:
sys.exit(1)
2016-12-08 14:04:04 +08:00
2015-04-23 21:17:12 +08:00
if options.sort:
lines.sort(key=lambda x: x.lstrip("#"))
with open(options.file[0], "w") as f:
2015-04-23 21:17:12 +08:00
f.write(''.join(filter(lambda line: line.strip(), lines)))