add emdownload and ncupdate

This commit is contained in:
Izalia Mae 2021-01-09 03:46:50 -05:00
parent 84391cb8bc
commit 649f1c8ff7
3 changed files with 216 additions and 1 deletions

View file

@ -1 +0,0 @@
3.8.0

96
emdownload.py Normal file
View file

@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""
Simple Emoji Grabber
by Izalia Mae
Installation: pip3 install mastodon.py
"""
import requests, sys, tarfile, tempfile
from mastodon import Mastodon
from pathlib import Path
version = '0.1'
name = f'SimpleEmojiGrabber/{version}'
if len(sys.argv) < 2 or 'help' in sys.argv:
filename = Path(__file__)
print(name+'\n')
print(f'Usage:\n {filename.name} <domain> [path]\n')
print('domain:\n The web domain to connect to')
print('path:\n The base path for the tar file. It will be saved as [path]/[domain].tar.gz')
sys.exit()
host = sys.argv[1]
token = Path('emoji_token.txt') #Gonna probably change this tbh
failed = []
options = {
'api_base_url': 'https://'+host
}
if token.is_file():
options['access_token'] = token.open().read().replace('\n', '')
mastodon = Mastodon(**options)
if len(sys.argv) < 3:
basepath = Path.cwd()
else:
basepath = sys.argv[2]
if patharg.startswith('~'):
basepath = Path.expanduser(patharg)
elif patharg.startswith('/'):
basepath = Path(arg)
else:
basepath = Path.cwd().joinpath(patharg)
basepath.mkdir(parents=True, exist_ok=True)
path = basepath.joinpath(host+'.tar.gz')
data = mastodon.custom_emojis()
if not data:
sys.exit()
with tempfile.TemporaryDirectory() as tmpdir:
with tarfile.open(str(path), 'w:gz') as tar:
tempdir = Path(tmpdir)
for emoji in data:
emojipath = tempdir.joinpath(f'{emoji.shortcode}.png')
if emojipath.exists():
continue
response = requests.get(emoji.url, headers={'User-Agent': name})
if not response:
print('Failed to fetch emoji:', emoji.shortcode)
failed.append(emoji.shortcode)
continue
with emojipath.open('wb') as fd:
#print(f'Saving emoji: {emoji.shortcode}, {emojipath}')
for chunk in response.iter_content(chunk_size=1024):
fd.write(chunk)
print(f'Adding emoji: {emojipath.name}')
tar.add(emojipath, emojipath.name)
print('Saved emojis in an archive at', path)
if len(failed) > 0:
print('Failed to save emojis:', ', '.join(failed))

120
ncupdate.py Executable file
View file

@ -0,0 +1,120 @@
#!/usr/bin/env python3
import json, signal, sys, time, traceback
from datetime import datetime
from pathlib import Path
from urllib.request import urlopen
def quit(*args):
print('Bye! :3')
sys.exit()
class Config(dict):
def __init__(self, path):
super().__init__()
self.path = Path(path)
self.load()
def load(self):
with self.path.open() as fd:
self.update(json.load(fd))
def save(self):
with self.path.open('w') as fd:
fd.write(json.dumps(self, indent='\t'))
class Log(object):
def __init__(self):
self.levels = {'merp': 0, 'verbose': 10, 'debug': 20, 'info': 30, 'error': 40}
for level, num in self.levels.items():
self.AddLevel(level, num)
def AddLevel(self, name, num):
self.levels[name] = num
setattr(self, name, lambda *args: self.log(name.upper(), *args))
def log(self, level, *args):
if len(args) == 0:
self.log('ERROR', 'Not enough args specified for Log.log')
return
d = datetime.now().strftime('%y-%m-%d, %H:%M:%S')
message = ' '.join([str(arg) for arg in args])
sys.stdout.write(f'[{d}] {level}: {message}\n')
sys.stdout.flush()
def GetIp():
try:
resp = urlopen('https://ident.me')
except Exception as e:
traceback.print_exc()
return
return resp.read().decode()
def main():
config = Config(Path('~/.config/ncdns.json').expanduser())
address = config.get('lastip')
domain = config.get('domain')
password = config.get('password')
hosts = config.get('hosts')
cycle = config.get('cycle', 3600)
if None in [domain, password, hosts]:
logging.error('Setup the domain, password, and hosts config options')
sys.exit()
while True:
new = GetIp()
if not new:
logging.error('Failed to get IP. Retrying in 60 seconds')
time.sleep(60)
continue
if new != address:
logging.info('Updating DNS with new IP:', new)
address = new
config['lastip'] = new
config.save()
for host in hosts:
try:
urlopen(f'https://dynamicdns.park-your-domain.com/update?host={host}&domain={domain}&password={password}&ip={new}')
except Exception as e:
traceback.print_exc()
logging.error(f'Failed to update {host}:', e)
logging.info('Done! :3')
time.sleep(config.get('cycle', 3600))
if __name__ == '__main__':
logging = Log()
signal.signal(signal.SIGTERM, quit)
signal.signal(signal.SIGINT, quit)
try:
logging.info('Starting Dynamic DNS Updater')
main()
except KeyboardInterrupt:
pass
logging.info('Bye! :3')