instead of trying to use subprocess, we send a command to the i2music site through api to run the updateplaylists script to compress and add new songs.

main
simp 2025-06-13 15:41:56 -04:00
parent 3289cbe5eb
commit 2af3ba25f1
4 changed files with 125 additions and 38 deletions

View File

@ -24,6 +24,9 @@ Most of the game related commands are changed in IRC with !admin <setting>
filetype_ = opus
playlist_directory = /path/i2music/static/playlists/Guessthesong
update_playlist_script = /path/i2music
i2music_hostname = 127.0.0.1
i2music_gunicorn_port = 5001
i2music_flask_port = 5002
[settings]
secret_key = <changeit> #for flask

28
app.py
View File

@ -33,6 +33,9 @@ def config_load(config_path):
update_playlist_script = (config['i2music']['update_playlist_script'])
filetype_ = (config['i2music']['filetype_'])
playlist_directory = (config['i2music']['playlist_directory'])
i2music_hostname = (config['i2music']['i2music_hostname'])
i2music_gunicorn_port = int(config['i2music']['i2music_gunicorn_port'])
i2music_flask_port = int(config['i2music']['i2music_flask_port'])
secret_key = (config['settings']['secret_key'])
ah = (config['settings']['ah'])
instance_url = (config['settings']['instance_url'])
@ -54,7 +57,7 @@ def config_load(config_path):
log.error(f"The 'config.ini' file was not found{e}")
except (ValueError) as e:
log.error(f"Cannot accept value: {e}")
return hostname, port, secret_key, channel, primary, auth_users, instance_url, username, password, port2, flask_port, ah, sam, gunicorn_port, tr, timeout, sc_instances, music_player_url, playlist, filetype_, playlist_directory, update_playlist_script
return hostname, port, secret_key, channel, primary, auth_users, instance_url, username, password, port2, flask_port, ah, sam, gunicorn_port, tr, timeout, sc_instances, music_player_url, playlist, filetype_, playlist_directory, update_playlist_script, i2music_hostname, i2music_gunicorn_port, i2music_flask_port
def load_settings_ini(config_path):
@ -94,7 +97,7 @@ def load_settings_ini(config_path):
return(config_dict)
settings_path = os.path.join(script_directory, 'config.txt')
hostname, port, secret_key, channel, primary, auth_users, instance_url, username, password, port2, flask_port, ah, sam, gunicorn_port, tr, timeout, sc_instances, music_player_url, playlist, filetype_, playlist_directory, update_playlist_script = config_load(settings_path)
hostname, port, secret_key, channel, primary, auth_users, instance_url, username, password, port2, flask_port, ah, sam, gunicorn_port, tr, timeout, sc_instances, music_player_url, playlist, filetype_, playlist_directory, update_playlist_script, i2music_hostname, i2music_gunicorn_port, i2music_flask_port = config_load(settings_path)
if sam:
from i2p import socket
else:
@ -1106,23 +1109,10 @@ class Irc_bot:
log.info(f"[Copied image to i2music] {rm_na_space(v['title'])}.{ftype}")
completed += 1
if completed != 0:
if 'linux' in platform:
p = 'linux'
elif 'darwin' in platform:
p = 'darwin'
elif 'win' in platform:
p = 'windows'
if p != 'windows':
try:
subprocess.run(["python3", update_playlist_script])
except Exception as e:
log.debug(f"Error: {e}")
else:
try:
subprocess.run(["py", update_playlist_script])
except Exception as e:
log.debug(f"Error: {e}")
try:
run_update_playlists(update_playlist_script, i2music_hostname, i2music_gunicorn_port, i2music_flask_port)
except Exception as e:
log.debug(f"Error: {e}")
Sl.downloading = False
log.debug('[finished downloading images/songs]')
time.sleep(5)

View File

@ -10,6 +10,9 @@ playlist = Guessthesong
filetype_ = opus
playlist_directory = /path/i2music/static/playlists/Guessthesong
update_playlist_script = /path/i2music
i2music_hostname = 127.0.0.1
i2music_gunicorn_port = 5002
i2music_flask_port = 5001
[settings]
secret_key = <changeit>

129
game.py
View File

