apply black formatting

This commit is contained in:
Hugh Rundle 2020-08-28 21:25:46 +10:00
parent beac59d440
commit e13646e459
3 changed files with 113 additions and 80 deletions

View File

@ -30,7 +30,7 @@ import yaml
from argparse import ArgumentParser from argparse import ArgumentParser
from datetime import datetime, timezone from datetime import datetime, timezone
import os import os
import pkg_resources import pkg_resources
# import funtions # import funtions
from ephemetoot import ephemetoot as func from ephemetoot import ephemetoot as func
@ -40,49 +40,81 @@ vnum = pkg_resources.require("ephemetoot")[0].version
parser = ArgumentParser() parser = ArgumentParser()
parser.add_argument( parser.add_argument(
"--archive-deleted", action="store_true", help="Only archive toots that are being deleted" "--archive-deleted",
action="store_true",
help="Only archive toots that are being deleted",
) )
parser.add_argument( parser.add_argument(
"--config", action="store", metavar="filepath", default="config.yaml", help="Filepath of your config file, absolute or relative to the current directory. If no --config path is provided, ephemetoot will use 'config.yaml'in the current directory" "--config",
action="store",
metavar="filepath",
default="config.yaml",
help="Filepath of your config file, absolute or relative to the current directory. If no --config path is provided, ephemetoot will use 'config.yaml'in the current directory",
) )
parser.add_argument( parser.add_argument(
"--datestamp", action="store_true", help="Include a datetime stamp for every action (e.g. deleting a toot)" "--datestamp",
action="store_true",
help="Include a datetime stamp for every action (e.g. deleting a toot)",
) )
parser.add_argument( parser.add_argument(
"--hide-skipped", "--hide_skipped", action="store_true", help="Do not write to log when skipping saved toots" "--hide-skipped",
"--hide_skipped",
action="store_true",
help="Do not write to log when skipping saved toots",
) )
parser.add_argument( parser.add_argument(
"--init", action="store_true", help="Create a config file that is saved in the current directory" "--init",
action="store_true",
help="Create a config file that is saved in the current directory",
) )
parser.add_argument( parser.add_argument(
"--pace", action="store_true", help="Slow deletion actions to match API rate limit to avoid pausing" "--pace",
action="store_true",
help="Slow deletion actions to match API rate limit to avoid pausing",
)
parser.add_argument("--quiet", action="store_true", help="Suppress most logging")
parser.add_argument(
"--retry-mins",
action="store",
metavar="minutes",
nargs="?",
const="1",
default="1",
type=int,
help="Number of minutes to wait between retries, when an error is thrown",
) )
parser.add_argument( parser.add_argument(
"--quiet", action="store_true", help="Suppress most logging" "--schedule",
) action="store",
parser.add_argument( metavar="filepath",
"--retry-mins", action="store", metavar="minutes", nargs="?", const="1", default="1", type=int, help="Number of minutes to wait between retries, when an error is thrown" nargs="?",
) const=".",
parser.add_argument( help="Save and load plist file on MacOS",
"--schedule", action="store", metavar="filepath", nargs="?", const=".", help="Save and load plist file on MacOS"
) )
parser.add_argument( parser.add_argument(
"--test", action="store_true", help="Do a test run without deleting any toots" "--test", action="store_true", help="Do a test run without deleting any toots"
) )
parser.add_argument( parser.add_argument(
"--time", action="store", metavar=('hour', 'minute'), nargs="*", help="Hour and minute to schedule: e.g. 9 30 for 9.30am" "--time",
action="store",
metavar=("hour", "minute"),
nargs="*",
help="Hour and minute to schedule: e.g. 9 30 for 9.30am",
) )
parser.add_argument( parser.add_argument(
"--version", action="store_true", help="Display the version numbers of the installed and latest versions" "--version",
action="store_true",
help="Display the version numbers of the installed and latest versions",
) )
options = parser.parse_args() options = parser.parse_args()
if options.config[0] == '~': if options.config[0] == "~":
config_file = os.path.expanduser(options.config) config_file = os.path.expanduser(options.config)
elif options.config[0] == '/': elif options.config[0] == "/":
config_file = options.config config_file = options.config
else: else:
config_file = os.path.join( os.getcwd(), options.config ) config_file = os.path.join(os.getcwd(), options.config)
def main(): def main():
try: try:
@ -95,11 +127,16 @@ def main():
func.schedule(options) func.schedule(options)
else: else:
if not options.quiet: if not options.quiet:
print('') print("")
print('============= EPHEMETOOT v' + vnum + ' ================') print("============= EPHEMETOOT v" + vnum + " ================")
print('Running at ' + str( datetime.now(timezone.utc).strftime('%a %d %b %Y %H:%M:%S %z') )) print(
print('================================================') "Running at "
print('') + str(
datetime.now(timezone.utc).strftime("%a %d %b %Y %H:%M:%S %z")
)
)
print("================================================")
print("")
if options.test: if options.test:
print("This is a test run...\n") print("This is a test run...\n")
with open(config_file) as config: with open(config_file) as config:
@ -111,5 +148,6 @@ def main():
print("🕵️ Missing config file") print("🕵️ Missing config file")
print("Run \033[92mephemetoot --init\033[0m to create a new one\n") print("Run \033[92mephemetoot --init\033[0m to create a new one\n")
if __name__ == '__main__':
main() if __name__ == "__main__":
main()

