about summary refs log tree commit diff stats
path: root/classes/Handler/LastreadHandler.php
diff options
context:
space:
mode:
Diffstat (limited to 'classes/Handler/LastreadHandler.php')
-rw-r--r--classes/Handler/LastreadHandler.php85
1 files changed, 85 insertions, 0 deletions
diff --git a/classes/Handler/LastreadHandler.php b/classes/Handler/LastreadHandler.php
new file mode 100644
index 0000000..e4ea81b
--- /dev/null
+++ b/classes/Handler/LastreadHandler.php
@@ -0,0 +1,85 @@
+<?php
+
+namespace Handler;
+
+use AuthRequired;
+use ORM;
+use Request;
+use RequestHandlerInterface;
+use Response;
+
+class LastreadHandler implements RequestHandlerInterface, AuthRequired
+{
+	private function handleGet(int $bookid): Response
+	{
+		if ($bookid) {
+			$book = ORM::for_table('epube_books')
+				->where('bookid', $bookid)
+				->where('owner', $_SESSION["owner"] ?? "")
+				->find_one();
+
+			if ($book) {
+				return (new Response())->withBody(json_encode([
+					"page" => (int)$book->lastread,
+					"cfi" => $book->lastcfi,
+					"total" => 100,
+					"timestamp" => (int)$book->lastts
+				]));
+			}
+		}
+
+		return (new Response())
+			->withStatus(404)
+			->withBody("Not found.");
+	}
+
+	private function handleStore(int $bookid, int $page, string $cfi, int $timestamp): Response
+	{
+		if ($bookid) {
+			$book = ORM::for_table('epube_books')
+				->where('bookid', $bookid)
+				->where('owner', $_SESSION["owner"] ?? "")
+				->find_one();
+
+			if ($book) {
+				if (($timestamp >= $book->lastts) && ($page >= $book->lastread || $page == PAGE_RESET_PROGRESS)) {
+					$book->set([
+						'lastread' => $page,
+						'lastcfi' => $cfi,
+						'lastts' => $timestamp,
+					]);
+				}
+			} else {
+				$book = ORM::for_table('epube_books')->create();
+				$book->set([
+					'bookid' => $bookid,
+					'owner' => $_SESSION["owner"] ?? "",
+					'lastread' => $page,
+					'lastcfi' => $cfi,
+					'lastts' => $timestamp,
+				]);
+			}
+
+			$book->save();
+		}
+
+		return (new Response())->withBody(json_encode(["page" => $page, "cfi" => $cfi]));
+	}
+
+	public function handle(Request $request): Response
+	{
+		$subOp = $request->getAttribute('op', '');
+		$bookid = (int) $request->getAttribute('id');
+
+		return match ($subOp) {
+			'getlastread'    => $this->handleGet($bookid),
+			'storelastread'  => $this->handleStore(
+				$bookid,
+				(int) $request->getAttribute('page'),
+				(string) $request->getAttribute('cfi', ''),
+				(int) $request->getAttribute('timestamp'),
+			),
+			default          => (new Response())->withStatus(404)->withBody("Not found."),
+		};
+	}
+}