M1: 数据模型 + sablog:import 脚本(MySQL 8 验证通过,不迁移 trackback 等过时功能)

This commit is contained in:
ak
2026-08-11 17:40:13 +08:00
parent 8d526a8cfd
commit f16bb75538
17 changed files with 1010 additions and 13 deletions
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Blog\Services;
use App\Models\Post;
use App\Support\MediaDisk;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
class AttachmentImporter
{
/**
* 将一条 sablog 附件记录写入媒体库。
*
* @param array{attachmentid:int,articleid:int,dateline:int,filename:string,filetype:string,filesize:int,downloads:int,filepath:string,thumb_filepath:string,thumb_width:int,thumb_height:int,isimage:int} $row
*/
public function create(int $postId, array $row, ?string $attachmentsDir, bool $syncNow): Media
{
$post = Post::find($postId);
// 游离附件(articleid=0 或对应文章不存在)统一挂到 id=0 占位文章上
if (! $post) {
$post = new Post(['id' => 0]);
}
$properties = [
'downloads' => (int) ($row['downloads'] ?? 0),
'isimage' => (bool) ($row['isimage'] ?? false),
'legacy_filepath' => $row['filepath'] ?? null,
'legacy_thumb' => $row['thumb_filepath'] ?? null,
'legacy_articleid' => (int) ($row['articleid'] ?? 0),
'pending_sync' => true,
];
$source = $this->locateSource($row['filepath'] ?? null, $attachmentsDir);
if ($source && $syncNow) {
$media = $post->addMedia($source)
->preservingOriginal()
->withCustomProperties($properties)
->usingFileName(basename($row['filename']) ?: basename($source))
->toMediaCollection('attachments', MediaDisk::name());
$media->setCustomProperty('pending_sync', false);
$media->save();
return $media;
}
return $this->createPendingRecord($post->id, $row, $properties);
}
private function locateSource(?string $filepath, ?string $attachmentsDir): ?string
{
if (! $attachmentsDir || ! $filepath) {
return null;
}
$candidate = rtrim($attachmentsDir, '/').'/'.ltrim($filepath, '/');
return is_file($candidate) ? $candidate : null;
}
private function createPendingRecord(int $postId, array $row, array $properties): Media
{
$disk = MediaDisk::name();
$media = new Media;
$media->model_type = Post::class;
$media->model_id = $postId;
$media->uuid = (string) Str::uuid();
$media->collection_name = 'attachments';
$media->name = pathinfo($row['filename'] ?? 'attachment', PATHINFO_FILENAME) ?: 'attachment';
$media->file_name = $row['filename'] ?: basename($row['filepath'] ?? 'attachment.bin');
$media->mime_type = $row['filetype'] ?: null;
$media->size = (int) ($row['filesize'] ?? 0);
$media->disk = $disk;
$media->conversions_disk = $disk;
$media->manipulations = [];
$media->custom_properties = $properties;
$media->generated_conversions = [];
$media->responsive_images = [];
$media->save();
return $media;
}
}