View File

@ -19,6 +19,7 @@ import requests
# local # local
from ephemetoot import plist from ephemetoot import plist
def init(): def init():
init_start = "\033[96m" init_start = "\033[96m"
@ -32,76 +33,64 @@ def init():
conf_user = "" conf_user = ""
while len(conf_user) < 1: while len(conf_user) < 1:
conf_user = input( conf_user = input(
init_start init_start
+ "Username" + "Username"
+ init_eg + init_eg
+ "(without the '@' - e.g. alice):" + "(without the '@' - e.g. alice):"
+ init_end + init_end
) )
conf_url = "" conf_url = ""
while len(conf_url) < 1: while len(conf_url) < 1:
conf_url = input( conf_url = input(
init_start init_start + "Base URL" + init_eg + "(e.g. example.social):" + init_end
+ "Base URL"
+ init_eg
+ "(e.g. example.social):"
+ init_end
) )
conf_days = "" conf_days = ""
while conf_days.isdigit() == False: while conf_days.isdigit() == False:
conf_days = input( conf_days = input(
init_start init_start + "Days to keep" + init_eg + "(default 365):" + init_end
+ "Days to keep"
+ init_eg
+ "(default 365):"
+ init_end
) )
conf_keep_pinned = "" conf_keep_pinned = ""
while conf_keep_pinned not in ["y", "n"]: while conf_keep_pinned not in ["y", "n"]:
conf_keep_pinned = input( conf_keep_pinned = input(
init_start init_start + "Keep pinned toots?" + init_eg + "(y or n):" + init_end
+ "Keep pinned toots?"
+ init_eg
+ "(y or n):"
+ init_end
) )
conf_pinned = "true" if conf_keep_pinned == "y" else "false" conf_pinned = "true" if conf_keep_pinned == "y" else "false"
conf_keep_toots = input( conf_keep_toots = input(
init_start init_start
+ "Toots to keep" + "Toots to keep"
+ init_eg + init_eg
+ " (optional list of IDs separated by commas):" + " (optional list of IDs separated by commas):"
+ init_end + init_end
) )
conf_keep_hashtags = input( conf_keep_hashtags = input(
init_start init_start
+ "Hashtags to keep" + "Hashtags to keep"
+ init_eg + init_eg
+ " (optional list separated by commas):" + " (optional list separated by commas):"
+ init_end + init_end
) )
conf_keep_visibility = input( conf_keep_visibility = input(
init_start init_start
+ "Visibility to keep" + "Visibility to keep"
+ init_eg + init_eg
+ " (optional list separated by commas):" + " (optional list separated by commas):"
+ init_end + init_end
) )
conf_archive = input( conf_archive = input(
init_start init_start
+ "Archive path" + "Archive path"
+ init_eg + init_eg
+ " (optional filepath for archive):" + " (optional filepath for archive):"
+ init_end + init_end
) )
# write out the config file # write out the config file
with open("config.yaml", "w") as configfile: with open("config.yaml", "w") as configfile:
@ -114,28 +103,29 @@ def init():
configfile.write("\n keep_pinned: " + conf_pinned) configfile.write("\n keep_pinned: " + conf_pinned)
if len(conf_keep_toots) > 0: if len(conf_keep_toots) > 0:
keep_list = conf_keep_toots.split(',') keep_list = conf_keep_toots.split(",")
configfile.write("\n toots_to_keep:") configfile.write("\n toots_to_keep:")
for toot in keep_list: for toot in keep_list:
configfile.write("\n - " + toot.strip()) configfile.write("\n - " + toot.strip())
if len(conf_keep_hashtags) > 0: if len(conf_keep_hashtags) > 0:
tag_list = conf_keep_hashtags.split(',') tag_list = conf_keep_hashtags.split(",")
configfile.write("\n hashtags_to_keep:") configfile.write("\n hashtags_to_keep:")
for tag in tag_list: for tag in tag_list:
configfile.write("\n - " + tag.strip()) configfile.write("\n - " + tag.strip())
if len(conf_keep_visibility) > 0: if len(conf_keep_visibility) > 0:
viz_list = conf_keep_visibility.split(',') viz_list = conf_keep_visibility.split(",")
configfile.write("\n visibility_to_keep:") configfile.write("\n visibility_to_keep:")
for mode in viz_list: for mode in viz_list:
configfile.write("\n - " + mode.strip()) configfile.write("\n - " + mode.strip())
if len(conf_archive) > 0: if len(conf_archive) > 0:
configfile.write("\n archive: " + conf_archive) configfile.write("\n archive: " + conf_archive)
configfile.close() configfile.close()
def version(vnum): def version(vnum):
try: try:
latest = requests.get( latest = requests.get(
@ -147,11 +137,14 @@ def version(vnum):
print("-------------------------------") print("-------------------------------")
print("Using: \033[92mVersion " + vnum + "\033[0m") print("Using: \033[92mVersion " + vnum + "\033[0m")
print("Latest: \033[92m" + latest_version + "\033[0m") print("Latest: \033[92m" + latest_version + "\033[0m")
print("To upgrade to the most recent version run \033[92mpip3 install --update ephemetoot\033[0m") print(
"To upgrade to the most recent version run \033[92mpip3 install --update ephemetoot\033[0m"
)
except Exception as e: except Exception as e:
print("Something went wrong:") print("Something went wrong:")
def schedule(options): def schedule(options):
try: try:
@ -172,7 +165,11 @@ def schedule(options):
lines[23] = " <integer>" + options.time[1] + "</integer>" lines[23] = " <integer>" + options.time[1] + "</integer>"
# write out file directly to ~/Library/LaunchAgents # write out file directly to ~/Library/LaunchAgents
f = open(os.path.expanduser("~/Library/LaunchAgents/") + "ephemetoot.scheduler.plist", mode="w") f = open(
os.path.expanduser("~/Library/LaunchAgents/")
+ "ephemetoot.scheduler.plist",
mode="w",
)
for line in lines: for line in lines:
if line == lines[-1]: if line == lines[-1]:
f.write(line) f.write(line)
@ -185,12 +182,12 @@ def schedule(options):
["launchctl unload ~/Library/LaunchAgents/ephemetoot.scheduler.plist"], ["launchctl unload ~/Library/LaunchAgents/ephemetoot.scheduler.plist"],
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
shell=True shell=True,
) )
# load the new file # load the new file
subprocess.run( subprocess.run(
["launchctl load ~/Library/LaunchAgents/ephemetoot.scheduler.plist"], ["launchctl load ~/Library/LaunchAgents/ephemetoot.scheduler.plist"],
shell=True shell=True,
) )
print("⏰ Scheduled!") print("⏰ Scheduled!")
except Exception as e: except Exception as e:
@ -569,7 +566,9 @@ def checkToots(config, options, retry_count=0):
except MastodonAPIError as e: except MastodonAPIError as e:
if e.args[1] == 401: if e.args[1] == 401:
print("\n🙅 User and/or access token does not exist or has been deleted (401)") print(
"\n🙅 User and/or access token does not exist or has been deleted (401)"
)
elif e.args[1] == 404: elif e.args[1] == 404:
print("\n🔭 Can't find that server (404)") print("\n🔭 Can't find that server (404)")
else: else:
@ -579,11 +578,7 @@ def checkToots(config, options, retry_count=0):
if retry_count == 0: if retry_count == 0:
print("\n📡 ephemetoot cannot connect to the server - are you online?") print("\n📡 ephemetoot cannot connect to the server - are you online?")
if retry_count < 4: if retry_count < 4:
print( print("Waiting " + str(options.retry_mins) + " minutes before trying again")
"Waiting "
+ str(options.retry_mins)
+ " minutes before trying again"
)
time.sleep(60 * options.retry_mins) time.sleep(60 * options.retry_mins)
retry_count += 1 retry_count += 1
print("Attempt " + str(retry_count + 1)) print("Attempt " + str(retry_count + 1))

View File

@ -1,4 +1,4 @@
default_file = '''<?xml version="1.0" encoding="UTF-8"?> default_file = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
@ -24,4 +24,4 @@ default_file = '''<?xml version="1.0" encoding="UTF-8"?>
<integer>00</integer> <integer>00</integer>
</dict> </dict>
</dict> </dict>
</plist>''' </plist>"""