Skip to content

Instantly share code, notes, and snippets.

@primetoxinz
Last active December 31, 2016 22:55
Show Gist options
  • Save primetoxinz/c1bdd052322ede054ddcb6e9a3f1d2ea to your computer and use it in GitHub Desktop.
Save primetoxinz/c1bdd052322ede054ddcb6e9a3f1d2ea to your computer and use it in GitHub Desktop.
Simple commandline filesystem chat
import os
import argparse
import json
from datetime import datetime
from jose import jwt
parser = argparse.ArgumentParser()
parser.add_argument('--send', '-s',dest='message',nargs=1, help="give a message to write to the file")
parser.add_argument('--listen', '-l',action="store_true", help="listens to changes to the file")
parser.add_argument('--file', '-f',dest='file',nargs=1,default="filechat",help="destination for the send and listen file, defaults to ./filechat")
class Listener(object):
def __init__(self,filename):
self._cached_stamp = 0
self.filename = filename
def update(self):
stamp = os.stat(self.filename).st_mtime
if stamp != self._cached_stamp:
self._cached_stamp = stamp
lines = open(self.filename,"r").readlines()
#don't read if the file is empty
if not lines:
return
token = lines[-1].rstrip()
j = jwt.decode(token, 'secret', algorithms=['HS256'])
#simply time stamp
d = datetime.strptime(j['time'],'%Y-%m-%dT%H:%M:%S').strftime('%H:%M')
print(d + " : " + j['message'])
def setup():
opts = parser.parse_args()
#create file
if not os.path.exists(opts.file):
print("creating")
f= open(opts.file, "w").close()
if opts.message:
if authenticate():
send(opts.file, opts.message[0])
else:
print('Failed to Authenticate, are you an Admin?')
if opts.listen:
listen(opts.file)
def authenticate():
return True
def listen(filename):
l = Listener(filename)
while True:
l.update()
def send(file,message):
with open(file,"a") as f:
token = jwt.encode({'message': message, 'time':datetime.now().strftime('%Y-%m-%dT%H:%M:%S')}, 'secret', algorithm='HS256')
f.write(token+"\n")
if __name__ == "__main__":
setup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment