1
0
mirror of https://codeberg.org/diginaut/digimarks.git synced 2026-02-04 20:50:26 +01:00

9 Commits

9 changed files with 127 additions and 43 deletions

2
.gitignore vendored
View File

@@ -77,6 +77,7 @@ celerybeat-schedule
# dotenv # dotenv
.env .env
*.env
# direnv # direnv
.envrc .envrc
@@ -97,6 +98,7 @@ ENV/
# vim # vim
*.swp *.swp
*.swo
# Zed editor # Zed editor
.zed .zed

View File

@@ -30,7 +30,7 @@ necessary packages:
git clone https://codeberg.org/diginaut/digimarks.git git clone https://codeberg.org/diginaut/digimarks.git
cd digimarks cd digimarks
# direnv will now create or activate a virtualenv # direnv will now create or activate a virtualenv
# See https://github.com/direnv/direnv/wiki/Python#uv for direnv uv config # See https://codeberg.org/diginaut/dotfiles/src/branch/master/.config/direnv/direnvrc for direnv uv config
# If you just want to run it, no need for development dependencies # If you just want to run it, no need for development dependencies
uv sync --active --no-dev uv sync --active --no-dev
# Otherwise, install everything in the active virtualenv # Otherwise, install everything in the active virtualenv

View File

