From 1bf4eb801f3a7f28f6f4104200a309eae2b73812 Mon Sep 17 00:00:00 2001 From: clonejo Date: Sun, 14 Jan 2024 20:23:08 +0100 Subject: [PATCH] Add last_updated field to be able to track outdated information / lost items --- main.py | 9 +++++++++ models.py | 3 ++- schemas.py | 3 ++- static/form.html | 3 +++ static/form.js | 6 ++++++ 5 files changed, 22 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 6df84df..23b9fd5 100644 --- a/main.py +++ b/main.py @@ -1,4 +1,5 @@ import re +import time from fastapi import Depends, FastAPI, Response from fastapi.staticfiles import StaticFiles @@ -44,6 +45,8 @@ async def list_items(db: Session = Depends(get_db)): @app.put("/api/items/{id}") async def put_item(id: str, item: Item, db: Session = Depends(get_db)): + if item.last_updated is None: + item.last_updated = rough_timestamp() if crud.put_item(db, id, item) == crud.PutItemResult.UPDATED: return Response(b"", status_code=204) return Response(b"", status_code=201) @@ -54,4 +57,10 @@ async def delete_item(id: str, db: Session = Depends(get_db)): crud.delete_item(db, id) +def rough_timestamp() -> int: + """Provides an current timestamp with reduced resolution, to improve anonymity.""" + granularity = 2**20 # about 12 days + return int(time.time()) // granularity * granularity + + app.mount("/", StaticFiles(directory="static", html=True), name="static") diff --git a/models.py b/models.py index 7aa9b21..1df2c2b 100644 --- a/models.py +++ b/models.py @@ -1,4 +1,4 @@ -from sqlalchemy import Boolean, Column, ForeignKey, String, Text +from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Text from database import Base @@ -15,3 +15,4 @@ class Item(Base): content = Column(Text) note = Column(Text) hidden = Column(Boolean, nullable=False) + last_updated = Column(Integer) diff --git a/schemas.py b/schemas.py index 218fe94..bf6f444 100644 --- a/schemas.py +++ b/schemas.py @@ -1,4 +1,4 @@ -from pydantic import BaseModel +from pydantic import BaseModel, Field class Item(BaseModel): @@ -11,6 +11,7 @@ class Item(BaseModel): content: str | None note: str | None hidden: bool + last_updated: int | None = Field(None) class Config: orm_mode = True diff --git a/static/form.html b/static/form.html index a5de3f2..d894279 100644 --- a/static/form.html +++ b/static/form.html @@ -43,6 +43,9 @@ + + + diff --git a/static/form.js b/static/form.js index 4ae4968..ec00949 100644 --- a/static/form.js +++ b/static/form.js @@ -39,6 +39,7 @@ function fillForm() { document.getElementById('content').value = item.content; document.getElementById('note').value = item.note; document.getElementById('hidden').checked = item.hidden; + document.getElementById('last_updated').value = formatTimestamp(item.last_updated); formCoordsToMap(); } @@ -172,3 +173,8 @@ function formCoordsToMap() { coordsToMap(coords_bl, coords_tr); } } + +function formatTimestamp(ts) { + const date = new Date(ts * 1000); + return date.toLocaleDateString(); +}