@typeroll/mcp-server 0.45.168 → 0.45.170

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/AGENTS.md +2 -1
  2. package/dist/bundled-content.js +26 -13
  3. package/dist/server.js +4 -0
  4. package/dist/tools/apps.js +33 -0
  5. package/dist/tools/fonts.js +1 -1
  6. package/dist/tools/forms.js +4 -3
  7. package/dist/tools/media.js +2 -2
  8. package/dist/tools/migration.js +1 -1
  9. package/dist/tools/pages.js +4 -0
  10. package/dist/tools/preview.js +4 -0
  11. package/dist/tools/settings.js +1 -1
  12. package/dist/tools/styles.js +1 -1
  13. package/dist/version.d.ts +1 -1
  14. package/dist/version.js +1 -1
  15. package/dist/workspace.d.ts +1 -1
  16. package/dist/workspace.js +17 -8
  17. package/package.json +1 -1
  18. package/skills/tr-brand.md +1 -1
  19. package/skills/tr-migrate-astro.md +4 -13
  20. package/skills/tr-migrate-multisite.md +10 -31
  21. package/skills/tr-migrate-wp.md +73 -384
  22. package/skills/tr-responsive.md +14 -0
  23. package/workspace-templates/scripts/README.md +18 -0
  24. package/workspace-templates/scripts/typeroll/browser.cjs +6 -1
  25. package/workspace-templates/scripts/typeroll/call.py +5 -2
  26. package/workspace-templates/scripts/typeroll/css_report.py +45 -0
  27. package/workspace-templates/scripts/typeroll/inventory.py +264 -0
  28. package/workspace-templates/scripts/typeroll/media_fit.py +112 -0
  29. package/workspace-templates/scripts/typeroll/migration.py +254 -0
  30. package/workspace-templates/scripts/typeroll/page_part.cjs +34 -0
  31. package/workspace-templates/scripts/typeroll/page_source.py +148 -0
  32. package/workspace-templates/scripts/typeroll/pages.py +156 -0
  33. package/workspace-templates/scripts/typeroll/read_pages.cjs +169 -0
  34. package/workspace-templates/scripts/typeroll/shoot_hosted.cjs +13 -6
  35. package/workspace-templates/scripts/typeroll/trlib.py +45 -7
  36. package/workspace-templates/scripts/typeroll/verify_migration.cjs +47 -0
  37. package/workspace-templates/scripts/typeroll/verify_migration.py +274 -0
  38. package/workspace-templates/scripts/typeroll/write_pages.py +542 -0
  39. package/workspace-templates/skills/typeroll-migrate-sources.md +36 -0
  40. package/workspace-templates/skills/typeroll-migrate.md +109 -0
  41. package/workspace-templates/workflows/design.md +1 -1
  42. package/workspace-templates/workflows/migration.md +12 -5
