Editor field & cookie working for survex online edits

This commit is contained in:
2024-12-27 22:57:34 +00:00
parent 60d24dc48e
commit 8dbad16ece
4 changed files with 55 additions and 20 deletions

View File

@@ -42,7 +42,7 @@ Read this now: https://nerderati.com/a-python-epoch-timestamp-timezone-trap/
TROG = {"pagecache": {"expedition": {}}, "caves": {"gcavelookup": {}, "gcavecount": {}}}
alphabet = []
sha = hashlib.new('sha256')
COOKIE_MAX_AGE = 12*60*60 # seconds
throw = 35.0
class DatabaseResetOngoing(Exception):
@@ -191,22 +191,31 @@ def parse_aliases(aliasfile):
return [(None, None)], "Fail on file reading"
return aliases, report
def only_commit(fname, message):
def only_commit(fname, message, editor=None):
"""Only used to commit a survex file edited and saved in view/survex.py"""
git = settings.GIT
cwd = fname.parent
filename = fname.name
# print(f'{fname=} ')
if editor:
editor = git_string(editor)
else:
# cannot happen as form verification has this as an obligatory field
editor = "Anathema Device <a.device@potatohut.expo>"
try:
print(f"git add {filename}")
cp_add = subprocess.run([git, "add", filename], cwd=cwd, capture_output=True, text=True)
if cp_add.returncode != 0:
msgdata = f"Ask a nerd to fix this problem in only_commit().\n--{cp_add.stderr}\n--{cp_add.stdout}\n--return code:{str(cp_add.returncode)}"
raise WriteAndCommitError(
f"CANNOT git ADD on server for this file {filename}. Edits saved but not added to git.\n\n" + msgdata
)
cp_commit = subprocess.run([git, "commit", "-m", message], cwd=cwd, capture_output=True, text=True)
print(f"git commit {filename}")
print(f"Committing:\n{message=}\n{editor=}")
cmd_commit = [git, "commit", "-m", message, "--author", f"{editor}"]
cp_commit = subprocess.run(cmd_commit, cwd=cwd, capture_output=True, text=True)
# This produces return code = 1 if it commits OK, but when the local repo still needs to be pushed to origin/loser
# which will be the case when running a test troggle system on a development machine
devok_text = """On branch master
@@ -229,9 +238,10 @@ nothing to commit, working tree clean
)
except subprocess.SubprocessError:
raise WriteAndCommitError(
f"CANNOT git COMMIT on server for this file {filename}. Subprocess error. Edits not saved.\nAsk a nerd to fix this."
)
msg = f"CANNOT git COMMIT on server for this file {filename}. Subprocess error. Edits not saved.\nAsk a nerd to fix this."
print(msg)
raise WriteAndCommitError(msg)
def git_string(author_string):
"""Rewrites the supplied editor string intoa git-complient author string

View File

@@ -14,7 +14,7 @@ from django.views.decorators.csrf import ensure_csrf_cookie
import troggle.core.views.caves
import troggle.settings as settings
from troggle.core.models.caves import Cave
from troggle.core.utils import WriteAndCommitError, current_expo, git_string, write_and_commit
from troggle.core.utils import COOKIE_MAX_AGE, WriteAndCommitError, current_expo, git_string, write_and_commit
from troggle.core.views.editor_helpers import HTMLarea
from troggle.core.views.uploads import edittxtpage
@@ -26,7 +26,7 @@ Then it was incorporated into troggle directly, rather than being an unnecessary
This is a succession of hacks and needs to be redisgned and refactored.
"""
COOKIE_MAX_AGE = 12*60*60 # seconds
default_head = """<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>CUCC Expedition - index</title>

View File

