Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions assets/fonts/sleep-journal/OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright 2011 The Lora Project Authors (https://github.com/cyrealtype/Lora-Cyrillic), with Reserved Font Name "Lora". Lora-Italic[wght].ttf: Copyright 2011 The Lora Project Authors (https://github.com/cyrealtype/Lora-Cyrillic), with Reserved Font Name "Lora".

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file added assets/fonts/sleep-journal/lora-bold.woff
Binary file not shown.
Binary file added assets/fonts/sleep-journal/lora-regular.woff
Binary file not shown.
Binary file added assets/fonts/sleep-journal/lora-semibold.woff
Binary file not shown.
16 changes: 16 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -985,3 +985,19 @@ progress. These rows have `history_only: true`, null `percentage`, `progress`,
or metadata. Pagination works across current and historical books. The app uses
this option for its Library. Without this option, the endpoint continues to return
only synced progress; the KOReader sync and progress change endpoints are unchanged.

### Sleep-image plugin support

Authenticated with the usual session or `x-auth-user` / `x-auth-key` headers.
These routes require a server version including migration `0049_sleep_backgrounds.sql`.

- `GET /api/v1/stats/sleep-image/status` → `{ "version": 1, "background": false }`.
- `GET /api/v1/stats/sleep-image?mode=overlay&width=480&height=800&timezone=America%2FNew_York&placement=bottom&metrics=books,goal,current,streak` → transparent PNG. `mode=custom` returns a full native 2-bit grayscale BMP using the account background, or built-in journal artwork when none exists (an open-book illustration, with an achievement medallion when the goal is reached). Dimensions are integers 240–1600, at most 2,000,000 pixels; encoded output is below 1 MB. Top/bottom placement and the listed metric names are supported. `preview=1` returns a browser-compatible PNG for Custom, with the same four native gray levels; omit it for the reader BMP. At the configured screen resolution, 2-bit BMP avoids per-refresh firmware conversion caching. Unknown options values return 400.
- `X-Sleep-Percent: 42` supplies the current visible-page percentage (0–100). Missing, unresolved, or invalid values omit that metric. This does not write progress, finish books, or trust a queued event as a new completion. Account totals reflect already-synced history; annual goals reuse the existing account goal.
- `PUT /api/v1/stats/sleep-image/background`, `Content-Type: image/png`: normalized PNG upload, at most 8 MB, 1600 pixels per axis and 2,000,000 decoded pixels. The app/plugin should resize and convert JPEG/other artwork to PNG before uploading. Invalid uploads preserve the previous background. PNG chunk structure is validated and IDAT inflation is bounded by the validated scanline budget before decoding, including interlaced input.
- `GET /api/v1/stats/sleep-image/background` → the signed-in account's PNG (404 when absent).
- `DELETE /api/v1/stats/sleep-image/background` → `{ "background": false }`.

All image/background responses are private and not cached. Backgrounds belong to one account, are cleared when its reading data/account is deleted, and are presentation data outside reading-history exports. No external image URL fetching is performed. IANA timezone rules are evaluated at each historical timestamp, including DST offsets. Dates already stored as local calendar days retain their original day. These routes work under `BASE_PATH` using the same prefix as all other APIs.

The sleep images use a reading-journal design: a compact transparent bookplate with serif type and an annual-goal seal tilted approximately ten degrees, or a full-page Custom composition with framed account artwork. Without artwork, Custom draws an original open-book illustration. Top/bottom placement and metric omission work in both modes; short landscape screens use the compact composition. Fonts (Lora regular/semibold/bold) and their SIL OFL license are bundled under `assets/fonts/sleep-journal`; rendering uses pure JavaScript and no runtime downloads or native graphics libraries.
4 changes: 4 additions & 0 deletions migrations/0049_sleep_backgrounds.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
CREATE TABLE sleep_backgrounds (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
png BLOB NOT NULL
);
58 changes: 58 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@
"@hono/node-server": "^1.13.7",
"@xmldom/xmldom": "^0.9.12",
"hono": "^4.6.16",
"opentype.js": "^1.3.4",
"pngjs": "^7.0.0",
"yauzl": "^3.4.0"
},
"devDependencies": {
"@types/node": "^22.10.5",
"@types/opentype.js": "^1.3.10",
"@types/pngjs": "^6.0.5",
"@types/yauzl": "^3.4.0",
"tsx": "^4.19.2",
"typescript": "^5.7.3",
Expand Down
4 changes: 3 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { progressRoutes } from './routes/v1/progress.js';
import { bookmarkRoutes } from './routes/v1/bookmarks.js';
import { clippingRoutes } from './routes/v1/clippings.js';
import { statsRoutes } from './routes/v1/stats.js';
import { sleepImageRoutes } from './routes/v1/sleep-image.js';
import { documentRoutes } from './routes/v1/documents.js';
import { connectorRoutes, oauthCallbackRoutes } from './routes/v1/connectors.js';
import { profileSettingsRoutes, publicProfileRoutes } from './routes/profile.js';
Expand Down Expand Up @@ -40,7 +41,7 @@ export function createApp(db: DB, config: Config, opts: AppOptions = {}): Hono<A
const apiCors = cors({
origin: config.corsOrigins === '*' ? '*' : config.corsOrigins,
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Accept', 'x-auth-user', 'x-auth-key'],
allowHeaders: ['Content-Type', 'Accept', 'x-auth-user', 'x-auth-key', 'X-Sleep-Percent'],
maxAge: 86400,
});
app.use('/users/*', apiCors);
Expand Down Expand Up @@ -88,6 +89,7 @@ export function createApp(db: DB, config: Config, opts: AppOptions = {}): Hono<A
v1.route('/', bookmarkRoutes(db));
v1.route('/', clippingRoutes(db));
v1.route('/', statsRoutes(db, opts.connectorTransport));
v1.route('/', sleepImageRoutes(db));
v1.route('/', documentRoutes(db, opts.connectorTransport));
v1.route('/', connectorRoutes(db, opts.connectorTransport, config.trustProxy, basePath, config.allowHttpLocalhost));
v1.route('/', meRoutes(db));
Expand Down
16 changes: 15 additions & 1 deletion src/db/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,21 @@ export function migrate(db: DB, migrationsDir: string = DEFAULT_MIGRATIONS_DIR):
// Newer installs already have the column, so the repair must accept both.
const hasBookorbitAttempt = file === '0032_bookorbit_stats_attempted_at.sql' &&
db.prepare('PRAGMA table_info(bookorbit_stats_sync)').all().some((column) => column.name === 'attempted_at');
if (!hasBookorbitAttempt) db.exec(sql);
// Development installs recorded this identical migration as 0044 before
// upstream assigned 0048. Adopt only that known history and exact schema;
// never drop goals or silently accept an unrelated existing table.
let hasLegacyReadingGoals = false;
if (file === '0048_reading_goals.sql' && applied.has('0044_reading_goals.sql')) {
const table = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='reading_goals'").get();
if (table) {
const normalized = (value: string) => value.trim().replace(/;$/, '').replace(/\s+/g, ' ').toLowerCase();
if (normalized(String(table.sql)) !== normalized(sql)) {
throw new Error('Cannot reconcile legacy reading_goals migration: existing table has an unexpected schema.');
}
hasLegacyReadingGoals = true;
}
}
if (!hasBookorbitAttempt && !hasLegacyReadingGoals) db.exec(sql);
db.prepare('INSERT INTO migrations (name, applied_at) VALUES (?, ?)').run(
file,
Math.floor(Date.now() / 1000)
Expand Down
12 changes: 8 additions & 4 deletions src/models/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ import { readBookorbitStats } from './bookorbit-stats.js';
* since a book can be finished offline and only synced days later.
* - Start and finish dates the user set by hand win over everything else.
*/
/** Minutes west of UTC, fixed for legacy APIs or resolved per Unix timestamp (seconds). */
export type ActivityTimezone = number | ((at: number) => number);
export const activityOffset = (timezone: ActivityTimezone, at: number) => typeof timezone === 'number' ? timezone : timezone(at);

export const FINISHED_AT = 0.98;

export interface LogRow {
Expand Down Expand Up @@ -84,13 +88,13 @@ export interface DayBook {
export function computeActivity(
rows: LogRow[],
docs: Map<string, DocInfo>,
tzOffsetMinutes = 0,
tzOffsetMinutes: ActivityTimezone = 0,
finishedDates: Map<string, number> = new Map(),
startDates: Map<string, number> = new Map()
): Activity {
// Device dates are calendar dates: pin them to local noon in the client
// timezone so they land on that same day however they're displayed.
const localNoon = (date: number | undefined) => (date ? date + 12 * 3600 + tzOffsetMinutes * 60 : null);
const localNoon = (date: number | undefined) => (date ? date + 12 * 3600 + activityOffset(tzOffsetMinutes, date + 12 * 3600) * 60 : null);
const byDoc = new Map<string, LogRow[]>();
for (const r of rows) {
const list = byDoc.get(r.document) ?? [];
Expand All @@ -109,7 +113,7 @@ export function computeActivity(
const readingDays = new Set<string>();
const days = new Map<string, { pages: number; syncs: number; books: Map<string, DayBook> }>();
// The day bucket for a sync, and this book's entry in it (opened at position `from`).
const dayKey = (at: number) => new Date((at - tzOffsetMinutes * 60) * 1000).toISOString().slice(0, 10);
const dayKey = (at: number) => new Date((at - activityOffset(tzOffsetMinutes, at) * 60) * 1000).toISOString().slice(0, 10);
const dayOf = (at: number, document: string, from: number) => {
const key = dayKey(at);
readingDays.add(key);
Expand Down Expand Up @@ -223,7 +227,7 @@ export function computeActivity(

/** A user's activity from the database: progress history, plus finish and start
* dates from device stats and reading days from a BookOrbit import. */
export function readingActivity(db: DB, userId: number, tz: number, options: { includeStatsOnly?: boolean } = {}): Activity {
export function readingActivity(db: DB, userId: number, tz: ActivityTimezone, options: { includeStatsOnly?: boolean } = {}): Activity {
const rows = db
.prepare('SELECT document, percentage, at FROM progress_log WHERE user_id = ?')
.all(userId) as unknown as LogRow[];
Expand Down
Loading
Loading