commit 07432b33c55391766360cd67ab8601fd42a95139 Author: sloumdrone Date: Sat Dec 15 11:31:35 2018 -0800 Finally adding to version control. Basics are working for viewing and adding topics diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6a91a43 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.sqlite \ No newline at end of file diff --git a/cspc.py b/cspc.py new file mode 100644 index 0000000..956fb71 --- /dev/null +++ b/cspc.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 + +import os +import sys +import sqlite3 as sql +import datetime, time +import subprocess + +class c: + black = '' + red = '\033[0;31m' + b_red = '\033[1;31m' + yellow = '\033[1;33m' + green = '\033[0;32m' + b_green = '\033[1;32m' + cyan = '\033[0;36m' + b_cyan = '\033[1;36m' + purple = '\033[1;35m' + blue = '\033[0;34m' + b_blue = '\033[1;34m' + white = '\033[1;37m' + end = '\033[0m' + +db_path = './cspc.sqlite' +userdir = os.path.expanduser('~') +user = os.path.split(userdir)[-1] +topic = None +post = None +available_ids = [] + + +def go_back(): + global post + global topic + + # If just viewed a post + if post and topic: + post = None + else: + post = None + topic = None + + +def get_prompt(): + if post: + ident = 'Post'.format(post) + elif topic: + ident = 'Posts'.format(topic) + else: + ident = 'Topics' + return '{}CSPC [{}{}{}] {}>{} '.format(c.yellow, c.white, ident, c.yellow, c.b_green, c.end) + + +def get_data(): + if post and topic: + # sql to view a post and its replies + pass + elif topic: + get_posts() + else: + get_topics() + + +def show_help(): + print('This is a help menu placeholder') + + +def make_add(): + action = False + if post and topic: + action = 'reply' + elif topic: + action = 'post' + else: + action = 'topic' + verify = input('{}Are you sure you would like to add a new {}{}{} (y/n)?{} '.format(c.cyan, c.b_blue, action, c.cyan, c.end)) + verify = verify.lower() + if verify in ['y','yes','yeah','yup','ya']: + add_new(action) + + +def add_new(a): + header = " 5 10 15 20 25 30 35 40 45 50\n ....|....|....|....|....|....|....|....|....|....|" + + title = None + body = None + + if not a == 'reply': + title = input('{}Enter the new {}s title:{} '.format(c.white, a, c.end)) + + content = [] + + if not a == 'topic': + print('{}Enter your content. To finish, enter a period as the only\ntext on its row.{}'.format(c.yellow, c.end)) + print(header) + + while True: + line = input('{}>{} '.format(c.green, c.end)) + if line == '.': + break + content.append(line) + + confirm = input('{}Submit the new {} (y/n)?{} '.format(c.white, a, c.end)) + if confirm.lower() in ['y','ya','yes','yeah']: + body = '\n'.join(content) + else: + print('{} not saved'.format(a)) + return False + + payload = {'title': title, 'body': body} + add_to_db(a, payload) + + +def parse_command(com): + global topic + global post + + comlist = ['add', 'help', 'quit', 'back'] + if com == 'back': + go_back() + elif com == 'help': + show_help() + elif com in ['quit', 'q', 'exit']: + sys.exit(0) + elif com == 'add': + make_add() + elif com == 'rm': + make_delete() + else: + try: + ident = int(com) + if not ident in available_ids: + print('{}ERROR: {} is not an available option!\n'.format(c.red, com, c.end)) + return False + if not topic: + topic = ident + elif not post: + post = ident + else: + print('{}A number command is not relevant right now...{}'.format(c.purple, c.end)) + except ValueError: + print('{}Input not recognized{}'.format(c.red, c.end)) + +#------- DB Related --------# + +def check_and_build_db(): + if not os.path.isfile(db_path): + conn = sql.connect(db_path) + c = conn.cursor() + + c.execute("CREATE TABLE data (topic_id INTEGER DEFAULT NULL, post_id INTEGER DEFAULT NULL, type text NOT NULL, title text DEFAULT NULL, body text DEFAULT NULL, author text NOT NULL, last_updated INTEGER NOT NULL)") + + conn.commit() + conn.close() + +def db_do(query, var=False, noresval=False): + if os.path.isfile(db_path): + conn = sql.connect(db_path) + c = conn.cursor() + if var: + c.execute(query, var) + else: + c.execute(query) + if noresval: + out = c.rowcount + else: + out = [] + for row in c: + out.append(row) + conn.commit() + conn.close() + return out + else: + print("{}ERROR:{} Database cannot be found or is corrupt".format(c.red, c.end)) + return False + + +def get_posts(): + global available_ids + global topic + available_ids = [] + q = "SELECT rowid, title, author, last_updated FROM data WHERE type = 'post' and topic_id = ? ORDER BY last_updated DESC" + v = (topic,) + res = db_do(q, v) + print('{}{:^6} | {:^35} | {:^12} | {:^18}{}'.format(c.yellow, 'ID', 'Post Title', 'Author', 'Last Updated', c.end)) + if not len(res): + print('{}There are no posts for this topic yet. Add one!{}'.format(c.cyan, c.end)) + else: + for row in res: + available_ids.append(row[0]) + dtime = datetime.datetime.utcfromtimestamp(row[3]).strftime('%Y-%m-%d %H:%M') + title = row[1] + if len(title) > 35: + title = '{}...'.format(title[:32]) + print('({:^4}) | {:35} | {:12} | {:18}'.format(row[0], title, row[2], dtime)) + return True + + +def get_topics(): + global available_ids + available_ids = [] + q = "SELECT title, last_updated, rowid FROM data WHERE type = 'topic' ORDER BY last_updated DESC" + res = db_do(q) + print('{}{:^6} | {:35} | {:18}{}'.format(c.yellow, 'ID', 'Topic Name', 'Last Updated', c.end)) + for row in res: + available_ids.append(row[2]) + dtime = datetime.datetime.utcfromtimestamp(row[1]).strftime('%Y-%m-%d %H:%M') + title = row[0] + if len(title) > 35: + title = '{}...'.format(title[:32]) + print('({:^4}) | {}{:35}{} | {:18}'.format(row[2], c.cyan, title, c.end, dtime)) + return True + + +def add_to_db(action, data): + update_time = int(time.time()) + q = "INSERT INTO data VALUES (?, ?, ?, ?, ?, ?, ?)" + v = (topic, post, action, data['title'], data['body'], user, update_time) + res = db_do(q, v, noresval=True) + if not res: + print("{}ERROR:{} There was an error adding your topic".format(c.red, c.end)) + return False + return True + +#------- Main loop --------# + +def mainloop(): + while True: + subprocess.run(['clear']) + print('{}Colorfield Space Bulletin Board{}\n\n'.format(c.b_blue, c.end)) + output = get_data() + # print the formatted data + print('') + command = input(get_prompt()) + print('') + if not command: + continue + parse_command(command) + + +if __name__ == '__main__': + check_and_build_db() + mainloop()