@@ -19,7 +19,7 @@ from troggle.core.models.caves import Cave, GetCaveLookup
from troggle.core.models.logbooks import LogbookEntry
from troggle.core.models.survex import SurvexBlock, SurvexFile #, SurvexDirectory
from troggle.core.models.wallets import Wallet
from troggle.core.utils import current_expo, only_commit
from troggle.core.utils import COOKIE_MAX_AGE, current_expo, git_string, only_commit
from troggle.parsers.survex import parse_one_file
"""Everything that views survexfiles
@@ -43,7 +43,7 @@ todo = """
SVXPATH = Path(settings.SURVEX_DATA)
# NB this template text must be identical to that in :loser:/templates/template.svx
survextemplatefile = """; *** THIS IS A TEMPLATE FILE NOT WHAT YOU MIGHT BE EXPECTING ***
survextemplatefile = """; *** THIS IS A TEMPLATE FILE - NOT WHAT YOU MIGHT BE EXPECTING ***
*** DO NOT SAVE THIS FILE WITHOUT RENAMING IT !! ***
;[Stuff in square brackets is example text to be replaced with real data,
@@ -152,6 +152,12 @@ class SvxForm(forms.Form):
datetime = forms.DateTimeField(widget=forms.TextInput(attrs={"readonly": True}))
outputtype = forms.CharField(widget=forms.TextInput(attrs={"readonly": True}))
code = forms.CharField(widget=forms.Textarea(attrs={"cols": 140, "rows": 36}))
who_are_you = forms.CharField(
widget=forms.TextInput(
attrs={"size": 100, "placeholder": "You are editing this page, who are you ? e.g. 'Animal <mta@gasthof.expo>'",
"style": "vertical-align: text-top;"}
)
)
survexfile = models.ForeignKey(SurvexFile, blank=True, null=True, on_delete=models.SET_NULL) # 1:1 ?
template = False
@@ -187,7 +193,7 @@ class SvxForm(forms.Form):
difflist = [diffline.strip() for diffline in difftext if not re.match(r"\s*$", diffline)]
return difflist
def SaveCode(self, rcode):
def SaveCode(self, rcode, editor):
fname = SVXPATH / (self.data["filename"] + ".svx")
if not fname.is_file():
if re.search(r"\[|\]", rcode):
@@ -214,7 +220,7 @@ class SvxForm(forms.Form):
"CANNOT save this file.\nPERMISSIONS incorrectly set on server for this file. Ask a nerd to fix this."
)
# javascript seems to insert CRLF on WSL1 whatever you say. So fix that:
# HTML forms standard behaviour is to insert CRLF whatever you say. So fix that:
fout.write(rcode.replace("\r", ""))
fout.write("\n")
fout.close()
@@ -223,9 +229,10 @@ class SvxForm(forms.Form):
comment = f"Online survex edit: {self.data['filename']}.svx"
else:
comment = f"Online survex edit: {self.data['filename']}.svx on dev machine '{socket.gethostname()}' "
only_commit(fname, comment)
print(f"Committing file which has been saved {editor=}")
only_commit(fname, comment, editor)
msg = "SAVED and committed to git (if there were differences)"
msg = f"SAVED and committed to git (if there were differences)\nEdited by:{editor}"
# should only call this is something changed
if parse_one_file(self.data["filename"]):
return msg
@@ -284,6 +291,8 @@ def svx(request, survex_file):
Needs refactoring. Too many piecemeal edits and odd state dependencies.
Why is all the action code in this Class ?! Confusing..
On Get does the SAME THING as svxcavesingle but is called when the .svx suffix is MISSING
"""
warning = False
@@ -299,7 +308,13 @@ def svx(request, survex_file):
dirname += "/"
nowtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
outputtype = "normal"
form = SvxForm({"filename": survex_file, "dirname": dirname, "datetime": nowtime, "outputtype": outputtype})
print(f"Reading cookie...")
editor_id = request.COOKIES.get('editor_id', 'speleologist') # if no cookie, then default string
editor = git_string(editor_id) # belt and braces, should have been validity checked on saving already
print(f"Cookie read: {editor_id=} reformatted as: {editor=}")
form = SvxForm({"filename": survex_file, "dirname": dirname, "datetime": nowtime, "outputtype": outputtype, "who_are_you":editor})
# if the form has been returned
difflist = []
@@ -309,6 +324,7 @@ def svx(request, survex_file):
if request.method == "POST": # If the form has been submitted...
rform = SvxForm(request.POST) #
if rform.is_valid(): # All validation rules pass (how do we check it against the filename and users?)
editor = rform.cleaned_data["who_are_you"]
rcode = rform.cleaned_data["code"]
outputtype = rform.cleaned_data["outputtype"] # used by CodeMirror ajax I think
difflist = form.DiffCode(rcode)
@@ -335,7 +351,9 @@ def svx(request, survex_file):
if "save" in rform.data:
if request.user.is_authenticated:
if difflist:
message = form.SaveCode(rcode)
editor = rform.cleaned_data["who_are_you"]
print(f"Saving code and editor id {editor=}")
message = form.SaveCode(rcode, editor)
else:
message = "NO DIFFERENCES - so not saving the file"
else:
@@ -395,6 +413,7 @@ def svx(request, survex_file):
events = events_on_dates(svxblocks)
year = year_for_svx(svxblocks)
form.data['who_are_you'] = editor
vmap = {
"year": year,
"settings": settings,
@@ -412,9 +431,14 @@ def svx(request, survex_file):
}
if outputtype == "ajax": # used by CodeMirror ajax I think
return render(request, "svxfiledifflistonly.html", vmap)
edit_response = render(request, "svxfiledifflistonly.html", vmap)
else:
edit_response = render(request, "svxfile.html", vmap)
edit_response.set_cookie('editor_id', editor, max_age=COOKIE_MAX_AGE) # cookie expires after COOKIE_MAX_AGE seconds
print(f"Cookie reset: {editor} for another {COOKIE_MAX_AGE/3600} hours")
return render(request, "svxfile.html", vmap)
return edit_response
SameDateEvents = namedtuple('SameDateEvents', ['trips', 'svxfiles', 'wallets', 'blocks'])

View File

@@ -54,6 +54,7 @@ $(document).ready(function()
<form id="codewikiform" action="" method="POST">{% csrf_token %}
<div class="codeframebit">{{form.code}}</div>
<div>Who are you? {{form.who_are_you}}</div>
<div style="display:none">{{form.filename}} {{form.dirname}} {{form.datetime}} {{form.outputtype}}</div>
<input type="submit" name="diff" value="Differences between edited and saved versions of this file" />
<input type="submit" name="save" value="Save this edited svx file"/>