import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import QRCode from 'qrcode';
import { settings } from '../config.js';
import { ah } from './auth.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const APK_DIR = settings.APK_DIR || path.resolve(__dirname, '..', '..', 'apk');
const APK_FILENAME = 'app-release.apk';
const APK_DOWNLOAD_URL = 'https://riadrayhan111-rr-locker-api.hf.space/api/v1/app/download';
const DEVICE_ADMIN_COMPONENT = 'com.riad.rrlkr/com.riad.rrlkr.admin.EMIDeviceAdminReceiver';
function apkPath() {
return path.join(APK_DIR, APK_FILENAME);
}
function baseUrl(req) {
const proto = req.headers['x-forwarded-proto'] || req.protocol;
return `${proto}://${req.get('host')}`;
}
function installHtml(downloadUrl) {
return `
RR Locker - Install
🔒
RR Locker
Device Management & Protection App
⚡ Ready to download. Tap the button below.
✅ Download started! Check your notification bar.
⬇ Download RR Locker
1
Tap "Download RR Locker" above
2
When done, open the notification or the Downloads folder
3
If prompted, enable "Allow from this source", then tap "Install"
4
Open the app and enter your Server URL to enroll
5
Grant all permissions when asked – required for protection
`;
}
export default function registerAppDistributionRoutes(router) {
// Direct APK download (GET + HEAD). Falls back to redirect if file missing.
const serveDownload = (req, res) => {
const p = apkPath();
if (fs.existsSync(p) && fs.statSync(p).isFile()) {
const size = fs.statSync(p).size;
res.set({
'Content-Disposition': `attachment; filename=${APK_FILENAME}`,
'Accept-Ranges': 'bytes',
'Cache-Control': 'public, max-age=3600',
'Content-Type': 'application/vnd.android.package-archive',
});
if (req.method === 'HEAD') {
res.set('Content-Length', String(size));
return res.end();
}
return res.sendFile(p);
}
return res.redirect(302, APK_DOWNLOAD_URL);
};
router.get('/app/download', serveDownload);
router.head('/app/download', serveDownload);
router.get('/app/download-local', ah(async (req, res) => {
const p = apkPath();
if (!fs.existsSync(p)) return res.json({ error: 'APK file not found', path: p });
return res.download(p, APK_FILENAME, {
headers: { 'Content-Type': 'application/vnd.android.package-archive' },
});
}));
router.get('/app/install', (req, res) => {
const downloadUrl = `${baseUrl(req)}/api/v1/app/download`;
res.type('html').send(installHtml(downloadUrl));
});
router.get('/app/qr-code', ah(async (req, res) => {
const installUrl = `${baseUrl(req)}/api/v1/app/install`;
const buf = await QRCode.toBuffer(installUrl, {
errorCorrectionLevel: 'H',
margin: 4,
scale: 10,
color: { dark: '#1a1a2e', light: '#ffffff' },
});
res.set({ 'Content-Type': 'image/png', 'Content-Disposition': 'inline; filename=rrlocker-qr.png', 'Cache-Control': 'no-cache' });
res.end(buf);
}));
router.get('/app/info', (req, res) => {
const p = apkPath();
const exists = fs.existsSync(p);
const size = exists ? fs.statSync(p).size : 0;
res.json({
app_name: 'RR Locker',
apk_available: true,
apk_size_mb: exists ? Math.round((size / (1024 * 1024)) * 100) / 100 : 9.6,
download_url: APK_DOWNLOAD_URL,
install_page_url: `${baseUrl(req)}/api/v1/app/install`,
qr_code_url: `${baseUrl(req)}/api/v1/app/qr-code`,
local_download_url: `${baseUrl(req)}/api/v1/app/download-local`,
device_admin_component: DEVICE_ADMIN_COMPONENT,
});
});
router.get('/app/check-update', (req, res) => {
const p = apkPath();
const currentVersion = parseInt(req.query.current_version, 10) || 0;
const versionFile = path.join(APK_DIR, 'version.json');
let latestVersion = 2;
let latestVersionName = '2.0.0';
let changelog = '';
let forceUpdate = false;
let minSupportedVersion = 1;
if (fs.existsSync(versionFile)) {
try {
const info = JSON.parse(fs.readFileSync(versionFile, 'utf8'));
latestVersion = info.version_code ?? latestVersion;
latestVersionName = info.version_name ?? latestVersionName;
changelog = info.changelog ?? '';
forceUpdate = info.force_update ?? false;
minSupportedVersion = info.min_supported_version ?? 1;
} catch { /* ignore */ }
}
const hasUpdate = currentVersion < latestVersion;
const apkAvailable = fs.existsSync(p);
const apkSize = apkAvailable ? fs.statSync(p).size : 0;
if (currentVersion < minSupportedVersion) forceUpdate = true;
res.json({
has_update: hasUpdate,
latest_version: latestVersion,
latest_version_name: latestVersionName,
current_version: currentVersion,
apk_url: APK_DOWNLOAD_URL,
apk_size: apkSize,
force_update: forceUpdate && hasUpdate,
changelog,
min_supported_version: minSupportedVersion,
});
});
}