fuck databases

This commit is contained in:
deadvey 2025-03-31 08:20:24 +01:00
parent fea74df90c
commit a3914aab97
9 changed files with 132 additions and 87 deletions

3
.gitignore vendored
View File

@ -2,3 +2,6 @@ config.py
__pycache__ __pycache__
*.swp *.swp
log log
.git/
users.py
posts.py

View File

@ -9,7 +9,7 @@ mariadb-server
``` CREATE DATABASE glogger; ``` CREATE DATABASE glogger;
USE glogger; USE glogger;
CREATE TABLE users ( userID INT PRIMARY KEY AUTO_INCREMENT NOT NULL, username VARCHAR(255) ); CREATE TABLE users ( userID INT PRIMARY KEY AUTO_INCREMENT NOT NULL, username VARCHAR(255) );
CREATE TABLE posts ( postID INT PRIMARY KEY AUTO_INCREMENT NOT NULL, userID INT, FOREIGN KEY(userID) REFERENCES users(userID), title VARCHAR(255), content TEXT, pubDate VARCHAR(255), editDate VARCHAR(255) ); CREATE TABLE posts ( postID INT PRIMARY KEY AUTO_INCREMENT NOT NULL, userID INT, FOREIGN KEY(userID) REFERENCES users(userID), title VARCHAR(255), content VARCHAR(MAX), pubDate VARCHAR(255), editDate VARCHAR(255) );
``` ```
# TO DO # TO DO
* Add RSS and/or ATOM support * Add RSS and/or ATOM support

View File

@ -16,38 +16,47 @@
import config import config
import parse_post import parse_post
import output import output
import initialise
try:
import posts
except:
print("No posts database")
try:
import users
except:
print("No users database")
from datetime import datetime from datetime import datetime
def create_user_page(userID, username, db): def create_user_page(userID, username):
with open(f"{config.webroot}/user/{username}.gmi", "w") as userfile: try:
output.log("Writing posts to userfile") with open(f"{config.webroot}/user/{username}.gmi", "w") as userfile:
cursor = db.cursor() output.log("Writing posts to userfile")
cursor.execute(f"SELECT * FROM posts WHERE userID = {userID} ORDER BY postID Desc") userfile.write(f"# {username}:\n")
userfile.write(f"# {username}:\n") for post_index in range(len(posts.posts)-1,-1,-1):
for x in cursor: post_content = config.user_page_post_format
post = config.user_page_post_format post_content = parse_post.parse_post_format(post_content, post_index, username)
post = parse_post.parse_post_format(post, x, username) userfile.write(post_content)
userfile.write(post) except:
print(f"Unable to open {username}.gmi")
initialise.initialise()
def create_post_page(post, db): def create_post_page(post_index):
with open(f"{config.webroot}/post/{post[0]}.gmi", "w") as postfile: try:
output.log("Writing post to postfile") with open(f"{config.webroot}/post/{post_index}.gmi", "w") as postfile:
output.log(post) output.log("Writing post to postfile")
postfile_content = config.post_page_post_format output.log(posts.posts[post_index])
postfile_content = parse_post.parse_post_format(postfile_content, post, post[1]) postfile_content = config.post_page_post_format
postfile.write(postfile_content) postfile_content = parse_post.parse_post_format(postfile_content, post_index, users.users[posts.posts[post_index]["userID"]])
postfile.write(postfile_content)
except:
print(f"Unable to open {post_index}.gmi")
initialise.initialise()
def create_timeline(db): def create_timeline():
with open(f"{config.webroot}/index.gmi", "w") as timeline_file: with open(f"{config.webroot}/index.gmi", "w") as timeline_file:
output.log("Writing posts to timeline") output.log("Writing posts to timeline")
users = [] for current_post_index in range(len(posts.posts)-1,-1,-1):
cursor = db.cursor() username = users.users[posts.posts[current_post_index]["userID"]]
cursor.execute(f"SELECT userName FROM users")
for x in cursor:
users += x
cursor.execute(f"SELECT * FROM posts ORDER BY postID Desc LIMIT {config.posts_in_timeline}")
for x in cursor:
username = users[x[1]-1]
post = config.timeline_post_format post = config.timeline_post_format
post = parse_post.parse_post_format(post, x, username) post = parse_post.parse_post_format(post, current_post_index, username)
timeline_file.write(post) timeline_file.write(post)

View File

@ -5,12 +5,6 @@ date_format = "%d/%m/%Y at %H:%M" # The date that is displayed on the page
post_seperator = "---------------------------------------------" post_seperator = "---------------------------------------------"
posts_in_timeline = 100 posts_in_timeline = 100
### SQL settings ###
host = "localhost"
user = "username"
password = "password"
database = "glogger"
### Logging ### ### Logging ###
logfile = "/path/to/logfile" logfile = "/path/to/logfile"
verbose = False verbose = False

View File

