Complete LinkSyncServer and LinkSyncExtension implementation

LinkSyncServer:
- Fix app.py imports, add CORS middleware, lifespan events
- Create api/routes.py router aggregator
- Create config/settings.py for centralized configuration
- Rewrite models/base.py with proper relationships and serialization
- Rewrite all API endpoints with real DB integration (auth, links, collections, sync, queries, tags)
- Add admin endpoints (user management, stats, audit log)
- Complete query parser with recursive descent and proper precedence
- Complete query executor with set operations and field filters
- Set up Alembic migrations with initial schema
- Create web interface (templates, CSS, JS)
- Add 42 passing tests (auth, links, collections, queries)
- Add deploy.ps1 and deploy.sh scripts
- Update README with deployment workflow

LinkSyncExtension:
- Create utils/api.js (REST client with retries, auth, error handling)
- Create utils/sync.js (3 sync modes + conflict detection)
- Create utils/collection.js (collection management)
- Create utils/query-engine.js (client-side query parser)
- Rewrite background.js (sync loop, bookmark events, message routing)
- Rewrite popup.js (tabs, settings modal, notifications, CRUD)
- Update popup.html (tabbed interface, query builder, modal)
- Update popup.css (full redesign)
- Create content/content.js (page metadata extraction)
- Create options.html/js (dedicated settings page)
- Generate icons (48x48, 96x96)
- Update manifest.json (host permissions, content scripts, options)
- Create AGENTS.md
This commit is contained in:
DavidSaylor
2026-05-19 13:21:26 -05:00
parent c5d3912070
commit 09d30427f4
54 changed files with 5918 additions and 3177 deletions

View File

