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

188 lines
5.7 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\n-b, --block, block A username to block/ignore\n-u, --unblock, unblock A username to unblock/unignore"
title = "\033[1mGAB v2.1\033[0m"
def blocked_users():
current_user = os.environ.get('USER')
fp = "/home/{}/.gab_block".format(current_user)
if not os.path.isfile(fp):
return []
with open(fp, 'r') as blockfile:
return blockfile.read().split("\n")
files = [[x, "/home/{}/.gab".format(x)] for x in os.listdir("/home/") if x not in blocked_users()]
log = {}
def read_file(user, path, num_lines):
global log
if os.path.isfile(path):
with open(path, "r") as f:
for line in range(num_lines):
msg = f.readline().split("|", 1)
dt = msg[0].strip()
if len(msg) == 2 and float(dt) < time.time():
log[dt] = "\033[7m {} \033[0m {}\033[0m".format(user, msg[1].strip())
def list_messages(count="5"):
global log
global files
try:
count = int(count)
except ValueError:
print("Error parsing list number, using default: 5")
count = 5
for x in files:
read_file(x[0], x[1], count)
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- - -")
for key in range(min(count, len(sorted_keys))):
print(log[sorted_keys[key]])
print("- - -")
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 add_message(msg):
user = os.environ.get('USER')
timestamp = str(time.time())
output = "{}|{}\n".format(timestamp, msg.strip())
fp = "/home/{}/.gab".format(user)
try:
with open(fp, 'r') as original:
data = original.read(12000)
with open(fp, 'w') as modified:
modified.write(output)
modified.write(data)
except FileNotFoundError:
with open(fp, 'a') as modified:
modified.write(output)
except:
print("Error adding text to chatlog")
return
print("Successfully added text to chatlog")
try:
os.chmod(fp, 0o644)
except PermissionError:
print("You do not have permission to modify the chatlog")
except FileNotFoundError:
print("The chatlog does not exist")
def block_user(user_to_block):
current_user = os.environ.get('USER')
fp = "/home/{}/.gab_block".format(current_user)
block_fp = "/home/{}/".format(user_to_block)
if not os.path.isdir(block_fp):
print("User '{}' does not exist, no action taken".format(user_to_block))
return
with open(fp, 'a') as blockfile:
blockfile.write(user_to_block)
blockfile.write("\n")
print("User '{}' has been blocked, you will not see their messages".format(user_to_block))
return
def unblock_user(user_to_unblock):
current_user = os.environ.get('USER')
fp = "/home/{}/.gab_block".format(current_user)
unblock_fp = "/home/{}/".format(user_to_unblock)
if not os.path.isfile(fp):
print("You do not have any users on your block list, no action taken")
return
if not os.path.isdir(unblock_fp):
print("User '{}' does not exist, no action taken".format(user_to_unblock))
return
blocked_users_list = [x for x in blocked_users() if x != user_to_unblock]
with open(fp, 'w') as blocked:
blocked.write("\n".join(blocked_users_list))
print("User '{}' has been removed from your block list".format(user_to_unblock))
def parse_command():
args = sys.argv[1:]
if not len(args):
list_messages()
elif args[0] in ["-h", "--help", "help"]:
print(help_text)
elif args[0] in ["list", "--list", "-l"]:
if len(args) == 2:
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])
elif args[0] in ["-b", "--block", "block"]:
if len(args) < 2:
print("Expected a user to block, but one was not received")
elif len(args) > 2:
print("Received too many arguments")
else:
block_user(args[1])
elif args[0] in ["-u", "--unblock", "unblock"]:
if len(args) < 2:
print("Expected a user to block, but one was not received")
elif len(args) > 2:
print("Received too many arguments")
else:
unblock_user(args[1])
else:
print("Unknown command: {}".format(args[0]))
if __name__ == '__main__':
parse_command()