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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ File names: Latin letters, digits, `.`, `_` and `-`. Up to 8 MB per file and
static mirror of the API's /catalog for Keira devices

lilka-catalog-api (api/, Cloudflare)
Worker + D1 + R2 apps, versions, files, users, ratings, moderation
Worker + D1 + R2 apps, versions, files, users, moderation
GitHub Actions ClamAV scan, icon_min, image compression, package.zip
```

Expand Down
2 changes: 1 addition & 1 deletion README.uk.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ scripts/mirror_api.py копіює каталог з API на Pages для пр
статичне дзеркало <API>/catalog для пристроїв Keira

lilka-catalog-api (Cloudflare)
Worker + D1 + R2 застосунки, версії, файли, користувачі, оцінки, модерація
Worker + D1 + R2 застосунки, версії, файли, користувачі, модерація
GitHub Actions ClamAV, icon_min, стиснення зображень, package.zip
```

Expand Down
3 changes: 1 addition & 2 deletions api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ flowchart LR
subgraph CF["lilka-catalog-api · Cloudflare Worker (api/)"]
API["API routes<br/>/auth · /apps · /mod · /scan"]
CAT["/catalog/…<br/>/catalog/export.json"]
D1[("D1<br/>users · sessions · apps<br/>versions · ratings · reports")]
D1[("D1<br/>users · sessions · apps<br/>versions · reports")]
R2[("R2<br/>&lt;id&gt;-&lt;name&gt;/v/&lt;version&gt;/&lt;file&gt;")]
end

Expand Down Expand Up @@ -175,7 +175,6 @@ All bodies are JSON unless noted. Authenticated calls send
| POST | `/apps` | user | Create draft; `kind`: `app`, `wallpaper` or `mod` |
| PATCH | `/apps/:slug` | owner, mod | Edit metadata, `status: hidden \| published`; moderators also `author`, `owner` (login) |
| POST | `/apps/:slug/versions` | owner, mod | Multipart: `version`, `keira_version`, `entry_type` (`lua`, `js`, `binary`, `archive`), `changelog`, files `entry`, `files[]`, `icon`, `screenshots[]`. Mods: no entry, model files as `files[]` |
| PUT | `/apps/:slug/rating` | user (not owner) | `{ "stars": 1..5 }` |
| POST | `/apps/:slug/reports` | user | `{ "reason": "..." }` |
| GET | `/users/:login/apps[?versions]` | user | Apps of a user (all of them, with versions, for the user themself or a moderator) |
| GET | `/files/:slug/:version/:name` | owner, mod | File by version id, for "My apps" and moderation previews |
Expand Down
6 changes: 2 additions & 4 deletions api/scripts/smoke.sh
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,6 @@ call 404 "approved file is not served to strangers" "${fan[@]}" "$API/files/smok
call 200 "owner gets the approved file" "${user[@]}" "$API/files/smoke-hello/$version_id/hello.lua"
call 200 "HEAD for the owner" -I "${user[@]}" "$API/files/smoke-hello/$version_id/hello.lua"

call 403 "owner cannot rate own app" "${user[@]}" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":5}'
call 200 "rate" "${fan[@]}" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":4}'
call 201 "report" "${fan[@]}" "${json[@]}" -X POST "$API/apps/smoke-hello/reports" -d '{"reason":"smoke"}'
call 200 "open reports" "${mod[@]}" "$API/mod/reports"