@@ -10,7 +10,7 @@ authors = [
] ]
description = 'Simple bookmarking service, using a SQLite database to store bookmarks, supporting tags, automatic title fetching and REST API calls.' description = 'Simple bookmarking service, using a SQLite database to store bookmarks, supporting tags, automatic title fetching and REST API calls.'
readme = "README.rst" readme = "README.rst"
requires-python = ">=3.10" requires-python = ">=3.11"
keywords = ["bookmarks", "api"] keywords = ["bookmarks", "api"]
license = { text = "Apache" } license = { text = "Apache" }
classifiers = [ classifiers = [
@@ -55,7 +55,7 @@ pub = [
"twine" "twine"
] ]
server = [ server = [
"uvicorn", "gunicorn>=23.0.0",
] ]
# dynamic = ["version"] # dynamic = ["version"]

View File

@@ -1,3 +1,3 @@
-r requirements.in -r requirements.in
uvicorn gunicorn

View File

@@ -1,7 +1,7 @@
# Core application # Core application
fastapi[all] fastapi[all]
sqlmodel sqlmodel
sqlalchemy sqlalchemy[asyncio]
pydantic pydantic
pydantic_settings pydantic_settings
alembic alembic

View File

@@ -10,7 +10,8 @@ import bs4
import httpx import httpx
from extract_favicon import from_html from extract_favicon import from_html
from fastapi import Query, Request from fastapi import Query, Request
from pydantic import AnyUrl from fastapi.exceptions import HTTPException
from pydantic import AnyUrl, ValidationError
from sqlmodel import select from sqlmodel import select
from digimarks import tags_service, utils from digimarks import tags_service, utils
@@ -34,8 +35,11 @@ async def set_information_from_source(bookmark: Bookmark, request: Request) -> B
"""Request the title by requesting the source url.""" """Request the title by requesting the source url."""
logger.info('Extracting information from url %s', bookmark.url) logger.info('Extracting information from url %s', bookmark.url)
try: try:
result = await request.app.requests_client.get(bookmark.url, headers={'User-Agent': DIGIMARKS_USER_AGENT}) result = await request.app.state.requests_client.get(
str(bookmark.url), headers={'User-Agent': DIGIMARKS_USER_AGENT}
)
bookmark.http_status = result.status_code bookmark.http_status = result.status_code
logger.info('HTTP status code %s for %s', bookmark.http_status, bookmark.url)
except httpx.HTTPError as err: except httpx.HTTPError as err:
# For example, "MissingSchema: Invalid URL 'abc': No schema supplied. Perhaps you meant http://abc?" # For example, "MissingSchema: Invalid URL 'abc': No schema supplied. Perhaps you meant http://abc?"
logger.error('Exception when trying to retrieve title for %s. Error: %s', bookmark.url, str(err)) logger.error('Exception when trying to retrieve title for %s. Error: %s', bookmark.url, str(err))
@@ -43,11 +47,12 @@ async def set_information_from_source(bookmark: Bookmark, request: Request) -> B
bookmark.title = '' bookmark.title = ''
return bookmark return bookmark
if bookmark.http_status == 200 or bookmark.http_status == 202: if bookmark.http_status == 200 or bookmark.http_status == 202:
html = bs4.BeautifulSoup(result.text, 'html.parser') html_content = bs4.BeautifulSoup(result.text, 'html.parser')
try: try:
bookmark.title = html.title.text.strip() bookmark.title = html_content.title.text.strip()
except AttributeError: except AttributeError as exc:
bookmark.title = '' logger.error('Error while trying to extract title from URL %s: %s', str(bookmark.url), str(exc))
raise HTTPException(status_code=400, detail='Error while trying to extract title')
url_parts = urlparse(str(bookmark.url)) url_parts = urlparse(str(bookmark.url))
root_url = url_parts.scheme + '://' + url_parts.netloc root_url = url_parts.scheme + '://' + url_parts.netloc
@@ -56,8 +61,8 @@ async def set_information_from_source(bookmark: Bookmark, request: Request) -> B
# with open(filename, 'wb') as out_file: # with open(filename, 'wb') as out_file:
# shutil.copyfileobj(response.raw, out_file) # shutil.copyfileobj(response.raw, out_file)
# Extraction was successful # Extraction was successful
logger.info('Extracting information was successful') logger.info('Extracting information was successful')
return bookmark return bookmark
@@ -72,11 +77,15 @@ def strip_url_params(url: str) -> str:
return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, '', parsed.fragment)) return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, '', parsed.fragment))
def update_bookmark_with_info(bookmark: Bookmark, request: Request, strip_params: bool = False): async def update_bookmark_with_info(bookmark: Bookmark, request: Request, strip_params: bool = False):
"""Automatically update title, favicon, etc.""" """Automatically update title, favicon, etc."""
if isinstance(bookmark.url, str):
# If type of the url is a 'simple' string, ensure it to be an AnyUrl
bookmark.url = AnyUrl(bookmark.url)
if not bookmark.title: if not bookmark.title:
# Title was empty, automatically fetch it from the url, will also update the status code # Title was empty, automatically fetch it from the url, will also update the status code
set_information_from_source(bookmark, request) await set_information_from_source(bookmark, request)
if strip_params: if strip_params:
# Strip URL parameters, e.g., tracking params # Strip URL parameters, e.g., tracking params
@@ -129,7 +138,12 @@ async def autocomplete_bookmark(
bookmark.user_key = user_key bookmark.user_key = user_key
# Auto-fill title, fix tags etc. # Auto-fill title, fix tags etc.
update_bookmark_with_info(bookmark, request, strip_params) try:
await update_bookmark_with_info(bookmark, request, strip_params)
except ValidationError as exc:
logger.error('ValidationError while autocompleting bookmark with URL %s', bookmark.url)
logger.error('Error was: %s', str(exc))
raise HTTPException(status_code=400, detail='Error while autocompleting, likely the URL contained an error')
url_hash = utils.generate_hash(str(bookmark.url)) url_hash = utils.generate_hash(str(bookmark.url))
result = await session.exec( result = await session.exec(
@@ -157,7 +171,7 @@ async def add_bookmark(
bookmark.user_key = user_key bookmark.user_key = user_key
# Auto-fill title, fix tags etc. # Auto-fill title, fix tags etc.
update_bookmark_with_info(bookmark, request, strip_params) await update_bookmark_with_info(bookmark, request, strip_params)
bookmark.url_hash = utils.generate_hash(str(bookmark.url)) bookmark.url_hash = utils.generate_hash(str(bookmark.url))
logger.info('Adding bookmark %s for user %s', bookmark.url_hash, user_key) logger.info('Adding bookmark %s for user %s', bookmark.url_hash, user_key)
@@ -193,7 +207,7 @@ async def update_bookmark(
bookmark_db.sqlmodel_update(bookmark_data) bookmark_db.sqlmodel_update(bookmark_data)
# Autofill title, fix tags, etc. where (still) needed # Autofill title, fix tags, etc. where (still) needed
update_bookmark_with_info(bookmark, request, strip_params) await update_bookmark_with_info(bookmark, request, strip_params)
session.add(bookmark_db) session.add(bookmark_db)
await session.commit() await session.commit()

View File

@@ -4,7 +4,7 @@ import logging
from collections.abc import Sequence from collections.abc import Sequence
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from datetime import UTC, datetime from datetime import UTC, datetime
from typing import Annotated from typing import Annotated, AsyncGenerator, cast
import httpx import httpx
from fastapi import Depends, FastAPI, HTTPException, Query, Request from fastapi import Depends, FastAPI, HTTPException, Query, Request
@@ -54,22 +54,32 @@ engine = create_async_engine(f'sqlite+aiosqlite:///{settings.database_file}', co
async def get_session() -> AsyncSession: async def get_session() -> AsyncSession:
"""SQLAlchemy session factory.""" """SQLAlchemy session factory."""
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async_session = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
async with async_session() as session: async with async_session() as session:
yield session yield session
# Shorter way of getting the DB session in an endpoint
SessionDep = Annotated[AsyncSession, Depends(get_session)] SessionDep = Annotated[AsyncSession, Depends(get_session)]
@asynccontextmanager @asynccontextmanager
async def lifespan(the_app: FastAPI): async def lifespan(the_app: FastAPI) -> AsyncGenerator[None, None]:
"""Upon start, initialise an AsyncClient and assign it to an attribute named requests_client on the app object.""" """Upon start, initialise an AsyncClient and assign it to an attribute named requests_client on the app object."""
the_app.requests_client = httpx.AsyncClient() async with httpx.AsyncClient() as requests_client:
yield the_app.state.requests_client = requests_client
await the_app.requests_client.aclose() yield
await the_app.state.requests_client.aclose()
async def get_requests_client(request: Request) -> httpx.AsyncClient:
"""Get the httpx client from the application object."""
return cast(httpx.AsyncClient, request.app.state.requests_client)
# Shorter way of getting the httpx client in an endpoint
RequestsDep = Annotated[AsyncSession, Depends(get_requests_client)]
app = FastAPI(lifespan=lifespan) app = FastAPI(lifespan=lifespan)
app.mount('/static', StaticFiles(directory=settings.static_dir), name='static') app.mount('/static', StaticFiles(directory=settings.static_dir), name='static')
app.mount('/content/favicons', StaticFiles(directory=settings.favicons_dir), name='favicons') app.mount('/content/favicons', StaticFiles(directory=settings.favicons_dir), name='favicons')
@@ -275,12 +285,24 @@ async def bookmarks_changed_since(
) )
latest_created_bookmark = result.first() latest_created_bookmark = result.first()
latest_modification = max(latest_modified_bookmark.modified_date, latest_created_bookmark.created_date) # There needs to be at least one bookmark of course
if latest_created_bookmark:
latest_created_datetime = latest_created_bookmark.created_date
else:
latest_created_datetime = datetime.min
# We only have a modified datetime when at least one has been edited
if latest_modified_bookmark:
latest_modified_datetime = latest_modified_bookmark.modified_date
else:
latest_modified_datetime = datetime.min
latest_modification = max(latest_modified_datetime, latest_created_datetime)
return { return {
'current_time': datetime.now(UTC), 'current_time': datetime.now(UTC),
'latest_change': latest_modified_bookmark.modified_date, 'latest_change': latest_modified_datetime,
'latest_created': latest_created_bookmark.created_date, 'latest_created': latest_created_datetime,
'latest_modification': latest_modification, 'latest_modification': latest_modification,
} }

View File

@@ -105,7 +105,7 @@ document.addEventListener('alpine:init', () => {
this.cache[this.userKey]['tags'] = await tagsResponse.json(); this.cache[this.userKey]['tags'] = await tagsResponse.json();
/* Filter bookmarks by (blacklisted) tags */ /* Filter bookmarks by (blacklisted) tags */
await this.filterBookmarksByTags(); this.filterBookmarksByTags();
this.loading = false; this.loading = false;
}, },
@@ -214,15 +214,18 @@ document.addEventListener('alpine:init', () => {
resetEditBookmark() { resetEditBookmark() {
this.bookmarkToEdit = { this.bookmarkToEdit = {
'url_hash': '',
'url': '', 'url': '',
'title': '', 'title': '',
'note': '', 'note': '',
'tags': '' 'tags': '',
'http_status': 0,
'strip_params': false
} }
}, },
async startAddingBookmark() { async startAddingBookmark() {
/* Open 'add bookmark' page */ /* Open 'add bookmark' page */
console.log('Start adding bookmark'); console.log('Open "add bookmark" modal');
this.resetEditBookmark(); this.resetEditBookmark();
// this.show_bookmark_details = true; // this.show_bookmark_details = true;
const editFormDialog = document.getElementById("editFormDialog"); const editFormDialog = document.getElementById("editFormDialog");
@@ -233,7 +236,54 @@ document.addEventListener('alpine:init', () => {
console.log('Bookmark URL changed'); console.log('Bookmark URL changed');
// let response = await fetch('/api/v1/' + this.userKey + '/autocomplete_bookmark/'); // let response = await fetch('/api/v1/' + this.userKey + '/autocomplete_bookmark/');
try { try {
const response = await fetch('/api/v1/' + this.userKey + '/autocomplete_bookmark/', { const response = await fetch('/api/v1/' + this.userKey + '/autocomplete_bookmark/?strip_params=' + this.bookmarkToEdit.strip_params, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// Bookmark form data
url_hash: this.bookmarkToEdit.url_hash,
url: this.bookmarkToEdit.url,
title: this.bookmarkToEdit.title,
note: this.bookmarkToEdit.note,
tags: this.bookmarkToEdit.tags
})
});
const data = await response.json();
// TODO: update form fields if needed (auto-fetched title for example
console.log('Got response');
console.log(response);
console.log(data);
if (response.ok) {
this.bookmarkToEdit.url_hash = data.url_hash;
this.bookmarkToEdit.url = data.url;
this.bookmarkToEdit.title = data.title;
this.bookmarkToEdit.note = data.note;
this.bookmarkToEdit.tags = data.tags;
this.bookmarkToEdit.http_status = data.http_status;
} else {
console.log('Error occurred');
this.bookmarkToEditError = data.detail;
}
} catch (error) {
// enter logic for when there is an error (ex. error toast)
console.log('error occurred');
console.log(error);
this.bookmarkToEditError = error.detail;
console.log('yesssh?');
}
},
async saveBookmark() {
console.log('Saving bookmark');
// this.bookmarkToEditVisible = false;
// this.show_bookmark_details = false;
},
async addBookmark() {
/* Post new bookmark to the backend */
console.log('Adding bookmark');
try {
const response = await fetch('/api/v1/' + this.userKey + '/add_bookmark/?strip_params=' + this.bookmarkToEdit.strip_params, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
@@ -249,21 +299,12 @@ document.addEventListener('alpine:init', () => {
const data = await response.json(); const data = await response.json();
// TODO: update form fields if needed (auto-fetched title for example // TODO: update form fields if needed (auto-fetched title for example
console.log(data); console.log(data);
this.bookmarkToEditError = 'lolwut'; // this.bookmarkToEditError = 'lolwut';
} catch (error) { } catch (error) {
// enter your logic for when there is an error (ex. error toast) // enter your logic for when there is an error (ex. error toast)
console.log(error) console.log(error)
} }
},
async saveBookmark() {
console.log('Saving bookmark');
// this.bookmarkToEditVisible = false;
// this.show_bookmark_details = false;
},
async addBookmark() {
/* Post new bookmark to the backend */
//
} }
}) })
}); });

View File

@@ -192,6 +192,10 @@
<input id="bookmark_url" type="text" name="bookmark_url" placeholder="url" <input id="bookmark_url" type="text" name="bookmark_url" placeholder="url"
x-on:change.debounce="$store.digimarks.bookmarkURLChanged()" x-on:change.debounce="$store.digimarks.bookmarkURLChanged()"
x-model="$store.digimarks.bookmarkToEdit.url"> x-model="$store.digimarks.bookmarkToEdit.url">
<p x-show="$store.digimarks.bookmarkToEdit.http_status > 202"
x-text="'HTTP statuscode: ' + $store.digimarks.bookmarkToEdit.http_status" x-cloak
class="error"></p>
<p>
</fieldset> </fieldset>
<fieldset class="form-group"> <fieldset class="form-group">
<label for="bookmark_title">Title</label> <label for="bookmark_title">Title</label>
@@ -212,16 +216,17 @@
x-model="$store.digimarks.bookmarkToEdit.tags"> x-model="$store.digimarks.bookmarkToEdit.tags">
</fieldset> </fieldset>
<p x-show="$store.digimarks.bookmarkToEditError" <p x-show="$store.digimarks.bookmarkToEditError"
x-data="$store.digimarks.bookmarkToEditError"></p> x-text="$store.digimarks.bookmarkToEditError" x-cloak class="error"></p>
<p> <p>
<label> <label>
<input type="checkbox" name="strip" id="strip"/> <input type="checkbox" x-model="$store.digimarks.bookmarkToEdit.strip_params"/>
<span>Strip parameters from url (like <em>?utm_source=social</em> - can break the link!)</span> <span>Strip parameters from url (like <em>?utm_source=social</em> - can break the link!)</span>
</label> </label>
</p> </p>
<div> <div>
<button value="cancel">Cancel</button> <button value="cancel">Cancel</button>
<button @click="$store.digimarks.saveBookmark()">Save</button> <button @click="$store.digimarks.saveBookmark()">Save</button>
<button @click="$store.digimarks.addBookmark()">Add</button>
</div> </div>
</form> </form>
</template> </template>