@ -606,6 +606,7 @@ def validate_image_url(url:str, file_upload:dict)->tuple:
'achaniseb6rz4sdqx2dg7y4lxlx4jt6zsxowoasx4edouaspf6wa.b32.i2p',
'convos.simp.i2p',
'i2peek-a-boo.i2p',
'1337s.i2p',
]
for k, v in file_upload.items():
accepted_b32.append(k)
@ -736,28 +737,28 @@ def search_sc(search_url:str, proxies:dict)->dict:
Uses BeatufiulSoup to search soundcloak, returning top result
"""
# requests.packages.urllib3.disable_warnings()
# try:
sitedown = False
response = requests.get(search_url, proxies=proxies, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
links_ = []
try:
sitedown = False
response = requests.get(search_url, proxies=proxies, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
links_ = []
try:
p2 = soup.p.get_text()
if p2.casefold() == 'The website was not reachable.':
sitedown = True
except Exception as e:
success = False
for link in soup.find_all('a'):
links_.append(str(link.get('href')))
if len(links_) > 2:
links_.pop(0)
success = True
else:
success = False
p2 = soup.p.get_text()
if p2.casefold() == 'The website was not reachable.':
sitedown = True
except Exception as e:
# log.error(f"Can't reach router {e}: {e}")
success = False
print(f"Can't reach router {e}: {e}")
for link in soup.find_all('a'):
links_.append(str(link.get('href')))
if len(links_) > 2:
links_.pop(0)
success = True
else:
success = False
# except Exception as e:
# # log.error(f"Can't reach router {e}: {e}")
# success = False
# print(f"Can't reach router {e}")
return links_, success, sitedown
def get_sc_audiofile(search_url:str, proxies:dict)->dict:
@ -895,3 +896,93 @@ def audio_file_downloader(url_endpoint:str, song_title:str, sc_instances:list, p
print('site down, trying again')
time.sleep(5)
return success, song_location
def read_txt_file(file_:str)->list:
"""given a path of a text file, returns each line as a list
Args:
file_ (str): the full path of the fext file
Returns:
list: text file split at line breaks
"""
lines_list =[]
if os.path.isfile(file_):
with open(file_, 'r') as file:
for line_number, line in enumerate(file, start=1):
rm_line_break = line.replace('\n', '')
lines_list.append(rm_line_break)
return lines_list
def send_message(payload:dict, url_:str)->tuple:
"""given a payload and a url, does http post request
Args:
payload (dict): payload to send
url_ (str): where to send it
Returns:
tuple: bool (success/failure), message with error code if any
"""
try:
response = requests.post(url_, json=payload)
print(response.status_code)
if response.status_code == 500 or response.status_code == 200:
return True, 'Sent'
else:
return False, f'Failed to send message. Status code: {response.status_code}'
except Exception as e:
return False, 'Failed to send'
def update_api(update_playlist_script:str, msg: str, txtfile:str)->None:
"""given a path for a textfile and a string, make a one line txt file
Args:
update_playlist_script (str): directory where updateplaylists.py is
msg (str): new api key
txtfile (str): textfile name
"""
file_ = f"{update_playlist_script}/{txtfile}"
file_exists = os.path.exists(file_)
new_line = f'{msg}\n'
if not file_exists:
file_object = open(file_, 'a')
file_object.write(new_line)
file_object.close()
else:
file_object = open(file_, 'w')
file_object.writelines(new_line)
file_object.close()
def run_update_playlists(update_playlist_script:str, i2music_hostname:int, i2music_gunicorn_port:int, i2music_flask_port:int):
"""sends update_playlists command to i2music
Args:
update_playlist_script (str): directory where updateplaylists.py is
i2music_hostname (int): hostname for i2music
i2music_gunicorn_port (int): gunicorn port of i2music
i2music_flask_port (int): flask port of i2music
"""
endpoint_path = os.path.join(update_playlist_script, '.endpoint')
print(endpoint_path)
if os.path.exists(endpoint_path):
endpoint = read_txt_file(os.path.join(update_playlist_script, '.endpoint'))[0]
api_key = random_string(40)
update_api(update_playlist_script, api_key, '.apikey')
payload = {
'key': api_key,
'command': 'update_playlists',
}
url_ = f'http://{i2music_hostname}:{i2music_gunicorn_port}/{endpoint}'
sent_ = send_message(payload, url_)[0]
if not sent_:
print(f"[Trying flask port {i2music_flask_port}] Couldn't reach gunicorn on port {i2music_gunicorn_port}")
url_ = f'http://{i2music_hostname}:{i2music_flask_port}/{endpoint}'
sent_ = send_message(payload, url_)[0]
if not sent_:
print(f"[Couldn't reach site] If it's running, check your 'gunicorn_port' and 'site_port' in your config file. Script is checking on ports {i2music_gunicorn_port} and {i2music_flask_port}")
if sent_:
print(f'[Refreshing site] Command sent')
print(f'[Done]')
else:
print(f"[Can't refresh i2music]] No file '.endpoint' found in script directory, is i2music running?")