Expand All @@ -114,9 +112,9 @@ jq -e '."@smoke-dev"[0].path == "smoke-hello"' "$work/body" >/dev/null || { echo
call 404 "catalog unknown kind" "${mirror[@]}" "$API/catalog/games/index_0.json"
call 401 "listing.json needs the mirror secret" "$API/catalog/apps/listing.json"
call 200 "listing.json for the site" "${mirror[@]}" "$API/catalog/apps/listing.json"
jq -e '.items[] | select(.path == "smoke-hello") | (.added != null) and (.updated != null) and .rating.average == 4 and .rating.count == 1 and .author == "@smoke-dev"' \
jq -e '.items[] | select(.path == "smoke-hello") | (.added != null) and (.updated != null) and .author == "@smoke-dev"' \
"$work/body" >/dev/null && li=ok || li="$(jq -c '.items[] | select(.path == "smoke-hello")' "$work/body")"
check "listing has dates, rating and author" ok "$li"
check "listing has dates and author" ok "$li"
pub=$(npx wrangler d1 execute lilka-catalog --local --json --command "SELECT published_at FROM apps WHERE slug = 'smoke-hello'" 2>/dev/null | jq -r '.[0].results[0].published_at')
check "published_at set on first approval" ok "$([ -n "$pub" ] && [ "$pub" != null ] && echo ok || echo missing)"

Expand Down
35 changes: 1 addition & 34 deletions api/src/apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ export interface AppRow {
updated_at: string;
owner_login: string;
owner_avatar: string | null;
rating_avg: number | null;
rating_count: number;
}

export interface VersionRow {
Expand Down Expand Up @@ -74,9 +72,7 @@ export interface VersionRow {
}

export const APP_SELECT = `
SELECT a.*, u.login AS owner_login, u.avatar_url AS owner_avatar,
(SELECT AVG(stars) FROM ratings r WHERE r.app_id = a.id) AS rating_avg,
(SELECT COUNT(*) FROM ratings r WHERE r.app_id = a.id) AS rating_count
SELECT a.*, u.login AS owner_login, u.avatar_url AS owner_avatar
FROM apps a JOIN users u ON u.id = a.owner_id`;

export function fileUrl(env: Env, slug: string, versionId: number, name: string): string {
Expand Down Expand Up @@ -145,7 +141,6 @@ export function serializeApp(env: Env, a: AppRow, latest: VersionRow | null) {
sources_url: a.sources_url,
license: a.license,
owner: { login: a.owner_login, avatar_url: a.owner_avatar },
rating: { average: a.rating_avg === null ? null : Math.round(a.rating_avg * 10) / 10, count: a.rating_count },
latest_version: latest ? serializeVersion(env, a.slug, latest, false) : null,
created_at: a.created_at,
updated_at: a.updated_at,
Expand Down Expand Up @@ -297,18 +292,9 @@ apps.get('/:slug', async (c) => {
.all<VersionRow>();
const latest = results.find((v) => v.status === 'approved') ?? null;

let myRating: number | null = null;
if (user) {
const row = await c.env.DB.prepare(`SELECT stars FROM ratings WHERE app_id = ? AND user_id = ?`)
.bind(app.id, user.id)
.first<{ stars: number }>();
myRating = row?.stars ?? null;
}

return c.json({
...serializeApp(c.env, app, latest),
can_manage: manage,
my_rating: myRating,
versions: results.map((v) => serializeVersion(c.env, app.slug, v, manage)),
});
});
Expand Down Expand Up @@ -492,25 +478,6 @@ apps.post('/:slug/versions', async (c) => {
return c.json(serializeVersion(c.env, app.slug, created!, true), 201);
});

apps.put('/:slug/rating', async (c) => {
const user = requireUser(c);
const app = await findApp(c.env, c.req.param('slug'));
if (!app || app.status !== 'published') fail(404, 'app not found');
if (app.owner_id === user.id) fail(403, 'cannot rate your own app');
const { stars } = await readJson<{ stars?: unknown }>(c);
if (typeof stars !== 'number' || !Number.isInteger(stars) || stars < 1 || stars > 5) {
fail(400, 'stars must be an integer from 1 to 5');
}
await c.env.DB.prepare(
`INSERT INTO ratings (app_id, user_id, stars) VALUES (?, ?, ?)
ON CONFLICT (app_id, user_id) DO UPDATE SET stars = excluded.stars, updated_at = datetime('now')`,
)
.bind(app.id, user.id, stars)
.run();
const updated = await findApp(c.env, app.slug);
return c.json({ average: updated!.rating_avg, count: updated!.rating_count, my_rating: stars });
});

apps.post('/:slug/reports', async (c) => {
const user = requireUser(c);
const app = await findApp(c.env, c.req.param('slug'));
Expand Down
10 changes: 2 additions & 8 deletions api/src/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ interface CatalogRow extends AppRow {
v_id: number;
published_at: string | null;
approved_at: string | null;
rating_sum: number | null;
keira_version: string | null;
entry_type: string | null;
entry_file: string | null;
Expand Down Expand Up @@ -61,11 +60,10 @@ async function published(env: Env, kind?: AppRow['kind'], slug?: string): Promis
`SELECT a.*, u.login AS owner_login, u.avatar_url AS owner_avatar,
v.id AS v_id, v.keira_version, v.entry_type, v.entry_file, v.files, v.files_meta, v.icon, v.icon_min,
v.screenshots, v.changelog, v.changelog_en, v.package, v.security, v.storage_prefix,
v.approved_at, COALESCE(r.n, 0) AS rating_count, r.total AS rating_sum
v.approved_at
FROM apps a
JOIN users u ON u.id = a.owner_id
JOIN versions v ON v.id = a.latest_version_id
LEFT JOIN (SELECT app_id, COUNT(*) AS n, SUM(stars) AS total FROM ratings GROUP BY app_id) r ON r.app_id = a.id
WHERE ${where.join(' AND ')}
ORDER BY a.slug COLLATE BINARY`,
)
Expand Down Expand Up @@ -231,7 +229,7 @@ function authorsDoc(rows: CatalogRow[]): Record<string, unknown[]> {
* listing.json: everything the website's list needs for one kind, in one file.
*
* Not part of the old build.py layout and not read by Keira, so it can carry
* what the catalog list sorts by (dates, rating) without touching the
* what the catalog list sorts by (dates, author) without touching the
* manifests devices parse. It also turns a list page from 1 index plus 12
* manifests into one request.
*/
Expand All @@ -247,10 +245,6 @@ function listingDoc(rows: CatalogRow[]) {
icon: row.icon ?? '',
added: row.published_at ?? row.approved_at,
updated: row.approved_at,
rating: {
average: row.rating_count ? Math.round((row.rating_sum! / row.rating_count) * 10) / 10 : null,
count: row.rating_count,
},
};
if (Object.keys(loc).length) {
entry.languages = Object.keys(loc);
Expand Down
85 changes: 1 addition & 84 deletions site/community.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ const COMMUNITY_STRINGS = {
'view-in-catalog': 'Відкрити в каталозі',
'versions': 'Версії',
'no-versions': 'Версій ще немає.',
'rating': '★ {average} ({count})',
'status-draft': 'чернетка',
'status-published': 'опубліковано',
'status-hidden': 'приховано',
Expand All @@ -84,18 +83,6 @@ const COMMUNITY_STRINGS = {
'status-rejected': 'відхилено',
'status-infected': 'знайдено загрозу',
'review-note': 'Коментар модератора',
'rating-title': 'Оцінка',
'rating-none': 'Ще ніхто не оцінив.',
// Plural forms by Intl.PluralRules: one / few / many (and other)
'rating-summary-one': '★ {average} · {count} оцінка',
'rating-summary-few': '★ {average} · {count} оцінки',
'rating-summary-many': '★ {average} · {count} оцінок',
'rating-summary-other': '★ {average} · {count} оцінки',
'rating-yours': 'Ваша оцінка:',
'rating-star': '{n} з 5',
'rating-sign-in': 'Увійдіть, щоб оцінити',
'rating-thanks': 'Дякуємо! Ваша оцінка ({stars}★) з’явиться в списку протягом години.',
'rating-own': 'Свій застосунок оцінити не можна.',
'files-removed': 'Файли цієї версії видалено після відхилення.',
'file-gone': 'Цього файлу вже немає.',
'scan-detail': 'Результат антивірусу',
Expand Down Expand Up @@ -196,7 +183,6 @@ const COMMUNITY_STRINGS = {
'view-in-catalog': 'Open in catalog',
'versions': 'Versions',
'no-versions': 'No versions yet.',
'rating': '★ {average} ({count})',
'status-draft': 'draft',
'status-published': 'published',
'status-hidden': 'hidden',
Expand All @@ -206,15 +192,6 @@ const COMMUNITY_STRINGS = {
'status-rejected': 'rejected',
'status-infected': 'threat found',
'review-note': 'Moderator note',
'rating-title': 'Rating',
'rating-none': 'No ratings yet.',
'rating-summary-one': '★ {average} · {count} rating',
'rating-summary-other': '★ {average} · {count} ratings',
'rating-yours': 'Your rating:',
'rating-star': '{n} of 5',
'rating-sign-in': 'Sign in to rate',
'rating-thanks': 'Thanks! Your rating ({stars}★) shows in the list within an hour.',
'rating-own': 'You cannot rate your own app.',
'files-removed': 'The files of this version were deleted when it was rejected.',
'file-gone': 'This file is no longer available.',
'scan-detail': 'Antivirus result',
Expand Down Expand Up @@ -491,64 +468,6 @@ class CommunityUI {
}
}

// --- Rating in the details view ------------------------------------------

// The average comes from listing.json on Pages (no Worker request); only
// sending a rating calls the API. The list picks it up on the next mirror run.
async mountRating(modalBody, type, slug, entry) {
if (!this.enabled || !['apps', 'wallpapers', 'mods'].includes(type)) return;
const section = document.createElement('div');
section.className = 'modal-section rating-section';
const header = modalBody.querySelector('.modal-header');
if (header) header.after(section); else modalBody.prepend(section);

const rating = entry && entry.rating;
const plural = rating && rating.count ? new Intl.PluralRules(this.app.currentLang).select(rating.count) : '';
const summary = rating && rating.count ?
this.t(`rating-summary-${plural}`, {average: rating.average, count: rating.count}) :
this.t('rating-none');
section.innerHTML = `
<h3>${this.esc(this.t('rating-title'))}</h3>
<p class="rating-summary">${this.esc(summary)}</p>
<div class="rating-action"></div>
<p class="community-hint rating-message" hidden></p>`;

await this.ready;
const action = section.querySelector('.rating-action');
if (!this.user) {
action.innerHTML = `<button class="btn-sm rating-sign-in">${this.esc(this.t('rating-sign-in'))}</button>`;
action.querySelector('button').addEventListener('click', () => this.signIn());
return;
}
action.innerHTML = `<span class="community-hint">${this.esc(this.t('rating-yours'))}</span>
<span class="rating-stars" role="group">${[1, 2, 3, 4, 5].map(n =>
`<button class="rating-star" data-stars="${n}" title="${this.esc(this.t('rating-star', {n}))}"
aria-label="${this.esc(this.t('rating-star', {n}))}">★</button>`).join('')}</span>`;
const message = section.querySelector('.rating-message');
const stars = [...action.querySelectorAll('.rating-star')];
const show = (n) => stars.forEach(b => b.classList.toggle('on', Number(b.dataset.stars) <= n));
action.querySelector('.rating-stars').addEventListener('mouseleave', () => show(Number(action.dataset.chosen || 0)));
stars.forEach(button => {
button.addEventListener('mouseenter', () => show(Number(button.dataset.stars)));
button.addEventListener('click', async () => {
const n = Number(button.dataset.stars);
stars.forEach(b => b.disabled = true);
try {
await this.request('PUT', `/apps/${encodeURIComponent(slug)}/rating`, {stars: n});
action.dataset.chosen = String(n);
show(n);
message.textContent = this.t('rating-thanks', {stars: n});
if (window.umami) window.umami.track('rate', {item: slug, stars: n});
} catch (error) {
message.textContent = error.status === 403 ? this.t('rating-own') : this.t('error', {message: error.message});
} finally {
message.hidden = false;
stars.forEach(b => b.disabled = false);
}
});
});
}

// --- API -------------------------------------------------------------------

async request(method, path, body) {
Expand Down Expand Up @@ -969,15 +888,13 @@ class CommunityUI {

renderMyApp(app) {
const [catalogType] = app.catalog_path.split('/');
const rating = app.rating && app.rating.count ?
`<span class="community-hint">${this.esc(this.t('rating', app.rating))}</span>` : '';
return `
<div class="community-card" data-slug="${this.esc(app.slug)}">
<div class="community-card-head">
<div>
<h3>${this.esc(this.appName(app))}</h3>
<code class="community-slug">${this.esc(app.slug)}</code>
${this.statusBadge(app.status)} ${rating}
${this.statusBadge(app.status)}
</div>
<div class="community-actions">
<button class="btn-sm" data-action="new-version">${this.esc(this.t('new-version'))}</button>
Expand Down
32 changes: 18 additions & 14 deletions site/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,21 +52,25 @@
<div id="error" class="error" style="display: none;"></div>

<div id="content">
<div class="list-toolbar">
<label for="sortSelect" data-i18n="sort-label">Sort by</label>
<select id="sortSelect">
<option value="newest" data-i18n="sort-newest">Newest</option>
<option value="updated" data-i18n="sort-updated">Recently updated</option>
<option value="rating" data-i18n="sort-rating">Top rated</option>
<option value="name" data-i18n="sort-name">Name</option>
<option value="author" data-i18n="sort-author">Author</option>
</select>
</div>
<!-- Pagination in the middle, sorting on the right -->
<div class="list-head">
<div class="pagination">
<button id="prevPage" class="btn" disabled>←</button>
<div id="pageNumbers" class="page-numbers"></div>
<button id="nextPage" class="btn" disabled>→</button>
</div>

<div class="pagination">
<button id="prevPage" class="btn" disabled>←</button>
<div id="pageNumbers" class="page-numbers"></div>
<button id="nextPage" class="btn" disabled>→</button>
<div class="list-toolbar">
<label for="sortSelect" data-i18n="sort-label">Sort by</label>
<select id="sortSelect">
<option value="newest" data-i18n="sort-newest">Newest</option>
<option value="updated" data-i18n="sort-updated">Recently updated</option>
<option value="name" data-i18n="sort-name">Name</option>
<option value="author" data-i18n="sort-author">Author</option>
</select>
<button id="sortReverse" class="sort-reverse" type="button" aria-pressed="false"
data-i18n-title="sort-reverse" title="Reverse order">↓</button>
</div>
</div>

<div id="items" class="items-grid"></div>
Expand Down
Loading
Loading