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: 2 additions & 0 deletions android-app/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
-->
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"><meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /></provider>

<activity
android:name=".PdfViewerActivity"
android:exported="false"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@
import android.os.Environment;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import androidx.core.content.FileProvider;
import android.os.Build;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import androidx.credentials.CredentialManager;
import androidx.credentials.CredentialManagerCallback;
Expand Down Expand Up @@ -358,6 +365,33 @@ public void emitSiteLink(String url) {
notifyListeners("siteDeepLink", payload, true);
}

@PluginMethod
public void getAppVersion(PluginCall call) {
try {
android.content.pm.PackageInfo info = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0);
JSObject result = new JSObject();
result.put("versionName", info.versionName == null ? "" : info.versionName);
result.put("versionCode", android.os.Build.VERSION.SDK_INT >= 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://"))
Expand Down
1 change: 1 addition & 0 deletions android-app/android/app/src/main/res/xml/file_paths.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android"><cache-path name="updates" path="." /></paths>
2 changes: 1 addition & 1 deletion android-app/test/app-frontend-smoke.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
4 changes: 2 additions & 2 deletions android-app/test/fcm.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
2 changes: 1 addition & 1 deletion android-app/test/features.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
23 changes: 23 additions & 0 deletions android-app/test/update-version.test.mjs
Original file line number Diff line number Diff line change
@@ -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/);
});
3 changes: 3 additions & 0 deletions android-app/www/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 */ }
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions android-app/www/js/native.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
22 changes: 22 additions & 0 deletions android-app/www/js/update.js
Original file line number Diff line number Diff line change
@@ -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 ? `<ul>${update.releaseNotes.map(x => `<li>${escapeHtml(x)}</li>`).join('')}</ul>` : '<p>Bug fixes and improvements.</p>';
const buttons = update.mandatory ? '<button class="btn btn--primary" id="update-now">Update Now</button>' : '<button class="btn btn--ghost" id="update-later">Later</button><button class="btn btn--primary" id="update-now">Update Now</button>';
ui.sheet({ title: 'Update Available', content: `<p>DSMNRU PYQ v${escapeHtml(update.version)}</p>${notes}<div class=\"sheet-actions\">${buttons}</div>` });
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 => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
4 changes: 2 additions & 2 deletions android-app/www/js/views/about.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `
<div class="stack">
<section class="card card-pad about-hero">
<div class="hero-emblem" aria-hidden="true"></div>
<h1>DSMNRU PYQ</h1>
<p class="h-sub">Dedicated Android app · v${APP_VERSION}<br>
<p class="h-sub">Dedicated Android app · v${versionName || 'Unknown'}<br>
Dr. Shakuntala Misra National Rehabilitation University<br>previous-year question-paper archive</p>
</section>

Expand Down
7 changes: 4 additions & 3 deletions android-app/www/js/views/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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); }

Expand All @@ -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();
Expand Down Expand Up @@ -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 = `<div class="sheet-list">${items.map((it) => `
<button class="sheet-item" data-act="${it.act}" type="button">${ui.icon(it.icon)}<span>${ui.esc(it.label)}<small>${ui.esc(it.sub)}</small></span><span class="tail">${ui.icon('chevron')}</span></button>`).join('')}</div>`;
more.addEventListener('click', (e) => {
Expand Down Expand Up @@ -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: `<p class="sheet-text">A dedicated Android app for the DSMNRU previous-year
question-paper archive — same data and accounts as the website, in a
native interface.<br><br>
Expand Down
43 changes: 43 additions & 0 deletions worker/src/appUpdate.js
Original file line number Diff line number Diff line change
@@ -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,
};
}
15 changes: 15 additions & 0 deletions worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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') {
Expand All @@ -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 ─────────

/**
Expand Down
17 changes: 17 additions & 0 deletions worker/test/app-update.test.cjs
Original file line number Diff line number Diff line change
@@ -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; });