Serverless and decentralized flat file chatting convention for users on a shared system. Comes w/ base implementation.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
gab2/gab

107 lines
3.1 KiB

#!/usr/bin/env python3
import os
import sys
import time
from datetime import datetime
help_text = "GAB - A simple chat interface\n\nsyntax: gab [flag] [value]\n\nflag value\n---------------- ---------------\n-h, --help, help None\n-m, --msg, msg Quoted text with the msg being added to chat\n-l, --list, list An integer representing the number of rows you\'d like to view, default 5"
title = "\033[1mGAB v2.0\033[0m"
files = [[x, "/home/{}/.gab".format(x)] for x in os.listdir("/home/")]
log = {}
def read_file(user, path):
global log
if os.path.isfile(path):
with open(path, "r") as f:
for line in f:
msg = line.split("|", 1)
if len(msg) == 2:
log[msg[0].strip()] = "\033[7m {} \033[0m {}".format(user, msg[1].strip())
def list_messages(count="5"):
global log
try:
count = int(count)
except ValueError:
print("Error parsing list number, using default: 5")
count = 5
sorted_keys = list(log.keys())
if len(sorted_keys) > 0:
sorted_keys.sort(reverse=True)
last_time = float(sorted_keys[0])
sorted_keys = sorted_keys[:min(len(sorted_keys), count)]
sorted_keys.sort(reverse=False)
print(title)
print("Last message: {}".format(diff_time_from_now(last_time)))
print("\n- - - - - - - - - - - - - - -\n")
for key in range(min(count, len(sorted_keys))):
print(log[sorted_keys[key]])
print("\n- - - - - - - - - - - - - - -\n")
else:
print(title)
print()
print("There are no messages to display")
def diff_time_from_now(t):
diff = time.time() - t
diff = int(diff)
out = ""
if diff // 3600 > 0:
out += "{}h ".format(diff // 3600)
diff = diff - (diff // 3600 * 3600)
if diff // 60 > 0:
out += "{}m ".format(diff // 60)
diff = diff - (diff // 60 * 60)
out += "{}s ago".format(diff)
return out
def generate_output():
global files
for x in files:
read_file(x[0], x[1])
def add_message(msg):
user = os.environ.get('USER')
timestamp = str(time.time())
try:
with open("/home/{}/.gab".format(user), "a") as f:
f.write("{}|{}\n".format(timestamp, msg.strip()))
print("Successfully added text to chatlog")
except:
print("Error adding text to chatlog")
def parse_command():
args = sys.argv[1:]
if not len(args):
generate_output()
list_messages()
elif args[0] in ["-h", "--help", "help"]:
print(help_text)
elif args[0] in ["list", "--list", "-l"]:
if len(args) == 2:
generate_output()
list_messages(args[1])
else:
print("Invalid command input to 'list'")
elif args[0] in ["-m", "--msg", "msg"]:
if len(args) < 2:
print("Expected a message, but one was not received")
elif len(args) > 2:
print("Received too many arguments")
else:
add_message(args[1])
else:
print("Unknown command: {}".format(args[0]))
if __name__ == '__main__':
parse_command()