@ -1,28 +1,22 @@
import mysql.connector import initialise
try:
import users
except:
print("No users database")
initialise.initialise()
import config import config
import newpost import newpost
import rebuild import rebuild
from datetime import datetime from datetime import datetime
db = mysql.connector.connect(
host=config.host,
user=config.user,
password=config.password,
database=config.database
)
cursor = db.cursor()
cursor.execute("SELECT * FROM users")
username = input("Username: ").lower() username = input("Username: ").lower()
# Check if this user exists # Check if this user exists
user_present = False user_present = False
for x in cursor: for current_user in range(len(users.users)):
if x[1] == username: if users.users[current_user] == username:
user_present = True user_present = True
userID = x[0] userID = current_user
if user_present == True: if user_present == True:
print('''What do you want to do? print('''What do you want to do?
1. Create (N)ew post 1. Create (N)ew post
@ -30,9 +24,8 @@ if user_present == True:
answer = input() answer = input()
if answer == 'N' or answer == '1': if answer == 'N' or answer == '1':
newpost.newpost(db, userID, username, datetime) newpost.newpost(userID, username, datetime)
if answer == 'R' or answer == '2': if answer == 'R' or answer == '2':
rebuild.rebuild(db) rebuild.rebuild()
else: else:
print('Sorry, that account does not exist, If it should, please ask the webadmin to add this account') print('Sorry, that account does not exist, If it should, please ask the webadmin to add this account')
db.commit()

35
initialise.py Normal file
View File

@ -0,0 +1,35 @@
import os
try:
import config
except:
print("You have no configuration file, please move example.config.py to config.py and modify the options to your usage")
exit()
def initialise():
# Create the posts db
try:
import posts
except:
with open("posts.py","w") as posts_db:
posts_db.write("posts = []")
# Create the users db
try:
import users
except:
users = []
print("What users do you want to have? You can always change this later by editing users.py (0 to finish)")
while True:
user_input = input()
if user_input == "0":
break
else:
users.append(user_input)
with open("users.py", "w") as users_db:
users_db.write(f"users = {users}")
# Create folders in the web directory
if not os.path.exists(f"{config.webroot}/post"):
os.makedirs(f"{config.webroot}/post")
if not os.path.exists(f"{config.webroot}/user"):
os.makedirs(f"{config.webroot}/user")
print("Successfully initialised Glogger")

View File

@ -18,7 +18,6 @@
# | editDate | varchar(255) | YES | | NULL | | # | editDate | varchar(255) | YES | | NULL | |
# +----------+--------------+------+-----+---------+----------------+ # +----------+--------------+------+-----+---------+----------------+
import mysql.connector
from datetime import datetime from datetime import datetime
import click # Used to write post content, it launches a text editor to type into import click # Used to write post content, it launches a text editor to type into
@ -26,20 +25,25 @@ import click # Used to write post content, it launches a text editor to type int
import create_pages import create_pages
import config import config
import rebuild import rebuild
try:
import posts
except:
print("No posts database")
try:
import users
except:
print("No users database")
import output
def newpost(db, userID, username, datetime): def newpost(userID, username, datetime):
title = input("Title: ") title = input("Title: ")
content = click.edit() content = click.edit()
content = content.replace("'", "&#39") content = content.replace("'", "&#39")
content = content.replace("\n", "\\n") content = content.replace("\n", "\n")
print(content) output.log(content)
datetime = datetime.now().strftime("%d%m%YZ%H%M%ST") datetime = datetime.now().strftime("%d%m%YZ%H%M%ST")
posts.posts.append({'userID': userID, 'title': title, 'content': content, 'pubdate': datetime, 'editdate': datetime})
with open("posts.py", "w") as posts_file:
posts_file.write(f"posts = {posts.posts}")
cursor = db.cursor() rebuild.rebuild()
cursor.execute(f"INSERT INTO posts (userID, title, content, pubDate, editDate) VALUES({userID}, '{title}', '{content}', '{datetime}', '{datetime}')")
cursor.execute(f"SELECT * FROM posts ORDER BY postID Desc LIMIT 1")
for x in cursor:
postID = x[0]
db.commit()
# Rebuild the config
rebuild.rebuild(db)

View File

@ -1,15 +1,17 @@
import config import config
from datetime import datetime from datetime import datetime
import posts
def parse_post_format(post, record, username): def parse_post_format(post, post_index, username):
post = post.replace("%S", config.post_seperator) post_data = posts.posts[post_index]
post = post.replace("%T", record[2]) post = post.replace("%S", config.post_seperator)
post = post.replace("%D", datetime.strptime(str(record[4]),"%d%m%YZ%H%M%ST").strftime(config.date_format)) post = post.replace("%T", post_data["title"])
post = post.replace("%E", datetime.strptime(str(record[5]),"%d%m%YZ%H%M%ST").strftime(config.date_format)) post = post.replace("%D", datetime.strptime(str(post_data["pubdate"]),"%d%m%YZ%H%M%ST").strftime(config.date_format))
post = post.replace("%C", record[3]) post = post.replace("%E", datetime.strptime(str(post_data["editdate"]),"%d%m%YZ%H%M%ST").strftime(config.date_format))
post = post.replace("%L", f"{config.site_url}/post/{record[0]}.gmi") post = post.replace("%C", post_data["content"])
post = post.replace("%U", f"{config.site_url}/user/{username}.gmi") post = post.replace("%L", f"{config.site_url}/post/{post_index}.gmi")
post = post.replace("%N", username) post = post.replace("%U", f"{config.site_url}/user/{username}.gmi")
post = post.replace("%N", username)
return post return post

View File

@ -1,11 +1,16 @@
import config import config
import create_pages import create_pages
def rebuild(db): try:
cursor = db.cursor() import users
cursor.execute('SELECT * FROM users') except:
for x in cursor: print("No users database")
create_pages.create_user_page(x[0], x[1], db) try:
create_pages.create_timeline(db) import posts
cursor.execute('SELECT posts.postID, users.username, posts.title, posts.content, posts.pubDate, posts.editDate FROM posts JOIN users ON posts.userID=users.userID') except:
for x in cursor: print("No posts database")
create_pages.create_post_page(x, db) def rebuild():
create_pages.create_timeline()
for current_user_index in range(len(users.users)):
create_pages.create_user_page(current_user_index, users.users[current_user_index])
for current_post_index in range(len(posts.posts)):
create_pages.create_post_page(current_post_index)