0.6 final

This commit is contained in:
Athena Funderburg committed 2026-11-04 14:03:18 +00:00
1 parent 7c0581eb97
commit b89e1932bb
160 files changed
+20534 -4664

No files matched your search

+34 -13
View File
@@ -6,9 +6,10 @@ from pathlib import Path
from typing import Optional, Tuple
STORAGE_BASE = Path('storage/dp')
PHOTO_STORAGE_BASE = Path('storage/photos')
THUMB_SIZE = (21, 21)
MSN_SIZE = (96, 96)
1
IM_SIZE = (96, 96)
def compute_md5(data: bytes) -> str:
return hashlib.md5(data).hexdigest()[:16]
@@ -33,30 +34,50 @@ def store_avatar_file(uuid: str, data: bytes, ext: str) -> str:
full_path = avatar_dir / f'{md5}.{ext}'
thumb_path = avatar_dir / f'{md5}_thumb.png'
msn_path = avatar_dir / f'{md5}_msn.png'
im_path = avatar_dir / f'{md5}_im.png'
if not full_path.exists():
full_path.write_bytes(data)
if not thumb_path.exists() or not msn_path.exists():
if not thumb_path.exists() or not im_path.exists():
try:
img = Image.open(BytesIO(data))
if not thumb_path.exists():
img.resize(THUMB_SIZE).save(str(thumb_path))
if not msn_path.exists():
img.resize(MSN_SIZE).save(str(msn_path))
if not im_path.exists():
img.resize(IM_SIZE).save(str(im_path))
except Exception:
pass
return md5
def store_photo_file(uuid: str, data: bytes, ext: str) -> str:
photo_dir = PHOTO_STORAGE_BASE / uuid
photo_dir.mkdir(parents=True, exist_ok=True)
name = f'{compute_md5(data)}.{ext}'
path = photo_dir / name
if not path.exists():
path.write_bytes(data)
return name
def get_photo_data(uuid: str, name: str) -> Optional[Tuple[bytes, str]]:
path = PHOTO_STORAGE_BASE / uuid / name
if not path.is_file():
return None
try:
data = path.read_bytes()
except OSError:
return None
return data, 'image/' + path.suffix.lstrip('.').lower()
def find_avatar_file(
uuid: str,
md5: str,
*,
small: bool = False,
msn: bool = False,
im: bool = False,
) -> Optional[Path]:
avatar_dir = get_avatar_dir(uuid)
if not avatar_dir.is_dir():
@@ -67,10 +88,10 @@ def find_avatar_file(
if thumb.is_file():
return thumb
elif msn:
msn_file = avatar_dir / f'{md5}_msn.png'
if msn_file.is_file():
return msn_file
elif im:
im_file = avatar_dir / f'{md5}_im.png'
if im_file.is_file():
return im_file
for p in avatar_dir.iterdir():
if p.is_file() and p.stem == md5:
@@ -84,12 +105,12 @@ def get_avatar_data(
md5: Optional[str],
*,
small: bool = False,
msn: bool = False,
im: bool = False,
) -> Optional[Tuple[bytes, str]]:
if not md5:
return None
path = find_avatar_file(uuid, md5, small=small, msn=msn)
path = find_avatar_file(uuid, md5, small=small, im=im)
if path is None:
return None
-27
View File
@@ -76,33 +76,8 @@ class Argon2PasswordHasher(Hasher):
cls.impl.verify(hash_str, password + salt)
return True
except (ValueError, VerifyMismatchError, binascii.Error):
# PBKDF2 fallback, migrate hash to Argon2
try:
parts = encoded.split(cls.separator)
alg = parts[0]
if alg != PBKDF2PasswordHasher.algorithm:
return False
_, *stuff, salt, _ = parts
if PBKDF2PasswordHasher.verify(password, encoded):
return 'MIGRATEMEPLSTHX'
except Exception:
return False
return False
class PBKDF2PasswordHasher(Hasher):
algorithm = 'pbkdf2_sha256'
iterations = 24000
@classmethod
def _encode_impl(cls, password: str, *stuff: Any, salt: str) -> Tuple[bytes, List[str]]:
assert len(stuff) <= 1
iterations: Optional[int] = (stuff[0] if stuff else None)
if iterations is None:
iterations = cls.iterations
iterations = int(iterations)
hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), iterations, None)
return hash, [str(iterations)]
class MD5PasswordHasher(Hasher):
algorithm = 'md5'
digest = hashlib.md5
@@ -204,7 +179,6 @@ class SHA1PasswordHasher(Hasher):
return secrets.compare_digest(encoded, encoded_2)
HASHERS[Argon2PasswordHasher.algorithm] = Argon2PasswordHasher
HASHERS[PBKDF2PasswordHasher.algorithm] = PBKDF2PasswordHasher
HASHERS[MD5PasswordHasher.algorithm] = MD5PasswordHasher
HASHERS[MD5CryptPasswordHasher.algorithm] = MD5CryptPasswordHasher
HASHERS[SHA1PasswordHasher.algorithm] = SHA1PasswordHasher
@@ -213,7 +187,6 @@ def gen_salt(length: int = 15) -> str:
return secrets.token_hex(length)[:length]
hasher = Argon2PasswordHasher
hasher_pbkdf2 = PBKDF2PasswordHasher
hasher_md5 = MD5PasswordHasher
hasher_md5crypt = MD5CryptPasswordHasher
hasher_sha1 = SHA1PasswordHasher
+197
View File
@@ -0,0 +1,197 @@
from datetime import date, datetime
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING:
from core.backend import Backend
from core.models import User
ICQ_INFO_KEY = 'ICQ_INFO'
INTEREST_SLOTS = 4
AFFILIATION_SLOTS = 3
MAX_QUEUED_AUTH_EVENTS = 50
_BASIC_FIELDS = ('nick', 'first', 'last', 'email', 'city', 'state', 'phone', 'fax', 'address', 'cell', 'zip')
_WORK_FIELDS = ('city', 'state', 'phone', 'fax', 'address', 'zip', 'company', 'department', 'position', 'webpage')
def _store(user: 'User') -> dict[str, Any]:
store = user.settings.get(ICQ_INFO_KEY)
if not isinstance(store, dict):
store = {}
user.settings[ICQ_INFO_KEY] = store
return store
def _section(user: 'User', name: str) -> dict[str, Any]:
store = _store(user)
section = store.get(name)
if not isinstance(section, dict):
section = {}
store[name] = section
return section
def _text(value: Any) -> str:
return '' if value is None else str(value)
def save(backend: 'Backend', user: 'User') -> None:
if user.detail is not None:
backend._mark_modified(user)
else:
backend._mark_modified(user, detail = backend._load_detail(user))
def nickname(user: 'User') -> str:
nick = _section(user, 'basic').get('nick')
if nick:
return str(nick)
name = user.status.name or ''
if not name or '@' in name:
return user.username
return name
def basic_info(user: 'User') -> dict[str, Any]:
stored = _section(user, 'basic')
profile = user.profile
info = {
'nick': nickname(user),
'first': stored.get('first', user.first_name or ''),
'last': stored.get('last', user.last_name or ''),
'email': stored.get('email', ''),
'city': stored.get('city', (profile.city if profile is not None else None) or ''),
'state': stored.get('state', (profile.state if profile is not None else None) or ''),
'phone': stored.get('phone', ''),
'fax': stored.get('fax', ''),
'address': stored.get('address', ''),
'cell': stored.get('cell', ''),
'zip': stored.get('zip', _text(profile.zip if profile is not None else None)),
'country': int(stored.get('country', 0) or 0),
'gmt': int(stored.get('gmt', 0) or 0),
# ICQ only ever shows an e-mail address its owner chose to publish
'publish_email': bool(stored.get('publish_email', False)),
}
for field in _BASIC_FIELDS:
info[field] = _text(info[field])
return info
def more_info(user: 'User') -> dict[str, Any]:
stored = _section(user, 'more')
profile = user.profile
return {
'gender': int(stored.get('gender', 0) or 0),
'homepage': _text(stored.get('homepage', (profile.website if profile is not None else None) or '')),
'birth_year': int(stored.get('birth_year', 0) or 0),
'birth_month': int(stored.get('birth_month', 0) or 0),
'birth_day': int(stored.get('birth_day', 0) or 0),
'lang1': int(stored.get('lang1', 0) or 0),
'lang2': int(stored.get('lang2', 0) or 0),
'lang3': int(stored.get('lang3', 0) or 0),
}
def work_info(user: 'User') -> dict[str, Any]:
stored = _section(user, 'work')
info = { field: _text(stored.get(field, '')) for field in _WORK_FIELDS }
info['country'] = int(stored.get('country', 0) or 0)
info['occupation'] = int(stored.get('occupation', 0) or 0)
return info
def notes(user: 'User') -> str:
stored = _store(user).get('notes')
if stored is not None:
return _text(stored)
profile = user.profile
return (profile.bio if profile is not None else None) or ''
def _pairs(user: 'User', name: str, slots: int) -> list[list[Any]]:
stored = _store(user).get(name)
pairs = []
if isinstance(stored, list):
for entry in stored[:slots]:
if isinstance(entry, (list, tuple)) and len(entry) == 2:
pairs.append([int(entry[0] or 0), _text(entry[1])])
while len(pairs) < slots:
pairs.append([0, ''])
return pairs
def interests(user: 'User') -> list[list[Any]]:
return _pairs(user, 'interests', INTEREST_SLOTS)
def affiliations(user: 'User') -> dict[str, list[list[Any]]]:
return {
'past': _pairs(user, 'past_affiliations', AFFILIATION_SLOTS),
'current': _pairs(user, 'affiliations', AFFILIATION_SLOTS),
}
def age(user: 'User', today: date | None = None) -> int:
more = more_info(user)
year, month, day = more['birth_year'], more['birth_month'], more['birth_day']
if not year or not month or not day:
return 0
today = today or datetime.utcnow().date()
try:
born = date(year, month, day)
except ValueError:
return 0
years = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
return max(0, years)
def set_basic(user: 'User', fields: dict[str, Any]) -> None:
_section(user, 'basic').update(fields)
def set_more(user: 'User', fields: dict[str, Any]) -> None:
_section(user, 'more').update(fields)
def set_work(user: 'User', fields: dict[str, Any]) -> None:
_section(user, 'work').update(fields)
def set_notes(user: 'User', text: str) -> None:
_store(user)['notes'] = text
def set_interests(user: 'User', pairs: list[list[Any]]) -> None:
_store(user)['interests'] = [[int(code), _text(keyword)] for code, keyword in pairs[:INTEREST_SLOTS]]
def set_affiliations(user: 'User', past: list[list[Any]], current: list[list[Any]]) -> None:
_store(user)['past_affiliations'] = [[int(code), _text(keyword)] for code, keyword in past[:AFFILIATION_SLOTS]]
_store(user)['affiliations'] = [[int(code), _text(keyword)] for code, keyword in current[:AFFILIATION_SLOTS]]
def permissions(user: 'User') -> dict[str, bool]:
stored = _section(user, 'perms')
return {
'auth_required': bool(stored.get('auth_required', False)),
'web_aware': bool(stored.get('web_aware', False)),
}
def set_permissions(user: 'User', *, auth_required: bool | None = None, web_aware: bool | None = None) -> None:
stored = _section(user, 'perms')
if auth_required is not None:
stored['auth_required'] = auth_required
if web_aware is not None:
stored['web_aware'] = web_aware
def requires_authorization(owner: 'User', requester: 'User') -> bool:
if owner is requester or not permissions(owner)['auth_required']:
return False
return requester.uuid not in (_store(owner).get('preauth') or [])
def record_preauth(owner: 'User', requester_uuid: str) -> None:
preauth = _store(owner).setdefault('preauth', [])
if requester_uuid not in preauth:
preauth.append(requester_uuid)
def queue_auth_event(user: 'User', event: dict[str, Any]) -> None:
queue = _store(user).setdefault('auth_events', [])
queue.append(event)
del queue[:-MAX_QUEUED_AUTH_EVENTS]
def take_auth_events(user: 'User') -> list[dict[str, Any]]:
store = _store(user)
queue = store.pop('auth_events', None)
return queue if isinstance(queue, list) else []
def latin1(text: str) -> bytes:
return text.encode('cp1252', errors = 'replace')
def from_latin1(data: bytes) -> str:
try:
return data.decode('cp1252')
except UnicodeDecodeError:
return data.decode('latin-1')
+11
View File
@@ -0,0 +1,11 @@
import os
from insclient import INSClient
import settings
def ins_client(identifier: str = 'AzuL-SERV') -> INSClient:
host = ('127.0.0.1' if settings.INS_HOST in ('0.0.0.0', '::', '') else settings.INS_HOST)
return INSClient(
identifier, key_file = os.path.join(settings.INS_KEY_DIR, '{}.client.key'.format(identifier.lower())),
enrollment_code = os.environ.get('INS_ENROLLMENT_CODE') or None, host = host, port = settings.INS_PORT, keepalive = False,
client_name = 'azul-script', client_version = settings.VERSION, label = 'azul scripts',
)
+39 -1
View File
@@ -1,6 +1,6 @@
from typing import FrozenSet, Any, Iterable, Optional, TypeVar, List, Dict, Tuple, Generic, TYPE_CHECKING
from abc import ABCMeta, abstractmethod
import asyncio, functools, itertools, traceback, ssl, jinja2, settings, sys, platform
import asyncio, functools, itertools, traceback, ssl, jinja2, settings, sys, platform, re
from datetime import datetime
from uuid import uuid4
from aiohttp import web
@@ -16,6 +16,11 @@ else:
def gen_uuid() -> str:
return str(uuid4())
_VALID_OSCAR_RE = re.compile(r'^[A-Za-z0-9]+$')
def is_valid_oscar_screenname(name: str) -> bool:
return bool(name) and _VALID_OSCAR_RE.match(name) is not None
T = TypeVar('T')
def first_in_iterable(iterable: Iterable[T]) -> Optional[T]:
for x in iterable: return x
@@ -73,6 +78,39 @@ class ProtocolRunner(Runner):
def create_servers(self, loop: asyncio.AbstractEventLoop) -> List[Any]:
return [loop.create_server(self._protocol, self.host, self.port, ssl = self.ssl_context)]
class DatagramRunner(Runner):
__slots__ = ('_protocol',)
_protocol: Any
def __init__(self, host: str, port: int, protocol: Any, *, args: Optional[List[Any]] = None, service: str) -> None:
super().__init__(host, port, service = service)
if args:
protocol = functools.partial(protocol, *args)
self._protocol = protocol
def create_servers(self, loop: asyncio.AbstractEventLoop) -> List[Any]:
return [self._create_endpoint(loop)]
async def _create_endpoint(self, loop: asyncio.AbstractEventLoop) -> 'DatagramServer':
transport, _ = await loop.create_datagram_endpoint(self._protocol, local_addr = (self.host, self.port))
return DatagramServer(transport)
class DatagramServer:
__slots__ = ('_transport',)
_transport: asyncio.BaseTransport
def __init__(self, transport: asyncio.BaseTransport) -> None:
self._transport = transport
def close(self) -> None:
self._transport.close()
async def wait_closed(self) -> None:
# a datagram endpoint has nothing to drain once it's closed
return None
class AIOHTTPRunner(Runner):
__slots__ = ('app', '_handler')