Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: URL Expiration #21

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
Binary file removed liberate.db
Binary file not shown.
27 changes: 26 additions & 1 deletion pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ dependencies = [
"SQLAlchemy>=2.0.25",
"psycopg2-binary>=2.9.9",
"validators>=0.22.0",
"aiosqlite>=0.19.0",
]
requires-python = ">=3.11.6"
readme = "README.md"
license = {text = "MIT"}

[tool.pdm.scripts]
start = "uvicorn src.link_liberate.main:app --host 0.0.0.0 --port 8080 --workers 1 --reload"
start = "uvicorn src.link_liberate.main:app --host 0.0.0.0 --port 8080 --workers 4 --reload"
dev = "uvicorn src.link_liberate.main:app --host 0.0.0.0 --port 8080 --reload"
test = "pytest"
mypy = "mypy src/link_liberate"
Expand Down
5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,8 @@ virtualenv==20.25.0
watchfiles==0.21.0
websockets==12.0
wrapt==1.16.0

SQLAlchemy~=2.0.25
validators~=0.22.0

aiosqlite~=0.19.0
16 changes: 16 additions & 0 deletions src/link_liberate/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

import aiosqlite
import asyncio

SQLALCHEMY_DATABASE_URL = "sqlite:///./liberate.db"

engine = create_engine(
Expand All @@ -19,3 +22,16 @@ def get_db():
yield db
finally:
db.close()


async def create_async_session():
async with aiosqlite.connect(SQLALCHEMY_DATABASE_URL) as db:
yield db


async def expire_uuid(uuid):
print("Expiring uuid:", uuid)
await asyncio.sleep(60) # Default expiration time is 60 mins
async with create_async_session() as db:
await db.execute("DELETE FROM liberatedlinks WHERE uuid = ?", (uuid,))
await db.commit()
13 changes: 8 additions & 5 deletions src/link_liberate/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.templating import Jinja2Templates

from typing import Annotated

from slowapi.errors import RateLimitExceeded
from slowapi import Limiter, _rate_limit_exceeded_handler

from slowapi.util import get_remote_address
from sqlalchemy.orm import Session
from asyncio import create_task
from starlette.templating import _TemplateResponse

from .utils import generate_uuid, make_proper_url, check_link
from .models import Base, LiberatedLink
from .database import engine, get_db
from .database import engine, get_db, expire_uuid

limiter = Limiter(key_func=get_remote_address)
app: FastAPI = FastAPI(title="link-liberate")
Expand All @@ -38,8 +42,7 @@
allow_headers=["*"],
)

templates: Jinja2Templates = Jinja2Templates(
directory=str(Path(BASE_DIR, "templates")))
templates: Jinja2Templates = Jinja2Templates(directory=str(Path(BASE_DIR, "templates")))


@app.get("/", response_class=HTMLResponse)
Expand Down Expand Up @@ -74,6 +77,7 @@ async def web_post(
db.add(new_liberated_link)
db.commit()
db.refresh(new_liberated_link)
await create_task(expire_uuid(uuid))
context = {"link": link, "short": f"{BASE_URL}/{uuid}"}
except Exception as e:
raise HTTPException(
Expand All @@ -91,8 +95,7 @@ async def get_link(
) -> RedirectResponse:
path: str = f"data/{uuid}"
try:
link = db.query(LiberatedLink).filter(
LiberatedLink.uuid == uuid).first()
link = db.query(LiberatedLink).filter(LiberatedLink.uuid == uuid).first()
return RedirectResponse(
url=link.link, status_code=status.HTTP_301_MOVED_PERMANENTLY
)
Expand Down
56 changes: 48 additions & 8 deletions src/link_liberate/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
margin: 0;
padding: 0;
}

.container {
max-width: 600px;
align-content: center;
Expand All @@ -21,20 +21,20 @@
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

a {
text-decoration: none !important;
}

h1 {
text-align: center;
color: #333;
}

.form-container {
text-align: center;
}

.link-input {
width: 100%;
padding: 10px;
Expand All @@ -43,7 +43,7 @@
border: 1px solid #ccc;
border-radius: 4px;
}

.submit-button {
background-color: #4CAF50;
color: #fff;
Expand All @@ -53,11 +53,51 @@
cursor: pointer;
font-size: 16px;
}

.submit-button:hover {
background-color: #45a049;
}


.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #555;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;

position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;

opacity: 0;
transition: opacity 0.3s;
}

.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
<title>
{% block title %}
Expand Down
25 changes: 25 additions & 0 deletions src/link_liberate/templates/liberate.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,33 @@
<div class="form-container">
<form method="post" action="/liberate">
<input type="text" name="content" class="link-input" placeholder="Enter your link...">
<div class="expiration-options">
<input type="checkbox" id="enable-expiration" name="enable-expiration" checked>
Enable link expiration
<div class="tooltip">🛈
<span class="tooltiptext">The shortened link will stop working after some time.</span>
</div>
<select name="expiration-time">
<option value="30">30 minutes</option>
<option value="60">60 minutes</option>
<option value="90">90 minutes</option>
</select>
</div>
<button type="submit" class="submit-button">Shorten</button>
</form>
</div>
</div>

<script>
const tooltipIcon = document.querySelector('.tooltip-icon');
const hiddenTooltip = document.querySelector('.hidden-tooltip');

tooltipIcon.addEventListener('mouseenter', () => {
hiddenTooltip.classList.remove('hidden');
});

tooltipIcon.addEventListener('mouseleave', () => {
hiddenTooltip.classList.add('hidden');
});
</script>
{% endblock %}
5 changes: 2 additions & 3 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,15 @@ def test_web():

def test_web_post(mocker):
# Patch the get_db function to return the db mock
mocker.patch('src.link_liberate.database.Session_Local', return_value=Mock())
mocker.patch("src.link_liberate.database.Session_Local", return_value=Mock())
client_mock = TestClient(app)
response = client_mock.post("/liberate", data={"content": "valid_content"})
assert response.status_code == 200



def test_get_link(mocker):
# Patch the get_db function to return the db mock
mocker.patch('src.link_liberate.database.Session_Local', return_value=Mock())
mocker.patch("src.link_liberate.database.Session_Local", return_value=Mock())
client_mock = TestClient(app)
response = client_mock.get("/valid_uuid", follow_redirects=False)
assert response.status_code == 301
Loading