diff --git a/android-app/android/app/src/main/AndroidManifest.xml b/android-app/android/app/src/main/AndroidManifest.xml index 7b8acb1..130a1df 100644 --- a/android-app/android/app/src/main/AndroidManifest.xml +++ b/android-app/android/app/src/main/AndroidManifest.xml @@ -54,6 +54,8 @@ method). Sits on top of MainActivity, so system Back returns to the paper detail screen. Never exported — it is launched by the app only. --> + + = 28 ? info.getLongVersionCode() : info.versionCode); + call.resolve(result); + } catch (Exception e) { call.reject("Unable to read installed app version"); } + } + + @PluginMethod + public void downloadAndInstall(PluginCall call) { + String source = call.getString("url", ""); + String name = sanitizeName(call.getString("fileName", "dsmnru-update.apk")); + if (!source.startsWith("https://github.com/") && !source.startsWith("https://objects.githubusercontent.com/")) { call.reject("Untrusted update URL"); return; } + Executors.newSingleThreadExecutor().execute(() -> { + File out = new File(getContext().getCacheDir(), name); + try { + HttpURLConnection c = (HttpURLConnection) new URL(source).openConnection(); c.setConnectTimeout(15000); c.setReadTimeout(30000); c.setInstanceFollowRedirects(true); + if (c.getResponseCode() < 200 || c.getResponseCode() >= 300) throw new Exception("Download failed: HTTP " + c.getResponseCode()); + try (InputStream in = c.getInputStream(); FileOutputStream fos = new FileOutputStream(out)) { byte[] b = new byte[8192]; int n; while ((n=in.read(b)) >= 0) fos.write(b,0,n); } + Intent i = new Intent(Intent.ACTION_VIEW); Uri uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName()+".fileprovider", out); i.setDataAndType(uri, "application/vnd.android.package-archive"); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(i); call.resolve(); + } catch (Exception e) { if (out.exists()) out.delete(); call.reject("Could not install update: " + e.getMessage()); } + }); + } + private boolean isHttpUrl(String url) { return url != null && (url.startsWith("https://") || url.startsWith("http://")) diff --git a/android-app/android/app/src/main/res/xml/file_paths.xml b/android-app/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..c415ce6 --- /dev/null +++ b/android-app/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1 @@ + diff --git a/android-app/test/app-frontend-smoke.test.mjs b/android-app/test/app-frontend-smoke.test.mjs index fc470f4..71c58f8 100644 --- a/android-app/test/app-frontend-smoke.test.mjs +++ b/android-app/test/app-frontend-smoke.test.mjs @@ -510,7 +510,7 @@ if (JSDOM) { await waitFor(() => view().querySelector('.profile-card')); assert.match(text(view().querySelector('.profile-card')), /Test Student/, 'profile shows display name'); assert.match(text(view().querySelector('.profile-card')), /stud@dsmnru\.in/, 'profile shows email'); - assert.match(text(view()), /Version 1\.4\.0/, 'app version visible on Profile'); + assert.match(text(view()), /Version Unknown/, 'app version visible on Profile'); assert.ok(await waitFor(() => view().querySelector('#pf-rewards .hero-title')), 'rewards section loads lazily'); assert.equal(view().querySelectorAll('#pf-rewards .hero-title')[0].textContent, '40', 'points balance from the SAME reward account the website reads'); diff --git a/android-app/test/fcm.test.mjs b/android-app/test/fcm.test.mjs index fef0d22..cc87e1d 100644 --- a/android-app/test/fcm.test.mjs +++ b/android-app/test/fcm.test.mjs @@ -62,8 +62,8 @@ test('Gradle wires firebase-messaging and keeps google-services conditional', () assert.match(gradle, /apply plugin: 'com\.google\.gms\.google-services'/, 'google-services plugin applied when google-services.json exists'); assert.match(gradle, /google-services\.json/, 'apply is guarded by the presence of google-services.json'); - assert.match(gradle, /versionCode 11/, 'versionCode increased for the 1.4.0 production release'); - assert.match(gradle, /versionName "1\.4\.0"/, 'versionName 1.4.0 (production release)'); + assert.match(gradle, /versionCode 12/, 'current production versionCode is 12'); + assert.match(gradle, /versionName \"1\.4\.1\"/, 'current production versionName is 1.4.1'); // Consistent package identity + stable debug signature (update-in-place). assert.match(gradle, /applicationId "com\.dsmnru\.pyq"/, 'single applicationId preserved'); assert.match(gradle, /signingConfig signingConfigs\.debug/, 'debug buildType uses the shared debug signing config'); diff --git a/android-app/test/features.test.mjs b/android-app/test/features.test.mjs index a655d20..705a376 100644 --- a/android-app/test/features.test.mjs +++ b/android-app/test/features.test.mjs @@ -720,7 +720,7 @@ test('v1.3.1 polish: [hidden] wins over component CSS; signup errors are per-for assert.ok(!authui.includes('GOOGLE_SIGNIN_SETUP.md'), 'no technical paths in user-facing Google fallback'); const profile = readFileSync(join(here, '../www/js/views/profile.js'), 'utf8'); - assert.match(profile, /1\.4\.0/, 'app version visible on Profile'); + assert.match(profile, /getAppVersion\(\)/, 'Profile uses native installed app version'); assert.match(profile, /avatar-img/, 'profile photo rendered where Firebase/Google provides one'); assert.match(profile, /saveProfileEdits/, 'profile editing wired to the SAME user profile'); assert.match(profile, /reward points/, 'upload/reward points visible in Profile'); diff --git a/android-app/test/update-version.test.mjs b/android-app/test/update-version.test.mjs new file mode 100644 index 0000000..b95e073 --- /dev/null +++ b/android-app/test/update-version.test.mjs @@ -0,0 +1,23 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { isNewer, parseUpdate } from '../www/js/update.js'; + +test('numeric installed versionCode controls update decisions', () => { + assert.equal(isNewer(13, 12), true); + assert.equal(isNewer(12, 12), false); + assert.equal(isNewer(11, 12), false); + assert.equal(isNewer(14, 12), true); +}); +test('metadata uses native versionCode and does not parse versionName', () => { + const raw = { version: '1.4.2', versionCode: 13, downloadUrl: 'https://github.com/Lav-developer/PYQ/releases/download/v1.4.2/app.apk' }; + assert.ok(parseUpdate(raw, 12)); + assert.equal(parseUpdate(raw, 13), null); + assert.equal(parseUpdate({ ...raw, version: '1.4.1', versionCode: 13 }, 12).versionCode, 13); +}); +test('Android UI has no duplicated version constants', async () => { + const fs = await import('node:fs/promises'); + const [about, profile, update] = await Promise.all(['../www/js/views/about.js','../www/js/views/profile.js','../www/js/update.js'].map(x => fs.readFile(new URL(x, import.meta.url), 'utf8'))); + assert.doesNotMatch(about, /APP_VERSION|1\.4\.0|1\.4\.1/); + assert.doesNotMatch(profile, /APP_VERSION|1\.4\.0|1\.4\.1/); + assert.doesNotMatch(update, /CURRENT_VERSION_CODE|versionCode\s*=\s*12/); +}); diff --git a/android-app/www/js/app.js b/android-app/www/js/app.js index 3d672fc..7ba2397 100644 --- a/android-app/www/js/app.js +++ b/android-app/www/js/app.js @@ -14,6 +14,7 @@ import { parseSiteUrl } from './slug.js'; import * as ui from './ui.js'; import { openAuthSheet, verificationPromptSheet, googleInfoSheet, initAuthUI } from './authui.js'; import { createDrawer } from './drawer.js'; +import { checkForUpdate } from './update.js'; import renderHome from './views/home.js'; import renderSearch from './views/search.js'; @@ -357,6 +358,7 @@ function wireAndroid() { state.online = navigator.onLine !== false; paintNetworkBanner(); auth.refreshIfNeeded(); + checkForUpdate({ ui }); checkLaunchLink(); }); } catch { /* older core without listeners — WebView defaults apply */ } @@ -381,6 +383,7 @@ document.addEventListener('visibilitychange', () => { // ── boot ─────────────────────────────────────────────────────────────── async function boot() { wireAndroid(); +checkForUpdate({ ui }); paintNetworkBanner(); // Restore a persisted Firebase session (zero requests when the token is diff --git a/android-app/www/js/native.js b/android-app/www/js/native.js index 1143e04..41fb07c 100644 --- a/android-app/www/js/native.js +++ b/android-app/www/js/native.js @@ -123,6 +123,16 @@ export const native = { return { ok: false, code: 'GOOGLE_SIGNIN_UNAVAILABLE', message: 'Native Google sign-in not available here' }; }, + async getAppVersion() { + if (isNative() && typeof bridge.getAppVersion === 'function') return bridge.getAppVersion(); + return { versionName: '', versionCode: 0 }; + }, + + async downloadAndInstall(url, fileName) { + if (isNative() && typeof bridge.downloadAndInstall === 'function') return bridge.downloadAndInstall({ url, fileName }); + throw new Error('In-app installation is available only in the Android app'); + }, + /** Save a direct .pdf to the device Downloads via DownloadManager. */ async download(url, fileName) { const safe = httpUrl(url); diff --git a/android-app/www/js/update.js b/android-app/www/js/update.js new file mode 100644 index 0000000..249bd7d --- /dev/null +++ b/android-app/www/js/update.js @@ -0,0 +1,22 @@ +import { native } from './native.js'; +import { WORKER_ORIGIN } from './api.js'; + +export function isNewer(remote, local) { return Number.isInteger(Number(remote)) && Number(remote) > Number(local); } +export function parseUpdate(raw, localVersionCode) { + if (!raw || typeof raw !== 'object' || !/^\d+\.\d+\.\d+$/.test(String(raw.version)) || !isNewer(raw.versionCode, localVersionCode) || !/^https:\/\/(github\.com|objects\.githubusercontent\.com)\//.test(String(raw.downloadUrl))) return null; + return { ...raw, versionCode: Number(raw.versionCode), releaseNotes: Array.isArray(raw.releaseNotes) ? raw.releaseNotes.filter(x => typeof x === 'string').slice(0, 5) : [], mandatory: raw.mandatory === true }; +} +let lastCheck = 0; +export async function checkForUpdate({ force = false, ui = null } = {}) { + if (!force && Date.now() - lastCheck < 6 * 60 * 60 * 1000) return null; + lastCheck = Date.now(); + try { const installed = await native.getAppVersion(); const r = await fetch(`${WORKER_ORIGIN}/api/app-update`, { headers: { Accept: 'application/json' } }); const update = parseUpdate(await r.json(), Number(installed.versionCode)); if (update && ui) showUpdate(update, ui); return update; } catch { return null; } +} +function showUpdate(update, ui) { + const notes = update.releaseNotes.length ? `` : '

Bug fixes and improvements.

'; + const buttons = update.mandatory ? '' : ''; + ui.sheet({ title: 'Update Available', content: `

DSMNRU PYQ v${escapeHtml(update.version)}

${notes}
${buttons}
` }); + document.querySelector('#update-later')?.addEventListener('click', () => ui.closeSheet()); + document.querySelector('#update-now')?.addEventListener('click', async () => { const b=document.querySelector('#update-now'); b.disabled=true; b.textContent='Downloading…'; try { await native.downloadAndInstall(update.downloadUrl, `dsmnru-pyq-${update.version}.apk`); } catch (e) { b.disabled=false; b.textContent='Try again'; ui.toast(e.message || 'Update failed', 'err'); } }); +} +function escapeHtml(s) { return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } diff --git a/android-app/www/js/views/about.js b/android-app/www/js/views/about.js index 8f9c24c..b9b7318 100644 --- a/android-app/www/js/views/about.js +++ b/android-app/www/js/views/about.js @@ -9,17 +9,17 @@ import { SITE_ORIGIN } from '../api.js'; import * as ui from '../ui.js'; -const APP_VERSION = '1.4.0'; export default async function renderAbout(root, ctx) { ctx.setHeader({ title: 'About', brand: false }); + const { versionName } = await ctx.native.getAppVersion(); root.innerHTML = `

DSMNRU PYQ

-

Dedicated Android app · v${APP_VERSION}
+

Dedicated Android app · v${versionName || 'Unknown'}
Dr. Shakuntala Misra National Rehabilitation University
previous-year question-paper archive

diff --git a/android-app/www/js/views/profile.js b/android-app/www/js/views/profile.js index 2cbb5a9..a4ccd12 100644 --- a/android-app/www/js/views/profile.js +++ b/android-app/www/js/views/profile.js @@ -11,7 +11,6 @@ * rendered — everything user-facing is human text. */ -const APP_VERSION = '1.4.0'; function esc(s) { return String(s == null ? '' : s); } @@ -28,6 +27,8 @@ function dateLabel(iso) { export default async function renderProfile(root, ctx) { const { ui, auth, store, api, native, router } = ctx; + const { versionName } = await native.getAppVersion(); + const appVersion = versionName || 'Unknown'; ctx.setHeader({ title: 'Profile', brand: false }); const user = auth.current(); @@ -174,7 +175,7 @@ export default async function renderProfile(root, ctx) { if (user && user.admin) { items.push({ act: 'admin', icon: 'tools', label: 'Open admin panel', sub: 'Administration stays on the website — there is no second panel' }); } - items.push({ act: 'about', icon: 'info', label: 'About this app', sub: `Version ${APP_VERSION}` }); + items.push({ act: 'about', icon: 'info', label: 'About this app', sub: `Version ${appVersion}` }); more.innerHTML = `
${items.map((it) => ` `).join('')}
`; more.addEventListener('click', (e) => { @@ -204,7 +205,7 @@ export default async function renderProfile(root, ctx) { break; case 'about': ui.sheet({ - title: `DSMNRU PYQ · Version ${APP_VERSION}`, + title: `DSMNRU PYQ · Version ${appVersion}`, content: `

A dedicated Android app for the DSMNRU previous-year question-paper archive — same data and accounts as the website, in a native interface.

diff --git a/worker/src/appUpdate.js b/worker/src/appUpdate.js new file mode 100644 index 0000000..fd874b5 --- /dev/null +++ b/worker/src/appUpdate.js @@ -0,0 +1,43 @@ +/** Pure GitHub release validation used by the Android update endpoint. */ +export function parseVersionCode(body) { + const match = String(body || '').match(/(?:android\s+)?versionCode\s*[:=]\s*(\d+)(?![.\d])/i); + if (!match) return null; + const code = Number(match[1]); + return Number.isSafeInteger(code) && code > 0 ? code : null; +} + +export function isTrustedApkAsset(asset) { + if (!asset || asset.state && asset.state !== 'uploaded') return false; + const name = String(asset.name || ''); + const url = String(asset.browser_download_url || ''); + if (!/\.apk$/i.test(name) || /(?:debug|unsigned|source|test)/i.test(name)) return false; + try { + const parsed = new URL(url); + return parsed.protocol === 'https:' && (parsed.hostname === 'github.com' || parsed.hostname === 'objects.githubusercontent.com'); + } catch { return false; } +} + +export function selectProductionApk(assets) { + const valid = (Array.isArray(assets) ? assets : []).filter(isTrustedApkAsset); + if (!valid.length) return null; + // Prefer an explicitly production-looking asset, then the largest APK. + return valid.sort((a, b) => { + const score = x => /(?:release|dsmnru[-_]?pyq)/i.test(String(x.name)) ? 1 : 0; + return score(b) - score(a) || Number(b.size || 0) - Number(a.size || 0); + })[0]; +} + +export function toUpdateMetadata(release) { + if (!release || release.draft || release.prerelease || !release.published_at || !/^v?\d+\.\d+\.\d+$/.test(String(release.tag_name || ''))) return null; + const versionCode = parseVersionCode(release.body); + const asset = selectProductionApk(release.assets); + if (!versionCode || !asset) return null; + return { + version: String(release.tag_name).replace(/^v/, ''), + versionCode, + downloadUrl: asset.browser_download_url, + releaseNotes: String(release.body || '').split('\n').map(x => x.replace(/^[-*]\s*/, '').trim()).filter(Boolean).slice(0, 5), + mandatory: false, + publishedAt: release.published_at, + }; +} diff --git a/worker/src/index.js b/worker/src/index.js index 5909f5b..ef4bde1 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -59,6 +59,7 @@ import { renderSitemapXml, } from './seo.js'; import { jwtVerify, createRemoteJWKSet } from 'jose'; +import { toUpdateMetadata } from './appUpdate.js'; // ─── Firebase ID Token Verification ─────────────────────────────── const FIREBASE_PROJECT_ID = 'dsmnru-data'; @@ -225,6 +226,8 @@ async function handleRequest(request, ctx) { response = await handleCourses(); } else if (path === '/api/homepage' && method === 'GET') { response = await handleHomepage(ctx); + } else if (path === '/api/app-update' && method === 'GET') { + response = await handleAppUpdate(); } else if (path === '/api/stats' && method === 'GET') { response = await handleStats(ctx); } else if (path === '/api/invalidate' && method === 'POST') { @@ -244,6 +247,18 @@ async function handleRequest(request, ctx) { return response; } + +async function handleAppUpdate() { + const response = await fetch('https://api.github.com/repos/Lav-developer/PYQ/releases?per_page=30', { + headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'DSMNRU-PYQ-updater' }, + }); + if (!response.ok) throw new Error(`GitHub releases: ${response.status}`); + const releases = await response.json(); + const candidates = (Array.isArray(releases) ? releases : []).map(toUpdateMetadata).filter(Boolean); + candidates.sort((a, b) => b.versionCode - a.versionCode); + return candidates.length ? jsonResponse(candidates[0]) : jsonResponse({ available: false }); +} + // ─── Helpers shared by list/search/homepage/stats handlers ───────── /** diff --git a/worker/test/app-update.test.cjs b/worker/test/app-update.test.cjs new file mode 100644 index 0000000..efa401d --- /dev/null +++ b/worker/test/app-update.test.cjs @@ -0,0 +1,17 @@ +(async () => { + const { parseVersionCode, selectProductionApk, toUpdateMetadata } = await import('../src/appUpdate.js'); + const assert = require('node:assert/strict'); + const apk = (name, url = `https://github.com/Lav-developer/PYQ/releases/download/v2/${name}`, size = 10) => ({ name, browser_download_url: url, state: 'uploaded', size }); + assert.equal(parseVersionCode('Android versionCode: 37'), 37); + assert.equal(parseVersionCode('versionCode: 1.4.2'), null); + assert.equal(parseVersionCode('release notes'), null); + const release = (extra = {}) => ({ tag_name: 'v2.0.0', published_at: '2026-01-01T00:00:00Z', body: 'versionCode: 37\n- Fast', assets: [apk('source.zip'), apk('debug.apk'), apk('dsmnru-pyq.apk', undefined, 20), apk('notes.txt')], ...extra }); + assert.equal(toUpdateMetadata({ ...release(), draft: true }), null); + assert.equal(toUpdateMetadata({ ...release(), prerelease: true }), null); + assert.equal(toUpdateMetadata({ ...release({ body: 'release notes' }) }), null); + assert.equal(toUpdateMetadata({ ...release({ assets: [apk('source.zip')] }) }), null); + assert.equal(selectProductionApk([apk('small.apk', undefined, 1), apk('dsmnru-pyq-release.apk', undefined, 2)]).name, 'dsmnru-pyq-release.apk'); + assert.equal(selectProductionApk([apk('app.apk', 'http://github.com/x/app.apk')]), null); + assert.equal(toUpdateMetadata(release()).versionCode, 37); + console.log('app-update tests: 9 passed'); +})().catch(error => { console.error(error); process.exitCode = 1; });