Writing new site in DB, Management page

This commit is contained in:
octospacc 2022-06-17 21:03:31 +02:00
parent 0b93d4da0a
commit 9b6a7718f4
8 changed files with 163 additions and 38 deletions

Binary file not shown.

View File

@ -1,4 +1,3 @@
{ {
"Development": true, "Development": true
"Port": 8080
} }

View File

@ -4,8 +4,12 @@
"DoDelete": "Delete", "DoDelete": "Delete",
"DoReply": "Reply", "DoReply": "Reply",
"Reply": "Reply", "Reply": "Reply",
"SecretKey": "Secret Key", "SecKey": "Secret Key",
"Optional": "Optional", "Optional": "Optional",
"YourName": "Your Name", "YourName": "Your Name",
"DoPost": "Post as New Comment" "DoPost": "Post as New Comment",
"Management": "Management",
"AddSite": "Add New Site",
"DelSite": "DELETE SITE",
"DangerZone": "Danger Zone"
} }

View File

@ -4,8 +4,12 @@
"DoDelete": "Cancella", "DoDelete": "Cancella",
"DoReply": "Rispondi", "DoReply": "Rispondi",
"Reply": "Risposta", "Reply": "Risposta",
"SecretKey": "Chiave Segreta", "SecKey": "Chiave Segreta",
"Optional": "Opzionale", "Optional": "Opzionale",
"YourName": "Il tuo Nome", "YourName": "Il tuo Nome",
"DoPost": "Pubblica come Nuovo Commento" "DoPost": "Pubblica come Nuovo Commento",
"Management": "Gestione",
"AddSite": "Aggiungi Nuovo Sito",
"DelSite": "CANCELLA SITO",
"DangerZone": "Zona Pericolosa"
} }

View File

@ -6,7 +6,14 @@
</style> </style>
</head> </head>
<body> <body>
<form action="/Comments" method="POST"> <div id="StatusGoodDiv">
{StatusGood}
</div>
<div id="StatusErrorDiv">
{StatusError}
</div>
<form action="/Comments" method="POST">
<input type="hidden" name="Lang" value="{Lang}">
{Form} {Form}
</form> </form>
</body> </body>

View File

@ -4,8 +4,8 @@
</div> </div>
<br> <br>
<div> <div>
<label>[Locale:SecretKey] ([Locale:Optional]):</label> <label>[Locale:SecKey] ([Locale:Optional]):</label>
<span><input type="password" name="SecretKey"></span> <span><input type="password" name="SecKey" value="{SecKey}"></span>
</div> </div>
<br> <br>
<div> <div>
@ -14,12 +14,12 @@
</div> </div>
<br> <br>
<div> <div>
<label>[Locale:YourName]</label> <label>[Locale:YourName]:</label>
<span><input type="text" name="User"></span> <span><input type="text" name="User" value="{User}"></span>
</div> </div>
<br> <br>
<div> <div>
<label>Reply:</label> <label>Reply:</label>
<button type="submit" name="Action" value="Post">[Locale:DoPost]</button> <button type="submit" name="Action" value="Post">[Locale:DoPost]</button>
<textarea name="Comment"></textarea> <textarea name="Comment">{Comment}</textarea>
</div> </div>

View File

@ -1,6 +1,31 @@
<html> <html>
<head> <head>
<link rel="stylesheet" href="Main.css">
</head> </head>
<body> <body>
<h3>PlainDiscuss > [Locale:Management]</h3>
<div id="StatusGoodDiv">
{StatusGood}
</div>
<div id="StatusErrorDiv">
{StatusError}
</div>
<form action="/Manage" method="POST">
<input type="hidden" name="Lang" value="{Lang}">
<div>
<button type="submit" name="Action" value="AddSite">[Locale:AddSite]</button>
</div>
<br>
<div>
<details>
<summary>[Locale:DangerZone]</summary>
<p>Are you sure? This will delete ALL comments from the Database! THERE IS NO GOING BACK!</p>
<label>[Locale:SecKey]:</label>
<span><input type="password" name="SecKey"></span>
<br><br>
<button type="submit" name="Action" value="DelSite">[Locale:DelSite]</button>
</details>
</div>
</form>
</body> </body>
</html> </html>

