From 96476044387e98ee1ee7a6eb992b521bd447813c Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Fri, 3 Mar 2023 16:55:33 +0100 Subject: Renamed whiteboard to webchat --- Makefile | 26 +- common.mk | 2 +- config.cpp | 2 +- config.h | 2 +- connectionregistry.h | 2 + debian/README.Debian | 32 +- debian/changelog | 74 +---- debian/control | 15 +- debian/rules | 4 +- debian/webchat.conf | 34 +++ debian/webchat.dirs | 1 + debian/webchat.docs | 1 + debian/webchat.webchat.service | 13 + debian/whiteboard.conf | 34 --- debian/whiteboard.dirs | 1 - debian/whiteboard.docs | 1 - debian/whiteboard.whiteboard.service | 13 - diff.cpp | 188 ------------ diff.h | 37 --- html/index.html | 17 +- html/pdf-icon-100.png | Bin 4526 -> 0 bytes html/pdf-icon-30.png | Bin 1356 -> 0 bytes html/pdf-icon-50.png | Bin 2317 -> 0 bytes html/pdf-icon.svg | 56 ---- html/stats.html | 2 +- html/stats.js | 6 +- html/webchat.css | 150 +++++++++ html/webchat.js | 351 +++++++++++++++++++++ html/whiteboard.css | 150 --------- html/whiteboard.js | 351 --------------------- main.cpp | 6 +- qrcode.cpp | 37 --- qrcode.h | 11 - tests/Makefile | 14 +- tests/test-diff.cpp | 199 ------------ tests/test-qrcode.cpp | 140 --------- tests/test-webchat.cpp | 255 ++++++++++++++++ tests/test-whiteboard.cpp | 255 ---------------- webassembly/Makefile | 2 +- webchat.conf | 34 +++ webchat.cpp | 571 +++++++++++++++++++++++++++++++++++ webchat.h | 35 +++ webserver.conf.example | 8 +- whiteboard.conf | 34 --- whiteboard.cpp | 571 ----------------------------------- whiteboard.h | 35 --- 46 files changed, 1513 insertions(+), 2259 deletions(-) create mode 100644 debian/webchat.conf create mode 100644 debian/webchat.dirs create mode 100644 debian/webchat.docs create mode 100644 debian/webchat.webchat.service delete mode 100644 debian/whiteboard.conf delete mode 100644 debian/whiteboard.dirs delete mode 100644 debian/whiteboard.docs delete mode 100644 debian/whiteboard.whiteboard.service delete mode 100644 diff.cpp delete mode 100644 diff.h delete mode 100644 html/pdf-icon-100.png delete mode 100644 html/pdf-icon-30.png delete mode 100644 html/pdf-icon-50.png delete mode 100644 html/pdf-icon.svg create mode 100644 html/webchat.css create mode 100644 html/webchat.js delete mode 100644 html/whiteboard.css delete mode 100644 html/whiteboard.js delete mode 100644 qrcode.cpp delete mode 100644 qrcode.h delete mode 100644 tests/test-diff.cpp delete mode 100644 tests/test-qrcode.cpp create mode 100644 tests/test-webchat.cpp delete mode 100644 tests/test-whiteboard.cpp create mode 100644 webchat.conf create mode 100644 webchat.cpp create mode 100644 webchat.h delete mode 100644 whiteboard.conf delete mode 100644 whiteboard.cpp delete mode 100644 whiteboard.h diff --git a/Makefile b/Makefile index aafa42a..24355b7 100755 --- a/Makefile +++ b/Makefile @@ -6,39 +6,39 @@ include common.mk -PROJECTNAME=whiteboard +PROJECTNAME=webchat DISTROS=base debian11 ubuntu2210 TGZNAME=$(PROJECTNAME)-$(VERSION).tar.xz INCLUDES=-I. -HEADERS=config.h qrcode.h storage.h whiteboard.h compiledsql.h connectionregistry.h diff.h +HEADERS=config.h storage.h webchat.h compiledsql.h connectionregistry.h SOURCES=$(HEADERS:.h=.cpp) OBJECTS=$(HEADERS:.h=.o) -TARGETS=whiteboard +TARGETS=webchat build: $(TARGETS) $(MAKE) -C webassembly all: build - ./whiteboard -c whiteboard.conf + ./webchat -c webchat.conf install: mkdir -p $(DESTDIR)/usr/bin - cp whiteboard $(DESTDIR)/usr/bin + cp webchat $(DESTDIR)/usr/bin - mkdir -p $(DESTDIR)/usr/lib/whiteboard/html - cp -r html/* $(DESTDIR)/usr/lib/whiteboard/html/ + mkdir -p $(DESTDIR)/usr/lib/webchat/html + cp -r html/* $(DESTDIR)/usr/lib/webchat/html/ - uglifyjs html/whiteboard.js -m -c > $(DESTDIR)/usr/lib/whiteboard/html/whiteboard.js || cp html/whiteboard.js $(DESTDIR)/usr/lib/whiteboard/html/whiteboard.js - htmlmin html/index.html $(DESTDIR)/usr/lib/whiteboard/html/index.html - cleancss -o $(DESTDIR)/usr/lib/whiteboard/html/whiteboard.css html/whiteboard.css + uglifyjs html/webchat.js -m -c > $(DESTDIR)/usr/lib/webchat/html/webchat.js || cp html/webchat.js $(DESTDIR)/usr/lib/webchat/html/webchat.js + htmlmin html/index.html $(DESTDIR)/usr/lib/webchat/html/index.html + cleancss -o $(DESTDIR)/usr/lib/webchat/html/webchat.css html/webchat.css mkdir -p $(DESTDIR)/etc - cp whiteboard.conf $(DESTDIR)/etc + cp webchat.conf $(DESTDIR)/etc # link -whiteboard: $(OBJECTS) main.o +webchat: $(OBJECTS) main.o $(CXX) $(LDFLAGS) $^ $(LDLIBS) $(LIBS) -o $@ # .cpp -> .o @@ -50,7 +50,7 @@ test: clean: -rm -f *.o $(TARGETS) *.gcov - -rm -f html/libwhiteboard.wasm html/libwhiteboard.js + -rm -f html/libwebchat.wasm html/libwebchat.js $(MAKE) -C tests clean $(MAKE) -C webassembly clean diff --git a/common.mk b/common.mk index 5f4c77c..de649da 100644 --- a/common.mk +++ b/common.mk @@ -67,5 +67,5 @@ SRC_ROOT=. endif VERSION=$(shell dpkg-parsechangelog --show-field Version --file $(SRC_ROOT)/debian/changelog) -CXXFLAGS+=-DWHITEBOARD_VERSION=\"$(VERSION)\" +CXXFLAGS+=-DWEBCHAT_VERSION=\"$(VERSION)\" diff --git a/config.cpp b/config.cpp index afb5cd2..15159a3 100644 --- a/config.cpp +++ b/config.cpp @@ -10,7 +10,7 @@ namespace pt = boost::property_tree; using namespace std::string_literals; namespace { - const std::string default_datapath {"/var/lib/whiteboard"}; + const std::string default_datapath {"/var/lib/webchat"}; const uint64_t default_maxage{0}; // timeout in seconds; 0 = no timeout const std::string default_listen {"::1:9000"}; const int default_threads{1}; diff --git a/config.h b/config.h index ce2fceb..53d400a 100644 --- a/config.h +++ b/config.h @@ -2,7 +2,7 @@ #include -const std::string default_config_filename{"/etc/whiteboard.conf"}; +const std::string default_config_filename{"/etc/webchat.conf"}; class Config { diff --git a/connectionregistry.h b/connectionregistry.h index c3c6884..e41e4f2 100644 --- a/connectionregistry.h +++ b/connectionregistry.h @@ -8,6 +8,8 @@ #include #include +// map connection <-> user id + class ConnectionRegistry { public: diff --git a/debian/README.Debian b/debian/README.Debian index 7450383..e683b0c 100644 --- a/debian/README.Debian +++ b/debian/README.Debian @@ -1,45 +1,45 @@ -whiteboard for Debian -===================== +webchat for Debian +================== -This package is the Debian version of whiteboard. +This package is the Debian version of webchat. It is a websocket application communicating to a webserver, e.g. Reichwein.IT webserver. -Via cron or systemd, whiteboard data in /var/lib/whiteboard is cleaned up once a day. -Data location and maximum data age can be configured via /etc/whiteboard.conf. +Via cron or systemd, webchat data in /var/lib/webchat is cleaned up once a day. +Data location and maximum data age can be configured via /etc/webchat.conf. Configuration ------------- -* You can add this to /etc/webserver.conf +* You can add this to /etc/webchat.conf - + static-files - /usr/lib/whiteboard/html + /usr/lib/webchat/html - + websocket - 127.0.0.1:9014 + 127.0.0.1:9015 -* Edit /etc/whiteboard.conf to adjust the whiteboard data path if different - from /var/lib/whiteboard +* Edit /etc/webchat.conf to adjust the webchat data path if different + from /var/lib/webchat * Enable: - # systemctl enable whiteboard.service + # systemctl enable webchat.service * Start: - # systemctl start whiteboard + # systemctl start webchat * Stop: - # systemctl stop whiteboard + # systemctl stop webchat * Query Status: - # systemctl status whiteboard + # systemctl status webchat and observe /var/log/syslog diff --git a/debian/changelog b/debian/changelog index de01abe..5891085 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,75 +1,5 @@ -whiteboard (1.9) UNRELEASED; urgency=medium - - * Updated build environment - * Added missing image files - - -- Roland Reichwein Mon, 20 Feb 2023 10:10:27 +0100 - -whiteboard (1.8) unstable; urgency=medium - - * Added config.maxconnections, defaults to 1000 - * Fixed package dependencies for PDF generation - * Touch documents on read (i.e. reset timeout on read) - * Validate id, server-side - - -- Roland Reichwein Sun, 19 Feb 2023 18:42:32 +0100 - -whiteboard (1.7) unstable; urgency=medium - - * Fix crash on stats.html page reload/close - * Focus on reconnect button - * Added Markdown to PDF download via pandoc - - -- Roland Reichwein Fri, 10 Feb 2023 18:01:37 +0100 - -whiteboard (1.6) unstable; urgency=medium - - * Added stats.html - * Use boost strands instead of mutex - - -- Roland Reichwein Mon, 06 Feb 2023 07:58:39 +0100 - -whiteboard (1.5) unstable; urgency=medium - - * Move from FCGI to websocket interface - * Position changes w/o file transmit - * Print version on main page - * Add reconnect button - * Add diff handling - - -- Roland Reichwein Mon, 30 Jan 2023 21:05:35 +0100 - -whiteboard (1.4) unstable; urgency=medium - - * Move from filesystem based documents to sqlite - * Add tests - * Separated out libreichwein - - -- Roland Reichwein Sat, 21 Jan 2023 12:20:20 +0100 - -whiteboard (1.3) unstable; urgency=medium - - * Page design (center) - * Follow editor's cursor - - -- Roland Reichwein Mon, 05 Dec 2022 19:22:27 +0100 - -whiteboard (1.2) unstable; urgency=medium - - * Fix build on Debian 11 - * UglifyJS on best-effort base - - -- Roland Reichwein Sat, 03 Dec 2022 17:03:11 +0100 - -whiteboard (1.1) unstable; urgency=medium - - * Compress Javascript - * Add QR Code - - -- Roland Reichwein Sat, 03 Dec 2022 16:10:06 +0100 - -whiteboard (1.0) unstable; urgency=medium +webchat (1.0) unstable; urgency=medium * Initial release - -- Roland Reichwein Sat, 05 Nov 2022 13:34:57 +0100 + -- Roland Reichwein Fri, 03 Mar 2023 16:16:00 +0100 diff --git a/debian/control b/debian/control index 9c75069..42fa7db 100644 --- a/debian/control +++ b/debian/control @@ -1,16 +1,17 @@ -Source: whiteboard +Source: webchat Section: web Priority: optional Maintainer: Roland Reichwein -Build-Depends: debhelper (>= 12), libboost-all-dev | libboost1.71-all-dev, clang | g++-9, llvm | g++-9, lld | g++-9, uglifyjs, python3-pkg-resources, htmlmin, cleancss, libqrcodegencpp-dev, libgraphicsmagick++-dev, pkg-config, libfmt-dev, libsqlitecpp-dev, googletest, gcovr, libreichwein-dev, emscripten +Build-Depends: debhelper (>= 12), libboost-all-dev | libboost1.71-all-dev, clang | g++-9, llvm | g++-9, lld | g++-9, uglifyjs, python3-pkg-resources, htmlmin, cleancss, pkg-config, libfmt-dev, libsqlitecpp-dev, googletest, gcovr, libreichwein-dev, emscripten Standards-Version: 4.5.0 Homepage: http://www.reichwein.it/whiteboard/ -Package: whiteboard +Package: webchat Architecture: any -Depends: ${shlibs:Depends}, ${misc:Depends}, libxml2-utils, pandoc, texlive-latex-recommended, texlive-latex-extra +Depends: ${shlibs:Depends}, ${misc:Depends}, libxml2-utils Recommends: webserver Homepage: http://www.reichwein.it/whiteboard/ -Description: Web application for an collaborative editor - Whiteboard is a text editor running on an HTML5 webpage (including a server - part) that enables collaborative editing and presenting. +Description: Web application for chat + Webchat is a cat web application, running on a webserver (e.g. Reichwein.IT + webserver) via websockets interface. Client-wise, it is implemented with + plain HTML and JavaScript. diff --git a/debian/rules b/debian/rules index 72c5b8c..48012e3 100755 --- a/debian/rules +++ b/debian/rules @@ -5,9 +5,9 @@ override_dh_fixperms: dh_fixperms - chmod a+rwx debian/whiteboard/var/lib/whiteboard + chmod a+rwx debian/webchat/var/lib/webchat override_dh_auto_install: dh_auto_install - dh_installsystemd --name whiteboard + dh_installsystemd --name webchat diff --git a/debian/webchat.conf b/debian/webchat.conf new file mode 100644 index 0000000..89645c0 --- /dev/null +++ b/debian/webchat.conf @@ -0,0 +1,34 @@ + + + /var/lib/webchat + + + ::1:8767 + + + 2592000 + + + 4 + + + 500 + diff --git a/debian/webchat.dirs b/debian/webchat.dirs new file mode 100644 index 0000000..c681efe --- /dev/null +++ b/debian/webchat.dirs @@ -0,0 +1 @@ +var/lib/webchat diff --git a/debian/webchat.docs b/debian/webchat.docs new file mode 100644 index 0000000..0812baa --- /dev/null +++ b/debian/webchat.docs @@ -0,0 +1 @@ +webserver.conf.example diff --git a/debian/webchat.webchat.service b/debian/webchat.webchat.service new file mode 100644 index 0000000..b41e655 --- /dev/null +++ b/debian/webchat.webchat.service @@ -0,0 +1,13 @@ +[Unit] +Description=Whiteboard +After=network.target + +[Service] +Type=simple +# Restart=always +ExecStart=/usr/bin/whiteboard + +Restart=always + +[Install] +WantedBy=multi-user.target diff --git a/debian/whiteboard.conf b/debian/whiteboard.conf deleted file mode 100644 index 6446d39..0000000 --- a/debian/whiteboard.conf +++ /dev/null @@ -1,34 +0,0 @@ - - - /var/lib/whiteboard - - - ::1:8765 - - - 2592000 - - - 4 - - - 500 - diff --git a/debian/whiteboard.dirs b/debian/whiteboard.dirs deleted file mode 100644 index 7b03c85..0000000 --- a/debian/whiteboard.dirs +++ /dev/null @@ -1 +0,0 @@ -var/lib/whiteboard diff --git a/debian/whiteboard.docs b/debian/whiteboard.docs deleted file mode 100644 index 0812baa..0000000 --- a/debian/whiteboard.docs +++ /dev/null @@ -1 +0,0 @@ -webserver.conf.example diff --git a/debian/whiteboard.whiteboard.service b/debian/whiteboard.whiteboard.service deleted file mode 100644 index b41e655..0000000 --- a/debian/whiteboard.whiteboard.service +++ /dev/null @@ -1,13 +0,0 @@ -[Unit] -Description=Whiteboard -After=network.target - -[Service] -Type=simple -# Restart=always -ExecStart=/usr/bin/whiteboard - -Restart=always - -[Install] -WantedBy=multi-user.target diff --git a/diff.cpp b/diff.cpp deleted file mode 100644 index 6ac24e7..0000000 --- a/diff.cpp +++ /dev/null @@ -1,188 +0,0 @@ -#include "diff.h" - -#include -#include -#include - -#include - -namespace pt = boost::property_tree; - -Diff::Diff() -{ -} - -Diff::Diff(const std::string& old_version, const std::string& new_version) -{ - create(old_version, new_version); -} - -std::string Diff::apply(const std::string& old_version) const -{ - std::string result{old_version}; - - if (m_pos0 <= m_pos1 && m_pos1 <= old_version.size()) { - result.erase(m_pos0, m_pos1 - m_pos0); - result.insert(m_pos0, m_data); - } - - return result; -} - -void Diff::create(const std::string& old_version, const std::string& new_version) -{ - auto front_mismatch{std::mismatch(old_version.cbegin(), old_version.cend(), new_version.cbegin(), new_version.cend())}; - std::string::difference_type old_pos0 {front_mismatch.first - old_version.cbegin()}; - auto& new_pos0 {old_pos0}; - - // equal - if (old_pos0 == old_version.size() && new_pos0 == new_version.size()) { - m_pos0 = 0; - m_pos1 = 0; - m_data.clear(); - return; - } - - // append at end - if (old_pos0 == old_version.size()) { - m_pos0 = old_pos0; - m_pos1 = old_pos0; - m_data = new_version.substr(new_pos0); - return; - } - - // remove from end - if (new_pos0 == new_version.size()) { - m_pos0 = old_pos0; - m_pos1 = old_version.size(); - m_data.clear(); - return; - } - - auto back_mismatch{std::mismatch(old_version.crbegin(), old_version.crend(), new_version.crbegin(), new_version.crend())}; - // i.e. the indices starting from which we can assume equality - size_t old_pos1 {old_version.size() - (back_mismatch.first - old_version.crbegin())}; - size_t new_pos1 {new_version.size() - (back_mismatch.second - new_version.crbegin())}; - - // complete equality is already handled above - - // insert at start - if (old_pos1 == 0) { - m_pos0 = 0; - m_pos1 = 0; - m_data = new_version.substr(0, new_pos1); - return; - } - - // remove from start - if (new_pos1 == 0) { - m_pos0 = 0; - m_pos1 = old_pos1; - m_data.clear(); - return; - } - - // re-adjust if search crossed - if (old_pos0 > old_pos1) { - old_pos0 = old_pos1; - new_pos0 = old_pos1; - } - if (new_pos0 > new_pos1) { - old_pos0 = new_pos1; - new_pos0 = new_pos1; - } - - // insert in the middle - if (old_pos0 == old_pos1) { - m_pos0 = old_pos0; - m_pos1 = old_pos0; - m_data = new_version.substr(new_pos0, new_pos1 - new_pos0); - return; - } - - // remove from the middle - if (new_pos0 == new_pos1) { - m_pos0 = old_pos0; - m_pos1 = old_pos1; - m_data.clear(); - return; - } - - // last resort: remove and add in the middle - m_pos0 = old_pos0; - m_pos1 = old_pos1; - m_data = new_version.substr(old_pos0, new_pos1 - new_pos0); -} - -Diff::Diff(const boost::property_tree::ptree& ptree) -{ - create(ptree); -} - -void Diff::create(const boost::property_tree::ptree& ptree) -{ - m_pos0 = ptree.get("diff.start"); - m_pos1 = ptree.get("diff.end"); - - if (m_pos0 > m_pos1) - throw std::runtime_error("Bad range in diff"); - - m_data = ptree.get("diff.data"); -} - -Diff::Diff(const std::string& xml) -{ - create(xml); -} - -void Diff::create(const std::string& xml) -{ - pt::ptree ptree; - std::istringstream ss{xml}; - pt::read_xml(ss, ptree); - - create(ptree); -} - -bool Diff::empty() const -{ - return m_pos0 == m_pos1 && m_data.empty(); -} - -boost::property_tree::ptree Diff::get_structure() const -{ - pt::ptree ptree; - ptree.put("diff.start", std::to_string(m_pos0)); - ptree.put("diff.end", std::to_string(m_pos1)); - ptree.put("diff.data", m_data); - - return ptree; -} - -std::string Diff::get_xml() const -{ - pt::ptree ptree{get_structure()}; - - std::ostringstream oss; - // write_xml_element instead of write_xml to omit header - //pt::xml_parser::write_xml(oss, xml); - pt::xml_parser::write_xml_element(oss, {}, ptree, -1, boost::property_tree::xml_writer_settings{}); - return oss.str(); -} - -extern "C" { - - const char* diff_create(const char* old_version, const char* new_version) - { - Diff diff{old_version, new_version}; - return strdup(diff.get_xml().c_str()); - } - - const char* diff_apply(const char* old_version, const char* diff) - { - Diff d{diff}; - - return strdup(d.apply(old_version).c_str()); - } - -} diff --git a/diff.h b/diff.h deleted file mode 100644 index 5c2c335..0000000 --- a/diff.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include - -#include - -class Diff -{ -public: - Diff(); - Diff(const std::string& old_version, const std::string& new_version); - void create(const std::string& old_version, const std::string& new_version); - - Diff(const boost::property_tree::ptree& ptree); - void create(const boost::property_tree::ptree& ptree); - - Diff(const std::string& xml); - void create(const std::string& xml); - - std::string apply(const std::string& old_version) const; - - bool empty() const; - - boost::property_tree::ptree get_structure() const; - std::string get_xml() const; - -private: - // diff replaces space from m_pos0 (inclusive) to m_pos1 (exclusive) with m_data - size_t m_pos0{}; - size_t m_pos1{}; - std::string m_data; -}; - -extern "C" { - const char* diff_create(const char* old_version, const char* new_version); - const char* diff_apply(const char* old_version, const char* diff); -} diff --git a/html/index.html b/html/index.html index b72e23b..260b1a9 100644 --- a/html/index.html +++ b/html/index.html @@ -3,30 +3,27 @@ - - Reichwein Whiteboard + + Reichwein.IT Webchat - - - + + +
-

Whiteboard

+

Webchat



- - Starting up... -

- Reichwein.IT Whiteboard by https://www.reichwein.it
+ Reichwein.IT Webchat by https://www.reichwein.it
diff --git a/html/pdf-icon-100.png b/html/pdf-icon-100.png deleted file mode 100644 index 9a20387..0000000 Binary files a/html/pdf-icon-100.png and /dev/null differ diff --git a/html/pdf-icon-30.png b/html/pdf-icon-30.png deleted file mode 100644 index 5f60d2f..0000000 Binary files a/html/pdf-icon-30.png and /dev/null differ diff --git a/html/pdf-icon-50.png b/html/pdf-icon-50.png deleted file mode 100644 index 62873ea..0000000 Binary files a/html/pdf-icon-50.png and /dev/null differ diff --git a/html/pdf-icon.svg b/html/pdf-icon.svg deleted file mode 100644 index 8b30bbb..0000000 --- a/html/pdf-icon.svg +++ /dev/null @@ -1,56 +0,0 @@ - - - - PDF file icon - - - - - - - - - - image/svg+xml - - PDF file icon - 08/10/2018 - - - Adobe Systems - - - - - CMetalCore - - - Fuente del texto "PDF": -Franklin Gothic Medium Cond - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/html/stats.html b/html/stats.html index 3f7e141..9501c18 100644 --- a/html/stats.html +++ b/html/stats.html @@ -18,7 +18,7 @@

Statistics

- +
Active Connections:
Number of Documents:
Number of Users:
Database Size (gross):Bytes
Database Size (net):Bytes
diff --git a/html/stats.js b/html/stats.js index 89c674a..4174877 100644 --- a/html/stats.js +++ b/html/stats.js @@ -20,9 +20,9 @@ var websocket; // Callbacks for websocket data of different types // -function on_stats(numberofdocuments, numberofconnections, dbsizegross, dbsizenet) +function on_stats(numberofusers, numberofconnections, dbsizegross, dbsizenet) { - document.getElementById("numberofdocuments").textContent = numberofdocuments; + document.getElementById("numberofusers").textContent = numberofusers; document.getElementById("numberofconnections").textContent = numberofconnections; document.getElementById("dbsizegross").textContent = dbsizegross; document.getElementById("dbsizenet").textContent = dbsizenet; @@ -40,7 +40,7 @@ function on_message(e) { var type = xmlDocument.getElementsByTagName("type")[0].textContent; if (type == "stats") { - on_stats(xmlDocument.getElementsByTagName("numberofdocuments")[0].textContent, + on_stats(xmlDocument.getElementsByTagName("numberofusers")[0].textContent, xmlDocument.getElementsByTagName("numberofconnections")[0].textContent, xmlDocument.getElementsByTagName("dbsizegross")[0].textContent, xmlDocument.getElementsByTagName("dbsizenet")[0].textContent); diff --git a/html/webchat.css b/html/webchat.css new file mode 100644 index 0000000..2d222d5 --- /dev/null +++ b/html/webchat.css @@ -0,0 +1,150 @@ +body { + font-family: sans-serif; +} + +figcaption { + text-align: center; + font-size: 8px; + color: #808080; +} + +figure { + display: inline-block; +} + +p { + margin: 30px 0px 30px 0px; +} + +div.status { + color: #FF0000; +} + +span.helper { + display: inline-block; + height: 100%; + vertical-align: middle; +} + +img.center-img { + vertical-align: middle; +} + +.clickable { + cursor: pointer; +} + +textarea { + /* + height: 30vh; + padding: 1em; + font-size: 1.5em; + text-align: left; + border: 1px solid #000; + */ + box-sizing: border-box; + resize: none; + + width: 100%; + height: 540px; +} + +.qrwindow { + position: fixed; + top: 50%; + left: 50%; + width: 400px; + height: 400px; + margin-top: -200px; + margin-left: -200px; + background-color: #FFFFFF; + opacity: 1; + z-index: 10; + border-width: 3px; + border-style: solid; + border-color: #FFFFFF; + padding: 10pt; + box-sizing: border-box; +} + +.qrcode { + width: 374px; + height: 374px; + + image-rendering: optimizeSpeed; /* */ + image-rendering: -moz-crisp-edges; /* Firefox */ + image-rendering: -o-crisp-edges; /* Opera */ + image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */ + image-rendering: pixelated; /* Chrome as of 2019 */ + image-rendering: optimize-contrast; /* CSS3 Proposed */ + -ms-interpolation-mode: nearest-neighbor; /* IE8+ */ +} + +.mobile { + width: 300px; + border-width: 80px 15px 80px 15px; + border-style: solid; + border-radius: 30px; + border-color: #000000; +} + +.logo { + display: block; + margin: 0 auto; +} + +.screenshot { + width: 400px; + border: 2px solid; + border-color: #8888AA; +} + +img.banner { + vertical-align: -5px; +} + +.button { + color:#FFFFFF; + background-color:#50B050; + text-decoration: none; + padding: 15px 20px; + font-size: 16px; + border: none; + border-radius: 6px; + cursor: pointer; +} + +.buttonred { + color:#FFFFFF; + background-color:#B05050; + text-decoration: none; + padding: 15px 20px; + font-size: 16px; + border: none; + border-radius: 6px; + cursor: pointer; +} + +@media only screen and (min-width: 1px) and (max-width: 630px) { + +.qrwindow { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + margin: 0; +} + +} + +@media only screen and (min-width: 631px) and (max-width: 950px) { +} + +@media only screen and (min-width: 951px) { + div.page { + max-width: 950px; + width: 100%; + margin: 0 auto; + } +} diff --git a/html/webchat.js b/html/webchat.js new file mode 100644 index 0000000..379c757 --- /dev/null +++ b/html/webchat.js @@ -0,0 +1,351 @@ +// started on main page load +function init() { + init_board(); +} + +var revision; +var modify_in_progress = 0; +var baseline = ""; // data contents relating to revision, acknowledged by server +var baseline_candidate = ""; // will become baseline, after ack by server + +// helper for breaking feedback loop +var caretpos = 0; + +function set_status(message) +{ + if (message == "") { + document.getElementById("status").textContent = message; + document.getElementById("status").style.display = 'inline'; + } else { + document.getElementById("status").textContent = ""; + document.getElementById("status").style.display = 'none'; + } +} + +function showQRWindow() +{ + document.getElementById("qrwindow").style.display = 'block'; +} + +function hideQRWindow() +{ + document.getElementById("qrwindow").style.display = 'none'; +} + +var websocket; + +// +// Callbacks for websocket data of different types +// + +function on_getfile(data, rev, pos) +{ + var board = document.getElementById("board"); + if (board.value != data) { + board.value = data; + } + revision = rev; + baseline = data; + textAreaSetPos("board", pos); +} + +function on_getdiff(diff, rev, pos) +{ + if (rev != revision + 1) + console.log("Revision skipped on diff receive: " + rev + " after " + revision); + + var board = document.getElementById("board"); + + var old_version_ptr = allocateUTF8(board.value); + var diff_ptr = allocateUTF8(new XMLSerializer().serializeToString(diff)); + var new_version_ptr = Module._diff_apply(old_version_ptr, diff_ptr); + var data = UTF8ToString(new_version_ptr); + board.value = data; + _free(old_version_ptr); + _free(new_version_ptr); + _free(diff_ptr); + + revision = rev; + baseline = data; + textAreaSetPos("board", pos); +} + +function on_getpos(pos) +{ + textAreaSetPos("board", pos); +} + +function on_newid(id) +{ + var new_location = document.location.origin + document.location.pathname + '?id=' + id; + window.location.href = new_location; +} + +function on_qrcode(png) +{ + var url = "data:image/png;base64," + png; + var img = document.getElementById("qrcode"); + img.src = url; + showQRWindow(); +} + +function on_version(version) +{ + document.getElementById("version").textContent = version; +} + +function on_pdf(pdf) +{ + var a = document.getElementById("download-a"); + a.href = "data:application/pdf;base64," + pdf; + a.download = get_id() + ".pdf" + a.click(); +} + +function on_modify_ack(rev) +{ + if (rev != revision + 1) + console.log("Revision skipped on published local change: " + rev + " after " + revision); + + revision = rev; + baseline = baseline_candidate; + modify_in_progress = 0; +} + +function on_message(e) { + var parser = new DOMParser(); + var xmlDocument = parser.parseFromString(e.data, "text/xml"); + + var type = xmlDocument.getElementsByTagName("type")[0].textContent; + + if (type == "getfile") { + on_getfile(xmlDocument.getElementsByTagName("data")[0].textContent, + parseInt(xmlDocument.getElementsByTagName("revision")[0].textContent), + parseInt(xmlDocument.getElementsByTagName("pos")[0].textContent)); + } else if (type == "getdiff") { + on_getdiff(xmlDocument.getElementsByTagName("diff")[0], + parseInt(xmlDocument.getElementsByTagName("revision")[0].textContent), + parseInt(xmlDocument.getElementsByTagName("pos")[0].textContent)); + } else if (type == "getpos") { + on_getpos(parseInt(xmlDocument.getElementsByTagName("pos")[0].textContent)); + } else if (type == "modify") { + on_modify_ack(parseInt(xmlDocument.getElementsByTagName("revision")[0].textContent)); + } else if (type == "newid") { + on_newid(xmlDocument.getElementsByTagName("id")[0].textContent); + } else if (type == "qrcode") { + on_qrcode(xmlDocument.getElementsByTagName("png")[0].textContent); + } else if (type == "version") { + on_version(xmlDocument.getElementsByTagName("version")[0].textContent); + } else if (type == "pdf") { + on_pdf(xmlDocument.getElementsByTagName("pdf")[0].textContent); + } else if (type == "error") { + alert(xmlDocument.getElementsByTagName("message")[0].textContent); + } else { + alert("Unhandled message type: " + e.data + "|" + type); + } +} + +function handleSelection() { + const activeElement = document.activeElement + + if (activeElement && activeElement.id === 'board') { + if (caretpos != activeElement.selectionStart) { + on_selectionchange(activeElement.selectionStart); + caretpos = activeElement.selectionStart; + } + } +} + +function connect_websocket() { + document.getElementById("reconnect").style.display = 'none'; + set_status("Connecting..."); + var newlocation = location.origin + location.pathname; + newlocation = newlocation.replace(/^http/, 'ws'); + if (newlocation.slice(-1) != "/") + newlocation += "/"; + newlocation += "websocket"; + + websocket = new WebSocket(newlocation); + + websocket.onmessage = function(e) { on_message(e); }; + + websocket.onopen = function(e) { + const searchParams = (new URL(document.location)).searchParams; + if (!searchParams.has('id')) { + redirect_to_new_page(); + return; + } + + websocket.send("getversion"); + websocket.send("getfile" + get_id() + ""); + set_status(""); // ok + document.getElementById("board").focus(); + }; + + websocket.onclose = function(e) { + alert("Server connection closed."); + document.getElementById("reconnect").style.display = 'inline'; + document.getElementById("reconnect").focus(); + }; + + websocket.onerror = function(e) { + alert("Error: Server connection closed."); + document.getElementById("reconnect").style.display = 'inline'; + document.getElementById("reconnect").focus(); + }; +} + +// button in html +function on_reconnect_click() { + connect_websocket(); +} + +function init_board() { + set_status("Loading..."); + Module.onRuntimeInitialized = () => { + connect_websocket(); + }; + + var board = document.getElementById("board"); + board.addEventListener("input", function() {on_input(); }); + // Need this workaround (different from direct on_selectionchange) for Chrome. + // Otherwise, callback will not be called on Chrome. + document.addEventListener("selectionchange", handleSelection); + //board.addEventListener("selectionchange", function() {on_selectionchange(); }); + + document.getElementById("qrwindow").onclick = function() { + hideQRWindow(); + } + + document.onkeydown = function(evt) { + if (evt.key == "Escape") { + hideQRWindow(); + } + } + + document.getElementById("board").focus(); +} + +function get_id() +{ + const searchParams = (new URL(document.location)).searchParams; + return searchParams.get('id'); +} + +// from html +function on_new_page() +{ + redirect_to_new_page(); +} + +function redirect_to_new_page() +{ + websocket.send("newid"); +} + +// local change done +function on_input() +{ + if (modify_in_progress == 1) { + console.log("Deferring on_input handler by 100ms"); + setTimeout(function(){on_input();}, 100); // re-try after 100ms + return; + } + modify_in_progress = 1; + + var parser = new DOMParser(); + var xmlDocument = parser.parseFromString("", "text/xml"); + + var requestElement = xmlDocument.getElementsByTagName("request")[0]; + + var commandElement = xmlDocument.createElement("command"); + commandElement.appendChild(document.createTextNode("modify")); + requestElement.appendChild(commandElement); + + var idElement = xmlDocument.createElement("id"); + idElement.appendChild(document.createTextNode(get_id())); + requestElement.appendChild(idElement); + + baseline_candidate = document.getElementById("board").value; + + if (baseline == baseline_candidate) { + modify_in_progress = 0; + return; + } + + var revisionElement = xmlDocument.createElement("baserev"); + revisionElement.appendChild(document.createTextNode(revision)); + requestElement.appendChild(revisionElement); + + var old_version = allocateUTF8(baseline); + var new_version = allocateUTF8(baseline_candidate); + var diff = Module._diff_create(old_version, new_version); + var diffDocument = parser.parseFromString(UTF8ToString(diff), "text/xml"); + _free(old_version); + _free(new_version); + _free(diff); + requestElement.appendChild(xmlDocument.importNode(diffDocument.getElementsByTagName("diff")[0], true)); + + var posElement = xmlDocument.createElement("pos"); + posElement.appendChild(document.createTextNode(document.getElementById("board").selectionStart)); + requestElement.appendChild(posElement); + + websocket.send(new XMLSerializer().serializeToString(xmlDocument)); +} + +// for cursor position +function on_selectionchange(pos) +{ + var parser = new DOMParser(); + var xmlDocument = parser.parseFromString("", "text/xml"); + + var requestElement = xmlDocument.getElementsByTagName("request")[0]; + + var commandElement = xmlDocument.createElement("command"); + commandElement.appendChild(document.createTextNode("cursorpos")); + requestElement.appendChild(commandElement); + + var idElement = xmlDocument.createElement("id"); + idElement.appendChild(document.createTextNode(get_id())); + requestElement.appendChild(idElement); + + var posElement = xmlDocument.createElement("pos"); + posElement.appendChild(document.createTextNode(pos)); + requestElement.appendChild(posElement); + + websocket.send(new XMLSerializer().serializeToString(xmlDocument)); +} + +function textAreaSetPos(id, pos) +{ + if (document.getElementById(id).selectionStart != pos) { + document.getElementById(id).selectionStart = pos; + document.getElementById(id).selectionEnd = pos; + caretpos = pos; + } +} + +// HTML button +function on_qrcode_click() +{ + var parser = new DOMParser(); + var xmlDocument = parser.parseFromString("", "text/xml"); + + var requestElement = xmlDocument.getElementsByTagName("request")[0]; + + var commandElement = xmlDocument.createElement("command"); + commandElement.appendChild(document.createTextNode("qrcode")); + requestElement.appendChild(commandElement); + + var idElement = xmlDocument.createElement("url"); + idElement.appendChild(document.createTextNode(document.location)); + requestElement.appendChild(idElement); + + websocket.send(new XMLSerializer().serializeToString(xmlDocument)); +} + +function on_pdf_click() +{ + websocket.send("pdf" + get_id() + ""); +} + diff --git a/html/whiteboard.css b/html/whiteboard.css deleted file mode 100644 index 2d222d5..0000000 --- a/html/whiteboard.css +++ /dev/null @@ -1,150 +0,0 @@ -body { - font-family: sans-serif; -} - -figcaption { - text-align: center; - font-size: 8px; - color: #808080; -} - -figure { - display: inline-block; -} - -p { - margin: 30px 0px 30px 0px; -} - -div.status { - color: #FF0000; -} - -span.helper { - display: inline-block; - height: 100%; - vertical-align: middle; -} - -img.center-img { - vertical-align: middle; -} - -.clickable { - cursor: pointer; -} - -textarea { - /* - height: 30vh; - padding: 1em; - font-size: 1.5em; - text-align: left; - border: 1px solid #000; - */ - box-sizing: border-box; - resize: none; - - width: 100%; - height: 540px; -} - -.qrwindow { - position: fixed; - top: 50%; - left: 50%; - width: 400px; - height: 400px; - margin-top: -200px; - margin-left: -200px; - background-color: #FFFFFF; - opacity: 1; - z-index: 10; - border-width: 3px; - border-style: solid; - border-color: #FFFFFF; - padding: 10pt; - box-sizing: border-box; -} - -.qrcode { - width: 374px; - height: 374px; - - image-rendering: optimizeSpeed; /* */ - image-rendering: -moz-crisp-edges; /* Firefox */ - image-rendering: -o-crisp-edges; /* Opera */ - image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */ - image-rendering: pixelated; /* Chrome as of 2019 */ - image-rendering: optimize-contrast; /* CSS3 Proposed */ - -ms-interpolation-mode: nearest-neighbor; /* IE8+ */ -} - -.mobile { - width: 300px; - border-width: 80px 15px 80px 15px; - border-style: solid; - border-radius: 30px; - border-color: #000000; -} - -.logo { - display: block; - margin: 0 auto; -} - -.screenshot { - width: 400px; - border: 2px solid; - border-color: #8888AA; -} - -img.banner { - vertical-align: -5px; -} - -.button { - color:#FFFFFF; - background-color:#50B050; - text-decoration: none; - padding: 15px 20px; - font-size: 16px; - border: none; - border-radius: 6px; - cursor: pointer; -} - -.buttonred { - color:#FFFFFF; - background-color:#B05050; - text-decoration: none; - padding: 15px 20px; - font-size: 16px; - border: none; - border-radius: 6px; - cursor: pointer; -} - -@media only screen and (min-width: 1px) and (max-width: 630px) { - -.qrwindow { - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - margin: 0; -} - -} - -@media only screen and (min-width: 631px) and (max-width: 950px) { -} - -@media only screen and (min-width: 951px) { - div.page { - max-width: 950px; - width: 100%; - margin: 0 auto; - } -} diff --git a/html/whiteboard.js b/html/whiteboard.js deleted file mode 100644 index 379c757..0000000 --- a/html/whiteboard.js +++ /dev/null @@ -1,351 +0,0 @@ -// started on main page load -function init() { - init_board(); -} - -var revision; -var modify_in_progress = 0; -var baseline = ""; // data contents relating to revision, acknowledged by server -var baseline_candidate = ""; // will become baseline, after ack by server - -// helper for breaking feedback loop -var caretpos = 0; - -function set_status(message) -{ - if (message == "") { - document.getElementById("status").textContent = message; - document.getElementById("status").style.display = 'inline'; - } else { - document.getElementById("status").textContent = ""; - document.getElementById("status").style.display = 'none'; - } -} - -function showQRWindow() -{ - document.getElementById("qrwindow").style.display = 'block'; -} - -function hideQRWindow() -{ - document.getElementById("qrwindow").style.display = 'none'; -} - -var websocket; - -// -// Callbacks for websocket data of different types -// - -function on_getfile(data, rev, pos) -{ - var board = document.getElementById("board"); - if (board.value != data) { - board.value = data; - } - revision = rev; - baseline = data; - textAreaSetPos("board", pos); -} - -function on_getdiff(diff, rev, pos) -{ - if (rev != revision + 1) - console.log("Revision skipped on diff receive: " + rev + " after " + revision); - - var board = document.getElementById("board"); - - var old_version_ptr = allocateUTF8(board.value); - var diff_ptr = allocateUTF8(new XMLSerializer().serializeToString(diff)); - var new_version_ptr = Module._diff_apply(old_version_ptr, diff_ptr); - var data = UTF8ToString(new_version_ptr); - board.value = data; - _free(old_version_ptr); - _free(new_version_ptr); - _free(diff_ptr); - - revision = rev; - baseline = data; - textAreaSetPos("board", pos); -} - -function on_getpos(pos) -{ - textAreaSetPos("board", pos); -} - -function on_newid(id) -{ - var new_location = document.location.origin + document.location.pathname + '?id=' + id; - window.location.href = new_location; -} - -function on_qrcode(png) -{ - var url = "data:image/png;base64," + png; - var img = document.getElementById("qrcode"); - img.src = url; - showQRWindow(); -} - -function on_version(version) -{ - document.getElementById("version").textContent = version; -} - -function on_pdf(pdf) -{ - var a = document.getElementById("download-a"); - a.href = "data:application/pdf;base64," + pdf; - a.download = get_id() + ".pdf" - a.click(); -} - -function on_modify_ack(rev) -{ - if (rev != revision + 1) - console.log("Revision skipped on published local change: " + rev + " after " + revision); - - revision = rev; - baseline = baseline_candidate; - modify_in_progress = 0; -} - -function on_message(e) { - var parser = new DOMParser(); - var xmlDocument = parser.parseFromString(e.data, "text/xml"); - - var type = xmlDocument.getElementsByTagName("type")[0].textContent; - - if (type == "getfile") { - on_getfile(xmlDocument.getElementsByTagName("data")[0].textContent, - parseInt(xmlDocument.getElementsByTagName("revision")[0].textContent), - parseInt(xmlDocument.getElementsByTagName("pos")[0].textContent)); - } else if (type == "getdiff") { - on_getdiff(xmlDocument.getElementsByTagName("diff")[0], - parseInt(xmlDocument.getElementsByTagName("revision")[0].textContent), - parseInt(xmlDocument.getElementsByTagName("pos")[0].textContent)); - } else if (type == "getpos") { - on_getpos(parseInt(xmlDocument.getElementsByTagName("pos")[0].textContent)); - } else if (type == "modify") { - on_modify_ack(parseInt(xmlDocument.getElementsByTagName("revision")[0].textContent)); - } else if (type == "newid") { - on_newid(xmlDocument.getElementsByTagName("id")[0].textContent); - } else if (type == "qrcode") { - on_qrcode(xmlDocument.getElementsByTagName("png")[0].textContent); - } else if (type == "version") { - on_version(xmlDocument.getElementsByTagName("version")[0].textContent); - } else if (type == "pdf") { - on_pdf(xmlDocument.getElementsByTagName("pdf")[0].textContent); - } else if (type == "error") { - alert(xmlDocument.getElementsByTagName("message")[0].textContent); - } else { - alert("Unhandled message type: " + e.data + "|" + type); - } -} - -function handleSelection() { - const activeElement = document.activeElement - - if (activeElement && activeElement.id === 'board') { - if (caretpos != activeElement.selectionStart) { - on_selectionchange(activeElement.selectionStart); - caretpos = activeElement.selectionStart; - } - } -} - -function connect_websocket() { - document.getElementById("reconnect").style.display = 'none'; - set_status("Connecting..."); - var newlocation = location.origin + location.pathname; - newlocation = newlocation.replace(/^http/, 'ws'); - if (newlocation.slice(-1) != "/") - newlocation += "/"; - newlocation += "websocket"; - - websocket = new WebSocket(newlocation); - - websocket.onmessage = function(e) { on_message(e); }; - - websocket.onopen = function(e) { - const searchParams = (new URL(document.location)).searchParams; - if (!searchParams.has('id')) { - redirect_to_new_page(); - return; - } - - websocket.send("getversion"); - websocket.send("getfile" + get_id() + ""); - set_status(""); // ok - document.getElementById("board").focus(); - }; - - websocket.onclose = function(e) { - alert("Server connection closed."); - document.getElementById("reconnect").style.display = 'inline'; - document.getElementById("reconnect").focus(); - }; - - websocket.onerror = function(e) { - alert("Error: Server connection closed."); - document.getElementById("reconnect").style.display = 'inline'; - document.getElementById("reconnect").focus(); - }; -} - -// button in html -function on_reconnect_click() { - connect_websocket(); -} - -function init_board() { - set_status("Loading..."); - Module.onRuntimeInitialized = () => { - connect_websocket(); - }; - - var board = document.getElementById("board"); - board.addEventListener("input", function() {on_input(); }); - // Need this workaround (different from direct on_selectionchange) for Chrome. - // Otherwise, callback will not be called on Chrome. - document.addEventListener("selectionchange", handleSelection); - //board.addEventListener("selectionchange", function() {on_selectionchange(); }); - - document.getElementById("qrwindow").onclick = function() { - hideQRWindow(); - } - - document.onkeydown = function(evt) { - if (evt.key == "Escape") { - hideQRWindow(); - } - } - - document.getElementById("board").focus(); -} - -function get_id() -{ - const searchParams = (new URL(document.location)).searchParams; - return searchParams.get('id'); -} - -// from html -function on_new_page() -{ - redirect_to_new_page(); -} - -function redirect_to_new_page() -{ - websocket.send("newid"); -} - -// local change done -function on_input() -{ - if (modify_in_progress == 1) { - console.log("Deferring on_input handler by 100ms"); - setTimeout(function(){on_input();}, 100); // re-try after 100ms - return; - } - modify_in_progress = 1; - - var parser = new DOMParser(); - var xmlDocument = parser.parseFromString("", "text/xml"); - - var requestElement = xmlDocument.getElementsByTagName("request")[0]; - - var commandElement = xmlDocument.createElement("command"); - commandElement.appendChild(document.createTextNode("modify")); - requestElement.appendChild(commandElement); - - var idElement = xmlDocument.createElement("id"); - idElement.appendChild(document.createTextNode(get_id())); - requestElement.appendChild(idElement); - - baseline_candidate = document.getElementById("board").value; - - if (baseline == baseline_candidate) { - modify_in_progress = 0; - return; - } - - var revisionElement = xmlDocument.createElement("baserev"); - revisionElement.appendChild(document.createTextNode(revision)); - requestElement.appendChild(revisionElement); - - var old_version = allocateUTF8(baseline); - var new_version = allocateUTF8(baseline_candidate); - var diff = Module._diff_create(old_version, new_version); - var diffDocument = parser.parseFromString(UTF8ToString(diff), "text/xml"); - _free(old_version); - _free(new_version); - _free(diff); - requestElement.appendChild(xmlDocument.importNode(diffDocument.getElementsByTagName("diff")[0], true)); - - var posElement = xmlDocument.createElement("pos"); - posElement.appendChild(document.createTextNode(document.getElementById("board").selectionStart)); - requestElement.appendChild(posElement); - - websocket.send(new XMLSerializer().serializeToString(xmlDocument)); -} - -// for cursor position -function on_selectionchange(pos) -{ - var parser = new DOMParser(); - var xmlDocument = parser.parseFromString("", "text/xml"); - - var requestElement = xmlDocument.getElementsByTagName("request")[0]; - - var commandElement = xmlDocument.createElement("command"); - commandElement.appendChild(document.createTextNode("cursorpos")); - requestElement.appendChild(commandElement); - - var idElement = xmlDocument.createElement("id"); - idElement.appendChild(document.createTextNode(get_id())); - requestElement.appendChild(idElement); - - var posElement = xmlDocument.createElement("pos"); - posElement.appendChild(document.createTextNode(pos)); - requestElement.appendChild(posElement); - - websocket.send(new XMLSerializer().serializeToString(xmlDocument)); -} - -function textAreaSetPos(id, pos) -{ - if (document.getElementById(id).selectionStart != pos) { - document.getElementById(id).selectionStart = pos; - document.getElementById(id).selectionEnd = pos; - caretpos = pos; - } -} - -// HTML button -function on_qrcode_click() -{ - var parser = new DOMParser(); - var xmlDocument = parser.parseFromString("", "text/xml"); - - var requestElement = xmlDocument.getElementsByTagName("request")[0]; - - var commandElement = xmlDocument.createElement("command"); - commandElement.appendChild(document.createTextNode("qrcode")); - requestElement.appendChild(commandElement); - - var idElement = xmlDocument.createElement("url"); - idElement.appendChild(document.createTextNode(document.location)); - requestElement.appendChild(idElement); - - websocket.send(new XMLSerializer().serializeToString(xmlDocument)); -} - -function on_pdf_click() -{ - websocket.send("pdf" + get_id() + ""); -} - diff --git a/main.cpp b/main.cpp index e1c1cf1..6a27658 100644 --- a/main.cpp +++ b/main.cpp @@ -1,8 +1,8 @@ -#include "whiteboard.h" +#include "webchat.h" int main(int argc, char* argv[]) { - Whiteboard whiteboard; - return whiteboard.run(argc, argv); + Webchat webchat; + return webchat.run(argc, argv); } diff --git a/qrcode.cpp b/qrcode.cpp deleted file mode 100644 index da747a5..0000000 --- a/qrcode.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "qrcode.h" - -#include - -#include - -#include - -using namespace qrcodegen; -using namespace Magick; - -void QRCode::init() -{ - Magick::InitializeMagick(NULL); -} - -std::string QRCode::getQRCode(const std::string& data) -{ - QrCode qrc {QrCode::encodeText(data.c_str(), QrCode::Ecc::MEDIUM)}; - - int size {qrc.getSize()}; - - Image image(fmt::format("{0}x{0}", size).c_str(), "white"); - image.type(GrayscaleType); - - for (int x = 0; x < size; x++) { - for (int y = 0; y < size; y++) { - image.pixelColor(x, y, qrc.getModule(x, y) ? "black" : "white"); - } - } - - image.magick("PNG"); - - Blob blob; - image.write(&blob); - return std::string{(char*)blob.data(), blob.length()}; -} diff --git a/qrcode.h b/qrcode.h deleted file mode 100644 index f37c318..0000000 --- a/qrcode.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include - -namespace QRCode -{ - void init(); - - // returns PNG file contents - std::string getQRCode(const std::string& data); -} diff --git a/tests/Makefile b/tests/Makefile index f3ec6c8..44c884a 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -11,15 +11,13 @@ CXXFLAGS+=--coverage LDFLAGS+=--coverage endif -UNITS=storage.cpp config.cpp compiledsql.cpp qrcode.cpp whiteboard.cpp connectionregistry.cpp diff.cpp +UNITS=storage.cpp config.cpp compiledsql.cpp webchat.cpp connectionregistry.cpp UNITTESTS=test-config.cpp \ test-storage.cpp \ test-connectionregistry.cpp \ test-compiledsql.cpp \ - test-qrcode.cpp \ - test-whiteboard.cpp \ - test-diff.cpp + test-webchat.cpp CXXFLAGS+=\ -I/usr/src/googletest/googletest/include \ @@ -54,19 +52,13 @@ config.o: ../config.cpp connectionregistry.o: ../connectionregistry.cpp $(CXX) $(CXXFLAGS) -o $@ -c $< -diff.o: ../diff.cpp - $(CXX) $(CXXFLAGS) -o $@ -c $< - storage.o: ../storage.cpp $(CXX) $(CXXFLAGS) -o $@ -c $< compiledsql.o: ../compiledsql.cpp $(CXX) $(CXXFLAGS) -o $@ -c $< -whiteboard.o: ../whiteboard.cpp - $(CXX) $(CXXFLAGS) -o $@ -c $< - -qrcode.o: ../qrcode.cpp +webchat.o: ../webchat.cpp $(CXX) $(CXXFLAGS) -o $@ -c $< libgmock.a: diff --git a/tests/test-diff.cpp b/tests/test-diff.cpp deleted file mode 100644 index d09c58e..0000000 --- a/tests/test-diff.cpp +++ /dev/null @@ -1,199 +0,0 @@ -#include - -#include -#include -#include - -#include - -#include - -#include "libreichwein/file.h" - -#include "diff.h" - -namespace fs = std::filesystem; -namespace pt = boost::property_tree; -using namespace Reichwein; - -class DiffTest: public ::testing::Test -{ -protected: - DiffTest(){ - } - - ~DiffTest(){ - } -}; - -TEST_F(DiffTest, constructor) -{ - // empty constructor - { - Diff d{}; - EXPECT_EQ(d.get_xml(), "00"); - } - - // constructor via xml diff - { - EXPECT_THROW(Diff d{""}, std::exception); - } - { - EXPECT_THROW(Diff d{""}, std::exception); - EXPECT_THROW(Diff d{"0abc"}, std::exception); - EXPECT_THROW(Diff d{"0abc"}, std::exception); - EXPECT_THROW(Diff d{"00"}, std::exception); - EXPECT_THROW(Diff d{"50abc"}, std::exception); - EXPECT_THROW(Diff d{"0abc"}, std::exception); - } - - { - Diff d{"00abc"}; - EXPECT_EQ(d.get_xml(), "00abc"); - } - - { - Diff d{"55abc"}; - EXPECT_EQ(d.get_xml(), "55abc"); - } - - { - Diff d{"550abc"}; - EXPECT_EQ(d.get_xml(), "550abc"); - } - - // constructor via ptree - { - pt::ptree ptree; - EXPECT_THROW(Diff d{ptree}, std::exception); - - ptree.put("diff.start", 0); - ptree.put("diff.end", 0); - ptree.put("diff.data", "abc"); - Diff d{ptree}; - EXPECT_EQ(d.get_xml(), "00abc"); - } - - // constructor via versions - { - Diff d{"", ""}; - EXPECT_EQ(d.get_xml(), "00"); - } - { - Diff d{"a", "a"}; - EXPECT_EQ(d.get_xml(), "00"); - } - { - Diff d{"a", "b"}; - EXPECT_EQ(d.get_xml(), "01b"); - } - { - Diff d{"0a1", "0b1"}; - EXPECT_EQ(d.get_xml(), "12b"); - } - { - Diff d{"0abc1", "00b01"}; - EXPECT_EQ(d.get_xml(), "140b0"); - } - { - Diff d{"0ab1", "00b01"}; - EXPECT_EQ(d.get_xml(), "130b0"); - } - { - Diff d{"0abc1", "00b1"}; - EXPECT_EQ(d.get_xml(), "140b"); - } - { - Diff d{"0abc1", ""}; - EXPECT_EQ(d.get_xml(), "05"); - } - { - Diff d{"bc1", "0abc1"}; - EXPECT_EQ(d.get_xml(), "000a"); - } - { - Diff d{"0abc1", "0ab"}; - EXPECT_EQ(d.get_xml(), "35"); - } - { - Diff d{"0abc1", "0abc123"}; - EXPECT_EQ(d.get_xml(), "5523"); - } - { - Diff d{"0abc1", "010abc1"}; - EXPECT_EQ(d.get_xml(), "0001"); - } - { - Diff d{"0abc1", "0ac1"}; - EXPECT_EQ(d.get_xml(), "23"); - } - { - Diff d{"0abc1", "0abxc1"}; - EXPECT_EQ(d.get_xml(), "33x"); - } - { - Diff d{"abc", "c"}; - EXPECT_EQ(d.get_xml(), "02"); - } - { - Diff d{"aaaa", "aa"}; - EXPECT_EQ(d.get_xml(), "24"); - } - { - Diff d{"baaaa", "baa"}; - EXPECT_EQ(d.get_xml(), "35"); - } - { - Diff d{"baaaab", "baab"}; - EXPECT_EQ(d.get_xml(), "13"); - } - { - Diff d{"baaaab", "baaaaaaab"}; - EXPECT_EQ(d.get_xml(), "11aaa"); - } -} - -TEST_F(DiffTest, empty) -{ - { - Diff d; - EXPECT_TRUE(d.empty()); - } - - { - Diff d{"13"}; - EXPECT_FALSE(d.empty()); - } - - { - Diff d{"11"}; - EXPECT_TRUE(d.empty()); - } - - { - Diff d{"11abc"}; - EXPECT_FALSE(d.empty()); - } - - { - Diff d{"00"}; - EXPECT_TRUE(d.empty()); - } -} - -TEST_F(DiffTest, diff_create) -{ - const char* result {diff_create("0abc1", "0ab")}; - - EXPECT_EQ(std::string(result), "35"); - free((void*)result); // this will be done by javascript side in real scenario -} - -TEST_F(DiffTest, diff_apply) -{ - const char* result {diff_apply("0abc1", "35")}; - - EXPECT_EQ(std::string(result), "0ab"); - free((void*)result); // this will be done by javascript side in real scenario -} - diff --git a/tests/test-qrcode.cpp b/tests/test-qrcode.cpp deleted file mode 100644 index 96cfdb0..0000000 --- a/tests/test-qrcode.cpp +++ /dev/null @@ -1,140 +0,0 @@ -#include - -#include -#include -#include -#include - -#include "libreichwein/file.h" - -#include "qrcode.h" - -namespace fs = std::filesystem; - -class QRCodeTest: public ::testing::Test -{ -protected: - QRCodeTest(){ - } - - ~QRCodeTest() override{ - } - - void SetUp() override - { - QRCode::init(); - } - - void TearDown() override - { - } - -}; - -TEST_F(QRCodeTest, empty) -{ - unsigned char empty_png[] = { - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, - 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x15, - 0x10, 0x00, 0x00, 0x00, 0x00, 0xdc, 0xec, 0x26, 0x09, 0x00, 0x00, 0x00, - 0xa7, 0x49, 0x44, 0x41, 0x54, 0x28, 0xcf, 0x7d, 0x92, 0x4b, 0x12, 0xc3, - 0x30, 0x08, 0x43, 0x79, 0x99, 0xde, 0xff, 0xca, 0xea, 0x82, 0x51, 0xf9, - 0xc4, 0xae, 0x17, 0x89, 0x01, 0x03, 0x02, 0x89, 0x18, 0x47, 0x8a, 0x00, - 0x29, 0x2d, 0xe8, 0xb1, 0x4f, 0x86, 0x7b, 0x48, 0x02, 0x7b, 0x57, 0xcc, - 0xa6, 0xd4, 0x43, 0xd3, 0x96, 0x22, 0x9e, 0x38, 0x9e, 0x9e, 0xe2, 0xf3, - 0x9c, 0x1f, 0x15, 0xde, 0x81, 0xf5, 0x5d, 0x43, 0x02, 0x3f, 0x3e, 0xd5, - 0x1f, 0xf8, 0x36, 0xee, 0x88, 0x08, 0xae, 0x59, 0x37, 0xac, 0x00, 0xfe, - 0xee, 0x9d, 0x76, 0x6f, 0x48, 0x52, 0xb5, 0xcc, 0x7b, 0xfd, 0xed, 0x1f, - 0x1b, 0xa8, 0xec, 0x64, 0x6d, 0x51, 0x31, 0xab, 0x15, 0xf2, 0xb2, 0xdc, - 0x91, 0x4e, 0x24, 0x48, 0x7d, 0xa3, 0x53, 0x03, 0xaf, 0x0d, 0x54, 0xd3, - 0x9b, 0x6c, 0x16, 0xa1, 0x7b, 0x34, 0x29, 0x82, 0xa9, 0x9e, 0x84, 0x61, - 0xc6, 0x66, 0xfd, 0xc7, 0x9b, 0x73, 0x93, 0x2d, 0xc0, 0xf4, 0xc3, 0x1f, - 0x65, 0xf1, 0x1b, 0xd8, 0x30, 0xae, 0xca, 0x9a, 0x83, 0x02, 0x1c, 0x94, - 0xe5, 0x4d, 0x27, 0x42, 0x57, 0x3e, 0x34, 0xde, 0x74, 0x16, 0xf2, 0x2f, - 0x2f, 0xd5, 0xa5, 0xd0, 0x5a, 0x61, 0xde, 0x49, 0x00, 0x00, 0x00, 0x00, - 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 - }; - // Test prepared with: - //File::setFile("empty.png", QRCode::getQRCode("")); - //then: xxd -i tests/empty.png >> tests/test-qrcode.cpp - - EXPECT_EQ(QRCode::getQRCode(""), std::string(reinterpret_cast(&empty_png[0]), sizeof(empty_png))); -} - -TEST_F(QRCodeTest, simple) -{ - unsigned char simple_png[] = { - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, - 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x15, - 0x10, 0x00, 0x00, 0x00, 0x00, 0xdc, 0xec, 0x26, 0x09, 0x00, 0x00, 0x00, - 0xa5, 0x49, 0x44, 0x41, 0x54, 0x28, 0xcf, 0x75, 0x52, 0xd1, 0x0e, 0xc0, - 0x40, 0x04, 0x6b, 0x17, 0xff, 0xff, 0xcb, 0xf6, 0xe0, 0x4c, 0x39, 0x93, - 0x6c, 0x09, 0x47, 0x55, 0x01, 0x9a, 0xb9, 0xbb, 0xbb, 0x03, 0xf9, 0xa9, - 0x99, 0x86, 0x48, 0x80, 0x8c, 0xe4, 0x2c, 0xd5, 0xb7, 0xcf, 0x2d, 0xa4, - 0xfa, 0xeb, 0x9b, 0x61, 0xb5, 0xd9, 0x1c, 0x00, 0x9e, 0x2d, 0x2d, 0x88, - 0xcc, 0xb8, 0xdd, 0x18, 0xa4, 0x3b, 0xa9, 0xad, 0x7f, 0x1b, 0xff, 0x29, - 0xc0, 0xbd, 0x8a, 0x5c, 0xf0, 0x52, 0xc7, 0x2e, 0x90, 0x2a, 0x91, 0x51, - 0x4b, 0xfa, 0xc9, 0x2e, 0xfc, 0x40, 0x55, 0x6c, 0xb2, 0xe1, 0xf5, 0x4e, - 0xd3, 0x7f, 0xaa, 0xf2, 0xa6, 0x52, 0x24, 0x48, 0x77, 0xd9, 0xfa, 0x9c, - 0x7c, 0xae, 0xf7, 0x52, 0xa0, 0xab, 0xaa, 0x71, 0xeb, 0x5b, 0xa9, 0x21, - 0xfa, 0x50, 0x67, 0x5b, 0xe3, 0x7a, 0xd0, 0x67, 0x8f, 0x0e, 0xe4, 0x59, - 0x6c, 0xa4, 0x94, 0x96, 0xda, 0x29, 0xca, 0x80, 0xf5, 0x5c, 0x52, 0x53, - 0x3d, 0x9a, 0xa3, 0xcb, 0x7d, 0xaf, 0x93, 0xf9, 0xa1, 0xd2, 0xb9, 0xea, - 0xc6, 0x92, 0xf1, 0x7a, 0x0f, 0xaa, 0xee, 0x8c, 0x03, 0x2f, 0x88, 0x71, - 0xb5, 0xba, 0xf0, 0x88, 0xba, 0xb0, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, - 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 - }; - // Test prepared with: - //File::setFile("simple.png", QRCode::getQRCode("abc")); - //then: xxd -i tests/simple.png >> tests/test-qrcode.cpp - EXPECT_EQ(QRCode::getQRCode("abc"), std::string(reinterpret_cast(&simple_png[0]), sizeof(simple_png))); -} - -TEST_F(QRCodeTest, url) -{ - unsigned char url_png[] = { - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, - 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x1d, - 0x10, 0x00, 0x00, 0x00, 0x00, 0x23, 0x68, 0xe4, 0x90, 0x00, 0x00, 0x01, - 0x1f, 0x49, 0x44, 0x41, 0x54, 0x38, 0xcb, 0x75, 0x54, 0xdb, 0x0e, 0xc5, - 0x30, 0x08, 0x92, 0xa5, 0xff, 0xff, 0xcb, 0x9c, 0x07, 0xe7, 0x41, 0xb4, - 0x6b, 0xb2, 0x64, 0x36, 0x5e, 0xa8, 0xa0, 0x11, 0x76, 0xc8, 0x08, 0x92, - 0x24, 0xcb, 0xde, 0x7f, 0x75, 0x4e, 0xba, 0xe7, 0x01, 0x22, 0x48, 0x20, - 0xbf, 0xb4, 0x2b, 0xe1, 0xfc, 0x03, 0x4e, 0x85, 0xd4, 0x75, 0x06, 0xe5, - 0xbf, 0xc2, 0xf3, 0xd6, 0x7d, 0x9f, 0x58, 0x07, 0x50, 0xbd, 0xc2, 0x11, - 0x97, 0xb3, 0x42, 0x3b, 0xd0, 0xb4, 0x33, 0x7c, 0x87, 0x1e, 0x7f, 0x81, - 0xd7, 0x51, 0x0a, 0x01, 0xbe, 0x25, 0x69, 0x1d, 0xfe, 0xfe, 0xac, 0xea, - 0x2d, 0x8b, 0x57, 0x50, 0xed, 0xe1, 0xbb, 0x73, 0x3a, 0xaf, 0x65, 0x7b, - 0xba, 0xd7, 0xea, 0x64, 0x94, 0x93, 0x1c, 0x2a, 0xd8, 0xd3, 0x92, 0x7f, - 0x95, 0xec, 0x90, 0xa9, 0x9f, 0xb2, 0x94, 0xee, 0x88, 0xf4, 0xba, 0x72, - 0x4e, 0xf5, 0x5a, 0x69, 0x6b, 0xf0, 0xdc, 0x6b, 0xf8, 0x4b, 0x85, 0xac, - 0x3f, 0x8a, 0x7c, 0xba, 0x0c, 0x66, 0x78, 0xe7, 0x55, 0xdc, 0x96, 0xda, - 0x5e, 0x99, 0x2b, 0x38, 0xc5, 0x3f, 0x61, 0x6d, 0x0a, 0x81, 0xf0, 0x56, - 0x4c, 0x4e, 0x7d, 0xe4, 0x7c, 0x24, 0x9f, 0x39, 0x74, 0xe5, 0x86, 0x86, - 0x87, 0x04, 0x2e, 0x23, 0xd0, 0xdb, 0x20, 0x8a, 0xe6, 0x60, 0x4f, 0x91, - 0x7c, 0x32, 0xe6, 0x2f, 0xdc, 0x12, 0x79, 0x31, 0x0a, 0x56, 0xe7, 0xb2, - 0xef, 0x07, 0x98, 0x8f, 0x8d, 0xe0, 0x6c, 0xd4, 0x04, 0xb6, 0xe1, 0xbf, - 0xc2, 0x98, 0x97, 0x5d, 0x43, 0xaa, 0x5f, 0xdb, 0xca, 0x6f, 0x57, 0xd3, - 0xee, 0xe4, 0xec, 0x3e, 0x9c, 0x4d, 0x8e, 0x81, 0xc2, 0x2d, 0x5d, 0x56, - 0x7e, 0x32, 0x44, 0xbc, 0xed, 0x6a, 0x1a, 0x87, 0xf4, 0x2a, 0xe8, 0x6b, - 0xad, 0x75, 0x51, 0xfa, 0x66, 0xf4, 0x07, 0x01, 0x97, 0x8d, 0x08, 0x90, - 0x09, 0xb5, 0xef, 0x64, 0xe7, 0xbf, 0x49, 0x62, 0x8e, 0xfa, 0xec, 0xfb, - 0x26, 0xad, 0x8d, 0xba, 0x3b, 0xf5, 0xf6, 0xf8, 0x22, 0x95, 0xf7, 0x0f, - 0x4c, 0x20, 0xaf, 0x2d, 0xca, 0xaf, 0x0d, 0xc5, 0x00, 0x00, 0x00, 0x00, - 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 - }; - // Test prepared with: - //File::setFile("url.png", QRCode::getQRCode("https://reichwein.it/whiteboard")); - //then: xxd -i tests/url.png >> tests/test-qrcode.cpp - EXPECT_EQ(QRCode::getQRCode("https://reichwein.it/whiteboard"), std::string(reinterpret_cast(&url_png[0]), sizeof(url_png))); -} - -TEST_F(QRCodeTest, deterministic) -{ - EXPECT_EQ(QRCode::getQRCode("data1"), QRCode::getQRCode("data1")); -} - -TEST_F(QRCodeTest, different_data) -{ - EXPECT_NE(QRCode::getQRCode("data1"), QRCode::getQRCode("data2")); -} diff --git a/tests/test-webchat.cpp b/tests/test-webchat.cpp new file mode 100644 index 0000000..3f70bcf --- /dev/null +++ b/tests/test-webchat.cpp @@ -0,0 +1,255 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "libreichwein/file.h" +#include "libreichwein/process.h" + +#include "config.h" +#include "storage.h" +#include "whiteboard.h" + +namespace bp = boost::process; +namespace fs = std::filesystem; +using namespace Reichwein; +using namespace std::string_literals; + +namespace { + const fs::path webserverConfigFilename{"./webserver.conf"}; + + const fs::path testConfigFilename{"./whiteboard.conf"}; + const fs::path testDbFilename{"./whiteboard.db3"}; +} + +class WhiteboardTest: public ::testing::Test +{ +protected: + WhiteboardTest(){ + } + + ~WhiteboardTest() override{ + } + + void SetUp() override + { + File::setFile(testConfigFilename, R"CONFIG( + + ::1:9876 + . + 2592000 + 4 + 3 + +)CONFIG"); + std::error_code ec; + fs::remove(testDbFilename, ec); + + m_config = std::make_shared(testConfigFilename); + + m_pid = fork(); + if (m_pid == -1) { + throw std::runtime_error("Error on fork(): "s + strerror(errno)); + } else if (m_pid == 0) { // child + Whiteboard whiteboard; + std::vector argvv{{"whiteboard", "-c", testConfigFilename.generic_string()}}; + char* argv[] = {argvv[0].data(), argvv[1].data(), argvv[2].data(), nullptr}; + whiteboard.run(argvv.size(), argv); + exit(0); + } + Process::wait_for_pid_listening_on(m_pid, 9876); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + + void TearDown() override + { + if (m_pid == 0) + throw std::runtime_error("Whiteboard not running on requesting SIGTERM"); + + if (kill(m_pid, SIGTERM) != 0) + throw std::runtime_error("Unable to SIGTERM Whiteboard"); + + if (int result = waitpid(m_pid, NULL, 0); result != m_pid) + throw std::runtime_error("waitpid returned "s + std::to_string(result)); + + std::error_code ec; + fs::remove(testDbFilename, ec); + fs::remove(testConfigFilename, ec); + } + + std::shared_ptr m_config; + pid_t m_pid{}; +}; + +class WebsocketClient +{ +public: + WebsocketClient() + { + std::string host = "::1"; + auto const port = "9876" ; + + // These objects perform our I/O + boost::asio::ip::tcp::resolver resolver{ioc_}; + ws_ = std::make_unique>(ioc_); + + // Look up the domain name + resolver_results_ = resolver.resolve(host, port); + + connect(); + handshake(); + } + + void connect() + { + // Make the connection on the IP address we get from a lookup + ep_ = boost::asio::connect(boost::beast::get_lowest_layer(*ws_), resolver_results_); + } + + void handshake() + { + // Update the host_ string. This will provide the value of the + // Host HTTP header during the WebSocket handshake. + // See https://tools.ietf.org/html/rfc7230#section-5.4 + std::string host{"[::1]:9876"}; + + // Set a decorator to change the User-Agent of the handshake + ws_->set_option(boost::beast::websocket::stream_base::decorator( + [](boost::beast::websocket::request_type& req) + { + req.set(boost::beast::http::field::user_agent, + std::string("Reichwein.IT Test Websocket Client")); + })); + + // Perform the websocket handshake + ws_->handshake(host, "/"); + + } + + void write(const std::string& data) + { + ws_->write(boost::asio::buffer(data)); + } + + std::string read() + { + boost::beast::flat_buffer buffer; + ws_->read(buffer); + return {boost::asio::buffers_begin(buffer.data()), boost::asio::buffers_end(buffer.data())}; + } + + ~WebsocketClient() + { + } + + bool is_open() + { + return ws_->is_open(); + } + +private: + boost::asio::io_context ioc_; + boost::asio::ip::tcp::resolver::results_type resolver_results_; + std::unique_ptr> ws_; + boost::asio::ip::tcp::endpoint ep_; +}; + +// +// tests via websocket server in separate process (hides coverage) +// + +TEST_F(WhiteboardTest, websocket_server_connection) +{ + WebsocketClient wc; +} + +TEST_F(WhiteboardTest, websocket_server_generate_id) +{ + WebsocketClient wc; + + wc.write("newid"); + std::string result0 {wc.read()}; + ASSERT_TRUE(boost::algorithm::starts_with(result0, "newid")); + ASSERT_TRUE(boost::algorithm::ends_with(result0, "")); + ASSERT_EQ(result0.size(), 58); + + wc.write("newid"); + std::string result1 {wc.read()}; + ASSERT_TRUE(boost::algorithm::starts_with(result1, "newid")); + ASSERT_TRUE(boost::algorithm::ends_with(result1, "")); + ASSERT_EQ(result1.size(), 58); + + ASSERT_NE(result0, result1); +} + +// check number of threads as configured +TEST_F(WhiteboardTest, threads) +{ + ASSERT_GE(Process::number_of_threads(m_pid), 4); +} + +TEST_F(WhiteboardTest, max_connections) +{ + WebsocketClient wc1; + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + ASSERT_TRUE(wc1.is_open()); + + WebsocketClient wc2; + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + ASSERT_TRUE(wc2.is_open()); + + WebsocketClient wc3; + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + ASSERT_TRUE(wc3.is_open()); + + ASSERT_THROW(WebsocketClient wc4, std::exception); +} + +TEST_F(WhiteboardTest, id) +{ + WebsocketClient wc; + + wc.write("getfile1"); + std::string result {wc.read()}; + + EXPECT_EQ(result, "getfile00"); + + wc.write("getfile"); + result = wc.read(); + EXPECT_EQ(result, "errorMessage handling error: Invalid id (empty)"); + + wc.write("getfile01234567890123456789"); + result = wc.read(); + EXPECT_EQ(result, "errorMessage handling error: Invalid id (size > 16)"); + + wc.write("getfileX"); + result = wc.read(); + EXPECT_EQ(result, "errorMessage handling error: Invalid id char: X"); + + wc.write("getfilea."); + result = wc.read(); + EXPECT_EQ(result, "errorMessage handling error: Invalid id char: ."); + + wc.write("getfilea$b"); + result = wc.read(); + EXPECT_EQ(result, "errorMessage handling error: Invalid id char: $"); +} + diff --git a/tests/test-whiteboard.cpp b/tests/test-whiteboard.cpp deleted file mode 100644 index 3f70bcf..0000000 --- a/tests/test-whiteboard.cpp +++ /dev/null @@ -1,255 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "libreichwein/file.h" -#include "libreichwein/process.h" - -#include "config.h" -#include "storage.h" -#include "whiteboard.h" - -namespace bp = boost::process; -namespace fs = std::filesystem; -using namespace Reichwein; -using namespace std::string_literals; - -namespace { - const fs::path webserverConfigFilename{"./webserver.conf"}; - - const fs::path testConfigFilename{"./whiteboard.conf"}; - const fs::path testDbFilename{"./whiteboard.db3"}; -} - -class WhiteboardTest: public ::testing::Test -{ -protected: - WhiteboardTest(){ - } - - ~WhiteboardTest() override{ - } - - void SetUp() override - { - File::setFile(testConfigFilename, R"CONFIG( - - ::1:9876 - . - 2592000 - 4 - 3 - -)CONFIG"); - std::error_code ec; - fs::remove(testDbFilename, ec); - - m_config = std::make_shared(testConfigFilename); - - m_pid = fork(); - if (m_pid == -1) { - throw std::runtime_error("Error on fork(): "s + strerror(errno)); - } else if (m_pid == 0) { // child - Whiteboard whiteboard; - std::vector argvv{{"whiteboard", "-c", testConfigFilename.generic_string()}}; - char* argv[] = {argvv[0].data(), argvv[1].data(), argvv[2].data(), nullptr}; - whiteboard.run(argvv.size(), argv); - exit(0); - } - Process::wait_for_pid_listening_on(m_pid, 9876); - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - } - - void TearDown() override - { - if (m_pid == 0) - throw std::runtime_error("Whiteboard not running on requesting SIGTERM"); - - if (kill(m_pid, SIGTERM) != 0) - throw std::runtime_error("Unable to SIGTERM Whiteboard"); - - if (int result = waitpid(m_pid, NULL, 0); result != m_pid) - throw std::runtime_error("waitpid returned "s + std::to_string(result)); - - std::error_code ec; - fs::remove(testDbFilename, ec); - fs::remove(testConfigFilename, ec); - } - - std::shared_ptr m_config; - pid_t m_pid{}; -}; - -class WebsocketClient -{ -public: - WebsocketClient() - { - std::string host = "::1"; - auto const port = "9876" ; - - // These objects perform our I/O - boost::asio::ip::tcp::resolver resolver{ioc_}; - ws_ = std::make_unique>(ioc_); - - // Look up the domain name - resolver_results_ = resolver.resolve(host, port); - - connect(); - handshake(); - } - - void connect() - { - // Make the connection on the IP address we get from a lookup - ep_ = boost::asio::connect(boost::beast::get_lowest_layer(*ws_), resolver_results_); - } - - void handshake() - { - // Update the host_ string. This will provide the value of the - // Host HTTP header during the WebSocket handshake. - // See https://tools.ietf.org/html/rfc7230#section-5.4 - std::string host{"[::1]:9876"}; - - // Set a decorator to change the User-Agent of the handshake - ws_->set_option(boost::beast::websocket::stream_base::decorator( - [](boost::beast::websocket::request_type& req) - { - req.set(boost::beast::http::field::user_agent, - std::string("Reichwein.IT Test Websocket Client")); - })); - - // Perform the websocket handshake - ws_->handshake(host, "/"); - - } - - void write(const std::string& data) - { - ws_->write(boost::asio::buffer(data)); - } - - std::string read() - { - boost::beast::flat_buffer buffer; - ws_->read(buffer); - return {boost::asio::buffers_begin(buffer.data()), boost::asio::buffers_end(buffer.data())}; - } - - ~WebsocketClient() - { - } - - bool is_open() - { - return ws_->is_open(); - } - -private: - boost::asio::io_context ioc_; - boost::asio::ip::tcp::resolver::results_type resolver_results_; - std::unique_ptr> ws_; - boost::asio::ip::tcp::endpoint ep_; -}; - -// -// tests via websocket server in separate process (hides coverage) -// - -TEST_F(WhiteboardTest, websocket_server_connection) -{ - WebsocketClient wc; -} - -TEST_F(WhiteboardTest, websocket_server_generate_id) -{ - WebsocketClient wc; - - wc.write("newid"); - std::string result0 {wc.read()}; - ASSERT_TRUE(boost::algorithm::starts_with(result0, "newid")); - ASSERT_TRUE(boost::algorithm::ends_with(result0, "")); - ASSERT_EQ(result0.size(), 58); - - wc.write("newid"); - std::string result1 {wc.read()}; - ASSERT_TRUE(boost::algorithm::starts_with(result1, "newid")); - ASSERT_TRUE(boost::algorithm::ends_with(result1, "")); - ASSERT_EQ(result1.size(), 58); - - ASSERT_NE(result0, result1); -} - -// check number of threads as configured -TEST_F(WhiteboardTest, threads) -{ - ASSERT_GE(Process::number_of_threads(m_pid), 4); -} - -TEST_F(WhiteboardTest, max_connections) -{ - WebsocketClient wc1; - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - ASSERT_TRUE(wc1.is_open()); - - WebsocketClient wc2; - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - ASSERT_TRUE(wc2.is_open()); - - WebsocketClient wc3; - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - ASSERT_TRUE(wc3.is_open()); - - ASSERT_THROW(WebsocketClient wc4, std::exception); -} - -TEST_F(WhiteboardTest, id) -{ - WebsocketClient wc; - - wc.write("getfile1"); - std::string result {wc.read()}; - - EXPECT_EQ(result, "getfile00"); - - wc.write("getfile"); - result = wc.read(); - EXPECT_EQ(result, "errorMessage handling error: Invalid id (empty)"); - - wc.write("getfile01234567890123456789"); - result = wc.read(); - EXPECT_EQ(result, "errorMessage handling error: Invalid id (size > 16)"); - - wc.write("getfileX"); - result = wc.read(); - EXPECT_EQ(result, "errorMessage handling error: Invalid id char: X"); - - wc.write("getfilea."); - result = wc.read(); - EXPECT_EQ(result, "errorMessage handling error: Invalid id char: ."); - - wc.write("getfilea$b"); - result = wc.read(); - EXPECT_EQ(result, "errorMessage handling error: Invalid id char: $"); -} - diff --git a/webassembly/Makefile b/webassembly/Makefile index 0487d2a..33d16ea 100644 --- a/webassembly/Makefile +++ b/webassembly/Makefile @@ -1,4 +1,4 @@ -TARGET=libwhiteboard.wasm +TARGET=libwebchat.wasm TARGETJS=$(TARGET:.wasm=.js) OBJS=diff.o diff --git a/webchat.conf b/webchat.conf new file mode 100644 index 0000000..2a08527 --- /dev/null +++ b/webchat.conf @@ -0,0 +1,34 @@ + + + /var/lib/webchat + + + ::1:9015 + + + 2592000 + + + 4 + + + 500 + diff --git a/webchat.cpp b/webchat.cpp new file mode 100644 index 0000000..c752ae0 --- /dev/null +++ b/webchat.cpp @@ -0,0 +1,571 @@ +#include "webchat.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "libreichwein/base64.h" +#include "libreichwein/file.h" +#include "libreichwein/tempfile.h" +#include "libreichwein/xml.h" + +#include "config.h" +#include "diff.h" +#include "qrcode.h" +#include "storage.h" + +namespace pt = boost::property_tree; +using namespace std::string_literals; +using namespace std::placeholders; +namespace fs = std::filesystem; +namespace bp = boost::process; + +namespace { + + void usage() { + std::cout << + "Usage: \n" + " whiteboard [options]\n" + "\n" + "Options:\n" + " -c : specify configuration file including path\n" + " -C : clean up database according to timeout rules (config: maxage)\n" + " -h : this help\n" + "\n" + "Without options, whiteboard will be started as websocket application" + << std::endl; + } + +} // namespace + +Whiteboard::Whiteboard() +{ +} + +namespace { + +pt::ptree make_ptree(const std::initializer_list>& key_values) +{ + pt::ptree ptree; + for (const auto& i: key_values) { + ptree.put(fmt::format("serverinfo.{}", i.first), i.second); + } + + return ptree; +} + +std::string make_xml(const std::initializer_list>& key_values) +{ + pt::ptree ptree{make_ptree(key_values)}; + return Reichwein::XML::plain_xml(ptree); +} + +// throws on invalid id +void validate_id(const std::string& id) { + if (!id.size()) + throw std::runtime_error("Invalid id (empty)"); + + if (id.size() > 16) + throw std::runtime_error("Invalid id (size > 16)"); + + for (const auto c: id) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z'))) + throw std::runtime_error("Invalid id char: "s + c); + } +} + +} // namespace + +class session: public std::enable_shared_from_this +{ +public: + using connection = std::shared_ptr>; + + session(ConnectionRegistry& registry, Storage& storage, std::mutex& storage_mutex, boost::asio::ip::tcp::socket socket): + m_registry(registry), + m_storage(storage), + m_storage_mutex(storage_mutex), + m_ws(std::make_shared(std::move(socket))), + m_connection_guard(m_registry, m_ws) + { + } + + ~session() + { + if (m_stats_timer) + m_stats_timer->cancel(); + m_stats_timer = nullptr; + } + + void do_read_handshake() + { + // Set a decorator to change the Server of the handshake + m_ws->set_option(boost::beast::websocket::stream_base::decorator( + [](boost::beast::websocket::response_type& res) + { + res.set(boost::beast::http::field::server, + std::string("Reichwein.IT Whiteboard")); + })); + + boost::beast::http::async_read(m_ws->next_layer(), m_buffer, m_parser, + boost::asio::bind_executor(m_ws->next_layer().get_executor(), boost::beast::bind_front_handler(&session::on_read_handshake, shared_from_this()))); + } + + void on_read_handshake(boost::beast::error_code ec, std::size_t bytes_transferred) + { + boost::ignore_unused(bytes_transferred); + if (ec) { + std::cerr << "Error on session handshake read: " << ec.message() << std::endl; + } else { + do_accept_handshake(); + } + } + + void do_accept_handshake() + { + m_req = m_parser.get(); + + m_ws->async_accept(m_req, boost::beast::bind_front_handler(&session::on_accept_handshake, shared_from_this())); + } + + void on_accept_handshake(boost::beast::error_code ec) + { + if (ec) { + std::cerr << "Error on session handshake accept: " << ec.message() << std::endl; + } else { + do_read(); + } + } + + void do_read() + { + if (m_buffer.size() > 0) { + m_buffer.consume(m_buffer.size()); + } + + m_ws->async_read(m_buffer, boost::beast::bind_front_handler(&session::on_read, shared_from_this())); + } + + void on_read(boost::beast::error_code ec, std::size_t bytes_transferred) + { + boost::ignore_unused(bytes_transferred); + if (ec) { + if (ec != boost::beast::websocket::error::closed) + std::cerr << "Error on session read: " << ec.message() << std::endl; + } else { + do_write(); + } + } + + void do_write() + { + m_ws->text(m_ws->got_text()); + std::string data(boost::asio::buffers_begin(m_buffer.data()), boost::asio::buffers_end(m_buffer.data())); + data = handle_request(data); + if (m_buffer.size() > 0) { + m_buffer.consume(m_buffer.size()); + } + if (data.size() > 0) { + boost::beast::ostream(m_buffer) << data; + m_ws->async_write(m_buffer.data(), + boost::asio::bind_executor(m_ws->next_layer().get_executor(), + boost::beast::bind_front_handler(&session::on_write, shared_from_this()))); + } else { + do_read(); + } + } + + void on_write(boost::beast::error_code ec, std::size_t bytes_transferred) + { + boost::ignore_unused(bytes_transferred); + + if (ec) { + std::cerr << "Error on session write: " << ec.message() << std::endl; + } else { + do_read(); + } + } + + void run() + { + do_read_handshake(); + } + + void on_write_notify(std::shared_ptr data, std::shared_ptr buffer, boost::beast::error_code ec, std::size_t bytes_transferred) + { + boost::ignore_unused(bytes_transferred); + + if (ec) { + std::cerr << "Error on session write notify: " << ec.message() << std::endl; + } + } + + void notify_other_connections_diff(const std::string& id, const Diff& diff) + { + std::for_each(m_registry.begin(id), m_registry.end(id), [&](const connection& ci) + { + if (m_ws != ci) { + pt::ptree ptree {make_ptree({ + {"type", "getdiff"}, + {"revision", std::to_string(m_storage.getRevision(id))}, + {"pos", std::to_string(m_storage.getCursorPos(id)) } + })}; + ptree.put_child("serverinfo.diff", diff.get_structure().get_child("diff")); + auto data{std::make_shared(Reichwein::XML::plain_xml(ptree))}; + auto buffer{std::make_shared(data->data(), data->size())}; + try { + ci->async_write(*buffer, boost::asio::bind_executor(ci->next_layer().get_executor(), + boost::beast::bind_front_handler(&session::on_write_notify, shared_from_this(), data, buffer))); + } catch (const std::exception& ex) { + std::cerr << "Warning: Notify getdiff write for " << ci << " not possible, id " << id << std::endl; + m_registry.dump(); + } + } + }); + } + + void notify_other_connections_pos(const std::string& id) + { + std::for_each(m_registry.begin(id), m_registry.end(id), [&](const connection& ci) + { + if (m_ws != ci) { + auto data{std::make_shared(make_xml({ + {"type", "getpos"}, + {"pos", std::to_string(m_storage.getCursorPos(id)) } + }))}; + auto buffer{std::make_shared(data->data(), data->size())}; + try { + ci->async_write(*buffer, boost::asio::bind_executor(ci->next_layer().get_executor(), + boost::beast::bind_front_handler(&session::on_write_notify, shared_from_this(), data, buffer))); + } catch (const std::exception& ex) { + std::cerr << "Warning: Notify getpos write for " << ci << " not possible, id " << id << std::endl; + m_registry.dump(); + } + } + }); + } + + std::string stats_xml() + { + return make_xml({ + {"type", "stats" }, + {"dbsizegross", std::to_string(m_storage.dbsize_gross()) }, + {"dbsizenet", std::to_string(m_storage.dbsize_net()) }, + {"numberofdocuments", std::to_string(m_storage.getNumberOfDocuments()) }, + {"numberofconnections", std::to_string(m_registry.number_of_connections()) }, + }); + } + + void on_write_stats(std::shared_ptr data, std::shared_ptr buffer, boost::beast::error_code ec, std::size_t bytes_transferred) + { + boost::ignore_unused(bytes_transferred); + + if (ec) { + std::cerr << "Error on session write stats: " << ec.message() << std::endl; + } + } + + void stats_callback(const boost::system::error_code&) + { + if (m_stats_timer) { + auto data{std::make_shared(stats_xml())}; + auto buffer{std::make_shared(data->data(), data->size())}; + m_ws->async_write(*buffer, boost::asio::bind_executor(m_ws->next_layer().get_executor(), + boost::beast::bind_front_handler(&session::on_write_stats, shared_from_this(), data, buffer))); + + m_stats_timer->expires_at(m_stats_timer->expires_at() + boost::asio::chrono::seconds(5)); + m_stats_timer->async_wait(boost::beast::bind_front_handler(&session::stats_callback, this)); + } + } + + void setup_stats_timer() + { + if (!m_stats_timer) { + m_stats_timer = std::make_shared(m_ws->next_layer().get_executor(), boost::asio::chrono::seconds(5)); + m_stats_timer->async_wait(boost::beast::bind_front_handler(&session::stats_callback, this)); + } + } + + std::string handle_request(const std::string& request) + { + try { + std::lock_guard lock(m_storage_mutex); + + pt::ptree xml; + std::istringstream ss{request}; + pt::xml_parser::read_xml(ss, xml); + + std::string command {xml.get("request.command")}; + + if (command == "modify") { + std::string id {xml.get("request.id")}; + validate_id(id); + + int baserev {xml.get("request.baserev")}; + if (baserev != m_storage.getRevision(id)) + return make_xml({{"type", "error"}, {"message", "Bad base revision ("s + std::to_string(baserev) + "). Current: "s + std::to_string(m_storage.getRevision(id)) }}); + + pt::ptree ptree; + ptree.put_child("diff", xml.get_child("request.diff")); + Diff d{ptree}; + if (!d.empty()) { + std::string data {m_storage.getDocument(id)}; + data = d.apply(data); + + m_storage.setDocument(id, data); + m_registry.setId(m_ws, id); + notify_other_connections_diff(id, d); + } + + int pos {xml.get("request.pos")}; + if (m_storage.getCursorPos(id) != pos) { + m_storage.setCursorPos(id, pos); + notify_other_connections_pos(id); + } + return make_xml({{"type", "modify"}, {"revision", std::to_string(m_storage.getRevision(id)) }}); + } else if (command == "cursorpos") { + std::string id {xml.get("request.id")}; + validate_id(id); + int pos {xml.get("request.pos")}; + if (m_storage.getCursorPos(id) != pos) { + m_storage.setCursorPos(id, pos); + notify_other_connections_pos(id); + } + return {}; + } else if (command == "getfile") { + std::string id {xml.get("request.id")}; + validate_id(id); + + std::string filedata; + try { + filedata = m_storage.getDocument(id); + } catch (const std::runtime_error&) { + m_storage.setDocument(id, filedata); + } + + if (filedata.size() > 30000000) + throw std::runtime_error("File too big"); + m_registry.setId(m_ws, id); + + return make_xml({ + {"type", "getfile"}, + {"data", filedata}, + {"revision", std::to_string(m_storage.getRevision(id)) }, + {"pos", std::to_string(m_storage.getCursorPos(id)) } + }); + } else if (command == "getpos") { + std::string id {xml.get("request.id")}; + validate_id(id); + + return make_xml({ + {"type", "getpos"}, + {"pos", std::to_string(m_storage.getCursorPos(id)) } + }); + } else if (command == "newid") { + return make_xml({{"type", "newid"}, {"id", m_storage.generate_id()}}); + } else if (command == "qrcode") { + std::string url{xml.get("request.url")}; + + if (url.size() > 1000) + throw std::runtime_error("URL too big"); + + std::string pngdata {QRCode::getQRCode(url)}; + + return make_xml({{"type", "qrcode"}, {"png", Reichwein::Base64::encode64(pngdata)}}); + } else if (command == "getversion") { + return make_xml({ + {"type", "version"}, + {"version", WHITEBOARD_VERSION } + }); + } else if (command == "getstats") { + setup_stats_timer(); + return stats_xml(); + } else if (command == "pdf") { + std::string id {xml.get("request.id")}; + validate_id(id); + Reichwein::Tempfile mdFilePath{".md"}; + Reichwein::File::setFile(mdFilePath.getPath(), m_storage.getDocument(id)); + Reichwein::Tempfile pdfFilePath{".pdf"}; + int system_result{bp::system("/usr/bin/pandoc", mdFilePath.getPath().generic_string(), "-o", pdfFilePath.getPath().generic_string())}; + if (system_result) + throw std::runtime_error("pandoc returned: "s + std::to_string(system_result)); + std::string pdfdata{Reichwein::File::getFile(pdfFilePath.getPath())}; + return make_xml({{"type", "pdf"}, {"pdf", Reichwein::Base64::encode64(pdfdata)}}); + } else { + throw std::runtime_error("Bad command: "s + command); + } + + } catch (const std::exception& ex) { + return make_xml({{"type", "error"}, {"message", "Message handling error: "s + ex.what()}}); + } + } +private: + ConnectionRegistry& m_registry; + Storage& m_storage; + std::mutex& m_storage_mutex; + connection m_ws; + ConnectionRegistry::RegistryGuard m_connection_guard; + + boost::beast::http::request_parser m_parser; + boost::beast::http::request m_req; + boost::beast::flat_buffer m_buffer; + + std::shared_ptr m_stats_timer{}; +}; + +void Whiteboard::do_accept() +{ + // The new connection gets its own strand + m_acceptor->async_accept(boost::asio::make_strand(*m_ioc), + std::bind(&Whiteboard::on_accept, this, _1, _2)); +} + +void Whiteboard::on_accept(boost::system::error_code ec, boost::asio::ip::tcp::socket socket) +{ + if (ec) { + std::cerr << "Error on accept: " << ec.message() << std::endl; + } else { + if (m_registry.number_of_connections() >= m_config->getMaxConnections()) { + // limit reached + socket.close(); + } else { + std::make_shared(m_registry, *m_storage, m_storage_mutex, std::move(socket))->run(); + } + } + + do_accept(); +} + +// for long running connections, don't timeout them but touch associated ids +// regularly, at cleanup time +void Whiteboard::touch_all_connections() +{ + std::for_each(m_registry.begin(), m_registry.end(), [&](const std::pair& i) + { + m_storage->touchDocument(i.second); + }); +} + +// the actual main() for testability +int Whiteboard::run(int argc, char* argv[]) +{ + try { + bool flag_cleanup{}; + fs::path configFile; + + if (argc == 2) { + if (argv[1] == "-h"s || argv[1] == "-?"s) { + usage(); + exit(0); + } else if (argv[1] == "-C"s) { + flag_cleanup = true; + } + } else if (argc == 3) { + if (argv[1] == "-c"s) { + configFile = argv[2]; + } + } + + if (configFile.empty()) + m_config = std::make_unique(); + else + m_config = std::make_unique(configFile); + + m_storage = std::make_unique(*m_config); + + if (flag_cleanup) { + m_storage->cleanup(); + exit(0); + } + + QRCode::init(); + + auto const address = boost::asio::ip::make_address(m_config->getListenAddress()); + auto const port = static_cast(m_config->getListenPort()); + + // The io_context is required for all I/O + m_ioc = std::make_unique(m_config->getThreads()); + + // for now, just terminate on SIGINT, SIGHUP and SIGTERM + boost::asio::signal_set signals(*m_ioc, SIGINT, SIGTERM, SIGHUP); + signals.async_wait([&](const boost::system::error_code& error, int signal_number){ + std::cout << "Terminating via signal " << signal_number << std::endl; + m_ioc->stop(); + }); + + // Storage cleanup once a day + boost::asio::steady_timer storage_cleanup_timer(*m_ioc, boost::asio::chrono::hours(24)); + std::function storage_cleanup_callback = + [&](const boost::system::error_code& error){ + std::lock_guard lock(m_storage_mutex); + if (!m_storage) + throw std::runtime_error("Storage not initialized"); + touch_all_connections(); + m_storage->cleanup(); + storage_cleanup_timer.expires_at(storage_cleanup_timer.expires_at() + boost::asio::chrono::hours(24)); + storage_cleanup_timer.async_wait(storage_cleanup_callback); + }; + storage_cleanup_timer.async_wait(storage_cleanup_callback); + + // The acceptor receives incoming connections + m_acceptor = std::make_unique(*m_ioc, boost::asio::ip::tcp::endpoint{address, port}); + + do_accept(); + + // Run the I/O service on the requested number of threads + std::vector v; + v.reserve(m_config->getThreads() - 1); + for (auto i = m_config->getThreads() - 1; i > 0; --i) { + v.emplace_back( + [&] + { + m_ioc->run(); + }); + } + m_ioc->run(); + + for (auto& t: v) { + t.join(); + } + + } catch (const std::exception& ex) { + std::cerr << "Error: " << ex.what() << std::endl; + } + + return 0; +} + diff --git a/webchat.h b/webchat.h new file mode 100644 index 0000000..cfec920 --- /dev/null +++ b/webchat.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#include "diff.h" +#include "config.h" +#include "connectionregistry.h" +#include "storage.h" + +class Webchat +{ +public: + Webchat(); + int run(int argc, char* argv[]); + +private: + std::unique_ptr m_config; + std::unique_ptr m_storage; + std::mutex m_storage_mutex; + + ConnectionRegistry m_registry; + + std::unique_ptr m_ioc; + std::unique_ptr m_acceptor; + + void do_accept(); + void on_accept(boost::system::error_code ec, boost::asio::ip::tcp::socket socket); + void touch_all_connections(); +}; + diff --git a/webserver.conf.example b/webserver.conf.example index 9193a5b..2ddd679 100644 --- a/webserver.conf.example +++ b/webserver.conf.example @@ -1,8 +1,8 @@ - + static-files - /usr/lib/whiteboard/html + /usr/lib/webchat/html - + websocket - 127.0.0.1:9014 + 127.0.0.1:9015 diff --git a/whiteboard.conf b/whiteboard.conf deleted file mode 100644 index 4622db9..0000000 --- a/whiteboard.conf +++ /dev/null @@ -1,34 +0,0 @@ - - - /var/lib/whiteboard - - - ::1:9014 - - - 2592000 - - - 4 - - - 500 - diff --git a/whiteboard.cpp b/whiteboard.cpp deleted file mode 100644 index 8fb5415..0000000 --- a/whiteboard.cpp +++ /dev/null @@ -1,571 +0,0 @@ -#include "whiteboard.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "libreichwein/base64.h" -#include "libreichwein/file.h" -#include "libreichwein/tempfile.h" -#include "libreichwein/xml.h" - -#include "config.h" -#include "diff.h" -#include "qrcode.h" -#include "storage.h" - -namespace pt = boost::property_tree; -using namespace std::string_literals; -using namespace std::placeholders; -namespace fs = std::filesystem; -namespace bp = boost::process; - -namespace { - - void usage() { - std::cout << - "Usage: \n" - " whiteboard [options]\n" - "\n" - "Options:\n" - " -c : specify configuration file including path\n" - " -C : clean up database according to timeout rules (config: maxage)\n" - " -h : this help\n" - "\n" - "Without options, whiteboard will be started as websocket application" - << std::endl; - } - -} // namespace - -Whiteboard::Whiteboard() -{ -} - -namespace { - -pt::ptree make_ptree(const std::initializer_list>& key_values) -{ - pt::ptree ptree; - for (const auto& i: key_values) { - ptree.put(fmt::format("serverinfo.{}", i.first), i.second); - } - - return ptree; -} - -std::string make_xml(const std::initializer_list>& key_values) -{ - pt::ptree ptree{make_ptree(key_values)}; - return Reichwein::XML::plain_xml(ptree); -} - -// throws on invalid id -void validate_id(const std::string& id) { - if (!id.size()) - throw std::runtime_error("Invalid id (empty)"); - - if (id.size() > 16) - throw std::runtime_error("Invalid id (size > 16)"); - - for (const auto c: id) { - if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z'))) - throw std::runtime_error("Invalid id char: "s + c); - } -} - -} // namespace - -class session: public std::enable_shared_from_this -{ -public: - using connection = std::shared_ptr>; - - session(ConnectionRegistry& registry, Storage& storage, std::mutex& storage_mutex, boost::asio::ip::tcp::socket socket): - m_registry(registry), - m_storage(storage), - m_storage_mutex(storage_mutex), - m_ws(std::make_shared(std::move(socket))), - m_connection_guard(m_registry, m_ws) - { - } - - ~session() - { - if (m_stats_timer) - m_stats_timer->cancel(); - m_stats_timer = nullptr; - } - - void do_read_handshake() - { - // Set a decorator to change the Server of the handshake - m_ws->set_option(boost::beast::websocket::stream_base::decorator( - [](boost::beast::websocket::response_type& res) - { - res.set(boost::beast::http::field::server, - std::string("Reichwein.IT Whiteboard")); - })); - - boost::beast::http::async_read(m_ws->next_layer(), m_buffer, m_parser, - boost::asio::bind_executor(m_ws->next_layer().get_executor(), boost::beast::bind_front_handler(&session::on_read_handshake, shared_from_this()))); - } - - void on_read_handshake(boost::beast::error_code ec, std::size_t bytes_transferred) - { - boost::ignore_unused(bytes_transferred); - if (ec) { - std::cerr << "Error on session handshake read: " << ec.message() << std::endl; - } else { - do_accept_handshake(); - } - } - - void do_accept_handshake() - { - m_req = m_parser.get(); - - m_ws->async_accept(m_req, boost::beast::bind_front_handler(&session::on_accept_handshake, shared_from_this())); - } - - void on_accept_handshake(boost::beast::error_code ec) - { - if (ec) { - std::cerr << "Error on session handshake accept: " << ec.message() << std::endl; - } else { - do_read(); - } - } - - void do_read() - { - if (m_buffer.size() > 0) { - m_buffer.consume(m_buffer.size()); - } - - m_ws->async_read(m_buffer, boost::beast::bind_front_handler(&session::on_read, shared_from_this())); - } - - void on_read(boost::beast::error_code ec, std::size_t bytes_transferred) - { - boost::ignore_unused(bytes_transferred); - if (ec) { - if (ec != boost::beast::websocket::error::closed) - std::cerr << "Error on session read: " << ec.message() << std::endl; - } else { - do_write(); - } - } - - void do_write() - { - m_ws->text(m_ws->got_text()); - std::string data(boost::asio::buffers_begin(m_buffer.data()), boost::asio::buffers_end(m_buffer.data())); - data = handle_request(data); - if (m_buffer.size() > 0) { - m_buffer.consume(m_buffer.size()); - } - if (data.size() > 0) { - boost::beast::ostream(m_buffer) << data; - m_ws->async_write(m_buffer.data(), - boost::asio::bind_executor(m_ws->next_layer().get_executor(), - boost::beast::bind_front_handler(&session::on_write, shared_from_this()))); - } else { - do_read(); - } - } - - void on_write(boost::beast::error_code ec, std::size_t bytes_transferred) - { - boost::ignore_unused(bytes_transferred); - - if (ec) { - std::cerr << "Error on session write: " << ec.message() << std::endl; - } else { - do_read(); - } - } - - void run() - { - do_read_handshake(); - } - - void on_write_notify(std::shared_ptr data, std::shared_ptr buffer, boost::beast::error_code ec, std::size_t bytes_transferred) - { - boost::ignore_unused(bytes_transferred); - - if (ec) { - std::cerr << "Error on session write notify: " << ec.message() << std::endl; - } - } - - void notify_other_connections_diff(const std::string& id, const Diff& diff) - { - std::for_each(m_registry.begin(id), m_registry.end(id), [&](const connection& ci) - { - if (m_ws != ci) { - pt::ptree ptree {make_ptree({ - {"type", "getdiff"}, - {"revision", std::to_string(m_storage.getRevision(id))}, - {"pos", std::to_string(m_storage.getCursorPos(id)) } - })}; - ptree.put_child("serverinfo.diff", diff.get_structure().get_child("diff")); - auto data{std::make_shared(Reichwein::XML::plain_xml(ptree))}; - auto buffer{std::make_shared(data->data(), data->size())}; - try { - ci->async_write(*buffer, boost::asio::bind_executor(ci->next_layer().get_executor(), - boost::beast::bind_front_handler(&session::on_write_notify, shared_from_this(), data, buffer))); - } catch (const std::exception& ex) { - std::cerr << "Warning: Notify getdiff write for " << ci << " not possible, id " << id << std::endl; - m_registry.dump(); - } - } - }); - } - - void notify_other_connections_pos(const std::string& id) - { - std::for_each(m_registry.begin(id), m_registry.end(id), [&](const connection& ci) - { - if (m_ws != ci) { - auto data{std::make_shared(make_xml({ - {"type", "getpos"}, - {"pos", std::to_string(m_storage.getCursorPos(id)) } - }))}; - auto buffer{std::make_shared(data->data(), data->size())}; - try { - ci->async_write(*buffer, boost::asio::bind_executor(ci->next_layer().get_executor(), - boost::beast::bind_front_handler(&session::on_write_notify, shared_from_this(), data, buffer))); - } catch (const std::exception& ex) { - std::cerr << "Warning: Notify getpos write for " << ci << " not possible, id " << id << std::endl; - m_registry.dump(); - } - } - }); - } - - std::string stats_xml() - { - return make_xml({ - {"type", "stats" }, - {"dbsizegross", std::to_string(m_storage.dbsize_gross()) }, - {"dbsizenet", std::to_string(m_storage.dbsize_net()) }, - {"numberofdocuments", std::to_string(m_storage.getNumberOfDocuments()) }, - {"numberofconnections", std::to_string(m_registry.number_of_connections()) }, - }); - } - - void on_write_stats(std::shared_ptr data, std::shared_ptr buffer, boost::beast::error_code ec, std::size_t bytes_transferred) - { - boost::ignore_unused(bytes_transferred); - - if (ec) { - std::cerr << "Error on session write stats: " << ec.message() << std::endl; - } - } - - void stats_callback(const boost::system::error_code&) - { - if (m_stats_timer) { - auto data{std::make_shared(stats_xml())}; - auto buffer{std::make_shared(data->data(), data->size())}; - m_ws->async_write(*buffer, boost::asio::bind_executor(m_ws->next_layer().get_executor(), - boost::beast::bind_front_handler(&session::on_write_stats, shared_from_this(), data, buffer))); - - m_stats_timer->expires_at(m_stats_timer->expires_at() + boost::asio::chrono::seconds(5)); - m_stats_timer->async_wait(boost::beast::bind_front_handler(&session::stats_callback, this)); - } - } - - void setup_stats_timer() - { - if (!m_stats_timer) { - m_stats_timer = std::make_shared(m_ws->next_layer().get_executor(), boost::asio::chrono::seconds(5)); - m_stats_timer->async_wait(boost::beast::bind_front_handler(&session::stats_callback, this)); - } - } - - std::string handle_request(const std::string& request) - { - try { - std::lock_guard lock(m_storage_mutex); - - pt::ptree xml; - std::istringstream ss{request}; - pt::xml_parser::read_xml(ss, xml); - - std::string command {xml.get("request.command")}; - - if (command == "modify") { - std::string id {xml.get("request.id")}; - validate_id(id); - - int baserev {xml.get("request.baserev")}; - if (baserev != m_storage.getRevision(id)) - return make_xml({{"type", "error"}, {"message", "Bad base revision ("s + std::to_string(baserev) + "). Current: "s + std::to_string(m_storage.getRevision(id)) }}); - - pt::ptree ptree; - ptree.put_child("diff", xml.get_child("request.diff")); - Diff d{ptree}; - if (!d.empty()) { - std::string data {m_storage.getDocument(id)}; - data = d.apply(data); - - m_storage.setDocument(id, data); - m_registry.setId(m_ws, id); - notify_other_connections_diff(id, d); - } - - int pos {xml.get("request.pos")}; - if (m_storage.getCursorPos(id) != pos) { - m_storage.setCursorPos(id, pos); - notify_other_connections_pos(id); - } - return make_xml({{"type", "modify"}, {"revision", std::to_string(m_storage.getRevision(id)) }}); - } else if (command == "cursorpos") { - std::string id {xml.get("request.id")}; - validate_id(id); - int pos {xml.get("request.pos")}; - if (m_storage.getCursorPos(id) != pos) { - m_storage.setCursorPos(id, pos); - notify_other_connections_pos(id); - } - return {}; - } else if (command == "getfile") { - std::string id {xml.get("request.id")}; - validate_id(id); - - std::string filedata; - try { - filedata = m_storage.getDocument(id); - } catch (const std::runtime_error&) { - m_storage.setDocument(id, filedata); - } - - if (filedata.size() > 30000000) - throw std::runtime_error("File too big"); - m_registry.setId(m_ws, id); - - return make_xml({ - {"type", "getfile"}, - {"data", filedata}, - {"revision", std::to_string(m_storage.getRevision(id)) }, - {"pos", std::to_string(m_storage.getCursorPos(id)) } - }); - } else if (command == "getpos") { - std::string id {xml.get("request.id")}; - validate_id(id); - - return make_xml({ - {"type", "getpos"}, - {"pos", std::to_string(m_storage.getCursorPos(id)) } - }); - } else if (command == "newid") { - return make_xml({{"type", "newid"}, {"id", m_storage.generate_id()}}); - } else if (command == "qrcode") { - std::string url{xml.get("request.url")}; - - if (url.size() > 1000) - throw std::runtime_error("URL too big"); - - std::string pngdata {QRCode::getQRCode(url)}; - - return make_xml({{"type", "qrcode"}, {"png", Reichwein::Base64::encode64(pngdata)}}); - } else if (command == "getversion") { - return make_xml({ - {"type", "version"}, - {"version", WHITEBOARD_VERSION } - }); - } else if (command == "getstats") { - setup_stats_timer(); - return stats_xml(); - } else if (command == "pdf") { - std::string id {xml.get("request.id")}; - validate_id(id); - Reichwein::Tempfile mdFilePath{".md"}; - Reichwein::File::setFile(mdFilePath.getPath(), m_storage.getDocument(id)); - Reichwein::Tempfile pdfFilePath{".pdf"}; - int system_result{bp::system("/usr/bin/pandoc", mdFilePath.getPath().generic_string(), "-o", pdfFilePath.getPath().generic_string())}; - if (system_result) - throw std::runtime_error("pandoc returned: "s + std::to_string(system_result)); - std::string pdfdata{Reichwein::File::getFile(pdfFilePath.getPath())}; - return make_xml({{"type", "pdf"}, {"pdf", Reichwein::Base64::encode64(pdfdata)}}); - } else { - throw std::runtime_error("Bad command: "s + command); - } - - } catch (const std::exception& ex) { - return make_xml({{"type", "error"}, {"message", "Message handling error: "s + ex.what()}}); - } - } -private: - ConnectionRegistry& m_registry; - Storage& m_storage; - std::mutex& m_storage_mutex; - connection m_ws; - ConnectionRegistry::RegistryGuard m_connection_guard; - - boost::beast::http::request_parser m_parser; - boost::beast::http::request m_req; - boost::beast::flat_buffer m_buffer; - - std::shared_ptr m_stats_timer{}; -}; - -void Whiteboard::do_accept() -{ - // The new connection gets its own strand - m_acceptor->async_accept(boost::asio::make_strand(*m_ioc), - std::bind(&Whiteboard::on_accept, this, _1, _2)); -} - -void Whiteboard::on_accept(boost::system::error_code ec, boost::asio::ip::tcp::socket socket) -{ - if (ec) { - std::cerr << "Error on accept: " << ec.message() << std::endl; - } else { - if (m_registry.number_of_connections() >= m_config->getMaxConnections()) { - // limit reached - socket.close(); - } else { - std::make_shared(m_registry, *m_storage, m_storage_mutex, std::move(socket))->run(); - } - } - - do_accept(); -} - -// for long running connections, don't timeout them but touch associated ids -// regularly, at cleanup time -void Whiteboard::touch_all_connections() -{ - std::for_each(m_registry.begin(), m_registry.end(), [&](const std::pair& i) - { - m_storage->touchDocument(i.second); - }); -} - -// the actual main() for testability -int Whiteboard::run(int argc, char* argv[]) -{ - try { - bool flag_cleanup{}; - fs::path configFile; - - if (argc == 2) { - if (argv[1] == "-h"s || argv[1] == "-?"s) { - usage(); - exit(0); - } else if (argv[1] == "-C"s) { - flag_cleanup = true; - } - } else if (argc == 3) { - if (argv[1] == "-c"s) { - configFile = argv[2]; - } - } - - if (configFile.empty()) - m_config = std::make_unique(); - else - m_config = std::make_unique(configFile); - - m_storage = std::make_unique(*m_config); - - if (flag_cleanup) { - m_storage->cleanup(); - exit(0); - } - - QRCode::init(); - - auto const address = boost::asio::ip::make_address(m_config->getListenAddress()); - auto const port = static_cast(m_config->getListenPort()); - - // The io_context is required for all I/O - m_ioc = std::make_unique(m_config->getThreads()); - - // for now, just terminate on SIGINT, SIGHUP and SIGTERM - boost::asio::signal_set signals(*m_ioc, SIGINT, SIGTERM, SIGHUP); - signals.async_wait([&](const boost::system::error_code& error, int signal_number){ - std::cout << "Terminating via signal " << signal_number << std::endl; - m_ioc->stop(); - }); - - // Storage cleanup once a day - boost::asio::steady_timer storage_cleanup_timer(*m_ioc, boost::asio::chrono::hours(24)); - std::function storage_cleanup_callback = - [&](const boost::system::error_code& error){ - std::lock_guard lock(m_storage_mutex); - if (!m_storage) - throw std::runtime_error("Storage not initialized"); - touch_all_connections(); - m_storage->cleanup(); - storage_cleanup_timer.expires_at(storage_cleanup_timer.expires_at() + boost::asio::chrono::hours(24)); - storage_cleanup_timer.async_wait(storage_cleanup_callback); - }; - storage_cleanup_timer.async_wait(storage_cleanup_callback); - - // The acceptor receives incoming connections - m_acceptor = std::make_unique(*m_ioc, boost::asio::ip::tcp::endpoint{address, port}); - - do_accept(); - - // Run the I/O service on the requested number of threads - std::vector v; - v.reserve(m_config->getThreads() - 1); - for (auto i = m_config->getThreads() - 1; i > 0; --i) { - v.emplace_back( - [&] - { - m_ioc->run(); - }); - } - m_ioc->run(); - - for (auto& t: v) { - t.join(); - } - - } catch (const std::exception& ex) { - std::cerr << "Error: " << ex.what() << std::endl; - } - - return 0; -} - diff --git a/whiteboard.h b/whiteboard.h deleted file mode 100644 index 53036ac..0000000 --- a/whiteboard.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include - -#include "diff.h" -#include "config.h" -#include "connectionregistry.h" -#include "storage.h" - -class Whiteboard -{ -public: - Whiteboard(); - int run(int argc, char* argv[]); - -private: - std::unique_ptr m_config; - std::unique_ptr m_storage; - std::mutex m_storage_mutex; - - ConnectionRegistry m_registry; - - std::unique_ptr m_ioc; - std::unique_ptr m_acceptor; - - void do_accept(); - void on_accept(boost::system::error_code ec, boost::asio::ip::tcp::socket socket); - void touch_all_connections(); -}; - -- cgit v1.2.3