-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate-import.py
More file actions
368 lines (314 loc) Β· 15 KB
/
Copy pathmigrate-import.py
File metadata and controls
368 lines (314 loc) Β· 15 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#!/usr/bin/env python3
"""
Directus to Payload API Migration Script
----------------------------------------
Uses Payload REST API to import all data directly to the live production instance.
Bypasses all local OpenNext/Node.js issues completely.
Usage:
python3 migrate-import.py --api-url https://payload-cms.atliq.workers.dev
Requirements:
pip install requests python-dotenv
"""
import os
import sys
import csv
import json
import requests
import argparse
from typing import Dict, List, Any, Optional
from pathlib import Path
from urllib.parse import urljoin
from html import unescape
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class PayloadMigrator:
def __init__(self, api_url: str, api_key: Optional[str] = None):
self.api_url = api_url.rstrip('/')
self.session = requests.Session()
self.id_maps: Dict[str, Dict[Any, Any]] = {
'media': {},
'categories': {},
'authors': {},
'posts': {},
'culture_posts': {},
'inquiries': {}
}
if api_key:
self.session.headers['Authorization'] = f'Bearer {api_key}'
def login(self, email: str, password: str) -> bool:
"""Login to Payload CMS to get authentication cookie"""
try:
response = self.session.post(
urljoin(self.api_url, '/api/users/login'),
json={'email': email, 'password': password}
)
response.raise_for_status()
logger.info("β
Logged in successfully")
return True
except Exception as e:
logger.error(f"β Login failed: {e}")
return False
def create_item(self, collection: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Create a single item in Payload"""
try:
response = self.session.post(
urljoin(self.api_url, f'/api/{collection}'),
json=data,
timeout=30
)
if response.status_code == 409:
# Conflict - already exists, find it
return self.find_existing(collection, data)
response.raise_for_status()
return response.json()['doc']
except Exception as e:
logger.error(f"β Failed to create {collection}: {e}")
if hasattr(e, 'response') and e.response is not None:
logger.debug(f"Response: {e.response.text}")
return None
def find_existing(self, collection: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Find existing item by unique field (slug or identifier)"""
try:
query = {}
if 'slug' in data:
query['where[slug][equals]'] = data['slug']
elif 'email' in data and 'name' in data:
query['where[email][equals]'] = data['email']
query['where[name][equals]'] = data['name']
else:
return None
response = self.session.get(
urljoin(self.api_url, f'/api/{collection}'),
params=query
)
response.raise_for_status()
docs = response.json()['docs']
if docs:
logger.info(f"β©οΈ Found existing {collection}: {data.get('slug', data.get('name'))}")
return docs[0]
return None
except Exception as e:
logger.debug(f"Not found: {e}")
return None
def import_media(self, csv_path: str) -> Dict[str, int]:
"""Import media records (files are already in R2)"""
logger.info("\nπ· Importing Media...")
media_map = {}
skipped = 0
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
existing = self.find_existing('media', {'filename': row['filename']})
if existing:
media_map[row['id']] = existing['id']
skipped += 1
continue
media_data = {
'alt': row.get('alt', row['filename']),
'filename': row['filename'],
'mimeType': row.get('type', 'image/jpeg'),
'filesize': int(row.get('filesize', 0)),
'width': int(row.get('width', 0)) if row.get('width') else None,
'height': int(row.get('height', 0)) if row.get('height') else None,
'url': row.get('url', ''),
'thumbnailURL': row.get('thumbnail_url', '')
}
result = self.create_item('media', media_data)
if result:
media_map[row['id']] = result['id']
logger.info(f"β
Media: {row['filename']} β {result['id']}")
logger.info(f"π· Media complete: {len(media_map)} imported, {skipped} skipped")
self.id_maps['media'] = media_map
return media_map
def import_categories(self, csv_path: str) -> Dict[Any, Any]:
"""Import categories"""
logger.info("\nπ Importing Categories...")
cat_map = {}
skipped = 0
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
existing = self.find_existing('categories', {'slug': row['slug']})
if existing:
cat_map[row['id']] = existing['id']
skipped += 1
continue
cat_data = {
'name': unescape(row['name']),
'slug': row['slug']
}
result = self.create_item('categories', cat_data)
if result:
cat_map[row['id']] = result['id']
logger.info(f"β
Category: {row['name']} β {result['id']}")
logger.info(f"π Categories complete: {len(cat_map)} imported, {skipped} skipped")
self.id_maps['categories'] = cat_map
return cat_map
def import_authors(self, csv_path: str) -> Dict[Any, Any]:
"""Import authors"""
logger.info("\nπ€ Importing Authors...")
author_map = {}
skipped = 0
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
existing = self.find_existing('authors', {'slug': row['slug']})
if existing:
author_map[row['id']] = existing['id']
skipped += 1
continue
author_data = {
'name': unescape(row['name']),
'slug': row['slug'],
'status': row.get('status', 'published'),
'linkedinUrl': row.get('linkedin_url', ''),
'legacyDescription': row.get('description', ''),
'profile': self.id_maps['media'].get(row.get('profile')),
'seo': {
'title': row.get('seo_title', ''),
'metaDescription': row.get('seo_meta_description', ''),
'canonicalUrl': row.get('seo_canonical_url', ''),
'noIndex': row.get('seo_no_index', 'false').lower() == 'true',
'noFollow': row.get('seo_no_follow', 'false').lower() == 'true',
'ogImage': self.id_maps['media'].get(row.get('seo_og_image')),
'sitemapChangeFrequency': row.get('seo_sitemap_change_frequency'),
'sitemapPriority': float(row['seo_sitemap_priority']) if row.get('seo_sitemap_priority') else None
}
}
result = self.create_item('authors', author_data)
if result:
author_map[row['id']] = result['id']
logger.info(f"β
Author: {row['name']} β {result['id']}")
logger.info(f"π€ Authors complete: {len(author_map)} imported, {skipped} skipped")
self.id_maps['authors'] = author_map
return author_map
def import_posts(self, csv_path: str, collection_name: str = 'posts') -> Dict[Any, Any]:
"""Import posts or culture posts"""
logger.info(f"\nπ Importing {collection_name}...")
post_map = {}
skipped = 0
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
existing = self.find_existing(collection_name, {'slug': row['slug']})
if existing:
post_map[row['id']] = existing['id']
skipped += 1
continue
# Map categories
categories = []
if 'categories' in row and row['categories']:
try:
directus_cat_ids = json.loads(row['categories'].replace("'", '"'))
categories = [
self.id_maps['categories'][cat_id]
for cat_id in directus_cat_ids
if cat_id in self.id_maps['categories']
]
except:
pass
# Map tags
tags = []
if 'tags' in row and row['tags']:
try:
tag_list = json.loads(row['tags'].replace("'", '"'))
tags = [{'tag': tag} for tag in tag_list]
except:
pass
post_data = {
'title': unescape(row['title']),
'slug': row['slug'],
'status': row.get('status', 'published'),
'publishedAt': row.get('date') or row.get('date_created'),
'excerpt': unescape(row.get('excerpt', '')),
'legacyContent': row.get('content', ''),
'categories': categories,
'tags': tags,
'seo': {
'title': row.get('seo_title', ''),
'metaDescription': row.get('seo_meta_description', ''),
'canonicalUrl': row.get('seo_canonical_url', ''),
'noIndex': row.get('seo_no_index', 'false').lower() == 'true',
'noFollow': row.get('seo_no_follow', 'false').lower() == 'true',
'ogImage': self.id_maps['media'].get(row.get('seo_og_image')),
'sitemapChangeFrequency': row.get('seo_sitemap_change_frequency'),
'sitemapPriority': float(row['seo_sitemap_priority']) if row.get('seo_sitemap_priority') else None
}
}
# Add author for regular posts only
if collection_name == 'posts' and 'author' in row:
post_data['author'] = self.id_maps['authors'].get(row['author'])
result = self.create_item(collection_name, post_data)
if result:
post_map[row['id']] = result['id']
logger.info(f"β
{collection_name[:-1].title()}: {row['title'][:50]}... β {result['id']}")
logger.info(f"π {collection_name.title()} complete: {len(post_map)} imported, {skipped} skipped")
self.id_maps[collection_name] = post_map
return post_map
def import_inquiries(self, csv_path: str) -> None:
"""Import inquiries"""
logger.info("\nπ₯ Importing Inquiries...")
imported = 0
skipped = 0
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
# Check for duplicates
existing = self.find_existing('inquiries', {
'email': row['email'],
'name': row['name']
})
if existing:
skipped += 1
continue
inquiry_data = {
'name': unescape(row['name']),
'email': row['email'],
'phone': row.get('phone', ''),
'company': row.get('company', ''),
'website': row.get('website', ''),
'subject': unescape(row.get('subject', '')),
'message': unescape(row.get('message', '')),
'sourceIp': row.get('source_ip', ''),
'status': row.get('status', 'new')
}
result = self.create_item('inquiries', inquiry_data)
if result:
imported += 1
logger.info(f"π₯ Inquiries complete: {imported} imported, {skipped} skipped")
def run_full_migration(self, data_dir: str = '.') -> None:
"""Run complete migration in correct dependency order"""
data_path = Path(data_dir)
logger.info("π Starting full Payload API migration")
logger.info(f"π Target API: {self.api_url}")
# Migration order matters!
self.import_media(data_path / 'Files 20260408.csv')
self.import_categories(data_path / 'Categories 20260408-1673.csv')
self.import_authors(data_path / 'Author 20260408-16650.csv')
self.import_posts(data_path / 'Posts 20260408-16745.csv', 'posts')
self.import_posts(data_path / 'CulturePosts 20260408-16723.csv', 'culture-posts')
self.import_inquiries(data_path / 'Inquiries 20260408-16737.csv')
logger.info("\nπ MIGRATION COMPLETE!")
logger.info("\nπ Summary:")
for collection, mapping in self.id_maps.items():
logger.info(f" {collection}: {len(mapping)} records")
def main():
parser = argparse.ArgumentParser(description='Migrate Directus data to Payload via REST API')
parser.add_argument('--api-url', required=True, help='Payload API base URL')
parser.add_argument('--email', help='Admin email (for login)')
parser.add_argument('--password', help='Admin password (for login)')
parser.add_argument('--data-dir', default='.', help='Directory containing CSV files')
args = parser.parse_args()
migrator = PayloadMigrator(args.api_url)
if args.email and args.password:
if not migrator.login(args.email, args.password):
sys.exit(1)
else:
logger.warning("β οΈ No credentials provided - API key required for protected collections")
migrator.run_full_migration(args.data_dir)
if __name__ == '__main__':
main()