feat(mobile): package frontend into native Android APK with Capacitor (camera, cleartext LAN traffic & dynamic server IP)
This commit is contained in:
@@ -1,8 +1,42 @@
|
||||
// ==============================================================================
|
||||
// Cliente HTTP Fetch con soporte para cookies HttpOnly y tipado estricto
|
||||
// Cliente HTTP Fetch con soporte para Capacitor (Android), cookies y Bearer
|
||||
// ==============================================================================
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
|
||||
const BASE_URL = '/api/v1';
|
||||
export function getBaseUrl(): string {
|
||||
// 1. URL personalizada en localStorage (útil para configurar IP de backend en tablet)
|
||||
const savedUrl = localStorage.getItem('on_ever_api_url');
|
||||
if (savedUrl && savedUrl.trim()) {
|
||||
const trimmed = savedUrl.trim();
|
||||
return trimmed.endsWith('/') ? trimmed.slice(0, -1) : trimmed;
|
||||
}
|
||||
|
||||
// 2. Variable de entorno Vite
|
||||
const viteApiUrl = (import.meta as any).env?.VITE_API_URL;
|
||||
if (viteApiUrl) {
|
||||
const envUrl = (viteApiUrl as string).trim();
|
||||
return envUrl.endsWith('/') ? envUrl.slice(0, -1) : envUrl;
|
||||
}
|
||||
|
||||
// 3. Si corre nativo en Capacitor (APK Android) y no se configuró URL
|
||||
if (Capacitor.isNativePlatform()) {
|
||||
return 'http://192.168.0.100:8000/api/v1';
|
||||
}
|
||||
|
||||
// 4. Modo navegador web estándar
|
||||
return '/api/v1';
|
||||
}
|
||||
|
||||
export function getWsBaseUrl(): string {
|
||||
const base = getBaseUrl();
|
||||
if (base.startsWith('http://') || base.startsWith('https://')) {
|
||||
const parsed = new URL(base);
|
||||
const wsProto = parsed.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return `${wsProto}//${parsed.host}`;
|
||||
}
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return `${protocol}//${window.location.host}`;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
@@ -17,7 +51,8 @@ export class ApiError extends Error {
|
||||
}
|
||||
|
||||
export async function request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
||||
const url = endpoint.startsWith('http') ? endpoint : `${BASE_URL}${endpoint}`;
|
||||
const baseUrl = getBaseUrl();
|
||||
const url = endpoint.startsWith('http') ? endpoint : `${baseUrl}${endpoint}`;
|
||||
|
||||
const headers = new Headers(options.headers || {});
|
||||
if (!headers.has('Content-Type') && !(options.body instanceof FormData)) {
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
HybridBinarizer,
|
||||
GlobalHistogramBinarizer,
|
||||
} from '@zxing/library';
|
||||
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import { accessApi } from '../../api/accessApi';
|
||||
import { DNIParsedResult } from '../../types';
|
||||
|
||||
@@ -560,6 +562,43 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
// Captura nativa con plugin oficial de Capacitor (Android Tablet Samsung)
|
||||
const handleCapacitorPhoto = async () => {
|
||||
if (!Capacitor.isNativePlatform()) {
|
||||
fileInputRef.current?.click();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const photo = await Camera.getPhoto({
|
||||
quality: 92,
|
||||
allowEditing: false,
|
||||
resultType: CameraResultType.DataUrl,
|
||||
source: CameraSource.Camera,
|
||||
});
|
||||
|
||||
if (photo.dataUrl) {
|
||||
stopCamera();
|
||||
const img = new Image();
|
||||
img.onload = async () => {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
ctx.drawImage(img, 0, 0);
|
||||
setCapturedPhotoUrl(photo.dataUrl!);
|
||||
await processImageExtraction(canvas);
|
||||
}
|
||||
};
|
||||
img.src = photo.dataUrl;
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (err.message && !err.message.includes('User cancelled') && !err.message.includes('cancelled')) {
|
||||
setErrorMsg(`Error en cámara nativa: ${err.message}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Reintentar captura volviendo a la cámara en vivo
|
||||
const handleRetake = () => {
|
||||
setCapturedPhotoUrl(null);
|
||||
@@ -1002,11 +1041,11 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onClick={handleCapacitorPhoto}
|
||||
style={{ minHeight: '54px', padding: '0 1rem', fontSize: '0.9rem' }}
|
||||
title="Tomar foto con app nativa o subir archivo"
|
||||
title="Tomar foto con app nativa de cámara o subir archivo"
|
||||
>
|
||||
📁 Galería / App
|
||||
📸 Cámara App / Galería
|
||||
</button>
|
||||
</>
|
||||
) : step === 'SUCCESS' ? (
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Hook de Comunicación en Tiempo Real vía WebSocket
|
||||
// ==============================================================================
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { getWsBaseUrl } from '../api/client';
|
||||
|
||||
interface WebSocketMessage {
|
||||
type: string;
|
||||
@@ -22,9 +23,8 @@ export function useWebSocket({ stationName, onMessage }: UseWebSocketOptions) {
|
||||
const connect = useCallback(() => {
|
||||
if (!stationName) return;
|
||||
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const host = window.location.host;
|
||||
const url = `${protocol}//${host}/ws/station/${encodeURIComponent(stationName)}`;
|
||||
const wsBase = getWsBaseUrl();
|
||||
const url = `${wsBase}/ws/station/${encodeURIComponent(stationName)}`;
|
||||
|
||||
try {
|
||||
const socket = new WebSocket(url);
|
||||
|
||||
@@ -7,6 +7,7 @@ import React, { useState, useEffect } from 'react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { workstationApi, WorkstationListItem } from '../api/workstationApi';
|
||||
import { useTheme } from '../hooks/useTheme';
|
||||
import { getBaseUrl } from '../api/client';
|
||||
import { APP_VERSION, APP_BUILD } from '../version';
|
||||
|
||||
export const LoginView: React.FC = () => {
|
||||
@@ -26,6 +27,10 @@ export const LoginView: React.FC = () => {
|
||||
const [availableWorkstations, setAvailableWorkstations] = useState<WorkstationListItem[]>([]);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
const [isServerModalOpen, setIsServerModalOpen] = useState<boolean>(false);
|
||||
const [serverUrl, setServerUrl] = useState<string>(() => {
|
||||
return localStorage.getItem('on_ever_api_url') || getBaseUrl();
|
||||
});
|
||||
|
||||
const isDark = theme === 'dark';
|
||||
|
||||
@@ -106,6 +111,31 @@ export const LoginView: React.FC = () => {
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsServerModalOpen(true)}
|
||||
style={{
|
||||
minHeight: '38px',
|
||||
padding: '0 0.85rem',
|
||||
fontSize: '0.85rem',
|
||||
backgroundColor: isDark ? 'rgba(30, 41, 59, 0.85)' : 'rgba(255, 255, 255, 0.9)',
|
||||
color: isDark ? '#F8FAFC' : '#0F172A',
|
||||
border: `1px solid ${isDark ? '#334155' : '#CBD5E1'}`,
|
||||
borderRadius: '19px',
|
||||
cursor: 'pointer',
|
||||
backdropFilter: 'blur(8px)',
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.4rem',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
title="Configurar IP de Servidor Backend"
|
||||
>
|
||||
<span>⚙️</span>
|
||||
<span>Servidor</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
@@ -625,6 +655,148 @@ export const LoginView: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Modal de Configuración de Servidor Backend (Tablet / APK) */}
|
||||
{isServerModalOpen && (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.75)',
|
||||
backdropFilter: 'blur(4px)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1000,
|
||||
padding: '1rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: isDark ? '#1E293B' : '#FFFFFF',
|
||||
borderRadius: '16px',
|
||||
padding: '1.5rem',
|
||||
width: '100%',
|
||||
maxWidth: '420px',
|
||||
border: `1px solid ${isDark ? '#334155' : '#CBD5E1'}`,
|
||||
boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.5)',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '1rem',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<div style={{ fontWeight: 800, fontSize: '1rem', color: isDark ? '#F8FAFC' : '#0F172A' }}>
|
||||
⚙️ Configurar Servidor Backend
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsServerModalOpen(false)}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
color: isDark ? '#94A3B8' : '#64748B',
|
||||
fontSize: '1.2rem',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p style={{ fontSize: '0.825rem', color: isDark ? '#94A3B8' : '#64748B', margin: 0 }}>
|
||||
Ingrese la dirección IP y puerto del servidor FastAPI en la red local.
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<label
|
||||
style={{
|
||||
display: 'block',
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 700,
|
||||
color: isDark ? '#94A3B8' : '#64748B',
|
||||
marginBottom: '0.35rem',
|
||||
textTransform: 'uppercase',
|
||||
}}
|
||||
>
|
||||
URL Base de API
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={serverUrl}
|
||||
onChange={(e) => setServerUrl(e.target.value)}
|
||||
placeholder="http://192.168.0.100:8000/api/v1"
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '42px',
|
||||
borderRadius: '8px',
|
||||
backgroundColor: isDark ? '#0F172A' : '#F8FAFC',
|
||||
border: `1px solid ${isDark ? '#374151' : '#CBD5E1'}`,
|
||||
color: isDark ? '#F8FAFC' : '#0F172A',
|
||||
padding: '0 12px',
|
||||
fontSize: '0.9rem',
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (serverUrl.trim()) {
|
||||
localStorage.setItem('on_ever_api_url', serverUrl.trim());
|
||||
} else {
|
||||
localStorage.removeItem('on_ever_api_url');
|
||||
}
|
||||
setIsServerModalOpen(false);
|
||||
window.location.reload();
|
||||
}}
|
||||
style={{
|
||||
flex: 1,
|
||||
height: '40px',
|
||||
backgroundColor: '#2563EB',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: '8px',
|
||||
fontWeight: 700,
|
||||
fontSize: '0.875rem',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
Guardar y Conectar
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
localStorage.removeItem('on_ever_api_url');
|
||||
setServerUrl(getBaseUrl());
|
||||
setIsServerModalOpen(false);
|
||||
window.location.reload();
|
||||
}}
|
||||
style={{
|
||||
height: '40px',
|
||||
padding: '0 1rem',
|
||||
backgroundColor: 'transparent',
|
||||
color: isDark ? '#94A3B8' : '#64748B',
|
||||
border: `1px solid ${isDark ? '#334155' : '#CBD5E1'}`,
|
||||
borderRadius: '8px',
|
||||
fontWeight: 600,
|
||||
fontSize: '0.825rem',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
Restablecer
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user