Allow for printing session results.

This commit is contained in:
Christopher T. Johnson
2023-12-13 10:49:05 -05:00
parent 12595771b6
commit a03289db51
7 changed files with 361 additions and 20 deletions

View File

@@ -1,7 +1,14 @@
import json
import os
import secrets
import smtplib
from datetime import datetime, timedelta
from email import policy
from email.message import EmailMessage
from html.parser import HTMLParser
from io import StringIO
from PyQt6.QtCore import QSize, Qt, pyqtSlot
from PyQt6.QtCore import QResource, QSize, Qt, pyqtSlot
from PyQt6.QtGui import QStandardItem, QStandardItemModel
from PyQt6.QtSql import QSqlQuery, QSqlQueryModel
from PyQt6.QtWidgets import QDialog, QDialogButtonBox, QStyledItemDelegate
@@ -10,6 +17,66 @@ from main import query_error
from ui.PeopleDialog import Ui_Dialog
class blockHandler(HTMLParser):
text = ""
blocks = []
active = 0
tags = [
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"p",
"b",
"i",
"em",
"st",
"span",
]
space = ["b", "i", "em", "st", "span"]
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs = True
self.text = ""
self.blocks = []
self.active = 0
return
def handle_starttag(self, tag, attrs):
if not tag in self.tags:
return
self.active += 1
if tag in self.space:
self.text += " "
self.text += f"<{tag}>"
return
def handle_endtag(self, tag):
if not tag in self.tags:
return
self.active -= 1
self.text += f"</{tag}>"
if tag in self.space:
self.text += " "
if self.active <= 0:
self.blocks.append(self.text)
self.text = ""
self.active = 0
return
def handle_data(self, data):
self.text += data
return
def get_block(self, block):
return self.blocks[block]
class MLStripper(HTMLParser):
def __init__(self):
super().__init__()
@@ -45,6 +112,9 @@ class PersonDialog(QDialog, Ui_Dialog):
super(PersonDialog, self).__init__(*args, **kwargs)
self.setupUi(self)
self.show()
QResource.registerResource(
os.path.join(os.path.dirname(__file__), "../ui/resources.rcc"), "/"
)
model = QSqlQueryModel()
query = QSqlQuery()
query.prepare("SELECT book_id, title " "FROM books " "ORDER BY title")
@@ -60,7 +130,8 @@ class PersonDialog(QDialog, Ui_Dialog):
self.sectionCombo.setModel(model)
self.sectionCombo.setEnabled(False)
self.sectionCombo.setCurrentIndex(-1)
self.printBtn.setEnabled(False)
self.emailBtn.setEnabled(False)
button = self.buttonBox.button(QDialogButtonBox.StandardButton.Ok)
button.setEnabled(False)
@@ -71,6 +142,8 @@ class PersonDialog(QDialog, Ui_Dialog):
self.sectionCombo.currentIndexChanged.connect(self.sectionSelected)
self.nameEdit.editingFinished.connect(self.checkLineEdits)
self.orgEdit.editingFinished.connect(self.checkLineEdits)
self.printBtn.clicked.connect(self.senditAction)
self.emailBtn.clicked.connect(self.senditAction)
if self.person_id > 0:
self.setPerson(self.person_id)
return
@@ -78,7 +151,7 @@ class PersonDialog(QDialog, Ui_Dialog):
def setPerson(self, person_id: int) -> None:
query = QSqlQuery()
query.prepare(
"SELECT p.name, p.organization, p.book_id, s.sequence "
"SELECT p.name, p.organization, p.book_id, p.email, s.sequence "
"FROM people p "
"LEFT JOIN person_book pb "
"ON (p.book_id = pb.book_id "
@@ -95,6 +168,7 @@ class PersonDialog(QDialog, Ui_Dialog):
self.person_id = person_id
self.nameEdit.setText(query.value("name"))
self.orgEdit.setText(query.value("organization"))
self.emailEdit.setText(query.value("email"))
model = self.bookCombo.model()
matches = model.match(
model.createIndex(0, 0),
@@ -104,12 +178,58 @@ class PersonDialog(QDialog, Ui_Dialog):
Qt.MatchFlag.MatchExactly,
)
if len(matches) != 1:
raise Excpetion(
raise Exception(
f"Match failed looking for book_id: {query.value('book_id')}"
)
row = int(matches[0].row())
self.bookCombo.setCurrentIndex(row)
self.sectionCombo.setCurrentIndex(query.value("sequence"))
query.prepare(
"SELECT * FROM sessions "
"WHERE person_id = :person_id "
"ORDER BY start DESC"
)
query.bindValue(":person_id", person_id)
if not query.exec():
query_error(query)
model = QSqlQueryModel()
model.setQuery(query)
self.sessionCombo.setModel(model)
self.sessionCombo.setModelColumn(2)
self.printBtn.setEnabled(True)
self.emailBtn.setEnabled(True)
return
@pyqtSlot()
def senditAction(self) -> None:
html = "<!DOCTYPE html>\n<html><head><title>Hello</title>\n"
html += (
'<style type="text/css">\n'
+ QResource(":email.css").data().decode("utf-8")
+ "</style>\n"
)
html += "</head><body>\n"
html += self.makeDefinitions()
html += self.makeText()
html += "</body>\n</html>\n"
if self.sender() == self.printBtn:
print(html)
return
msg = EmailMessage(policy=policy.default)
start = datetime.fromisoformat(self.sessionCombo.currentText())
msg["Subject"] = f"TT English, Session: {start.date().isoformat()}"
msg["From"] = "Christopher T. Johnson <cjohnson@troglodite.com>"
msg["To"] = self.emailEdit.text().strip()
msg.set_content("There is a html message you should read")
msg.add_alternative(html, subtype="html")
server = smtplib.SMTP(secrets.SMTP_HOST, secrets.SMTP_PORT)
server.set_debuglevel(1)
if secrets.SMTP_STARTTLS:
server.starttls()
server.login(secrets.SMTP_USER, secrets.SMTP_PASSWORD)
server.send_message(msg)
server.quit()
return
@pyqtSlot(int)
@@ -222,3 +342,82 @@ class PersonDialog(QDialog, Ui_Dialog):
else:
button.setEnabled(False)
return
def makeDefinitions(self) -> str:
query = QSqlQuery()
query.prepare(
"SELECT w.word, w.definition FROM sessions s "
"LEFT JOIN session_word sw "
"ON (s.session_id = s.session_id) "
"LEFT JOIN words w "
"ON (sw.word_id = w.word_id) "
"WHERE s.session_id = :session_id "
"ORDER BY w.word"
)
row = self.sessionCombo.currentIndex()
model = self.sessionCombo.model()
index = model.index(row, 0)
session_id = index.data()
query.bindValue(":session_id", session_id)
if not query.exec():
query_error(query)
html = '<div class="words">\n<dl>\n'
while query.next():
html += "<dt>" + query.value("word") + "</dt>\n<dd>\n"
data = json.loads(query.value("definition"))
if "phonetics" in data:
for p in data["phonetics"]:
if "text" in p:
html += '<p class="phonetic">' + p["text"] + "</p>\n"
html += '<dl class="meanings">\n'
for meaning in data["meanings"]:
html += "<dt>" + meaning["partOfSpeech"] + "</dt>\n<dd><ul>\n"
for definition in meaning["definitions"]:
html += "<li>" + definition["definition"] + "</li>\n"
html += "</ul>\n"
html += "</dl>\n</dd>\n"
html += "</dl>\n</div>\n"
return html
def makeText(self) -> str:
query = QSqlQuery()
section_query = QSqlQuery()
html = '<div class="text">'
session_id = (
self.sessionCombo.model()
.index(self.sessionCombo.currentIndex(), 0)
.data()
)
query.prepare(
"SELECT * FROM session_block sb "
"WHERE sb.session_id = :session_id "
"ORDER BY sb.section_id, sb.block"
)
query.bindValue(":session_id", session_id)
if not query.exec():
query_error(query)
section_query.prepare(
"SELECT * FROM sections " "WHERE section_id = :section_id"
)
section_id = 0
while query.next():
if section_id != query.value("section_id"):
section_id = query.value("section_id")
section_query.bindValue(":section_id", section_id)
if not section_query.exec():
query_error(section_query)
if not section_query.next():
raise Exception(f"Missing section {section_id}")
section = blockHandler()
section.feed(section_query.value("content"))
html += section.get_block(query.value("block")) + "\n"
html += "</div>\n"
return html
def makeStats(self) -> str:
html = '<div class="stats">'
html += "</div>\n"
return html