#!/usr/bin/env python3 """Build/test the pinned Instagram bridge with Xessenger's session-isolation patch, with a message holding several photos read as one album, and with rooms made only for inbox threads active within thread_backfill.days_limit (recent-chats.patch), and with its account keys stored sealed with the bridge's key when XESSENGER_SEAL_KEY_FILE is set (mautrix-seal.patch), and with each contact's username named from what the bridge stored of it, for the handle of the encrypted profiles of contacts known before the bridge kept it, and cleared when a profile names none (ghost-identifiers.patch), and with a thread Instagram answers without its direct thread, asked for its info, answered as errors.ErrUnsupported rather than read as a nil pointer (a history move then uses what the bridge holds: chat-info-unsupported.patch), and with the name and identifiers of a contact the bridge named kept when Instagram gives its placeholder for a person it does not show, the name that did not reach Matrix still sent again (placeholder-profile.patch, with mautrix-ghost-profile.patch in mautrix-go).""" import argparse import json import os from pathlib import Path import shutil import subprocess import tempfile ROOT = Path(__file__).resolve().parent def run(args, **kwargs): return subprocess.run(args, check=True, text=True, **kwargs) def writable(directory): for path in [directory, *directory.rglob('*')]: path.chmod(path.stat().st_mode | 0o200) def patch_dependency(source_dir, path, patches): """Build with a copy of the dependency version the bridge pins (go.sum checks the download), patched. The copy lives in the source tree and the replace is relative, so the binary records no temporary directory.""" module = json.loads(run(['go', 'mod', 'download', '-json', path], cwd=source_dir, capture_output=True).stdout) target = source_dir / '.xessenger' / path.rsplit('/', 1)[-1] shutil.copytree(module['Dir'], target) writable(target) for patch in patches: run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / patch)], cwd=target) run(['go', 'mod', 'edit', '-replace='+path+'=./'+target.relative_to(source_dir).as_posix()], cwd=source_dir) def use_seal(source_dir): """The seal package in seal/, the same in every bridge, which the patched mautrix-go imports.""" shutil.copytree(ROOT / 'seal', source_dir / '.xessenger' / 'seal') run(['go', 'mod', 'edit', '-require=xessenger.local/seal@v0.0.0', '-replace=xessenger.local/seal=./.xessenger/seal'], cwd=source_dir) def use_bridgekit(source_dir, command): """services/bridgekit, Xessenger's extension every bridge runs with (QA-289), installed in main.go (bridgekit.patch): taken from the repository, or in Docker from the bridgekit build context the Dockerfile copies to XESSENGER_BRIDGEKIT. Looked up only here: the --warm layer has neither.""" bridgekit = Path(os.environ.get('XESSENGER_BRIDGEKIT') or ROOT.parents[2] / 'services' / 'bridgekit') shutil.copytree(bridgekit, source_dir / '.xessenger' / 'bridgekit', ignore=shutil.ignore_patterns('*_test.go', 'testdata')) run(['go', 'mod', 'edit', '-require=xessenger/bridgekit@v0.0.0', '-replace=xessenger/bridgekit=./.xessenger/bridgekit'], cwd=source_dir) run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / 'bridgekit.patch')], cwd=source_dir) # The patch must change the command this script builds, or the bridge would run without the extension. if 'bridgekit.Install(' not in (source_dir / command / 'main.go').read_text(): raise RuntimeError(f'bridgekit.patch does not install bridgekit in {command}') def build(output=None, test=False, warm=False): lock = json.loads((ROOT / 'upstream.json').read_text()) source = json.loads(run(['go', 'mod', 'download', '-json', lock['Path']+'@'+lock['Version']], capture_output=True).stdout) if any(source.get(k) != v for k, v in lock.items()): raise RuntimeError('Upstream module does not match the pinned checksums') with tempfile.TemporaryDirectory(prefix='xessenger-instagram-') as temp: source_dir = Path(temp) / 'source' shutil.copytree(source['Dir'], source_dir) writable(source_dir) env = dict(os.environ, CGO_ENABLED='1') # Every build runs with -trimpath: Go keys its build cache on the package directory otherwise, and this one # is new each time. --warm compiles the unpatched upstream into that cache for the image's next layer, with # mautrix-go taken from a copy as below, so only what the patches touch compiles again. if warm: patch_dependency(source_dir, 'maunium.net/go/mautrix', []) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-o', os.devnull, './cmd/mautrix-instagram'], cwd=source_dir, env=env) return for patch in ['shared-sessions.patch', 'single-owner.patch', 'peer-profile.patch', 'album.patch', 'recent-chats.patch', 'ghost-identifiers.patch', 'chat-info-unsupported.patch', 'placeholder-profile.patch']: run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / patch)], cwd=source_dir) # The login's secrets are sealed in mautrix-go; Instagram keeps no whatsmeow device. use_seal(source_dir) patch_dependency(source_dir, 'maunium.net/go/mautrix', ['mautrix-seal.patch', 'mautrix-device-keys.patch', 'mautrix-ghost-profile.patch']) shutil.copy(ROOT / 'seal_test.go', source_dir / 'pkg/metaid/xessenger_seal_test.go') use_bridgekit(source_dir, 'cmd/mautrix-instagram') if test: run(['go', 'test', '-trimpath', '-tags', 'goolm', './pkg/igconnector', './pkg/metaid', './pkg/msgconv/igconv'], cwd=source_dir, env=env) run(['go', 'test', '-p', '1', '-trimpath', '-tags', 'goolm', '-run', 'Xessenger', 'maunium.net/go/mautrix/bridgev2/database', 'maunium.net/go/mautrix/crypto/xessengertest'], cwd=source_dir, env=env) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-o', os.devnull, './cmd/mautrix-instagram'], cwd=source_dir, env=env) if output: output = Path(output).resolve() output.parent.mkdir(parents=True, exist_ok=True) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-ldflags', '-X main.Tag=v0.2609.0-xessenger-shared-sessions', '-o', str(output), './cmd/mautrix-instagram'], cwd=source_dir, env=env) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output') parser.add_argument('--test', action='store_true') parser.add_argument('--warm', action='store_true', help='only compile the unpatched upstream into the Go build cache') args = parser.parse_args() if args.warm and (args.output or args.test): parser.error('--warm runs alone') if not args.output and not args.test and not args.warm: parser.error('Choose --test and/or --output, or --warm') build(args.output, args.test, args.warm)