File size: 3,326 Bytes
a359f6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python3
"""Wrap a validated Live Photo pair in a cross-platform .pvt package (no transcoding)."""
import argparse
import hashlib
import json
from pathlib import Path
import plistlib
import shutil
import tempfile


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def package(pair_dir, output):
    pair_dir, output = Path(pair_dir).resolve(), Path(output).absolute()
    manifest = json.loads((pair_dir / 'manifest.json').read_text())
    if manifest.get('metadataVerified') is not True:
        raise ValueError('Pair must pass metadata validation first')
    load = manifest.get('localPHLivePhotoLoad')
    if manifest.get('backend') == 'portable-python':
        from pair_live_photo import verify_pair
        verify_pair(pair_dir, manifest)  # Re-read files; do not trust a manifest flag alone.
        if load not in ('passed', 'not_available'):
            raise ValueError('Known Apple loading failure blocks delivery')
    elif load != 'passed':
        raise ValueError('Native backend must pass PHLivePhoto validation first')
    if output.suffix.lower() != '.pvt':
        raise ValueError('Output must end in .pvt')
    resources = {}
    for key, suffix in [('photo', '.jpg'), ('video', '.mov')]:
        source = (pair_dir / manifest[key]).resolve()
        if source.parent != pair_dir or not source.is_file():
            raise ValueError('Invalid resource path: ' + str(source))
        resources[output.stem + suffix] = source
    metadata = {'PFVideoComplementMetadataVersionKey': '1'}
    reused = output.exists()
    if reused:
        if not output.is_dir() or set(p.name for p in output.iterdir()) != set(resources) | {'metadata.plist'}:
            raise ValueError('Existing output differs; choose a new name')
        if plistlib.loads((output / 'metadata.plist').read_bytes()) != metadata:
            raise ValueError('Existing metadata differs')
        for name, source in resources.items():
            if digest(output / name) != digest(source):
                raise ValueError('Existing resource differs: ' + name)
    else:
        output.parent.mkdir(parents=True, exist_ok=True)
        staging = Path(tempfile.mkdtemp(prefix='.livecanvas-', dir=output.parent))
        try:
            for name, source in resources.items():
                shutil.copyfile(source, staging / name)
                if digest(staging / name) != digest(source):
                    raise ValueError('Copy verification failed')
            (staging / 'metadata.plist').write_bytes(plistlib.dumps(metadata))
            staging.rename(output)
        finally:
            if staging.exists():
                shutil.rmtree(staging)
    return {'package': str(output), 'identifier': manifest['identifier'],
            'resourcesUnchanged': True, 'reused': reused,
            'metadataVerified': True, 'localPHLivePhotoLoad': load,
            'sha256': {name: digest(output / name) for name in resources},
            'photosImport': 'not_tested', 'iPhonePlayback': 'not_tested'}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('pair_dir')
    parser.add_argument('output_pvt')
    args = parser.parse_args()
    print(json.dumps(package(args.pair_dir, args.output_pvt), ensure_ascii=False, indent=2))