diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..95d08ec --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,27 @@ +name: WordPress release + +on: + push: + tags: + - 'v*' + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: Check out the tagged source + env: + TAG: ${{ gitea.ref_name }} + COMMIT: ${{ gitea.sha }} + run: | + git clone --depth 1 --branch "$TAG" https://git.labs.casa/josh/eventLabs.git source + test "$(git -C source rev-parse HEAD)" = "$(git -C source rev-parse "$COMMIT^{commit}")" + - name: Build and publish the WordPress ZIP + working-directory: source + env: + TAG: ${{ gitea.ref_name }} + EVENTLABS_RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 scripts/release.py "$TAG" --publish diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ca90fc0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/dist/ +__pycache__/ diff --git a/README.md b/README.md index bba6fb4..168835a 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,19 @@ Publish an events calendar, design single-event pages in Elementor, and sync club events from burnWorks. eventLabs manages schedules, venues, organizers, and series in WordPress and provides its own versioned REST API. +[Download the latest release](https://git.labs.casa/josh/eventLabs/releases/latest) · [API reference](docs/API.md) · [Release guide](docs/RELEASING.md) +  ## Get started -1. Install this directory in `wp-content/plugins/burn-events/` and activate **eventLabs** under **Plugins**. Requires WordPress 6.9+ and PHP 8.1+. The Elementor builder and widgets use Elementor Free. +1. Download `eventlabs-vX.Y.Z.zip` from the [latest release](https://git.labs.casa/josh/eventLabs/releases/latest). Upload it through **Plugins → Add Plugin → Upload Plugin**, then activate **eventLabs**. Requires WordPress 6.9+ and PHP 8.1+. The Elementor builder and widgets use Elementor Free. 2. Open **Events → Add Event**. Set the schedule, link a venue, and publish. Use **Events → Settings → View calendar** to open the public calendar. 3. Use **Events → Single Event Templates → Create starter template** to design a single-event layout. Publish it, then assign it to an event or choose **Use as default**. 4. Add **Event Calendar** or **Event List** from the **eventLabs** widget category in Elementor. You can also embed a calendar with `[burn_events view="month"]`. +Starting with **0.5.2**, the active plugin checks Gitea for stable releases and shows updates in WordPress. If you installed **0.5.1** or earlier, upload the latest release ZIP once and choose **Replace current with uploaded** to get the updater. An install mounted from the development checkout should be updated through Git. + ## Calendar and publishing - **Calendar views** include List, Month, Week, Day, Photo, Map, and Summary. In Month and Week, multi-day bars span their dates and show event previews on hover and keyboard focus. Set a custom color under **Events → Event Categories**. diff --git a/burn-events.php b/burn-events.php index 29da5c1..6974076 100644 --- a/burn-events.php +++ b/burn-events.php @@ -1,13 +1,14 @@ slug ?? '' ) ) { + return $result; + } + $release = self::latest(); + if ( ! $release ) { + return $result; + } + return (object) [ + 'name' => 'eventLabs', + 'slug' => self::SLUG, + 'author' => 'hostLabs', + 'version' => $release['version'], + 'requires' => $release['requires'], + 'requires_php' => $release['requires_php'], + 'homepage' => self::REPO, + 'download_link' => $release['package'], + 'sections' => [ + 'description' => '
' . esc_html__( 'Calendars, recurring events, and a Single Event template builder for Elementor.', 'burn-events' ) . '
', + 'changelog' => '' . esc_html__( 'Read the eventLabs release notes', 'burn-events' ) . '
', + ], + ]; + } + + private static function latest(): ?array { + // WordPress caches the update response. Reuse it within the request without delaying “Check again.” + static $loaded = false; + static $update = null; + if ( $loaded ) { + return $update; + } + $loaded = true; + $release = self::json( self::LATEST ); + $tag = $release['tag_name'] ?? null; + if ( ! is_string( $tag ) || ! preg_match( '/^v' . self::VERSION . '$/D', $tag ) || false !== ( $release['draft'] ?? null ) || false !== ( $release['prerelease'] ?? null ) || ! is_array( $release['assets'] ?? null ) ) { + return null; + } + $names = array_column( $release['assets'], 'name' ); + if ( ! in_array( self::archive_name( $tag ), $names, true ) || ! in_array( self::MANIFEST, $names, true ) ) { + return null; + } + $manifest = self::manifest( $tag ); + if ( ! $manifest ) { + return null; + } + $update = [ + 'slug' => self::SLUG, + 'version' => $manifest['version'], + 'requires' => $manifest['requires'], + 'requires_php' => $manifest['requires_php'], + 'url' => self::REPO . '/releases/tag/' . $tag, + 'package' => self::asset_url( $tag, self::archive_name( $tag ) ), + ]; + return $update; + } + + public static function download( $reply, $package ) { + $base = preg_quote( self::REPO . '/releases/download/', '~' ); + if ( false !== $reply || ! is_string( $package ) || ! preg_match( '~^' . $base . '(v' . self::VERSION . ')/eventlabs-\1\.zip$~D', $package, $match ) ) { + return $reply; + } + $manifest = self::manifest( $match[1] ); + if ( ! $manifest ) { + return new \WP_Error( 'eventlabs_update_manifest', __( 'The eventLabs release manifest is unavailable or invalid.', 'burn-events' ) ); + } + require_once ABSPATH . 'wp-admin/includes/file.php'; + $file = wp_tempnam( self::archive_name( $match[1] ) ); + if ( ! $file ) { + return new \WP_Error( 'eventlabs_update_file', __( 'WordPress could not create a temporary file for the eventLabs update.', 'burn-events' ) ); + } + $response = wp_safe_remote_get( $package, [ + 'timeout' => 60, + 'redirection' => 2, + 'user-agent' => 'eventLabs/' . BURN_EVENTS_VERSION, + 'stream' => true, + 'filename' => $file, + 'limit_response_size' => $manifest['size'] + 1, + ] ); + if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { + wp_delete_file( $file ); + return new \WP_Error( 'eventlabs_update_download', __( 'WordPress could not download the eventLabs release ZIP.', 'burn-events' ) ); + } + clearstatcache( true, $file ); + if ( $manifest['size'] !== filesize( $file ) || $manifest['sha256'] !== hash_file( 'sha256', $file ) ) { + wp_delete_file( $file ); + return new \WP_Error( 'eventlabs_update_checksum', __( 'The eventLabs download did not match the release checksum.', 'burn-events' ) ); + } + return $file; + } + + private static function manifest( string $tag ): ?array { + $manifest = self::json( self::asset_url( $tag, self::MANIFEST ) ); + if ( ! $manifest || substr( $tag, 1 ) !== ( $manifest['version'] ?? null ) || self::archive_name( $tag ) !== ( $manifest['package'] ?? null ) ) { + return null; + } + foreach ( [ 'requires', 'requires_php' ] as $key ) { + if ( ! is_string( $manifest[ $key ] ?? null ) || ! preg_match( '/^[0-9]+\.[0-9]+(?:\.[0-9]+)?$/D', $manifest[ $key ] ) ) { + return null; + } + } + if ( ! is_string( $manifest['sha256'] ?? null ) || ! preg_match( '/^[a-f0-9]{64}$/D', $manifest['sha256'] ) || ! is_int( $manifest['size'] ?? null ) || $manifest['size'] < 1 || $manifest['size'] > self::MAX_ZIP_BYTES ) { + return null; + } + return $manifest; + } + + private static function json( string $url ): ?array { + $response = wp_safe_remote_get( $url, [ + 'timeout' => 8, + 'redirection' => 2, + 'user-agent' => 'eventLabs/' . BURN_EVENTS_VERSION, + 'headers' => [ 'Accept' => 'application/json' ], + 'limit_response_size' => 128 * 1024, + ] ); + if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { + return null; + } + $data = json_decode( wp_remote_retrieve_body( $response ), true ); + return is_array( $data ) ? $data : null; + } + + private static function archive_name( string $tag ): string { + return 'eventlabs-' . $tag . '.zip'; + } + + private static function asset_url( string $tag, string $name ): string { + return self::REPO . '/releases/download/' . $tag . '/' . $name; + } +} diff --git a/scripts/release.py b/scripts/release.py new file mode 100644 index 0000000..ea49021 --- /dev/null +++ b/scripts/release.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Build an installable eventLabs ZIP, and optionally publish its tag to Gitea.""" + +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import HTTPRedirectHandler, Request, build_opener +from uuid import uuid4 +from zipfile import ZipFile + + +ROOT = Path(__file__).resolve().parent.parent +HOST = 'https://git.labs.casa' +REPO = '/josh/eventLabs' +API = HOST + '/api/v1/repos' + REPO +PACKAGE_DIR = 'burn-events/' +MANIFEST = 'eventlabs-update.json' +VERSION = r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)' +REQUIREMENT = r'[0-9]+\.[0-9]+(?:\.[0-9]+)?' +RUNTIME = ('burn-events.php', 'assets', 'includes', 'templates') +MAX_ZIP_BYTES = 32 * 1024 * 1024 +USER_AGENT = 'eventLabs-release' + + +def git(*args): + return subprocess.check_output(['git', '-C', str(ROOT), *args]) + + +def build(ref, output): + commit = git('rev-parse', '--verify', '--end-of-options', ref + '^{commit}').decode().strip() + source = git('show', commit + ':burn-events.php').decode() + + def header(name, pattern): + found = re.findall(r'^\s*\* ' + re.escape(name) + r': (' + pattern + r')\s*$', source, re.M) + if len(found) != 1: + raise ValueError(f'Expected one valid {name} header in burn-events.php.') + return found[0] + + version = header('Version', VERSION) + tag = 'v' + version + constants = re.findall(r"^define\( 'BURN_EVENTS_VERSION', '([^']+)' \);$", source, re.M) + if constants != [version]: + raise ValueError('The plugin version header and BURN_EVENTS_VERSION must match.') + if (ref.startswith('refs/tags/') or re.fullmatch('v' + VERSION, ref)) and ref.removeprefix('refs/tags/') != tag: + raise ValueError(f'Release tag must match the plugin version: {tag}.') + + archive_name = f'eventlabs-{tag}.zip' + data = { + 'version': version, + 'requires': header('Requires at least', REQUIREMENT), + 'requires_php': header('Requires PHP', REQUIREMENT), + 'package': archive_name, + 'commit': commit, + } + if header('Update URI', r'\S+') != HOST + REPO: + raise ValueError('The plugin Update URI must point to the eventLabs release repository.') + output.mkdir(parents=True, exist_ok=True) + archive = output / archive_name + temporary = output / (archive_name + '.tmp') + try: + subprocess.run( + ['git', '-C', str(ROOT), 'archive', '--format=zip', '-9', '--prefix=' + PACKAGE_DIR, + '--output=' + str(temporary.resolve()), commit, '--', *RUNTIME], + check=True, env={**os.environ, 'TZ': 'UTC'}, + ) + data['size'] = temporary.stat().st_size + if not 0 < data['size'] <= MAX_ZIP_BYTES: + raise ValueError('The WordPress release ZIP must be at most 32 MiB.') + with ZipFile(temporary) as package: + if package.read(PACKAGE_DIR + 'burn-events.php').decode() != source or package.testzip() is not None: + raise ValueError('The release ZIP is incomplete or corrupt.') + data['sha256'] = hashlib.sha256(temporary.read_bytes()).hexdigest() + temporary.replace(archive) + finally: + temporary.unlink(missing_ok=True) + manifest = output / MANIFEST + manifest.write_text(json.dumps(data, indent=2) + '\n', encoding='utf-8') + print(f'Built {archive} and {manifest}', flush=True) + return tag, data, archive, manifest + + +class NoRedirect(HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + # API write requests must never forward a repository credential to a redirect target. + return None + + +def authorization(): + token = os.environ.get('EVENTLABS_RELEASE_TOKEN', '').strip() + if token: + return 'token ' + token + result = subprocess.run( + ['git', '-C', str(ROOT), 'credential', 'fill'], + input=f'protocol=https\nhost=git.labs.casa\npath={REPO[1:]}.git\n\n', + capture_output=True, text=True, env={**os.environ, 'GIT_TERMINAL_PROMPT': '0'}, + ) + fields = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line) + if result.returncode or not fields.get('username') or not fields.get('password'): + raise ValueError('Set EVENTLABS_RELEASE_TOKEN or configure Git credentials for git.labs.casa.') + encoded = base64.b64encode((fields['username'] + ':' + fields['password']).encode()).decode() + return 'Basic ' + encoded + + +def publish(tag, data, archive, manifest): + auth = authorization() + opener = build_opener(NoRedirect()) + + def api(method, path, *, payload=None, attachment=None, missing=False): + headers = {'Authorization': auth, 'User-Agent': USER_AGENT, 'Accept': 'application/json'} + body = None + if payload is not None: + body = json.dumps(payload).encode() + headers['Content-Type'] = 'application/json' + if attachment is not None: + boundary = uuid4().hex + headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary + body = ( + f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{attachment.name}"\r\n' + 'Content-Type: application/octet-stream\r\n\r\n' + ).encode() + attachment.read_bytes() + f'\r\n--{boundary}--\r\n'.encode() + path += '?' + urlencode({'name': attachment.name}) + request = Request(API + path, method=method, data=body, headers=headers) + try: + with opener.open(request, timeout=90) as response: + return json.load(response) + except HTTPError as error: + if missing and error.code == 404: + return None + raise ValueError(f'Gitea {method} {path} returned HTTP {error.code}.') from None + + remote_tag = api('GET', '/tags/' + tag) + if remote_tag.get('commit', {}).get('sha') != data['commit']: + raise ValueError(f'Push {tag} for this exact commit before publishing.') + marker = f"SHA-256: `{data['sha256']}`" + release = api('GET', '/releases/tags/' + tag, missing=True) + if release is None: + release = api('POST', '/releases', payload={ + 'tag_name': tag, 'target_commitish': data['commit'], 'name': f'eventLabs {tag}', + 'draft': True, 'prerelease': False, + 'body': f"Install `{archive.name}` through Plugins → Add Plugin → Upload Plugin.\n\n" + f"Source commit: `{data['commit']}`\n\n{marker}", + }) + if release.get('tag_name') != tag or release.get('prerelease') or marker not in (release.get('body') or ''): + raise ValueError(f'An existing release for {tag} does not match this package. Check it on Gitea.') + attachments = {asset['name']: asset['size'] for asset in release.get('assets') or []} + if release.get('draft'): + path = '/releases/' + str(int(release['id'])) + for file in (archive, manifest): + size = file.stat().st_size + if file.name in attachments: + if attachments[file.name] != size: + raise ValueError(f'Existing draft attachment has the wrong size: {file.name}.') + continue + uploaded = api('POST', path + '/assets', attachment=file) + if uploaded.get('name') != file.name or uploaded.get('size') != size: + raise ValueError(f'Gitea did not store the complete attachment: {file.name}.') + api('PATCH', path, payload={'draft': False}) + + # Confirm the same anonymous download URLs WordPress will use. + download = HOST + REPO + '/releases/download/' + tag + '/' + for file in (archive, manifest): + request = Request(download + file.name, headers={'User-Agent': USER_AGENT}) + with build_opener().open(request, timeout=45) as response: + expected = file.read_bytes() + if response.read(len(expected) + 1) != expected: + raise ValueError(f'Public release download does not match the build: {file.name}.') + print(HOST + REPO + '/releases/tag/' + tag) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('ref', nargs='?', default='HEAD', help='Git ref to package; default HEAD') + parser.add_argument('--out', type=Path, default=ROOT / 'dist') + parser.add_argument('--publish', action='store_true', help='Publish both assets to the already pushed tag') + args = parser.parse_args() + if args.publish and not re.fullmatch('v' + VERSION, args.ref): + parser.error('--publish requires a stable tag like v0.5.2') + ref = 'refs/tags/' + args.ref if args.publish else args.ref + try: + release = build(ref, args.out) + if args.publish: + publish(*release) + except (ValueError, OSError, subprocess.CalledProcessError, URLError) as error: + print(f'Release failed: {error}', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main())