@@ -2,219 +2,99 @@
LinkSyncServer - Query Executor
"""
from typing import List, Dict, Any, Optional
from sqlalchemy.orm import Session
from sqlalchemy import func, and_, or_
import logging
import sys
sys.path.insert(0, 'models')
from base import Bookmark, User
from typing import Any, Dict, List
logger = logging.getLogger(__name__)
def parse_query_expression(query_expression: dict, expressions: list = None) -> Dict[str, Any]:
"""
Parse query expression in dict format.
Example:
{
"operation": "OR",
"operands": [
{"operation": "TERM", "value": "work"},
{"operation": "TERM", "value": "company"}
]
}
"""
if not query_expression:
return
operation = query_expression.get('operation')
operands = query_expression.get('operands', [])
if not operands:
# Top-level expression (e.g., TERM)
if operation == 'TERM':
value = query_expression.get('value', '')
if value.startswith('url:'):
search_term = value[4:]
return parse_term(search_term, 'url')
elif value.startswith('tag:'):
search_term = value[4:]
return parse_term(search_term, 'tags')
elif value.startswith('title:'):
search_term = value[6:]
return parse_term(search_term, 'title')
elif value.startswith('description:'):
search_term = value[12:]
return parse_term(search_term, 'description')
elif value.startswith('id:'):
return {'operation': 'EQUALS', 'value': value[3:]}
else:
# Default: search title and description
return {'operation': 'OR', 'operands': [
{'operation': 'TERM', 'value': value, 'field': 'title'},
{'operation': 'TERM', 'value': value, 'field': 'description'}
]}
def parse_term(term: str, field: str):
"""
Parse field:value term.
Returns SQLAlchemy filter clause.
"""
# Handle different field types
field_filters = {
'tags': lambda term: and_(*[Bookmark.tags.ilike(f'%{term}%') for tag in term.split(',')]),
'title': lambda term: Bookmark.title.ilike(f'%{term}%'),
'description': lambda term: Bookmark.description.ilike(f'%{term}%'),
'url': lambda term: Bookmark.url.ilike(f'%{term}%'),
'path': lambda term: Bookmark.path.ilike(f'%{term}%')
}
# Get filter function
filter_fn = field_filters.get(field, lambda term: Bookmark.tags.ilike(f'%{term}%'))
# Apply filter
filter_clause = filter_fn(term)
# Return filter clause with field
return {'field': field, 'value': term, 'clause': filter_clause}
def parse_or_filter(operators: list, operands: list) -> Any:
"""
Parse OR filter.
Operators: ['AND', 'OR', 'XOR']
"""
if not operands:
return False
# Default to AND for safety
op_type = operators[0] if operators else 'AND'
if op_type == 'OR':
return or_(*[parse_and_filter(operators[1:], operands[1:]) for _ in range(1)])
elif op_type == 'AND':
return and_(*[parse_and_filter(operators[1:], operands[1:]) for _ in range(1)])
else:
# XOR: not supported yet
raise ValueError("XOR not supported")
def parse_and_filter(operands: list) -> Any:
"""Parse AND filter (default)."""
if not operands:
return False
# Parse each operand
clauses = []
for operand in operands:
if isinstance(operand, str):
clause = operand
elif isinstance(operand, dict):
if operand.get('operation') == 'EQUALS':
clause = operand['value']
elif operand.get('operation') == 'TERM':
clauses.append(parse_term(operand.get('value', ''), operand.get('field', 'tags')))
# Add other term types as needed
else:
clauses.append(operand)
else:
raise ValueError(f"Unknown operand type: {type(operand)}")
if not clauses:
return False
return clauses
def execute_query(query_expression: dict) -> List[Dict[str, Any]]:
"""
Execute query and return results.
query_expression: dict from parser
returns: list of bookmarks
"""
# Default session
session = Session()
if not query_expression:
def execute_query(parsed: Dict[str, Any], bookmarks: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
if not parsed or not bookmarks:
return []
# Parse query expression
try:
# Handle single-term queries
if query_expression.get('operation') == 'TERM':
search_term = query_expression.get('value', '')
field = query_expression.get('field', 'title')
if field == 'tags':
tags = search_term.split(',')
filters = [Bookmark.tags.contains(tag) for tag in tags]
result = session.query(Bookmark).filter(or_(*filters)).all()
elif field == 'title':
result = session.query(Bookmark).filter(Bookmark.title.contains(search_term)).all()
elif field == 'description':
result = session.query(Bookmark).filter(Bookmark.description.contains(search_term)).all()
elif field == 'url':
result = session.query(Bookmark).filter(Bookmark.url.contains(search_term)).all()
else:
# Default: search title and description
filters = [
or_(Bookmark.title.contains(search_term),
Bookmark.description.contains(search_term))
]
result = session.query(Bookmark).filter(or_(*filters)).all()
elif query_expression.get('operation') == 'AND':
# AND clause
clauses = parse_and_filter(query_expression.get('operands', []))
if isinstance(clauses, list):
result = session.query(Bookmark).filter(and_(*clauses)).all()
else:
result = session.query(Bookmark).filter(clauses).all()
else:
# Default: search title and description
search_term = query_expression.get('value', '')
result = session.query(Bookmark).filter(
or_(Bookmark.title.contains(search_term),
Bookmark.description.contains(search_term))
).all()
except Exception as e:
logger.error(f"Query execution error: {e}")
result = []
return result
result_ids = _evaluate_node(parsed, bookmarks)
return [b for b in bookmarks if b["id"] in result_ids]
def create_bookmarks_from_sync(sync_data: dict):
"""
Create bookmarks from sync response.
sync_data: dict from GitHub API
"""
if not sync_data:
return []
# Parse sync JSON
sync_info = sync_data.get('_links', {}).get('sync', {}).get('_links', {})
# Extract bookmarks
bookmarks = []
if 'objects' in sync_data:
for obj in sync_data['objects']:
if 'title' in obj:
bookmarks.append({
'url': obj.get('url', ''),
'title': obj.get('title', ''),
'description': obj.get('description', ''),
'tags': obj.get('tags', []),
'favicon_url': obj.get('favicon_url', ''),
'path': obj.get('path', ''),
'visit_count': obj.get('visit_count', 0)
})
return bookmarks
def _evaluate_node(node: Dict[str, Any], bookmarks: List[Dict[str, Any]]) -> set:
operation = node.get("operation", "")
if operation == "OR":
operands = node.get("operands", [])
if not operands:
return set()
result = _evaluate_node(operands[0], bookmarks)
for operand in operands[1:]:
result |= _evaluate_node(operand, bookmarks)
return result
if operation == "AND":
operands = node.get("operands", [])
if not operands:
return set()
result = _evaluate_node(operands[0], bookmarks)
for operand in operands[1:]:
result &= _evaluate_node(operand, bookmarks)
return result
if operation == "XOR":
operands = node.get("operands", [])
if not operands:
return set()
result = _evaluate_node(operands[0], bookmarks)
for operand in operands[1:]:
result ^= _evaluate_node(operand, bookmarks)
return result
if operation == "TERM":
value = node.get("value", "").lower()
return {
b["id"]
for b in bookmarks
if value in b.get("title", "").lower()
or value in b.get("description", "").lower()
or value in b.get("url", "").lower()
or value in b.get("notes", "").lower()
}
if operation == "TERM_SET":
terms = node.get("value", [])
terms_lower = [t.lower() for t in terms]
result = set()
for b in bookmarks:
text = (
f"{b.get('title', '')} {b.get('description', '')} {b.get('url', '')} {b.get('notes', '')}"
).lower()
if any(term in text for term in terms_lower):
result.add(b["id"])
return result
if operation.startswith("FIELD:"):
field = operation.split(":", 1)[1].upper()
value = node.get("value", "").lower()
return _evaluate_field(field, value, bookmarks)
logger.warning(f"Unknown operation: {operation}")
return set()
def _evaluate_field(field: str, value: str, bookmarks: List[Dict[str, Any]]) -> set:
if field == "URL":
return {b["id"] for b in bookmarks if value in b.get("url", "").lower()}
if field == "TAG":
return {
b["id"]
for b in bookmarks
if any(value in t.lower() for t in (b.get("tags") or []))
}
if field == "TITLE":
return {b["id"] for b in bookmarks if value in b.get("title", "").lower()}
if field == "DESCRIPTION":
return {b["id"] for b in bookmarks if value in b.get("description", "").lower()}
if field == "PATH":
return {b["id"] for b in bookmarks if value in (b.get("path") or "").lower()}
if field == "ID":
return {b["id"] for b in bookmarks if b.get("id") == value}
logger.warning(f"Unknown field: {field}")
return set()