Зафиксировать рабочий BreathMonitor v1 и сервер
This commit is contained in:
@@ -0,0 +1,464 @@
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.sql.*;
|
||||
import java.time.*;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
/** Lightweight standalone server: HTTP API, SQLite, immutable record parser and a static dashboard.
|
||||
* Deploy behind a HTTPS reverse-proxy (Caddy); never expose the raw HTTP port publicly.
|
||||
* JDK 21 + org.xerial:sqlite-jdbc (shaded by Gradle). No Spring, Node, or external database.
|
||||
*/
|
||||
public final class BreathServer {
|
||||
private static final int RECORD = 32, MAX_UPLOAD = 16 * 1024 * 1024, ITERATIONS = 210_000;
|
||||
private static final long SESSION_TTL = 14L * 24 * 3600 * 1000;
|
||||
private static final SecureRandom RNG = new SecureRandom();
|
||||
private static final String DB_URL = "jdbc:sqlite:" + Path.of(System.getenv().getOrDefault("BREATH_DATA_DIR", "data"), "statistics.db").toAbsolutePath();
|
||||
private static final Path DATA = Path.of(System.getenv().getOrDefault("BREATH_DATA_DIR", "data")).toAbsolutePath();
|
||||
private static final Path WEB = Path.of(System.getenv().getOrDefault("BREATH_WEB_DIR", "web")).toAbsolutePath();
|
||||
private static final String ORIGIN = System.getenv().getOrDefault("PUBLIC_ORIGIN", "https://breathmonitor.shineup.me");
|
||||
private static final String BIND = System.getenv().getOrDefault("BREATH_BIND", "127.0.0.1");
|
||||
private static final int PORT = Integer.parseInt(System.getenv().getOrDefault("BREATH_PORT", "8090"));
|
||||
private static final DateTimeFormatter DAY = DateTimeFormatter.BASIC_ISO_DATE;
|
||||
private static final Map<String, LoginThrottle> THROTTLES = new ConcurrentHashMap<>();
|
||||
private static final Object UPLOAD_LOCK = new Object();
|
||||
|
||||
record User(long id, String login, boolean published) {}
|
||||
record FileSummary(long cycles, long durationMs, long inhaleMs, long exhaleMs, long maxCycleMs) {}
|
||||
static final class HttpError extends Exception {
|
||||
final int status;
|
||||
HttpError(int status, String message) { super(message); this.status = status; }
|
||||
}
|
||||
static final class LoginThrottle { long start = System.currentTimeMillis(); int attempts; }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Files.createDirectories(DATA);
|
||||
Class.forName("org.sqlite.JDBC");
|
||||
initialize();
|
||||
if (args.length > 0) {
|
||||
if (args.length == 2 && args[0].equals("create-user")) { createUser(args[1]); return; }
|
||||
if (args.length == 2 && args[0].equals("reset-password")) { resetPassword(args[1]); return; }
|
||||
System.err.println("Usage: java -jar BreathServer.jar [create-user <login> | reset-password <login>]");
|
||||
System.exit(2);
|
||||
}
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getByName(BIND), PORT), 64);
|
||||
server.createContext("/", BreathServer::dispatch);
|
||||
server.setExecutor(Executors.newFixedThreadPool(12));
|
||||
server.start();
|
||||
System.out.printf("BreathMonitor listening on http://%s:%d (public origin %s)%n", BIND, PORT, ORIGIN);
|
||||
}
|
||||
|
||||
private static Connection connection() throws SQLException {
|
||||
Connection c = DriverManager.getConnection(DB_URL);
|
||||
try (Statement s = c.createStatement()) {
|
||||
s.execute("PRAGMA foreign_keys=ON");
|
||||
s.execute("PRAGMA busy_timeout=5000");
|
||||
}
|
||||
return c;
|
||||
}
|
||||
private static void initialize() throws SQLException {
|
||||
try (Connection c = connection(); Statement s = c.createStatement()) {
|
||||
s.execute("PRAGMA journal_mode=WAL");
|
||||
s.execute("""
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY, login TEXT NOT NULL UNIQUE,
|
||||
salt TEXT NOT NULL, password_hash TEXT NOT NULL,
|
||||
published INTEGER NOT NULL DEFAULT 0)
|
||||
""");
|
||||
s.execute("""
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
user_id INTEGER NOT NULL, device_id TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL, created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(user_id,device_id), FOREIGN KEY(user_id) REFERENCES users(id))
|
||||
""");
|
||||
s.execute("CREATE UNIQUE INDEX IF NOT EXISTS devices_tokens ON devices(token_hash)");
|
||||
s.execute("""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL, FOREIGN KEY(user_id) REFERENCES users(id))
|
||||
""");
|
||||
s.execute("""
|
||||
CREATE TABLE IF NOT EXISTS uploads (
|
||||
user_id INTEGER NOT NULL, device_id TEXT NOT NULL, day TEXT NOT NULL,
|
||||
bytes INTEGER NOT NULL, sha256 TEXT NOT NULL, cycles INTEGER NOT NULL,
|
||||
duration_ms INTEGER NOT NULL, inhale_ms INTEGER NOT NULL,
|
||||
exhale_ms INTEGER NOT NULL, max_cycle_ms INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(user_id,device_id,day), FOREIGN KEY(user_id) REFERENCES users(id))
|
||||
""");
|
||||
}
|
||||
}
|
||||
private static String readPassword(String prompt) throws IOException {
|
||||
Console console = System.console();
|
||||
if (console != null) {
|
||||
char[] p = console.readPassword("%s", prompt);
|
||||
if (p == null) throw new IOException("Password input cancelled");
|
||||
String result = new String(p); Arrays.fill(p, '\0'); return result;
|
||||
}
|
||||
System.out.print(prompt);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
|
||||
String result = reader.readLine();
|
||||
if (result == null) throw new IOException("Password input cancelled");
|
||||
return result;
|
||||
}
|
||||
private static void createUser(String login) throws Exception {
|
||||
validLogin(login);
|
||||
String pwd = readPassword("New password (1..63 characters): ");
|
||||
if (pwd.isEmpty() || pwd.length() > 63) throw new IllegalArgumentException("Password must contain 1..63 characters");
|
||||
String salt = tokenBytes(16), hash = passwordHash(pwd, salt);
|
||||
try (Connection c = connection(); PreparedStatement p = c.prepareStatement("INSERT INTO users(login,salt,password_hash) VALUES(?,?,?)")) {
|
||||
p.setString(1, login); p.setString(2, salt); p.setString(3, hash); p.executeUpdate();
|
||||
}
|
||||
System.out.println("Created user: " + login + ". Sign in on the dashboard, then pair the device.");
|
||||
}
|
||||
private static void resetPassword(String login) throws Exception {
|
||||
validLogin(login); String pwd = readPassword("New password (1..63 characters): ");
|
||||
if (pwd.isEmpty() || pwd.length() > 63) throw new IllegalArgumentException("Password must contain 1..63 characters");
|
||||
String salt = tokenBytes(16), hash = passwordHash(pwd, salt);
|
||||
try (Connection c = connection()) {
|
||||
c.setAutoCommit(false);
|
||||
try (PreparedStatement p = c.prepareStatement("UPDATE users SET salt=?,password_hash=? WHERE login=?")) {
|
||||
p.setString(1, salt); p.setString(2, hash); p.setString(3, login);
|
||||
if (p.executeUpdate() != 1) throw new IllegalArgumentException("Unknown user: " + login);
|
||||
}
|
||||
try (PreparedStatement p = c.prepareStatement("DELETE FROM sessions WHERE user_id=(SELECT id FROM users WHERE login=?)")) {
|
||||
p.setString(1, login); p.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement p = c.prepareStatement("DELETE FROM devices WHERE user_id=(SELECT id FROM users WHERE login=?)")) {
|
||||
p.setString(1, login); p.executeUpdate();
|
||||
}
|
||||
c.commit();
|
||||
}
|
||||
System.out.println("Password updated, web sessions and device tokens revoked.");
|
||||
}
|
||||
private static byte[] fromHex(String hex) { return HexFormat.of().parseHex(hex); }
|
||||
private static String tokenBytes(int n) { byte[] v = new byte[n]; RNG.nextBytes(v); return HexFormat.of().formatHex(v); }
|
||||
private static String sha(byte[] b) {
|
||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(b)); }
|
||||
catch (NoSuchAlgorithmException ex) { throw new AssertionError(ex); }
|
||||
}
|
||||
private static String sha(String v) { return sha(v.getBytes(StandardCharsets.UTF_8)); }
|
||||
private static String passwordHash(String pwd, String salt) throws Exception {
|
||||
PBEKeySpec spec = new PBEKeySpec(pwd.toCharArray(), fromHex(salt), ITERATIONS, 256);
|
||||
try { return HexFormat.of().formatHex(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded()); }
|
||||
finally { spec.clearPassword(); }
|
||||
}
|
||||
private static void validLogin(String login) throws HttpError {
|
||||
if (!login.matches("[a-z0-9_-]{3,24}")) throw new HttpError(400, "Login must be 3..24 lowercase characters, numbers, '_' or '-'");
|
||||
}
|
||||
private static void validDevice(String device) throws HttpError {
|
||||
if (!device.matches("[0-9A-F]{12}")) throw new HttpError(400, "Invalid device ID");
|
||||
}
|
||||
private static void validDay(String day) throws HttpError {
|
||||
if (day.equals("undated")) return;
|
||||
if (!day.matches("20[2-9][0-9][0-1][0-9][0-3][0-9]")) throw new HttpError(400, "Invalid day");
|
||||
try { LocalDate.parse(day, DAY); } catch (Exception ex) { throw new HttpError(400, "Invalid calendar date"); }
|
||||
}
|
||||
private static void dispatch(HttpExchange x) {
|
||||
try {
|
||||
Headers h = x.getResponseHeaders();
|
||||
h.set("X-Content-Type-Options", "nosniff"); h.set("Referrer-Policy", "no-referrer");
|
||||
h.set("X-Frame-Options", "DENY"); h.set("Cache-Control", "no-store");
|
||||
h.set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'");
|
||||
String path = x.getRequestURI().getPath(), method = x.getRequestMethod();
|
||||
switch (path) {
|
||||
case "/api/health" -> { if (!method.equals("GET")) throw new HttpError(405,"Method not allowed"); json(x,200,"{\"ok\":true}"); }
|
||||
case "/api/device/login" -> { requireMethod(method,"POST"); deviceLogin(x); }
|
||||
case "/api/device/upload" -> { requireMethod(method,"PUT"); deviceUpload(x); }
|
||||
case "/api/login" -> { requireMethod(method,"POST"); requireBrowserOrigin(x); browserLogin(x); }
|
||||
case "/api/logout" -> { requireMethod(method,"POST"); requireBrowserOrigin(x); browserLogout(x); }
|
||||
case "/api/me" -> { requireMethod(method,"GET"); me(x); }
|
||||
case "/api/stats" -> { requireMethod(method,"GET"); stats(x); }
|
||||
case "/api/leaderboard" -> { requireMethod(method,"GET"); leaderboard(x); }
|
||||
case "/api/privacy" -> { requireMethod(method,"POST"); requireBrowserOrigin(x); privacy(x); }
|
||||
default -> { if (!method.equals("GET")&& !method.equals("HEAD")) throw new HttpError(405,"Method not allowed"); serveWeb(x,path,method); }
|
||||
}
|
||||
} catch (HttpError err) { sendError(x,err.status,err.getMessage()); }
|
||||
catch (Exception err) { System.err.println("API error: " + err); sendError(x,500,"Internal error"); }
|
||||
finally { x.close(); }
|
||||
}
|
||||
private static void requireMethod(String actual,String expected) throws HttpError { if (!actual.equals(expected))throw new HttpError(405,"Expected " + expected); }
|
||||
private static void requireBrowserOrigin(HttpExchange x) throws HttpError {
|
||||
String origin = x.getRequestHeaders().getFirst("Origin");
|
||||
if (!ORIGIN.equals(origin)) throw new HttpError(403,"Origin mismatch");
|
||||
}
|
||||
private static byte[] readLimited(HttpExchange x, int limit) throws IOException, HttpError {
|
||||
long len = 0;
|
||||
try { len = Long.parseLong(Optional.ofNullable(x.getRequestHeaders().getFirst("Content-Length")).orElse("-1")); }
|
||||
catch (NumberFormatException err) { throw new HttpError(400,"Invalid content length"); }
|
||||
if (len > limit) throw new HttpError(413,"Payload too large");
|
||||
try (InputStream in = x.getRequestBody(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
byte[] buf = new byte[8192]; int n;
|
||||
while ((n=in.read(buf))!=-1) { if (out.size()+n > limit) throw new HttpError(413,"Payload too large"); out.write(buf,0,n); }
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
private static String[] credentials(HttpExchange x, boolean device) throws Exception {
|
||||
String body = new String(readLimited(x, 1024),StandardCharsets.UTF_8);
|
||||
String[] parts = body.split("\\n",-1);
|
||||
if (parts.length != (device?3:2)) throw new HttpError(400,"Invalid credential payload");
|
||||
validLogin(parts[0]);
|
||||
if (device) validDevice(parts[2]);
|
||||
return parts;
|
||||
}
|
||||
private static String remoteAddress(HttpExchange x) {
|
||||
// Caddy is trusted and the server binds to 127.0.0.1: use its Remote-IP as a throttle key.
|
||||
String ip = x.getRequestHeaders().getFirst("X-Forwarded-For");
|
||||
return ip!=null && ip.length()<100 ? ip.split(",")[0].trim() : x.getRemoteAddress().getAddress().getHostAddress();
|
||||
}
|
||||
private static void throttle(HttpExchange x) throws HttpError {
|
||||
String ip=remoteAddress(x); long now=System.currentTimeMillis();
|
||||
LoginThrottle l=THROTTLES.computeIfAbsent(ip,key->new LoginThrottle());
|
||||
synchronized (l) {
|
||||
if (now-l.start>60000){l.start=now;l.attempts=0;}
|
||||
if (++l.attempts>12) throw new HttpError(429,"Too many login attempts, try again later");
|
||||
}
|
||||
if (THROTTLES.size()>10000) THROTTLES.clear();
|
||||
}
|
||||
private static User checkCredentials(String login,String pass) throws Exception {
|
||||
try(Connection c=connection();PreparedStatement p=c.prepareStatement("SELECT id,salt,password_hash,published FROM users WHERE login=?")) {
|
||||
p.setString(1,login);
|
||||
try(ResultSet rs=p.executeQuery()){
|
||||
if(!rs.next())return null;
|
||||
String actual=passwordHash(pass,rs.getString("salt"));
|
||||
if (!MessageDigest.isEqual(fromHex(actual),fromHex(rs.getString("password_hash"))))return null;
|
||||
return new User(rs.getLong("id"),login,rs.getInt("published")==1);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static void deviceLogin(HttpExchange x) throws Exception {
|
||||
throttle(x);
|
||||
String[] values=credentials(x,true);
|
||||
User user=checkCredentials(values[0],values[1]);
|
||||
if(user==null) throw new HttpError(401,"Invalid credentials");
|
||||
String token=tokenBytes(32);
|
||||
try(Connection c=connection(); PreparedStatement p=c.prepareStatement("""
|
||||
INSERT INTO devices(user_id,device_id,token_hash,created_at) VALUES(?,?,?,?)
|
||||
ON CONFLICT(user_id,device_id) DO UPDATE SET token_hash=excluded.token_hash,created_at=excluded.created_at
|
||||
""")) {
|
||||
p.setLong(1,user.id());p.setString(2,values[2]);p.setString(3,sha(token));p.setLong(4,System.currentTimeMillis());p.executeUpdate();
|
||||
}
|
||||
send(x,200,"text/plain; charset=utf-8",token.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
private static void browserLogin(HttpExchange x) throws Exception {
|
||||
throttle(x);String[] values=credentials(x,false);
|
||||
User user=checkCredentials(values[0],values[1]);
|
||||
if(user==null)throw new HttpError(401,"Invalid credentials");
|
||||
String token=tokenBytes(32);long expiry=System.currentTimeMillis()+SESSION_TTL;
|
||||
try(Connection c=connection();PreparedStatement p=c.prepareStatement("INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(?,?,?)")){
|
||||
p.setString(1,sha(token));p.setLong(2,user.id());p.setLong(3,expiry);p.executeUpdate();
|
||||
}
|
||||
x.getResponseHeaders().add("Set-Cookie","bm_session="+token+"; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age="+(SESSION_TTL/1000));
|
||||
json(x,200,"{\"ok\":true}");
|
||||
}
|
||||
private static User loggedIn(HttpExchange x) throws Exception {
|
||||
String cookie=Optional.ofNullable(x.getRequestHeaders().getFirst("Cookie")).orElse("");
|
||||
String token=null;
|
||||
for(String piece:cookie.split(";")){
|
||||
String s=piece.trim();if(s.startsWith("bm_session=")){token=s.substring("bm_session=".length());break;}
|
||||
}
|
||||
if(token==null || !token.matches("[0-9a-f]{64}"))throw new HttpError(401,"Please sign in");
|
||||
try(Connection c=connection(); PreparedStatement p=c.prepareStatement("""
|
||||
SELECT u.id,u.login,u.published FROM sessions s JOIN users u ON u.id=s.user_id
|
||||
WHERE s.token_hash=? AND s.expires_at>?
|
||||
""")){
|
||||
p.setString(1,sha(token));p.setLong(2,System.currentTimeMillis());
|
||||
try(ResultSet rs=p.executeQuery()){
|
||||
if(!rs.next())throw new HttpError(401,"Session expired");
|
||||
return new User(rs.getLong(1),rs.getString(2),rs.getInt(3)!=0);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static void browserLogout(HttpExchange x) throws Exception {
|
||||
try { loggedIn(x); } catch(HttpError e) { /* Expired sessions still get cookie cleared. */ }
|
||||
String cookie=Optional.ofNullable(x.getRequestHeaders().getFirst("Cookie")).orElse("");
|
||||
for(String p:cookie.split(";")) {
|
||||
String v=p.trim(); if(v.startsWith("bm_session=")){
|
||||
try(Connection c=connection();PreparedStatement s=c.prepareStatement("DELETE FROM sessions WHERE token_hash=?")){
|
||||
s.setString(1,sha(v.substring("bm_session=".length())));s.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
x.getResponseHeaders().add("Set-Cookie","bm_session=; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0");
|
||||
json(x,200,"{\"ok\":true}");
|
||||
}
|
||||
private static void me(HttpExchange x) throws Exception {
|
||||
User u=loggedIn(x);
|
||||
json(x,200,"{\"login\":"+quoted(u.login())+",\"published\":"+u.published()+"}");
|
||||
}
|
||||
private static void privacy(HttpExchange x) throws Exception {
|
||||
User u=loggedIn(x);String body=new String(readLimited(x,16),StandardCharsets.US_ASCII).trim();
|
||||
if (!body.equals("true")&&!body.equals("false"))throw new HttpError(400,"Expected true or false");
|
||||
try(Connection c=connection();PreparedStatement p=c.prepareStatement("UPDATE users SET published=? WHERE id=?")){
|
||||
p.setInt(1,body.equals("true")?1:0);p.setLong(2,u.id());p.executeUpdate();
|
||||
}
|
||||
json(x,200,"{\"ok\":true}");
|
||||
}
|
||||
private static String param(HttpExchange x,String name) {
|
||||
String q=x.getRequestURI().getRawQuery();if(q==null)return null;
|
||||
for(String pair:q.split("&")) {
|
||||
String[] kv=pair.split("=",2);if(kv[0].equals(name))return kv.length==2?URLDecoder.decode(kv[1],StandardCharsets.UTF_8):"";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private static User authorizeDevice(HttpExchange x,String device) throws Exception {
|
||||
String auth=x.getRequestHeaders().getFirst("Authorization");
|
||||
if(auth==null||!auth.matches("Bearer [0-9a-f]{64}"))throw new HttpError(401,"Invalid bearer token");
|
||||
try(Connection c=connection();PreparedStatement p=c.prepareStatement("""
|
||||
SELECT u.id,u.login,u.published FROM devices d JOIN users u ON u.id=d.user_id
|
||||
WHERE d.token_hash=? AND d.device_id=?
|
||||
""")){
|
||||
p.setString(1,sha(auth.substring(7)));p.setString(2,device);
|
||||
try(ResultSet rs=p.executeQuery()){
|
||||
if(!rs.next())throw new HttpError(401,"Unknown device or revoked token");
|
||||
return new User(rs.getLong(1),rs.getString(2),rs.getInt(3)!=0);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static FileSummary verifyAndSummarize(byte[] body) throws HttpError {
|
||||
if(body.length==0||body.length%RECORD!=0)throw new HttpError(400,"File must contain complete 32-byte records");
|
||||
long cycles=0,total=0,inhale=0,exhale=0,max=0;
|
||||
CRC32 crc=new CRC32();
|
||||
for(int pos=0;pos<body.length;pos+=RECORD){
|
||||
int version=body[pos]&255, type=body[pos+1]&255;
|
||||
if(version!=1||type<1||type>10)throw new HttpError(400,"Invalid record type/version at offset "+pos);
|
||||
crc.reset();crc.update(body,pos,28);
|
||||
long got=ByteBuffer.wrap(body,pos+28,4).order(ByteOrder.LITTLE_ENDIAN).getInt()&0xffffffffL;
|
||||
if(crc.getValue()!=got)throw new HttpError(400,"CRC32 mismatch at offset "+pos);
|
||||
if(type==1){
|
||||
long i=((body[pos+16]&255)|((body[pos+17]&255)<<8))*100L;
|
||||
long e=((body[pos+18]&255)|((body[pos+19]&255)<<8))*100L;
|
||||
cycles++; inhale+=i;exhale+=e;total+=i+e;max=Math.max(max,i+e);
|
||||
}
|
||||
}
|
||||
return new FileSummary(cycles,total,inhale,exhale,max);
|
||||
}
|
||||
private static void deviceUpload(HttpExchange x) throws Exception {
|
||||
String day=param(x,"date");if(day==null)throw new HttpError(400,"Missing date");validDay(day);
|
||||
String device=x.getRequestHeaders().getFirst("X-Device-ID");if(device==null)throw new HttpError(400,"Missing X-Device-ID");validDevice(device);
|
||||
User user=authorizeDevice(x,device);
|
||||
byte[] body=readLimited(x,MAX_UPLOAD);
|
||||
FileSummary summary=verifyAndSummarize(body);
|
||||
String hash=sha(body);
|
||||
Path dest=DATA.resolve("logs").resolve(user.login()).resolve(device).resolve(user.login()+"_"+day+".bin");
|
||||
synchronized(UPLOAD_LOCK){
|
||||
Files.createDirectories(dest.getParent());
|
||||
if(Files.exists(dest)){
|
||||
byte[] prior=Files.readAllBytes(dest);
|
||||
// Device journals are append-only: old bytes may never be replaced or truncated.
|
||||
if(body.length<prior.length || !MessageDigest.isEqual(Arrays.copyOf(body,prior.length),prior))
|
||||
throw new HttpError(409,"Upload does not extend stored journal; reconcile manually");
|
||||
}
|
||||
Path tmp=Files.createTempFile(dest.getParent(),"upload-",".part");
|
||||
try {
|
||||
Files.write(tmp,body,StandardOpenOption.WRITE,StandardOpenOption.TRUNCATE_EXISTING);
|
||||
try{Files.move(tmp,dest,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}
|
||||
catch(AtomicMoveNotSupportedException err){Files.move(tmp,dest,StandardCopyOption.REPLACE_EXISTING);}
|
||||
}finally{Files.deleteIfExists(tmp);}
|
||||
// Repeated identical uploads are idempotent thanks to the per-device/date PRIMARY KEY.
|
||||
try(Connection c=connection();PreparedStatement p=c.prepareStatement("""
|
||||
INSERT INTO uploads(user_id,device_id,day,bytes,sha256,cycles,duration_ms,inhale_ms,exhale_ms,max_cycle_ms,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(user_id,device_id,day) DO UPDATE SET
|
||||
bytes=excluded.bytes, sha256=excluded.sha256,cycles=excluded.cycles,
|
||||
duration_ms=excluded.duration_ms,inhale_ms=excluded.inhale_ms,
|
||||
exhale_ms=excluded.exhale_ms,max_cycle_ms=excluded.max_cycle_ms,updated_at=excluded.updated_at
|
||||
""")){
|
||||
p.setLong(1,user.id());p.setString(2,device);p.setString(3,day);p.setInt(4,body.length);
|
||||
p.setString(5,hash);p.setLong(6,summary.cycles());p.setLong(7,summary.durationMs());
|
||||
p.setLong(8,summary.inhaleMs());p.setLong(9,summary.exhaleMs());
|
||||
p.setLong(10,summary.maxCycleMs());p.setLong(11,System.currentTimeMillis());p.executeUpdate();
|
||||
}
|
||||
}
|
||||
json(x,200,"{\"ok\":true,\"bytes\":"+body.length+",\"cycles\":"+summary.cycles()+"}");
|
||||
}
|
||||
private static void stats(HttpExchange x) throws Exception {
|
||||
User user=loggedIn(x);
|
||||
StringBuilder daily=new StringBuilder("[");
|
||||
String sql="""
|
||||
SELECT day,SUM(cycles),SUM(duration_ms),SUM(inhale_ms),SUM(exhale_ms),MAX(max_cycle_ms)
|
||||
FROM uploads WHERE user_id=? AND day <> 'undated' GROUP BY day ORDER BY day DESC LIMIT 400
|
||||
""";
|
||||
long totalCycles=0,totalDuration=0,totalDays=0,lastSync=0,undated=0;
|
||||
try(Connection c=connection()){
|
||||
try(PreparedStatement p=c.prepareStatement(sql)){
|
||||
p.setLong(1,user.id());try(ResultSet rs=p.executeQuery()){
|
||||
while(rs.next()){
|
||||
long cycles=rs.getLong(2),duration=rs.getLong(3);
|
||||
if(daily.length()>1)daily.append(',');
|
||||
daily.append("{\"day\":").append(quoted(rs.getString(1)))
|
||||
.append(",\"cycles\":").append(cycles)
|
||||
.append(",\"durationMs\":").append(duration)
|
||||
.append(",\"inhaleMs\":").append(rs.getLong(4))
|
||||
.append(",\"exhaleMs\":").append(rs.getLong(5))
|
||||
.append(",\"maxCycleMs\":").append(rs.getLong(6)).append('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
try(PreparedStatement p=c.prepareStatement("SELECT COALESCE(SUM(cycles),0),COALESCE(SUM(duration_ms),0),COUNT(DISTINCT CASE WHEN day<>'undated' THEN day END),COALESCE(MAX(updated_at),0) FROM uploads WHERE user_id=?")){
|
||||
p.setLong(1,user.id());try(ResultSet rs=p.executeQuery()){rs.next();totalCycles=rs.getLong(1);totalDuration=rs.getLong(2);totalDays=rs.getLong(3);lastSync=rs.getLong(4);}
|
||||
}
|
||||
try(PreparedStatement p=c.prepareStatement("SELECT COALESCE(SUM(cycles),0) FROM uploads WHERE user_id=? AND day='undated'")){
|
||||
p.setLong(1,user.id());try(ResultSet rs=p.executeQuery()){rs.next();undated=rs.getLong(1);}
|
||||
}
|
||||
}
|
||||
daily.append(']');
|
||||
json(x,200,"{\"login\":"+quoted(user.login())+",\"totalCycles\":"+totalCycles+
|
||||
",\"totalDurationMs\":"+totalDuration+",\"activeDays\":"+totalDays+
|
||||
",\"lastSyncMs\":"+lastSync+",\"undatedCycles\":"+undated+",\"daily\":"+daily+"}");
|
||||
}
|
||||
private static void leaderboard(HttpExchange x) throws Exception {
|
||||
StringBuilder b=new StringBuilder("[ ");
|
||||
try(Connection c=connection();PreparedStatement p=c.prepareStatement("""
|
||||
SELECT u.login,COALESCE(SUM(f.cycles),0),COALESCE(SUM(f.duration_ms),0),
|
||||
COUNT(DISTINCT CASE WHEN f.day<>'undated' THEN f.day END)
|
||||
FROM users u LEFT JOIN uploads f ON f.user_id=u.id
|
||||
WHERE u.published=1 GROUP BY u.id ORDER BY SUM(f.duration_ms) DESC LIMIT 100
|
||||
""");ResultSet rs=p.executeQuery()){
|
||||
boolean first=true;
|
||||
while(rs.next()){
|
||||
if(!first)b.append(',');first=false;
|
||||
b.append("{\"login\":").append(quoted(rs.getString(1)))
|
||||
.append(",\"cycles\":").append(rs.getLong(2))
|
||||
.append(",\"durationMs\":").append(rs.getLong(3))
|
||||
.append(",\"activeDays\":").append(rs.getLong(4)).append('}');
|
||||
}
|
||||
}
|
||||
b.append(']');json(x,200,b.toString());
|
||||
}
|
||||
private static String quoted(String s){return "\""+s.replace("\\","\\\\").replace("\"","\\\"")+"\"";}
|
||||
private static void serveWeb(HttpExchange x,String path,String method) throws Exception {
|
||||
String name = switch(path){case "/","/index.html" -> "index.html";
|
||||
case "/app.js" -> "app.js";case "/style.css" -> "style.css";
|
||||
default -> null;};
|
||||
if(name==null)throw new HttpError(404,"Not found");
|
||||
Path target=WEB.resolve(name);if(!Files.isRegularFile(target))throw new HttpError(404,"Frontend files not installed");
|
||||
String ct=name.endsWith(".js")?"application/javascript; charset=utf-8":name.endsWith(".css")?"text/css; charset=utf-8":"text/html; charset=utf-8";
|
||||
byte[] bytes=Files.readAllBytes(target);
|
||||
if(method.equals("HEAD")){x.getResponseHeaders().set("Content-Type",ct);x.sendResponseHeaders(200,-1);return;}
|
||||
send(x,200,ct,bytes);
|
||||
}
|
||||
private static void sendError(HttpExchange x,int status,String message) {
|
||||
try {json(x,status,"{\"error\":"+quoted(message)+"}");}catch(IOException ignored){}
|
||||
}
|
||||
private static void json(HttpExchange x,int status,String json) throws IOException {
|
||||
send(x,status,"application/json; charset=utf-8",json.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
private static void send(HttpExchange x,int status,String type,byte[] bytes) throws IOException {
|
||||
x.getResponseHeaders().set("Content-Type",type);x.sendResponseHeaders(status,bytes.length);
|
||||
try(OutputStream o=x.getResponseBody()){o.write(bytes);}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user