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))
############################################################################### insert_sql = """INSERT INTO welcome(datetime, users, users_hour)
VALUES(%s,%s,%s) RETURNING datetime;"""
conn = None
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
users_before = current_id try:
users_hour = 0
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 = welcome_db, user = welcome_db_user, password = "", host = "/var/run/postgresql", port = "5432") cur.execute(insert_sql, (now, current_id, users_hour))
cur = conn.cursor() datetime = cur.fetchone()[0]
cur.execute("SELECT DISTINCT ON (datetime) users FROM welcome WHERE datetime > current_timestamp - INTERVAL '70 minutes' ORDER BY datetime asc LIMIT 1") conn.commit()
row = cur.fetchone() cur.close()
users_before = row[0] except (Exception, psycopg2.DatabaseError) as error:
cur.close() print(error)
users_hour = current_id - users_before finally:
except (Exception, psycopg2.DatabaseError) as error: if conn is not None:
print (error) conn.close()
finally: ###############################################################################
# WORK OUT THE TOOT TEXT
###############################################################################
if conn is not None: # Calculate difference in times
conn.close() hourly_change_string = ""
daily_change_string = ""
weekly_change_string = ""
users_hourly_change_string = ""
print("-----------------") try:
print("current users: "+str(current_id))
print("users before: "+str(users_before))
print("users / hour: "+str(users_hour))
insert_sql = """INSERT INTO welcome(datetime, users, users_hour) conn = None
VALUES(%s,%s,%s) RETURNING datetime;"""
conn = None
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 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 = welcome_db, user = welcome_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(insert_sql, (now, current_id, users_hour)) if row[0] == None:
datetime = cur.fetchone()[0] users_last_hour = 0
conn.commit() else:
cur.close() users_last_hour = row[0]
except (Exception, psycopg2.DatabaseError) as error: cur.execute("SELECT DISTINCT ON (datetime) users,datetime FROM welcome WHERE datetime > current_timestamp - INTERVAL '1 day' ORDER BY datetime asc LIMIT 1")
print(error) row = cur.fetchone()
finally: if row[0] == None:
if conn is not None: users_last_day = 0
conn.close() else:
############################################################################### users_last_day = row[0]
# WORK OUT THE TOOT TEXT
###############################################################################
# Calculate difference in times cur.execute("SELECT DISTINCT ON (datetime) users,datetime FROM welcome WHERE datetime > current_timestamp - INTERVAL '7 days' ORDER BY datetime asc LIMIT 1")
hourly_change_string = "" row = cur.fetchone()
daily_change_string = ""
weekly_change_string = ""
users_hourly_change_string = ""
try: 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)
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))
conn.close() ###################################################################################
################################################################################# # Hourly change
if hour_inc != 0:
welcome_users = [] users_hourly_change = current_id - users_last_hour
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)
if users_hourly_change > 0:
hourly_change_string = "+" + format(users_hourly_change, ",d") + in_the_last_hour_str + "\n"
if time.localtime().tm_isdst == 0: # Daily change
if day_inc != 0:
interval_time = '60 minutes' daily_change = current_id - users_last_day
elif time.localtime().tm_isdst == 1: 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)
if daily_change > 0:
daily_change_string = "+" + format(daily_change, ",d") + in_the_last_day_str + "\n"
interval_time = '120 minutes' # Weekly change
if week_inc != 0:
conn = None weekly_change = current_id - users_last_week
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)
try: if weekly_change > 0:
weekly_change_string = "+" + format(weekly_change, ",d") + in_the_last_week_str + "\n"
conn = psycopg2.connect(database = mastodon_db, user = mastodon_db_user, password = "", host = "/var/run/postgresql", port = "5432") elif users_hourly_change < 0:
cur = conn.cursor() hourly_change_string = format(users_hourly_change, ",d") + in_the_last_hour_str + "\n"
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)") # Daily change
if day_inc != 0:
daily_change = current_id - users_last_day
daily_evolution_str = get_locale("daily_evolution_str", welcome_lang)
print(daily_evolution_str + ': %s'%daily_change)
if daily_change < 0:
daily_change_string = format(daily_change, ",d") + in_the_last_day_str + "\n"
rows = cur.fetchall() # Weekly change
if week_inc != 0:
for row in rows: weekly_change = current_id - users_last_week
weekly_evolution_str = get_locale("weekly_evolution_str", welcome_lang)
print(weekly_evolution_str + ': %s'%weekly_change)
if weekly_change < 0:
weekly_change_string = format(weekly_change, ",d") + in_the_last_week_str + "\n"
if row[1] == None: ###############################################################################
# TOOT IT!
welcome_users.append(row[0]) ###############################################################################
cur.close() if len(welcome_users) > 0:
except (Exception, psycopg2.DatabaseError) as error: welcomes_str = get_locale("welcomes_str", welcome_lang)
we_have_str = get_locale("we_have_str", welcome_lang)
print(error) users_str = get_locale("users_str", welcome_lang)
finally: toot_text = "\n"
toot_text += mastodon_hostname + ' ' + welcomes_str + ':\n\n'
if conn is not None: toot_text += new_users_string + "\n"
toot_text += "\n"
conn.close() toot_text += "\n\n" + we_have_str + ' ' + str(current_id) + users_str + "\n\n"
toot_text += hourly_change_string
i = 0 toot_text += daily_change_string
toot_text += weekly_change_string
new_users_string = "" toot_text += "\n"
while i < len(welcome_users): print("Tooting...")
print(toot_text)
new_users_string = new_users_string+"@"+welcome_users[i] if len(toot_text) < 500:
mastodon.status_post(toot_text, in_reply_to_id=None, )
i += 1 else:
toot_text1, toot_text2 = toot_text[:int(len(toot_text)/2)], toot_text[int(len(toot_text)/2):]
if i < len(welcome_users): toot_id = mastodon.status_post(toot_text1, in_reply_to_id=None,)
mastodon.status_post(toot_text2, in_reply_to_id=toot_id,)
new_users_string = new_users_string+", " print(toot_text1)
print(toot_text2)
#########################################################################################################
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!")