View File

@ -7,6 +7,7 @@
| =============================== """ | =============================== """
import json import json
import secrets
import sqlite3 import sqlite3
import time import time
from ast import literal_eval from ast import literal_eval
@ -41,11 +42,18 @@ def GetLocales():
Locales.update({Lang:Locale}) Locales.update({Lang:Locale})
return Locales return Locales
def SelectLocale(Data):
if Data['Lang'] and Data['Lang'] in Locales:
return Locales[Data['Lang']]
else:
return Locales[Config['Default Locale']]
def GetConfig(): def GetConfig():
Config = { Config = {
'Development': False, 'Development': False,
'Port': 8080, 'Port': 8080,
'Default Locale': 'en'} 'Default Locale': 'en',
'Antispam Time': 0}
File = ReadFile('Config.json') File = ReadFile('Config.json')
if File: if File:
File = json.loads(File) File = json.loads(File)
@ -60,7 +68,8 @@ def InitDB():
DB.commit() DB.commit()
def GetDB(): def GetDB():
return sqlite3.connect('Comments.db') DB = sqlite3.connect('Comments.db')
return DB
def GetComments(Site, Page): def GetComments(Site, Page):
DB = GetDB() DB = GetDB()
@ -69,24 +78,26 @@ def GetComments(Site, Page):
PageID = DB.cursor().execute('SELECT "ID" FROM "Pages" WHERE "Site" == "{}" AND "Path" == "{}"'.format(SiteID, Page)) PageID = DB.cursor().execute('SELECT "ID" FROM "Pages" WHERE "Site" == "{}" AND "Path" == "{}"'.format(SiteID, Page))
Comments = DB.cursor().execute('SELECT * FROM "Comments" WHERE "Page" == "{}"'.format(PageID)) Comments = DB.cursor().execute('SELECT * FROM "Comments" WHERE "Page" == "{}"'.format(PageID))
DB.close() DB.commit()
return Comments return Comments
def PatchHTML(Data): def PatchCommentsHTML(Data):
FormBase = ReadFile('Source/Form.Base.html') FormBase = ReadFile('Source/Form.Base.html')
FormMain = ReadFile('Source/Form.Main.html') FormMain = ReadFile('Source/Form.Main.html')
FormComment = ReadFile('Source/Form.Comment.html') FormComment = ReadFile('Source/Form.Comment.html')
if Data['Lang'] and Data['Lang'] in Locales: Locale = SelectLocale(Data)
Locale = Locales[Data['Lang']]
else:
Locale = Locales[Config['Default Locale']]
for String in Locale: for String in Locale:
FormBase = FormBase.replace('[Locale:{}]'.format(String), Locale[String]) FormBase = FormBase.replace('[Locale:{}]'.format(String), Locale[String])
FormMain = FormMain.replace('[Locale:{}]'.format(String), Locale[String]) FormMain = FormMain.replace('[Locale:{}]'.format(String), Locale[String])
FormComment = FormComment.replace('[Locale:{}]'.format(String), Locale[String]) FormComment = FormComment.replace('[Locale:{}]'.format(String), Locale[String])
FormMain = FormMain.format(
SecKey=Data['SecKey'] if Data['SecKey'] else '',
User=Data['User'] if Data['User'] else '',
Comment=Data['Comment'] if Data['Comment'] else '')
Comments = '' Comments = ''
for Comment in GetComments(Data['Site'], Data['Page']): for Comment in GetComments(Data['Site'], Data['Page']):
Comments += "\n<hr>\n" + FormComment.format( Comments += "\n<hr>\n" + FormComment.format(
@ -95,43 +106,118 @@ def PatchHTML(Data):
ID="ID", ID="ID",
Comment="Comment") Comment="Comment")
return FormBase.format(Style='',Form=FormMain+Comments) return FormBase.format(
Lang=Data['Lang'] if Data['Lang'] else '',
Style='',
Site=Data['Site'] if Data['Site'] else '',
Page=Data['Page'] if Data['Page'] else '',
Form=FormMain+Comments,
StatusGood='',
StatusError='')
def Get(Req): def CommentsGet(Req):
Data = {} Data = {}
for i in ['Lang','StyleFile','Site','Page']: for i in ['Lang','StyleFile','Site','Page']:
Data.update({i:Req.args.get(i)}) Data.update({i:Req.args.get(i)})
return PatchHTML(Data) return PatchCommentsHTML(Data)
def Post(Req): def CommentsPost(Req):
Data = {} Data = {}
for i in ['Lang','StyleFile','Site','Page','User','CAPTCHA','Comment','SecretKey','Action','Reply','Report','Delete']: for i in ['Lang','StyleFile','Site','Page','User','CAPTCHA','Comment','SecKey','Action','Reply','Report','Delete']:
Data.update({i:Req.args.get(i)}) Data.update({i:Req.form.get(i)})
return PatchHTML(Data) return PatchCommentsHTML(Data)
@App.route('/Manage.html')
def SendManage():
return send_file('Manage.html')
@App.route('/Main.css')
def SendCSS():
return send_file('Main.css')
@App.route('/Comments', methods=['GET', 'POST']) @App.route('/Comments', methods=['GET', 'POST'])
def Comments(): def Comments():
Req = request Req = request
if Req.method == 'GET': if Req.method == 'GET':
return Get(Req) return CommentsGet(Req)
if Req.method == 'POST': if Req.method == 'POST':
return Post(Req) return CommentsPost(Req)
@App.route('/Main.css')
def SendCSS():
return send_file('Main.css')
def AddSite():
PubKey = secrets.token_urlsafe(32)
SecKey = secrets.token_urlsafe(64)
Good, Error = "", ""
try:
DB = GetDB()
DB.cursor().execute('INSERT INTO "Sites"("PubKey", "SecKey") VALUES("{}", "{}")'.format(PubKey, SecKey))
DB.commit()
Good = """\
<p>
Created your new site API keys. Please store these safely, they can't be recovered.
<br><br>
Public Key (for showing comments on your site): <pre>{}</pre>
Secret Key (for managing comments, KEEP IT SECRET): <pre>{}</pre>
</p>""".format(PubKey, SecKey)
except Exception:
Error = "<p>Server error. Please try again later.</p>"
return Good, Error
def DelSite():
pass
def PatchManageHTML(Data):
HTML = ReadFile('Source/Manage.html')
Locale = SelectLocale(Data)
for String in Locale:
HTML = HTML.replace('[Locale:{}]'.format(String), Locale[String])
if 'Action' in Data and Data['Action']:
if Data['Action'] == 'AddSite':
Good, Error = AddSite()
elif Data['Action'] == 'DelSite':
Good, Error = DelSite()
else:
Good, Error = '', ''
return HTML.format(
Lang=Data['Lang'] if Data['Lang'] else '',
StatusGood=Good,
StatusError=Error)
"""
def ManageGet(Req):
Data = {}
for i in ['Lang']:
Data.update({i:Req.args.get(i)})
return PatchManageHTML(Data)
def ManagePost(Req):
Data = {}
for i in ['Lang', 'Action']:
Data.update({i:Req.form.get(i)})
return PatchManageHTML(Data)
"""
@App.route('/Manage', methods=['GET', 'POST'])
def SendManage():
Req = request
Data = {}
if Req.method == 'GET':
#return ManageGet(Req)
for i in ['Lang']:
Data.update({i:Req.args.get(i)})
elif Req.method == 'POST':
#return ManagePost(Req)
for i in ['Lang', 'Action']:
Data.update({i:Req.form.get(i)})
return PatchManageHTML(Data)
if __name__ == '__main__': if __name__ == '__main__':
Locales = GetLocales() Locales = GetLocales()
Config = GetConfig() Config = GetConfig()
#DB = sqlite3.connect('Comments.db')
DB = GetDB() DB = GetDB()
InitDB() InitDB()
DB.close() #DB.close()
if Config['Development']: if Config['Development']:
App.run(host='0.0.0.0', port=Config['Port'], debug=True) App.run(host='0.0.0.0', port=Config['Port'], debug=True)