Added ca, es and en language support

This commit is contained in:
spla 2021-05-21 13:50:16 +02:00
pare d54306e919
commit f157e821bb
S'han modificat 4 arxius amb 353 adicions i 220 eliminacions

17
app/locales/ca.txt Normal file
Veure arxiu

@ -0,0 +1,17 @@
current_users_str: usuaris actuals
users_before_str: usuaris abans
users_hour_str: usuaris per hora
new_users_last_hour_str: nous usuaris darrera hora
new_users_last_day_str: nous usuaris darrer dia
new_users_last_week_str: nous usuaris darrera setmana
hourly_users_evolution_str: evolució horaria d'usuaris
in_the_last_hour_str: en la darrera hora
daily_users_evolution_str: evolució diaria d'usuaris
in_the_last_day_str: en el darrer dia
weekly_users_evolution_str: evolució setmanal d'usuaris
in_the_last_week_str: en la darrera setmana
daily_evolution_str: Evolució diaria
weekly_evolution_str: Evolució setmanal
welcomes_str: dona la benvinguda a
we_have_str: Ja som
users_str: usuaris

17
app/locales/en.txt Normal file
Veure arxiu

@ -0,0 +1,17 @@
current_users_str: current users
users_before_str: users before
users_hour_str: users per hour
new_users_last_hour_str: new users last hour
new_users_last_day_str: new users last day
new_users_last_week_str: new users last week
hourly_users_evolution_str: hourly users evolution
in_the_last_hour_str: in the last hour
daily_users_evolution_str: daily users evolution
in_the_last_day_str: in the last day
weekly_users_evolution_str: weekly users evolution
in_the_last_week_str: in the last week
daily_evolution_str: Daily evolution
weekly_evolution_str: Weekly evolution
welcomes_str: welcomes
we_have_str: We have
users_str: users

17
app/locales/es.txt Normal file
Veure arxiu

@ -0,0 +1,17 @@
current_users_str: usuarios actuales
users_before_str: usuarios anteriores
users_hour_str: usuarios por hora
new_users_last_hour_str: nuevos usuarios última hora
new_users_last_day_str: nuevos usuarios último dia
new_users_last_week_str: nuevos usuaris última setmana
hourly_users_evolution_str: evolución horaria de usuarios
in_the_last_hour_str: en la última hora
daily_users_evolution_str: evolución diaria de usuarios
in_the_last_day_str: en el último dia
weekly_users_evolution_str: evolución semanal de usuarios
in_the_last_week_str: en la última semana
daily_evolution_str: Evolución diaria
weekly_evolution_str: Evolución semanal
welcomes_str: da la bienvenida a
we_have_str: Ya somos
users_str: usuarios

Veure arxiu

