ActiPubTagBooster/reboostTag.py

99 строки
2.9 KiB
Python
Исполняемый файл

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
"""
import os
from os.path import isfile, isdir, dirname, join, realpath
import sys
import io
import json
from datetime import datetime
from toot.console import main
# Command line Arguments
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-d", "--dry-run", default=False, action="store_true", help="Don't reboost")
parser.add_argument("-c", "--count", type=int, help="How many toots to read")
parser.add_argument("-t", "--tag", type=str, help="Which tag to follow")
parser.add_argument("-p", "--cache-path", type=str, default="/var/cache/ActiPubTagBooster", help="Which path to use for storing ")
args = parser.parse_args()
# Variables
dry_run = args.dry_run # The safe mode
tag = args.tag # The tag to reboost
count = args.count # The number of toots to load
cache_path = args.cache_path # The tag file cache path
most_recent = None # The first item id in the loaded list
# last_seen_file is the cache file for a given tag
last_seen_file = join(cache_path, "reboost.{}.lastseen".format( tag ))
# Exit if cache path doesn't exist
if( not isdir( cache_path) ):
print( "Critical error: please create directory {}".format( cache_path) )
os._exit(2)
# Touch last seen file if not exists
if( isfile( last_seen_file ) ):
wrapper = open(last_seen_file, 'r',encoding="utf-8")
last_seen = next(wrapper)
else:
try:
open(last_seen_file, 'w').close()
last_seen = 0
except IOError as e:
print("Couldn't open or write to file (%s)." % e)
# redirect sys.stdout to a buffer
stdout = sys.stdout
sys.stdout = io.StringIO()
# Build a fake list of args to run the toot main() function on
sim_args = [sys.argv[0], 'timeline', '-t', tag, '-c', str(count), '--json', '-1']
sys.argv = sim_args
main()
# get main() output and restore sys.stdout
output = sys.stdout.getvalue()
sys.stdout = stdout
# Convert the received JSON to a list
itemList = json.loads( output)
# Loop through items
#print ('Running with last_seen being: {}'.format(last_seen))
for item in itemList:
# Set the most recent id
if None == most_recent :
most_recent = item['id']
# if never seen, and therefore recent, reboost
if( last_seen != item['id'] and dry_run != True ):
print("{}; Reboosting item #{} by {}".format(datetime.now().strftime("%y/%m/%d %H:%M:%S"),item['id'], item['account']['acct']) )
# Build a fake list of args to run the toot main() function on
sim_args = [sys.argv[0], 'reblog', str(item['id'])]
sys.argv = sim_args
main()
# We've seen you already that toot, break
else:
break;
# Update the cache file with new value, if exists
if( last_seen != most_recent) :
print( "Saving most_recent as last_seen: {}".format(most_recent))
handle = open(last_seen_file, 'w')
handle.write(most_recent)
handle.close()