@@ -0,0 +1,45 @@
1
+ """List the site's CSS and every value outside its design system, with a reason.
2
+
3
+ Uses the platform's own audit (lint_design_tokens) and saves
4
+ qa/migration/css.json. Write why a deviation stays in
5
+ qa/migration/css-reasons.json, by place or by value:
6
+ {"site": "...", "page:about": "...", "#1a2b3c": "..."}. Changes nothing.
7
+ """
8
+ import argparse
9
+ import json
10
+ import migration
11
+ import trlib
12
+
13
+
14
+ def report(reasons):
15
+ settings = trlib.call('read_site_settings')
16
+ css = settings.get('settings', settings).get('custom_css') or ''
17
+ audit = trlib.call('lint_design_tokens')
18
+ grouped = {}
19
+ for finding in [*audit.get('findings', []), *audit.get('css_findings', [])]:
20
+ source = finding.get('source') or 'site'
21
+ key = (source, finding['code'], str(finding.get('value', '')))
22
+ row = grouped.setdefault(key, {'place': source, 'code': finding['code'], 'value': str(finding.get('value', '')),
23
+ 'suggestions': finding.get('suggestions') or [], 'used': 0,
24
+ 'reason': reasons.get(source) or reasons.get(str(finding.get('value', ''))) or ''})
25
+ row['used'] += 1
26
+ rows = sorted(grouped.values(), key=lambda row: (bool(row['reason']), row['place'], row['code'], row['value']))
27
+ if css.strip():
28
+ rows.insert(0, {'place': 'site', 'code': 'site_css', 'value': f'{len(css)} characters', 'suggestions': [], 'used': 1, 'reason': reasons.get('site', '')})
29
+ return {'site_css': css, 'rows': rows, 'without_reason': sum(not row['reason'] for row in rows)}
30
+
31
+
32
+ def main():
33
+ argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter).parse_args()
34
+ data = report(migration.read_json(migration.folder() / 'css-reasons.json', {}))
35
+ migration.write_json(migration.folder() / 'css.json', data)
36
+ open_rows = [row for row in data['rows'] if not row['reason']]
37
+ print(json.dumps({'rows': len(data['rows']), 'without_reason': open_rows}, ensure_ascii=False, indent=2))
38
+ return 1 if open_rows else 0
39
+
40
+
41
+ if __name__ == '__main__':
42
+ try:
43
+ raise SystemExit(main())
44
+ except migration.StepError as error:
45
+ raise SystemExit(str(error))
@@ -0,0 +1,264 @@
1
+ """Step 1: list everything on the old site. Reads public pages only.
2
+
3
+ Finds the addresses, opens every page in a browser and saves what a visitor sees
4
+ (read_pages.cjs): pictures at two widths, texts in order, links and media. It does
5
+ not judge what a page is; that is the migrating agent's work. Saves
6
+ qa/migration/inventory.json and the pages under sources/private/migration/. Run it
7
+ again to continue: saved pages are not read twice (--refresh reads again).
8
+ """
9
+ import argparse
10
+ import hashlib
11
+ from html.parser import HTMLParser
12
+ import json
13
+ import os
14
+ import re
15
+ import subprocess
16
+ from pathlib import Path
17
+ import sys
18
+ import urllib.parse
19
+ import xml.etree.ElementTree as ET
20
+ import migration
21
+ from check_url_parity import fetch, origin
22
+
23
+ SKIP_TYPES = {'attachment', 'nav_menu_item', 'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation',
24
+ 'wp_global_styles', 'wp_font_family', 'wp_font_face', 'revision'}
25
+ VIDEO = re.compile(r'(?:youtube(?:-nocookie)?\.com|youtu\.be|vimeo\.com)', re.I)
26
+ FILE = re.compile(r'\.(?:jpe?g|png|gif|webp|avif|svg|pdf|mp4|webm|mp3|zip|docx?|xlsx?|pptx?)$', re.I)
27
+
28
+
29
+ class Page(HTMLParser):
30
+ """Links, media, forms and main headings of one fetched page."""
31
+
32
+ def __init__(self, base):
33
+ super().__init__(convert_charrefs=True)
34
+ self.base, self.links, self.media, self.forms, self.h1 = base, set(), set(), 0, 0
35
+
36
+ def handle_starttag(self, tag, attrs):
37
+ data = dict(attrs)
38
+ if tag == 'base' and data.get('href'):
39
+ self.base = urllib.parse.urljoin(self.base, data['href'])
40
+ if tag == 'a' and data.get('href'):
41
+ url = urllib.parse.urljoin(self.base, data['href'])
42
+ (self.media if FILE.search(urllib.parse.urlsplit(url).path) else self.links).add(url)
43
+ for value in (data.get('src'), data.get('data-src'), data.get('poster')):
44
+ if value and tag in ('img', 'source', 'video', 'audio') and not value.startswith('data:'):
45
+ self.media.add(urllib.parse.urljoin(self.base, value))
46
+ if tag == 'form' and 'search' not in (data.get('role') or '') + (data.get('class') or ''):
47
+ self.forms += 1
48
+ self.h1 += tag == 'h1'
49
+
50
+
51
+ def page_key(url):
52
+ return hashlib.sha256(url.encode()).hexdigest()[:24]
53
+
54
+
55
+ def normalize(url, base):
56
+ """One spelling per page on the old host; None for other hosts and files."""
57
+ parts = urllib.parse.urlsplit(urllib.parse.urljoin(base, url))
58
+ home = urllib.parse.urlsplit(base)
59
+ strip = lambda host: (host or '').lower().removeprefix('www.')
60
+ if parts.scheme not in ('http', 'https') or strip(parts.hostname) != strip(home.hostname) or FILE.search(parts.path):
61
+ return None
62
+ if re.match(r'^/(wp-admin|wp-login|wp-json|wp-content|xmlrpc|feed)\b', parts.path) or parts.path.rstrip('/').endswith('/feed'):
63
+ return None
64
+ return urllib.parse.urlunsplit((home.scheme, home.netloc, parts.path or '/', '', ''))
65
+
66
+
67
+ def sitemap_urls(base, get):
68
+ queue, seen, found = [base + '/sitemap.xml', base + '/sitemap_index.xml', base + '/wp-sitemap.xml'], set(), set()
69
+ status, _, body = get(base + '/robots.txt')
70
+ if status == 200:
71
+ queue += re.findall(r'(?im)^\s*sitemap:\s*(\S+)', body.decode('utf8', 'replace'))
72
+ while queue and len(seen) < 200:
73
+ url = queue.pop(0)
74
+ if url in seen or not normalize_host(url, base):
75
+ continue
76
+ seen.add(url)
77
+ status, location, body = get(url)
78
+ if status in (301, 302, 307, 308) and location:
79
+ queue.append(urllib.parse.urljoin(url, location))
80
+ continue
81
+ # A document type can define entities; a sitemap has no use for one.
82
+ if status != 200 or b'<!DOCTYPE' in body[:2000] or b'<!ENTITY' in body:
83
+ continue
84
+ try:
85
+ tree = ET.fromstring(body)
86
+ except ET.ParseError:
87
+ continue
88
+ for node in tree:
89
+ loc = next((child.text for child in node if child.tag.endswith('}loc') or child.tag == 'loc'), None)
90
+ if loc:
91
+ (queue.append if node.tag.endswith('sitemap') else found.add)(loc.strip())
92
+ return found
93
+
94
+
95
+ def normalize_host(url, base):
96
+ strip = lambda value: (urllib.parse.urlsplit(value).hostname or '').lower().removeprefix('www.')
97
+ return strip(url) == strip(base)
98
+
99
+
100
+ def wordpress(base, get):
101
+ """Types and records of the public REST API; None when there is no such API."""
102
+ status, _, body = get(base + '/wp-json/wp/v2/types')
103
+ if status != 200:
104
+ return None
105
+ try:
106
+ types = json.loads(body)
107
+ except ValueError:
108
+ return None
109
+ result = {}
110
+ for slug, info in types.items():
111
+ if slug in SKIP_TYPES or not isinstance(info, dict) or not info.get('rest_base'):
112
+ continue
113
+ records, page, complete = [], 1, False
114
+ while page <= 100:
115
+ status, _, body = get(f"{base}/wp-json/wp/v2/{info['rest_base']}?per_page=100&page={page}&_embed=wp:featuredmedia,author")
116
+ if status == 400 and page > 1:
117
+ complete = True
118
+ break
119
+ try:
120
+ rows = json.loads(body) if status == 200 else None
121
+ except ValueError:
122
+ rows = None
123
+ if not isinstance(rows, list):
124
+ break
125
+ records += rows
126
+ if len(rows) < 100:
127
+ complete = True
128
+ break
129
+ page += 1
130
+ result[slug] = {'label': info.get('name') or slug, 'records': records, 'complete': complete}
131
+ return result
132
+
133
+
134
+ def picture_name(url):
135
+ """A file name a person can recognise, and that no other page has."""
136
+ path = re.sub(r'[^a-z0-9]+', '-', urllib.parse.unquote(urllib.parse.urlsplit(url).path).lower()).strip('-')[:60]
137
+ return f'{path or "start"}-{page_key(url)[:6]}'
138
+
139
+
140
+ def render(pages):
141
+ """Read pages in a browser. What could not be read has no file afterwards."""
142
+ plan = migration.private() / 'read-plan.json'
143
+ migration.write_json(plan, {'pages': [{**page, 'name': picture_name(page['url'])} for page in pages],
144
+ 'out': str(migration.private() / 'pages'), 'screens': str(migration.private() / 'screens')})
145
+ subprocess.run(['node', str(Path(__file__).with_name('read_pages.cjs')), str(plan)], check=False)
146
+ os.environ['TYPEROLL_PROFILE_SHOWN'] = '1'
147
+
148
+
149
+ def seen(url):
150
+ return migration.read_json(migration.private() / 'pages' / f'{page_key(url)}.json')
151
+
152
+
153
+ def build(base, limit, refresh, get=fetch, reader=render):
154
+ store = migration.private() / 'html'
155
+ store.mkdir(parents=True, exist_ok=True)
156
+ wp = wordpress(base, get)
157
+ queue, sources = [], {}
158
+
159
+ def add(url, source):
160
+ clean = normalize(url, base)
161
+ if clean and clean not in sources:
162
+ queue.append(clean)
163
+ if clean:
164
+ sources.setdefault(clean, set()).add(source)
165
+
166
+ add(base + '/', 'start')
167
+ for url in sitemap_urls(base, get):
168
+ add(url, 'sitemap')
169
+ types, owner = {}, {}
170
+ for slug, info in (wp or {}).items():
171
+ for record in info['records']:
172
+ if record.get('link'):
173
+ add(record['link'], 'rest')
174
+ owner[normalize(record['link'], base)] = (slug, record['id'])
175
+ types[slug] = {'label': info['label'], 'count': len(info['records']), 'complete': info['complete']}
176
+ migration.write_json(migration.private() / 'records' / f'{slug}.json', info['records'])
177
+ rows, media, forms, videos, outside, index = [], {}, [], [], {}, 0
178
+ while index < len(queue) and index < limit:
179
+ # Addresses first, then the pages among them; pages can show new addresses.
180
+ batch, waiting = queue[index:limit], []
181
+ index += len(batch)
182
+ for url in batch:
183
+ file = store / f'{page_key(url)}.json'
184
+ saved = None if refresh else migration.read_json(file)
185
+ if saved is None:
186
+ status, location, body = get(url)
187
+ saved = {'url': url, 'status': status, 'location': urllib.parse.urljoin(url, location) if location else None,
188
+ 'page': status == 200 and b'<' in body[:1000]}
189
+ # A failed read is tried again next time instead of being kept.
190
+ if status:
191
+ migration.write_json(file, saved)
192
+ if len(rows) % 50 == 49:
193
+ print(f'{len(rows) + 1} addresses asked', file=sys.stderr)
194
+ row = {'url': url, 'path': urllib.parse.urlsplit(url).path, 'status': saved['status'], 'page': saved['page']}
195
+ if saved['location']:
196
+ row['redirects_to'] = saved['location']
197
+ add(saved['location'], 'redirect')
198
+ if url in owner:
199
+ row['source_type'], row['record'] = owner[url]
200
+ rows.append(row)
201
+ if saved['page'] and (refresh or not (migration.private() / 'pages' / f'{page_key(url)}.json').is_file()):
202
+ waiting.append({'url': url, 'key': page_key(url)})
203
+ if waiting:
204
+ reader(waiting)
205
+ for row in rows[-len(batch):]:
206
+ page = seen(row['url']) if row['page'] else None
207
+ row['read'] = page is not None
208
+ for link in page['links'] if page else []:
209
+ if not FILE.search(urllib.parse.urlsplit(link).path):
210
+ add(link, 'link')
211
+ for row in rows:
212
+ page = seen(row['url']) if row['read'] else None
213
+ if not page:
214
+ continue
215
+ row.update({'title': page['title'].strip(), 'h1': page['h1']})
216
+ for link in page['links']:
217
+ if FILE.search(urllib.parse.urlsplit(link).path):
218
+ media.setdefault(link.split('#')[0], []).append(row['path'])
219
+ for item in page['outline']:
220
+ if item['kind'] in ('image', 'picture') and item.get('src') and not item['src'].startswith('data:'):
221
+ media.setdefault(item['src'].split('#')[0], []).append(row['path'])
222
+ if page['forms']:
223
+ forms.append({'path': row['path'], 'forms': page['forms']})
224
+ found = sorted({link for link in page['videos'] if VIDEO.search(link) or re.search(r'\.(mp4|webm)(\?|$)', link, re.I)})
225
+ if found:
226
+ videos.append({'path': row['path'], 'videos': found})
227
+ for item in page.get('outside') or []:
228
+ # Pictures from another site are grouped per site; a badge in the footer shows once.
229
+ key = (item['kind'], item['host'] if item['kind'] == 'img' else item['src'])
230
+ outside.setdefault(key, {**item, 'used_on': []})['used_on'].append(row['path'])
231
+ for row in rows:
232
+ row['found_in'] = sorted(sources[row['url']])
233
+ unread = [row['url'] for row in rows if row['status'] == 0 or row['status'] >= 500 or row['status'] in (401, 403, 429) or row['page'] and not row['read']]
234
+ notes = []
235
+ notes += [f'The list of {slug} is not complete.' for slug, info in types.items() if not info['complete']]
236
+ if index < len(queue):
237
+ notes.append(f'{len(queue) - index} addresses were not read. Run again with a higher --limit.')
238
+ if unread:
239
+ notes.append(f'{len(unread)} addresses could not be read.')
240
+ ok = index >= len(queue) and not unread and all(info['complete'] for info in types.values())
241
+ migration.save('inventory', ok, source=base, wordpress=wp is not None, urls=sorted(rows, key=lambda row: row['path']), types=types,
242
+ media=[{'url': url, 'used_on': sorted(set(where))[:5]} for url, where in sorted(media.items())],
243
+ forms=forms, videos=videos, unread=unread, notes=notes,
244
+ outside=[{**item, 'pages': len(item['used_on']), 'used_on': sorted(set(item['used_on']))[:5]} for item in sorted(outside.values(), key=lambda item: -len(item['used_on']))])
245
+ return ok, {'urls': len(rows), 'types': {slug: info['count'] for slug, info in types.items()}, 'media': len(media),
246
+ 'forms': len(forms), 'videos': len(videos), 'outside': len(outside), 'notes': notes}
247
+
248
+
249
+ def main():
250
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
251
+ parser.add_argument('source', type=origin)
252
+ parser.add_argument('--limit', type=int, default=3000)
253
+ parser.add_argument('--refresh', action='store_true')
254
+ args = parser.parse_args()
255
+ ok, summary = build(args.source, args.limit, args.refresh)
256
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
257
+ return 0 if ok else 1
258
+
259
+
260
+ if __name__ == '__main__':
261
+ try:
262
+ raise SystemExit(main())
263
+ except migration.StepError as error:
264
+ raise SystemExit(str(error))
@@ -0,0 +1,112 @@
1
+ """Copy a file the media library refused from its address: a shorter name, pictures at most
2
+ 2560 px wide, films under 24 MB. Mechanical only, the same for every site; needs ffmpeg.
3
+
4
+ media_fit.py URL copy one file and print its media_id and address
5
+ """
6
+ import hashlib
7
+ import json
8
+ import mimetypes
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import unicodedata
15
+ import urllib.parse
16
+ import urllib.request
17
+ from pathlib import Path
18
+
19
+ import trlib
20
+
21
+ LIMIT = 24 * 1024 * 1024
22
+ FETCH_LIMIT = 1024 * 1024 * 1024
23
+ TYPES = {'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
24
+ '.avif': 'image/avif', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.webm': 'video/webm'}
25
+
26
+
27
+ def short_name(url, limit=60):
28
+ """The file's own name, cut before its extension, so the type stays known."""
29
+ name = urllib.parse.unquote(urllib.parse.urlsplit(url).path.rsplit('/', 1)[-1]) or 'file'
30
+ name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore').decode()
31
+ stem, dot, extension = name.rpartition('.')
32
+ stem, extension = (stem, extension.lower()) if dot and len(extension) <= 5 else (name, '')
33
+ stem = re.sub(r'[^a-zA-Z0-9_-]+', '-', stem).strip('-')[:limit].rstrip('-') or 'file'
34
+ return f'{stem}.{extension}' if extension else stem
35
+
36
+
37
+ def fetch(url, folder):
38
+ path = Path(folder) / short_name(url)
39
+ request = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (compatible; TyperollMigration/1.0)'})
40
+ with urllib.request.urlopen(request, timeout=120) as response, path.open('wb') as out:
41
+ size = 0
42
+ while chunk := response.read(1024 * 1024):
43
+ size += len(chunk)
44
+ if size > FETCH_LIMIT:
45
+ raise ValueError(f'{url} is larger than 1 GB')
46
+ out.write(chunk)
47
+ return path
48
+
49
+
50
+ def ffmpeg(*args):
51
+ if not shutil.which('ffmpeg'):
52
+ raise RuntimeError('ffmpeg is not installed; install it (brew install ffmpeg or apt-get install ffmpeg) and run again')
53
+ done = subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', *map(str, args)], capture_output=True, text=True)
54
+ if done.returncode:
55
+ raise RuntimeError('ffmpeg failed: ' + done.stderr.strip()[-300:])
56
+
57
+
58
+ def duration(path):
59
+ done = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', str(path)], capture_output=True, text=True)
60
+ return float(done.stdout.strip() or 0)
61
+
62
+
63
+ def fit(path):
64
+ """The same file, or a smaller copy that fits the library. A picture keeps its proportions."""
65
+ kind = TYPES.get(path.suffix.lower(), '')
66
+ if path.stat().st_size <= LIMIT or kind in ('image/svg+xml', 'application/pdf', 'image/gif'):
67
+ return path
68
+ if kind.startswith('image/'):
69
+ # PNG keeps transparency; every other picture becomes a JPEG.
70
+ for width in (2560, 1920, 1280):
71
+ out = path.with_name(f'{path.stem}-{width}{".png" if kind == "image/png" else ".jpg"}')
72
+ ffmpeg('-i', path, '-vf', f"scale='min({width},iw)':-2", *(() if kind == 'image/png' else ('-q:v', '3')), out)
73
+ if out.stat().st_size <= LIMIT:
74
+ return out
75
+ if kind.startswith('video/'):
76
+ seconds = max(duration(path), 1)
77
+ for width in (1920, 1280):
78
+ out = path.with_name(f'{path.stem}-{width}.mp4')
79
+ rate = int(LIMIT * 8 * 0.92 / seconds) - 128_000
80
+ ffmpeg('-i', path, '-vf', f"scale='min({width},iw)':-2", '-c:v', 'libx264', '-preset', 'slow', '-b:v', max(rate, 300_000),
81
+ '-maxrate', max(rate, 300_000), '-bufsize', max(rate, 300_000) * 2, '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', out)
82
+ if out.stat().st_size <= LIMIT:
83
+ return out
84
+ raise ValueError(f'{path.name} is still larger than 24 MB after scaling down')
85
+
86
+
87
+ def upload(path):
88
+ kind = TYPES.get(path.suffix.lower()) or mimetypes.guess_type(path.name)[0] or ''
89
+ if kind not in TYPES.values():
90
+ raise ValueError(f'{path.name}: the media library takes pictures, PDF, MP4 and WebM only')
91
+ data = path.read_bytes()
92
+ grant = trlib.call('create_upload_url', {'filename': path.name, 'content_type': kind, 'size': len(data)})
93
+ request = urllib.request.Request(grant['upload_url'], data=data, method='PUT', headers={'Content-Type': kind, 'Content-Length': str(len(data))})
94
+ with urllib.request.urlopen(request, timeout=300) as response:
95
+ if response.status not in (200, 201):
96
+ raise RuntimeError(f'The upload of {path.name} answered HTTP {response.status}')
97
+ trlib.call('finalize_media', {'media_id': grant['media_id'], 'expected_sha256': hashlib.sha256(data).hexdigest()})
98
+ return {'media_id': grant['media_id'], 'url': grant['cdn_url'], 'filename': grant.get('filename') or path.name}
99
+
100
+
101
+ def copy(url):
102
+ """{media_id, url, filename, scaled} for a file the library refused from its address."""
103
+ with tempfile.TemporaryDirectory() as folder:
104
+ original = fetch(url, folder)
105
+ fitted = fit(original)
106
+ return {**upload(fitted), 'scaled': fitted != original}
107
+
108
+
109
+ if __name__ == '__main__':
110
+ if len(sys.argv) != 2:
111
+ sys.exit(__doc__)
112
+ print(json.dumps(copy(sys.argv[1]), indent=2))