-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfillNewTable.js
620 lines (587 loc) · 22.2 KB
/
fillNewTable.js
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
'use strict';
const ghost = require('knex')({
client: 'mysql',
connection: {
host: 'localhost',
user: 'root',
password: 'password',
database: 'gazelle_ghost',
charset: 'utf8'
}
});
const wordpress = require('knex')({
client: 'mysql',
connection: {
host: 'localhost',
user: 'root',
password: 'password',
database: 'gazelle_wordpress',
charset: 'utf8'
}
});
const _ = require('lodash');
function disconnect() {
wordpress.destroy();
ghost.destroy();
}
// From ghost/core/server/models/base.js
function slugify (title) {
// Remove URL reserved chars: `:/?#[]@!$&'()*+,;=` as well as `\%<>|^~£"`
let slug = title.replace(/[:\/\?#\[\]@!$&'()*+,;=\\%<>\|\^~£"]/g, '')
.replace(/(\s|\.)/g, '-')
.replace(/-+/g, '-')
.toLowerCase();
slug = slug.charAt(slug.length - 1) === '-' ? slug.substr(0, slug.length - 1) : slug;
slug = /^(ghost|ghost\-admin|admin|wp\-admin|wp\-login|dashboard|logout|login|signin|signup|signout|register|archive|archives|category|categories|tag|tags|page|pages|post|posts|user|users|rss)$/g
.test(slug) ? slug + '-post' : slug;
return slug;
}
// The categories from the wordpress database lazily hardcoded to avoid a bit of code
// Taken by a distinct select of inner join on categories of each post
let categories = [
{name: "Uncategorized", slug: "uncategorized"},
{name: "Features", slug: "features"},
{name: "News", slug: "news"},
{name: "Opinion", slug: "opinion"},
{name: "Creative", slug: "creative"},
{name: "Video", slug: "video"},
{name: "Media", slug: "media"},
{name: "Research", slug: "research"},
]
// Use the choiceFlag to choose which table to insert
// The available choiceFlags are:
// cat
// meta
// issue
// author
// authors_posts
// order
const choiceFlag = "order";
// We will let teams table start out empty and editor's can handle it themselves
if (choiceFlag === "cat") {
// Fill categories table
ghost('categories').insert(categories).then(() => {}).then(() => {
disconnect();
});
}
else if (choiceFlag === "meta") {
// Fill posts_meta table
const manuallyEditedSlugs = ['iran', 'iran2', 'gabo', 'gabo2', 'welcome-to-ghost'];
const categorySlugToId = {};
categories.forEach((val, index) => {
categorySlugToId[val.slug] = index+1;
});
console.log(JSON.stringify(categorySlugToId, null, 4));
wordpress.select('post_name', 'post_title', 'meta_value')
.from('wp_posts')
.leftJoin('wp_postmeta', 'wp_posts.ID', '=', 'wp_postmeta.post_id')
.whereIn('post_status', ['draft', 'publish']).andWhere('post_type', '=', 'post').andWhere('wp_postmeta.meta_key', '=', 'gazelle_views_count')
.then((wordpressRowsViews) => {
wordpress.select('post_name', 'post_title', 'slug')
.from('wp_posts')
.leftJoin('wp_term_relationships', 'wp_term_relationships.object_id', '=', 'wp_posts.ID')
.leftJoin('wp_term_taxonomy', 'wp_term_taxonomy.term_taxonomy_id', '=', 'wp_term_relationships.term_taxonomy_id')
.leftJoin('wp_terms', 'wp_terms.term_id', '=', 'wp_term_taxonomy.term_id')
.whereIn('post_status', ['draft', 'publish']).andWhere('post_type', '=', 'post').andWhere('wp_term_taxonomy.taxonomy', '=', 'category')
.then((wordpressRowsCategory) => {
ghost.select('id', 'published_at', 'slug', 'status')
.from('posts')
.whereNotIn('slug', manuallyEditedSlugs)
.then((ghostRows) => {
const insertArray = [];
ghostRows.forEach((ghostRow) => {
const insertObject = {};
insertObject.id = ghostRow.id;
insertObject.description = null;
if (ghostRow.status === "published") {
insertObject["gazelle_published_at"] = ghostRow["published_at"];
}
else if (ghostRow.status === "draft") {
insertObject["gazelle_published_at"] = null;
}
else {
console.log("unexpected publish date event");
insertObject["gazelle_published_at"] = null;
}
// adding category
const categoryRows = wordpressRowsCategory.filter((wordpressRow) => {
let wordpressSlug = wordpressRow.post_name || slugify(wordpressRow.post_title);
if (wordpressSlug === ghostRow.slug) {
return true;
}
return false;
});
let categoryId;
if (categoryRows.length === 0) {
console.log(ghostRow.slug + " had no category");
categoryId = categorySlugToId["uncategorized"];
}
else if (categoryRows.length === 1) {
if (categorySlugToId[categoryRows[0].slug]) {
categoryId = categorySlugToId[categoryRows[0].slug];
}
else {
console.log("slug made uncategorized from: " + categoryRows[0].slug);
}
}
else if (categoryRows.length === 2) {
const filtered = categoryRows.filter((row) => {
if (row.slug === "uncategorized") {
return false;
}
return true;
});
if (filtered.length === 1 && categorySlugToId[filtered[0].slug]) {
categoryId = categorySlugToId[filtered[0].slug];
}
else if (categoryRows[0].slug === categoryRows[1].slug) {
categoryId = categorySlugToId[categoryRows[0].slug];
}
else {
switch(ghostRow.slug) {
case "arts-capstones":
categoryId = categorySlugToId["creative"];
break;
case "australianz":
case "film-race":
case "foreign-correspondent-clare":
case "student-government-elections-meet-the-candidates":
categoryId = categorySlugToId["news"];
break;
case "global-celebrations":
case "pearl-cultivation-rak":
categoryId = categorySlugToId["features"];
break;
case "open-campus":
categoryId = categorySlugToId["video"];
break;
default:
console.log("2 categories but not as expected");
console.log(categoryRows[0].slug, categoryRows[1].slug);
console.log(ghostRow.slug);
categoryId = categorySlugToId["uncategorized"];
}
}
}
else {
console.log("unexpected more than 2 categories for an article")
categoryId = categorySlugToId["uncategorized"];
}
if (!categoryId || categoryId < 1 || categoryId > 9) {
console.log(categoryId);
}
if (!categoryId || !(typeof categoryId) === "number") {
console.log("one slipped through somehow: " + ghostRow.slug);
categoryId = categorySlugToId["uncategorized"];
}
insertObject["category_id"] = categoryId;
// Adding views
const viewRows = wordpressRowsViews.filter((wordpressRow) => {
let wordpressSlug = wordpressRow.post_name || slugify(wordpressRow.post_title);
if (wordpressSlug === ghostRow.slug) {
return true;
}
return false;
});
let views;
if (viewRows.length === 0) {
views = 0;
}
else if (viewRows.length === 1) {
views = viewRows[0]["meta_value"]
}
else {
console.log(ghostRow.slug, "had more than 1 view data");
views = 0;
}
insertObject["views"] = views;
// push object to array
insertArray.push(insertObject);
});
// Hardcode a few special values
insertArray.push(
{
id: 699,
description: null,
"gazelle_published_at": "2015-04-04 14:02:08",
"category_id": categorySlugToId.news,
views: 0,
},
{
id: 697,
description: null,
"gazelle_published_at": "2015-04-11 12:41:31",
"category_id": categorySlugToId.features,
views: 0,
},
{
id: 549,
description: null,
"gazelle_published_at": "2015-05-02 13:10:05",
"category_id": categorySlugToId.news,
views: 0,
},
{
id: 548,
description: null,
"gazelle_published_at": "2015-05-09 14:00:48",
"category_id": categorySlugToId.features,
views: 0,
},
{
// The Welcome-To-Ghost post
id: 1,
description: null,
"gazelle_published_at": null,
"category_id": categorySlugToId.uncategorized,
views: 0,
}
);
ghost('posts_meta').insert(insertArray).then(() => {
disconnect();
console.log("success");
}).catch((err) => {
disconnect();
console.error(err);
})
});
});
});
}
else if (choiceFlag === "author") {
// Insert authors table
wordpress.distinct().select('name', 'slug')
.from('wp_posts')
.innerJoin('wp_term_relationships', 'wp_term_relationships.object_id', '=', 'wp_posts.ID')
.innerJoin('wp_term_taxonomy', 'wp_term_taxonomy.term_taxonomy_id', '=', 'wp_term_relationships.term_taxonomy_id')
.innerJoin('wp_terms', 'wp_terms.term_id', '=', 'wp_term_taxonomy.term_id')
.whereIn('post_status', ['draft', 'publish']).andWhere('post_type', '=', 'post').andWhere('wp_term_taxonomy.taxonomy', '=', 'author')
.then((authorRows) => {
authorRows.map((row) => {
if (row.slug.substring(0, 4) === "cap-") {
row.slug = row.slug.substring(4, row.slug.length)
}
return row;
})
console.log("Filtered authors:")
authorRows = authorRows.filter((row) => {
if (row.slug.search(/\d/) !== -1 || row.name.search(/\d/) !== -1) {
console.log("Slug:", row.slug, "Name:", row.name);
return false;
}
return true;
});
// Other than name and slug will simply be nulled as we don't have the other information in database
ghost('authors')
.insert(authorRows)
.then(disconnect);
});
}
else if (choiceFlag === "issue") {
// Insert issues table
wordpress.distinct().select('name', 'slug')
.from('wp_posts')
.innerJoin('wp_term_relationships', 'wp_term_relationships.object_id', '=', 'wp_posts.ID')
.innerJoin('wp_term_taxonomy', 'wp_term_taxonomy.term_taxonomy_id', '=', 'wp_term_relationships.term_taxonomy_id')
.innerJoin('wp_terms', 'wp_terms.term_id', '=', 'wp_term_taxonomy.term_id')
.whereIn('post_status', ['draft', 'publish']).andWhere('post_type', '=', 'post').andWhere('wp_term_taxonomy.taxonomy', '=', 'issue')
.then((issues) => {
wordpress.distinct().select('name', 'slug', 'post_date', 'post_date_gmt')
.from('wp_posts')
.innerJoin('wp_term_relationships', 'wp_term_relationships.object_id', '=', 'wp_posts.ID')
.innerJoin('wp_term_taxonomy', 'wp_term_taxonomy.term_taxonomy_id', '=', 'wp_term_relationships.term_taxonomy_id')
.innerJoin('wp_terms', 'wp_terms.term_id', '=', 'wp_term_taxonomy.term_id')
.whereIn('post_status', ['draft', 'publish']).andWhere('post_type', '=', 'post').andWhere('wp_term_taxonomy.taxonomy', '=', 'issue')
.then((wordpressDataRows) => {
const insertArray = issues.map((issue, index) => {
const posts = wordpressDataRows.filter((dataRow) => {
if (issue.name === dataRow.name && issue.slug === dataRow.slug) {
return true;
}
return false;
});
const dateCount = {};
posts.forEach((post) => {
let date = new Date(post["post_date_gmt"]);
if (!date.getTime()) {
date = new Date(post["post_date"])
}
let dateString = date.getFullYear().toString();
let month = date.getMonth()+1;
if (month < 10) {
dateString += "-0" + month.toString();
}
else {
dateString += "-" + month.toString();
}
let day = date.getDate();
if (day < 10) {
dateString += "-0" + day.toString();
}
else {
dateString += "-" + day.toString();
}
if (dateCount.hasOwnProperty(dateString)) {
dateCount[dateString]++;
}
else {
dateCount[dateString] = 1;
}
});
let publishDate;
let maxCount = -1;
_.forEach(dateCount, (val, key) => {
if (val > maxCount) {
publishDate = key;
maxCount = val;
}
});
if (maxCount === -1) {
throw new Error("There were no posts in the issue: " + issue.name);
}
let name = issue.name;
// Not using slug anymore, we switched to using issue_order, but I'll just keep it here
// let slug = slugify(issue.name);
// Assuming the issues are fetched chronologically by the select statement
// Because this is also what it seemed like.
// Remember to also double check that everything is correct in the database though.
let order = index+1;
return {
name: name,
issue_order: order,
published_at: publishDate,
};
});
ghost('issues').insert(insertArray)
.then(disconnect);
});
});
}
else if (choiceFlag === "authors_posts") {
// Insert authors_posts table
function normalizeAuthor(slug) {
if (slug.substring(0, 4) === "cap-") {
slug = slug.substring(4, slug.length)
}
// Got this from logging the filtered authors
if (slug === "amanda-randone2") {
slug = "amanda-randone";
}
if (slug === "kate-melville-rea-2") {
slug = "kate-melville-rea";
}
return slug;
}
wordpress.select('slug', 'post_name', 'post_title', 'post_content')
.from('wp_posts')
.innerJoin('wp_term_relationships', 'wp_term_relationships.object_id', '=', 'wp_posts.ID')
.innerJoin('wp_term_taxonomy', 'wp_term_taxonomy.term_taxonomy_id', '=', 'wp_term_relationships.term_taxonomy_id')
.innerJoin('wp_terms', 'wp_terms.term_id', '=', 'wp_term_taxonomy.term_id')
.whereIn('post_status', ['draft', 'publish']).andWhere('post_type', '=', 'post').andWhere('wp_term_taxonomy.taxonomy', '=', 'author')
.then((wordpressPosts) => {
ghost.select('id', 'slug')
.from('posts')
.then((ghostPosts) => {
ghost.select('id', 'slug')
.from('authors')
.then((ghostAuthors) => {
wordpressPosts = wordpressPosts.filter((post) => {
if (!post.post_name && !post.post_title) {
return false;
}
if (!post.post_content) {
return false;
}
return true;
});
const insertArray = wordpressPosts.map((wpPost) => {
let wordpressPostSlug = wpPost.post_name || slugify(wpPost.post_title);
let wordpressAuthorSlug = normalizeAuthor(wpPost.slug);
let ghostPostId = ghostPosts.find((post) => {
return wordpressPostSlug === post.slug;
});
if (ghostPostId === undefined) {
console.log("post");
console.log(wordpressPostSlug, "is undefined");
}
else {
ghostPostId = ghostPostId.id;
}
let ghostAuthorId = ghostAuthors.find((author) => {
return wordpressAuthorSlug === author.slug;
});
if (ghostAuthorId === undefined) {
console.log("author");
console.log(wordpressAuthorSlug, "is undefined");
}
else {
ghostAuthorId = ghostAuthorId.id;
}
return {
author_id: ghostAuthorId,
post_id: ghostPostId,
};
});
ghost('authors_posts').insert(insertArray)
.then(() => {
console.log("success");
})
.then(disconnect());
});
});
});
}
else if (choiceFlag === "order") {
// Insert categories_order and posts_order table
wordpress.select('name', 'post_name', 'post_title')
.from('wp_posts')
.innerJoin('wp_term_relationships', 'wp_term_relationships.object_id', '=', 'wp_posts.ID')
.innerJoin('wp_term_taxonomy', 'wp_term_taxonomy.term_taxonomy_id', '=', 'wp_term_relationships.term_taxonomy_id')
.innerJoin('wp_terms', 'wp_terms.term_id', '=', 'wp_term_taxonomy.term_id')
.whereIn('post_status', ['draft', 'publish']).andWhere('post_type', '=', 'post').andWhere('wp_term_taxonomy.taxonomy', '=', 'issue')
.then((posts_issues) => {
wordpress.select('post_name', 'post_title')
.from('wp_posts')
.innerJoin('wp_term_relationships', 'wp_term_relationships.object_id', '=', 'wp_posts.ID')
.innerJoin('wp_term_taxonomy', 'wp_term_taxonomy.term_taxonomy_id', '=', 'wp_term_relationships.term_taxonomy_id')
.innerJoin('wp_terms', 'wp_terms.term_id', '=', 'wp_term_taxonomy.term_id')
.whereIn('post_status', ['draft', 'publish']).andWhere('post_type', '=', 'post').andWhere('wp_term_taxonomy.taxonomy', '=', 'post_tag')
.andWhere('wp_terms.slug', '=', 'pick').andWhere('name', '=', 'pick')
.then((posts_picks) => {
ghost.select('slug', 'category_id', 'posts.id')
.from('posts')
.innerJoin('posts_meta', 'posts_meta.id', '=', 'posts.id')
.whereNotNull('gazelle_published_at')
.then((posts_categories) => {
ghost.select('name', 'id')
.from('issues')
.then((issues) => {
const issues_categoriesInsert = [];
const issues_postsInsert = [];
const postsToDelete = [];
issues.forEach((issue) => {
const posts = posts_categories.filter((ghostPost) => {
const wpPost = posts_issues.find((wordpressPost) => {
const wordpressPostSlug = wordpressPost.post_name || slugify(wordpressPost.post_title);
return wordpressPostSlug === ghostPost.slug;
});
if (wpPost === undefined) {
if (postsToDelete.find((post) => {return post.id === ghostPost.id}) === undefined) {
postsToDelete.push(ghostPost);
}
return false;
}
// wpPost.name is the name of the issue
return wpPost.name === issue.name;
});
// console.log("posts in issue:", posts.length);
const picks = [];
// Get the first 3 picked articles and ignore rest
// Delete them from posts array and put them in picks
posts.filter((post) => {
if (picks.length === 3) {
return true;
}
const postIsPick = posts_picks.find((pickPost) => {
const wordpressPostSlug = pickPost.post_name || slugify(pickPost.post_title);
return wordpressPostSlug === post.slug;
}) !== undefined;
if (postIsPick) {
picks.push(post);
return false;
}
return true;
});
const categories = [];
posts.forEach((post) => {
if (categories.find((catId) => {return catId === post.category_id}) === undefined) {
categories.push(post.category_id);
}
});
// console.log(categories.length);
const postsByCategory = {};
categories.forEach((catId) => {
postsByCategory[catId] = [];
posts.forEach((post) => {
if (post.category_id === catId) {
postsByCategory[catId].push(post);
}
})
})
// fill issues_categoriesInsert
categories.forEach((catId, index) => {
issues_categoriesInsert.push({
issue_id: issue.id,
category_id: catId,
categories_order: index,
});
});
// fill issues_postsInsert
if (picks.length !== 3) {
console.log(JSON.stringify(picks, null, 4));
throw new Error("not 3 picks");
}
// type 1 is featured
issues_postsInsert.push({
issue_id: issue.id,
type: 1,
post_id: picks[0].id,
posts_order: 0,
});
// type 2 is editor's pick
issues_postsInsert.push({
issue_id: issue.id,
type: 2,
post_id: picks[1].id,
posts_order: 0,
});
issues_postsInsert.push({
issue_id: issue.id,
type: 2,
post_id: picks[2].id,
posts_order: 1,
});
_.forEach(postsByCategory, (category) => {
category.forEach((post, index) => {
issues_postsInsert.push({
issue_id: issue.id,
type: 0,
post_id: post.id,
posts_order: index,
});
});
});
});
const idsToDelete = postsToDelete.map((post) => {return post.id});
console.log("Posts to be deleted because they have no issue");
console.log(postsToDelete.length);
console.log(JSON.stringify(postsToDelete, null, 4));
// console.log("data");
// console.log(JSON.stringify(issues_categoriesInsert, null, 4));
// console.log("data2\n\n\n\n");
// console.log(JSON.stringify(issues_postsInsert, null, 4));
// Delete the posts that need to be deleted
ghost('posts_meta').whereIn('id', idsToDelete).del()
.then(() => {
ghost('authors_posts').whereIn('post_id', idsToDelete).del()
.then(() => {
ghost('posts').whereIn('id', idsToDelete).del()
.then(() => {
// Insert orders
ghost('issues_posts_order').insert(issues_postsInsert)
.then(() => {
ghost('issues_categories_order').insert(issues_categoriesInsert)
.then(() => {console.log("success")})
.then(disconnect());
});
});
});
});
});
});
});
});
}
else {
throw new Error("Incorrect choiceFlag input")
}