@ -45,6 +45,30 @@ def db_config():
return (mastodon_db, mastodon_db_user, welcome_db, welcome_db_user) return (mastodon_db, mastodon_db_user, welcome_db, welcome_db_user)
def get_locale( parameter, welcome_lang):
if welcome_lang not in ['ca','es','en']:
print("lang must be 'ca', 'es' or 'en'")
sys.exit(0)
language_filepath = f"app/locales/{welcome_lang}.txt"
if not os.path.isfile(language_filepath):
print("File %s not found, exiting."%language_filepath)
sys.exit(0)
with open( language_filepath ) as f:
for line in f:
if line.startswith( parameter ):
return line.replace(parameter + ":", "").strip()
print(language_filepath + " Missing parameter %s "%parameter)
sys.exit(0)
def usage():
print('usage: python ' + sys.argv[0] + ' --ca (or --es or --en)')
# Returns the parameter from the specified file # Returns the parameter from the specified file
def get_parameter( parameter, file_path ): def get_parameter( parameter, file_path ):
# Check if secrets file exists # Check if secrets file exists
@ -67,319 +91,377 @@ def get_parameter( parameter, file_path ):
if __name__ == '__main__': if __name__ == '__main__':
mastodon, mastodon_hostname = mastodon() # usage modes
mastodon_db, mastodon_db_user, welcome_db, welcome_db_user = db_config() if len(sys.argv) == 1:
############################################################################### usage()
# current registered users
###############################################################################
try: elif len(sys.argv) >= 2:
welcome_lang = ''
if sys.argv[1] == '--ca':
welcome_lang = 'ca'
if sys.argv[1] == '--es':
welcome_lang = 'es'
elif sys.argv[1] == '--en':
welcome_lang = 'en'
if not welcome_lang in ['ca', 'es', 'en']:
print("\nOnly 'ca', 'es' and 'en' languages are supported.\n")
sys.exit(0)
mastodon, mastodon_hostname = mastodon()
mastodon_db, mastodon_db_user, welcome_db, welcome_db_user = db_config()
###############################################################################
# current registered users
###############################################################################
try:
conn = None
conn = psycopg2.connect(database = mastodon_db, user = mastodon_db_user, password = "", host = "/var/run/postgresql", port = "5432")
cur = conn.cursor()
cur.execute("SELECT count(*) FROM users WHERE disabled='f' and approved='t'")
row = cur.fetchone()
if row != None:
current_id = row[0]
else:
current_id = 0
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print (error)
finally:
if conn is not None:
conn.close()
###############################################################################
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
users_before = current_id
users_hour = 0
conn = None conn = None
conn = psycopg2.connect(database = mastodon_db, user = mastodon_db_user, password = "", host = "/var/run/postgresql", port = "5432") try:
cur = conn.cursor() conn = psycopg2.connect(database = welcome_db, user = welcome_db_user, password = "", host = "/var/run/postgresql", port = "5432")
cur.execute("SELECT count(*) FROM users WHERE disabled='f' and approved='t'") cur = conn.cursor()
row = cur.fetchone() cur.execute("SELECT DISTINCT ON (datetime) users FROM welcome WHERE datetime > current_timestamp - INTERVAL '70 minutes' ORDER BY datetime asc LIMIT 1")
if row != None: row = cur.fetchone()
current_id = row[0] users_before = row[0]
else: cur.close()
current_id = 0 users_hour = current_id - users_before
cur.close() except (Exception, psycopg2.DatabaseError) as error:
except (Exception, psycopg2.DatabaseError) as error: print (error)
print (error) finally:
finally: if conn is not None:
if conn is not None: conn.close()
conn.close() current_users_str = get_locale("current_users_str", welcome_lang)
users_before_str = get_locale("users_before_str", welcome_lang)
users_hour_str = get_locale("users_hour_str", welcome_lang)
############################################################################### print("-----------------")
print(current_users_str + ': ' + str(current_id))
print(users_before_str + ': ' + str(users_before))
print(users_hour_str + ': ' + str(users_hour))
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") insert_sql = """INSERT INTO welcome(datetime, users, users_hour)
VALUES(%s,%s,%s) RETURNING datetime;"""
conn = None
users_before = current_id now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
users_hour = 0
conn = None try:
try: conn = psycopg2.connect(database = welcome_db, user = welcome_db_user, password = "", host = "/var/run/postgresql", port = "5432")
conn = psycopg2.connect(database = welcome_db, user = welcome_db_user, password = "", host = "/var/run/postgresql", port = "5432") cur = conn.cursor()
cur = conn.cursor() cur.execute(insert_sql, (now, current_id, users_hour))
cur.execute("SELECT DISTINCT ON (datetime) users FROM welcome WHERE datetime > current_timestamp - INTERVAL '70 minutes' ORDER BY datetime asc LIMIT 1") datetime = cur.fetchone()[0]
row = cur.fetchone() conn.commit()
users_before = row[0] cur.close()
cur.close() except (Exception, psycopg2.DatabaseError) as error:
users_hour = current_id - users_before print(error)
except (Exception, psycopg2.DatabaseError) as error: finally:
print (error) if conn is not None:
finally: conn.close()
if conn is not None: ###############################################################################
# WORK OUT THE TOOT TEXT
###############################################################################
conn.close() # Calculate difference in times
print("-----------------") hourly_change_string = ""
print("current users: "+str(current_id)) daily_change_string = ""
print("users before: "+str(users_before)) weekly_change_string = ""
print("users / hour: "+str(users_hour)) users_hourly_change_string = ""
insert_sql = """INSERT INTO welcome(datetime, users, users_hour) try:
VALUES(%s,%s,%s) RETURNING datetime;"""
conn = None
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") conn = None
try: conn = psycopg2.connect(database = welcome_db, user = welcome_db_user, password = "", host = "/var/run/postgresql", port = "5432")
conn = psycopg2.connect(database = welcome_db, user = welcome_db_user, password = "", host = "/var/run/postgresql", port = "5432") cur = conn.cursor()
cur = conn.cursor() cur.execute("SELECT DISTINCT ON (datetime) users, datetime FROM welcome WHERE datetime > current_timestamp - INTERVAL '62 minutes' ORDER BY datetime asc LIMIT 1")
cur.execute(insert_sql, (now, current_id, users_hour)) row = cur.fetchone()
datetime = cur.fetchone()[0] if row[0] == None:
conn.commit() users_last_hour = 0
cur.close() else:
except (Exception, psycopg2.DatabaseError) as error: users_last_hour = row[0]
print(error) cur.execute("SELECT DISTINCT ON (datetime) users,datetime FROM welcome WHERE datetime > current_timestamp - INTERVAL '1 day' ORDER BY datetime asc LIMIT 1")
finally: row = cur.fetchone()
if conn is not None: if row[0] == None:
conn.close() users_last_day = 0
############################################################################### else:
# WORK OUT THE TOOT TEXT
###############################################################################
# Calculate difference in times users_last_day = row[0]
hourly_change_string = "" cur.execute("SELECT DISTINCT ON (datetime) users,datetime FROM welcome WHERE datetime > current_timestamp - INTERVAL '7 days' ORDER BY datetime asc LIMIT 1")
daily_change_string = ""
weekly_change_string = ""
users_hourly_change_string = ""
try: row = cur.fetchone()
if row[0] == None:
users_last_week = 0
else:
users_last_week = row[0]
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print (error)
finally:
if conn is not None:
conn.close()
#################################################################################
welcome_users = []
if time.localtime().tm_isdst == 0:
interval_time = '60 minutes'
elif time.localtime().tm_isdst == 1:
interval_time = '120 minutes'
conn = None conn = None
conn = psycopg2.connect(database = welcome_db, user = welcome_db_user, password = "", host = "/var/run/postgresql", port = "5432") try:
cur = conn.cursor() conn = psycopg2.connect(database = mastodon_db, user = mastodon_db_user, password = "", host = "/var/run/postgresql", port = "5432")
cur.execute("SELECT DISTINCT ON (datetime) users, datetime FROM welcome WHERE datetime > current_timestamp - INTERVAL '62 minutes' ORDER BY datetime asc LIMIT 1") cur = conn.cursor()
row = cur.fetchone() cur.execute("select username, domain from accounts where (created_at + interval '" + interval_time + "' > (now() - interval '1 hour')) and domain is null and id in (select account_id from users where approved and not disabled)")
if row[0] == None: rows = cur.fetchall()
users_last_hour = 0 for row in rows:
else: if row[1] == None:
users_last_hour = row[0] welcome_users.append(row[0])
cur.execute("SELECT DISTINCT ON (datetime) users,datetime FROM welcome WHERE datetime > current_timestamp - INTERVAL '1 day' ORDER BY datetime asc LIMIT 1") cur.close()
row = cur.fetchone() except (Exception, psycopg2.DatabaseError) as error:
if row[0] == None: print(error)
users_last_day = 0 finally:
else: if conn is not None:
users_last_day = row[0] conn.close()
cur.execute("SELECT DISTINCT ON (datetime) users,datetime FROM welcome WHERE datetime > current_timestamp - INTERVAL '7 days' ORDER BY datetime asc LIMIT 1") i = 0
row = cur.fetchone() new_users_string = ""
if row[0] == None: while i < len(welcome_users):
users_last_week = 0 new_users_string = new_users_string+"@"+welcome_users[i]
else:
users_last_week = row[0] i += 1
cur.close() if i < len(welcome_users):
except (Exception, psycopg2.DatabaseError) as error: new_users_string = new_users_string+", "
print (error) #########################################################################################################
finally: hour_inc = current_id - users_last_hour
day_inc = current_id - users_last_day
week_inc = current_id - users_last_week
if conn is not None: new_users_last_hour_str = get_locale("new_users_last_hour_str", welcome_lang)
new_users_last_day_str = get_locale("new_users_last_day_str", welcome_lang)
new_users_last_week_str = get_locale("new_users_last_week_str", welcome_lang)
conn.close() print("------------------------")
print(new_users_last_hour_str + ': ' + str(hour_inc))
print(new_users_last_day_str + ': ' + str(day_inc))
print(new_users_last_week_str + ': ' + str(week_inc))
################################################################################# ###################################################################################
welcome_users = [] # Hourly change
if hour_inc != 0:
if time.localtime().tm_isdst == 0: users_hourly_change = current_id - users_last_hour
interval_time = '60 minutes' hourly_users_evolution_str = get_locale("hourly_users_evolution_str", welcome_lang)
in_the_last_hour_str = get_locale("in_the_last_hour_str", welcome_lang)
print(hourly_users_evolution_str + ': %s'%users_hourly_change)
elif time.localtime().tm_isdst == 1: if users_hourly_change > 0:
hourly_change_string = "+" + format(users_hourly_change, ",d") + in_the_last_hour_str + "\n"
interval_time = '120 minutes' # Daily change
if day_inc != 0:
conn = None daily_change = current_id - users_last_day
try: daily_users_evolution_str = get_locale("daily_users_evolution_str", welcome_lang)
in_the_last_day_str = get_locale("in_the_last_day_str", welcome_lang)
print(daily_users_evolution_str + ': %s'%daily_change)
conn = psycopg2.connect(database = mastodon_db, user = mastodon_db_user, password = "", host = "/var/run/postgresql", port = "5432") if daily_change > 0:
daily_change_string = "+" + format(daily_change, ",d") + in_the_last_day_str + "\n"
cur = conn.cursor() # Weekly change
if week_inc != 0:
cur.execute("select username, domain from accounts where (created_at + interval '" + interval_time + "' > (now() - interval '1 hour')) and domain is null and id in (select account_id from users where approved and not disabled)") weekly_change = current_id - users_last_week
rows = cur.fetchall() weekly_users_evolution_str = get_locale("weekly_users_evolution_str", welcome_lang)
in_the_last_week_str = get_locale("in_the_last_week_str", welcome_lang)
print(weekly_users_evolution_str + ': %s'%weekly_change)
for row in rows: if weekly_change > 0:
weekly_change_string = "+" + format(weekly_change, ",d") + in_the_last_week_str + "\n"
if row[1] == None: elif users_hourly_change < 0:
welcome_users.append(row[0]) hourly_change_string = format(users_hourly_change, ",d") + in_the_last_hour_str + "\n"
cur.close() # Daily change
if day_inc != 0:
daily_change = current_id - users_last_day
except (Exception, psycopg2.DatabaseError) as error: daily_evolution_str = get_locale("daily_evolution_str", welcome_lang)
print(daily_evolution_str + ': %s'%daily_change)
print(error) if daily_change < 0:
daily_change_string = format(daily_change, ",d") + in_the_last_day_str + "\n"
finally: # Weekly change
if week_inc != 0:
if conn is not None: weekly_change = current_id - users_last_week
conn.close() weekly_evolution_str = get_locale("weekly_evolution_str", welcome_lang)
print(weekly_evolution_str + ': %s'%weekly_change)
i = 0 if weekly_change < 0:
weekly_change_string = format(weekly_change, ",d") + in_the_last_week_str + "\n"
new_users_string = "" ###############################################################################
# TOOT IT!
###############################################################################
while i < len(welcome_users): if len(welcome_users) > 0:
new_users_string = new_users_string+"@"+welcome_users[i] welcomes_str = get_locale("welcomes_str", welcome_lang)
we_have_str = get_locale("we_have_str", welcome_lang)
users_str = get_locale("users_str", welcome_lang)
i += 1 toot_text = "\n"
toot_text += mastodon_hostname + ' ' + welcomes_str + ':\n\n'
toot_text += new_users_string + "\n"
toot_text += "\n"
toot_text += "\n\n" + we_have_str + ' ' + str(current_id) + users_str + "\n\n"
toot_text += hourly_change_string
toot_text += daily_change_string
toot_text += weekly_change_string
toot_text += "\n"
if i < len(welcome_users): print("Tooting...")
print(toot_text)
if len(toot_text) < 500:
mastodon.status_post(toot_text, in_reply_to_id=None, )
else:
toot_text1, toot_text2 = toot_text[:int(len(toot_text)/2)], toot_text[int(len(toot_text)/2):]
toot_id = mastodon.status_post(toot_text1, in_reply_to_id=None,)
mastodon.status_post(toot_text2, in_reply_to_id=toot_id,)
print(toot_text1)
print(toot_text2)
new_users_string = new_users_string+", " print("Done!")
#########################################################################################################
hour_inc = current_id - users_last_hour
day_inc = current_id - users_last_day
week_inc = current_id - users_last_week
print("------------------------")
print("new users last hour: "+str(hour_inc))
print("new users last day: "+str(day_inc))
print("new users last week: "+str(week_inc))
###################################################################################
# Hourly change
if hour_inc != 0:
users_hourly_change = current_id - users_last_hour
print("Hourly users evolution: %s"%users_hourly_change)
if users_hourly_change > 0:
hourly_change_string = "+" + format(users_hourly_change, ",d") + " en la darrera hora\n"
# Daily change
if day_inc != 0:
daily_change = current_id - users_last_day
print("Daily users evolution: %s"%daily_change)
if daily_change > 0:
daily_change_string = "+" + format(daily_change, ",d") + " in the last day\n"
# Weekly change
if week_inc != 0:
weekly_change = current_id - users_last_week
print("Weekly users evolution: %s"%weekly_change)
if weekly_change > 0:
weekly_change_string = "+" + format(weekly_change, ",d") + " in the last week\n"
elif users_hourly_change < 0:
hourly_change_string = format(users_hourly_change, ",d") + " in the last hour\n"
# Daily change
if day_inc != 0:
daily_change = current_id - users_last_day
print("Daily evolution: %s"%daily_change)
if daily_change < 0:
daily_change_string = format(daily_change, ",d") + " in the last day\n"
# Weekly change
if week_inc != 0:
weekly_change = current_id - users_last_week
print("Weekly evolution: %s"%weekly_change)
if weekly_change < 0:
weekly_change_string = format(weekly_change, ",d") + " in the last week\n"
###############################################################################
# TOOT IT!
###############################################################################
if len(welcome_users) > 0:
toot_text = "\n"
toot_text += mastodon_hostname + " welcomes:" + "\n\n"
toot_text += new_users_string + "\n"
toot_text += "\n"
toot_text += "\n\nWe have " + str(current_id) + " users\n\n"
toot_text += hourly_change_string
toot_text += daily_change_string
toot_text += weekly_change_string
toot_text += "\n"
print("Tooting...")
print(toot_text)
if len(toot_text) < 500:
mastodon.status_post(toot_text, in_reply_to_id=None, )
else:
toot_text1, toot_text2 = toot_text[:int(len(toot_text)/2)], toot_text[int(len(toot_text)/2):]
toot_id = mastodon.status_post(toot_text1, in_reply_to_id=None,)
mastodon.status_post(toot_text2, in_reply_to_id=toot_id,)
print(toot_text1)
print(toot_text2)
print("Done!")