Commit b4a922a7 authored by Dominik Woiwode's avatar Dominik Woiwode
Browse files

Init pter 2.0

parent 4951e691
import datetime
import hashlib
import os
from enum import Enum
from pathlib import Path
from typing import Optional
import requests
NOT_APPROVED_SIGN = "*"
ATTACHEMENT_SIGN = "+"
FACHGRUPPENVOLLVERSAMMLUNG_SIGN = ">"
TEMPLATE_FOLDER = "templates"
class Template(Enum):
UNDEFINED = None
FINF = "pandoc.finf.tex"
FSR = "pandoc.fsr.tex"
TOPICS = "pandoc.topics.tex"
ATTACHEMENT = "pandoc.attachement.tex"
def fullPath(self):
return str(Path(os.path.join(TEMPLATE_FOLDER, self.value)).absolute())
# === Source Types ===
class SourceTypes:
def __init__(self, url: str):
self.url: str = url
def __repr__(self):
return f"{self.__class__.__name__}({self.url})"
def retrieveContent(self):
raise NotImplementedError()
class Etherpad(SourceTypes):
def retrieveContent(self):
url = f"{self.url}.txt"
response = requests.get(url)
return response.content.decode("utf-8")
class CodiMD(SourceTypes):
def retrieveContent(self):
url = f"{self.url}/download"
response = requests.get(url)
return response.content.decode("utf-8")
class LocalCache(SourceTypes):
def retrieveContent(self):
with open(self.url, "r", encoding="utf-8") as d:
return d.read()
# === Pad Types ===
class BasePad:
def __init__(self, source: SourceTypes, *_, rawPath=None, **kwargs):
self.source = source
self.metadata = kwargs
self.rawPath = rawPath or hashlib.md5(source.url.encode("utf-8"))
def __repr__(self):
return f"{self.__class__.__name__}({self.source})"
def download(self, path, override=True):
content = self.source.retrieveContent()
if not override and os.path.exists(path):
raise FileExistsError(f"{path} already exists!")
with open(path, "w", encoding="utf-8") as d:
d.write(content)
def compile(self, outFilePath, template: Template = None):
outPath = Path(outFilePath)
os.makedirs(outPath.parent, exist_ok=True)
metadataStr = " " + " ".join([f'-M {key}="{val}"' for key, val in self.metadata.items()])
templateStr = ""
if template is not None and template != Template.UNDEFINED:
templateStr = f' --template="{template.fullPath()}" '
cmd = f'pandoc "{self.rawPath}"{metadataStr}{templateStr}-o "{str(outPath.absolute())}"'
os.system(cmd)
class ProtocolPad(BasePad):
def __init__(self, source: SourceTypes, *_, date=None, isFachgruppenvollversammlung=False, isApproved=False):
super().__init__(source)
self.date = date
self.isApproved = isApproved
self.isFachgruppenvollversammlung = isFachgruppenvollversammlung
def __repr__(self):
return super(ProtocolPad, self).__repr__()[:-1] + f", {self.date})"
def sendMailAsApproved(self):
pass
def sendMailAsUnapproved(self):
pass
def uploadToCloud(self):
pass
def uploadToGrav(self):
pass
class AttachementPad(BasePad):
pass
class PadCollection(BasePad):
def __init__(self, source: SourceTypes):
super().__init__(source)
def getPads(self):
"""
Parsing the protocollink-Pad for urls.
"""
HTTPS = "https://"
pads = list()
for line in self.source.retrieveContent().split("\n"):
pad = self.parsePad(line)
if pad is None:
continue
pads.append(pad)
return pads
def parsePad(self, line) -> Optional[BasePad]:
url, *comment = line.split("#")
if not url.strip():
return None
prefixes, url = url.split("https://")
url = f"https://{url}"
url = url.strip()
if "/p/" in url:
retrieveClass = Etherpad
else:
retrieveClass = CodiMD
src = retrieveClass(url.strip())
isAttachement = ATTACHEMENT_SIGN in prefixes
isFachgrupenvollversammlung = FACHGRUPPENVOLLVERSAMMLUNG_SIGN in prefixes
isApproved = NOT_APPROVED_SIGN not in prefixes
kwargs = dict()
if isAttachement:
padType = AttachementPad
kwargs["date"] = None
kwargs["name"] = None
kwargs["version"] = None
kwargs["isApproved"] = isApproved
else:
padType = ProtocolPad
kwargs["isApproved"] = isApproved
try:
date = datetime.datetime.strptime(comment[0].strip(), "%d.%m.%Y")
except Exception:
dateStr = url.split("protokoll")[-1][:8]
date = datetime.datetime.strptime(dateStr, "%Y%m%d")
kwargs["date"] = date
kwargs["isFachgruppenvollversammlung"] = isFachgrupenvollversammlung
return padType(src, **kwargs)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description="Download and convert finf/fsr-protocols using pandoc")
parser.add_argument("-urls", nargs="+", type=str, default=[])
parser.add_argument("-pad", type=str, default=None)
# parser.add_argument("--prefixes", type=str, default="",
# help=f"Add additional information to pad:\n"
# f"Not approved: {NOT_APPROVED_SIGN}\n"
# f"Fachschaftenvollversammlung: {FACHSCHAFTENVERSAMMLUNG_SIGN}\n"
# f"Attachement: {ATTACHEMENT_SIGN}\n")
parser.add_argument("--finf", action="store_true")
parser.add_argument("--topics", action="store_true")
parser.add_argument("--fsr", action="store_true")
parser.add_argument("--download", action="store_true")
parser.add_argument("--ignoreOld", action="store_true")
parser.add_argument("--compile", action="store_true")
parser.add_argument("--attachementsOnly", action="store_true")
parser.add_argument("--newOnly", action="store_true")
parser.add_argument("--override", action="store_true")
parser.add_argument("--mail", action="store_true")
parsed = parser.parse_args()
urls = parsed.urls
if not urls and parsed.pad is None:
parser.print_usage()
exit()
if parsed.finf and parsed.fsr:
raise AttributeError("Cannot have --finf AND --fsr")
if parsed.finf:
DEFAULT_TYPE = "finf"
if parsed.fsr:
DEFAULT_TYPE = "fsr"
if parsed.override:
OVERRIDE_ACCEPTED = True
pads = getPadsFromCollectionPad(parsed.pad)
pads += [PadOld.fromURL(url, prefixes=parsed.prefixes) for url in urls]
if parsed.newOnly:
pads = [pad for pad in pads if not pad.approved]
if parsed.ignoreOld:
pads = [pad for pad in pads if not pad.isOldPad()]
if parsed.attachementsOnly:
pads = [pad for pad in pads if pad.isAttachement()]
if parsed.download:
downloadPads(pads)
# if parsed.topics:
# allPads(pads)
if parsed.compile:
compilePads(pads)
import tkinter as tk
import linkToPDF2 as pter
class ProtokollGUI(tk.Tk):
def __init__(self, rootPad:pter.SourceTypes):
super().__init__(screenName="ProtokollHelper")
self.rootPad = pter.PadCollection(rootPad)
print(self.rootPad.getPads())
self.folders = dict()
self.folderIndex = 0
self.folders = {
"MainFolder": self.rootPad.getPads()
}
self.topRow = tk.Frame(self)
self.topRow.pack(fill=tk.X, expand=True)
self.folderLabel = tk.Label(self.topRow)
self.leftButton = tk.Button(self.topRow, text="<", state=tk.DISABLED, command=self.updateFolderIndex(-1))
self.rightButton = tk.Button(self.topRow, text=">", command=self.updateFolderIndex(1))
self.leftButton.pack(side=tk.LEFT)
self.folderLabel.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.rightButton.pack(side=tk.LEFT)
self.padFrame = tk.Frame(self)
self.padFrame.pack()
self.updatePadFrame()
def updateFolderIndex(self, i):
def wrapper(*args,**kwargs):
self.folderIndex = (self.folderIndex + i) % len(self.folders)
self.updatePadFrame()
return wrapper
def updatePadFrame(self):
folderName = list(self.folders.keys())[self.folderIndex]
self.folderLabel.configure(text=folderName)
pads = self.folders[folderName]
for i, pad in enumerate(pads):
assert isinstance(pad, pter.ProtocolPad)
tk.Label(self.padFrame, text=pad.source.url,anchor=tk.W, bg="red").grid(row=i,column=0, sticky=tk.W) # URL
tk.Label(self.padFrame, text=pad.date,anchor=tk.W, bg="blue").grid(row=i,column=1) # Date
# Button Download
btnDownload = tk.Button(self.padFrame, text="Download")
btnDownload.grid(row=i, column=2)
# Button Compile
btnCompile = tk.Button(self.padFrame, text="Compile")
btnCompile.grid(row=i, column=3)
# Button Mail FR
btnMailFR = tk.Button(self.padFrame, text="Vorläufige FR-Mail")
btnMailFR.grid(row=i, column=4)
# Button Mail FR-Info
btnMailFRInfo = tk.Button(self.padFrame, text="FR-Info Mail", state=tk.DISABLED)
btnMailFRInfo.grid(row=i, column=5)
# Button Website
btnWebsite = tk.Button(self.padFrame, text="Approved Website", state=tk.DISABLED)
btnWebsite.grid(row=i, column=6)
# Button Cloud
btnCloud = tk.Button(self.padFrame, text="Approved Cloud", state=tk.DISABLED)
btnCloud.grid(row=i, column=7)
if __name__ == '__main__':
gui = ProtokollGUI(pter.LocalCache("data/rootPad.md"))
gui.mainloop()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment