Post-Migrator/services/migration/migrate-categories.go

101 lines
2.8 KiB
Go

package migration
import (
"database/sql"
"federated.computer/wp-sync-slowtwitch/services/slowtwitch"
"federated.computer/wp-sync-slowtwitch/services/wordpress"
"fmt"
"strings"
)
type MigrateCategories struct {
SlowtwitchDatabase *sql.DB
ResultsDatabase *sql.DB
WordpressBaseUrl string
WordpressUser string
WordpressPassword string
}
func (migration *MigrateCategories) Execute() []CategoryResult {
categories := slowtwitch.GetCategories(migration.SlowtwitchDatabase)
var output []CategoryResult
for _, category := range categories {
hasBeenMigrated := HasBeenMigrated(category.Id, migration.ResultsDatabase)
if hasBeenMigrated {
fmt.Println("This category has already been migrated.")
continue
}
errorMessage := ""
//Get wordpress parent if exists
wordpressParentId, err := getWordpressParentCategoryId(category, migration, errorMessage)
if err != nil {
errorMessage = errorMessage + err.Error()
err = nil
}
//convert url for redirect
slowtwitchPath := slowtwitch.ConvertUrlToCategoryFormat(category.FullName)
slowtwitchUrl := slowtwitch.GetURL(slowtwitchPath)
httpStatus := slowtwitch.GetPageStatus(slowtwitchUrl)
//create in wp
createWordpressCategory := wordpress.CreateCategory{
Name: strings.Trim(category.Name, " "),
Description: "",
ParentId: wordpressParentId,
}
wordpressCategory := createWordpressCategory.Execute(migration.WordpressBaseUrl, migration.WordpressUser, migration.WordpressPassword)
//submit redirect
createRedirect := wordpress.CreateRedirect{
Url: slowtwitchPath,
Title: "Category: " + wordpressCategory.Name,
MatchType: "page",
ActionType: "url",
ActionCode: 301,
GroupId: 1,
ActionData: wordpress.ActionData{
Url: wordpressCategory.Slug,
},
}
_, err = createRedirect.Execute(migration.WordpressBaseUrl, migration.WordpressUser, migration.WordpressPassword)
if err != nil {
errorMessage = errorMessage + err.Error()
err = nil
}
//submit results
overallResult := CategoryResult{
WordpressId: wordpressCategory.Id,
SlowtwitchId: category.Id,
OldUrl: slowtwitchUrl,
OldUrlStatus: httpStatus,
NewUrl: wordpressCategory.Link,
IsSuccess: true,
ErrorMessage: errorMessage,
}
err = CreateCategoryResult(overallResult, migration.ResultsDatabase)
if err != nil {
fmt.Println(err)
err = nil
}
output = append(output, overallResult)
}
return output
}
func getWordpressParentCategoryId(category slowtwitch.SlowtwitchCategory, migration *MigrateCategories, errorMessage string) (int, error) {
if category.FatherId != 0 {
parentCategory, err := GetSlowtwitchCategoryResult(category.FatherId, migration.ResultsDatabase)
if err != nil {
return 0, err
} else {
return parentCategory.WordpressId, nil
}
}
return 0, nil
}