Files
wticreatorstudio/Modules/StudioPlus/Imports/StudioPlusVideoImport.php
T
2024-02-12 22:54:20 -05:00

282 lines
9.6 KiB
PHP

<?php
namespace Modules\StudioPlus\Imports;
use App\Models\Staff;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Modules\RolePermission\Entities\Role;
use Maatwebsite\Excel\Concerns\ToCollection;
use Modules\StudioPlus\Entities\StudioPlusCategory;
use Modules\StudioPlus\Entities\StudioPlusChannel;
use Modules\StudioPlus\Entities\StudioPlusThumbnail;
use Modules\StudioPlus\Entities\StudioPlusVideo;
use Modules\StudioPlus\Entities\StudioPlusVideoMeta;
use Modules\StudioPlusWtiiabaddon\Entities\StudioPlusAsin;
class StudioPlusVideoImport implements ToCollection
{
public function collection(Collection $rows)
{
try {
DB::beginTransaction();
$columns = [];
$newRows = [];
foreach ($rows as $key => $row) {
if ($key === 0) {
$columns = $row->toArray();
continue;
}
foreach ($columns as $key => $column) {
$newRows[$column] = $row[$key];
}
if (!isset($newRows['Email'])) continue;
//$user = $this->firstOrCreateUserByEmail($newRows['Email'], $newRows['Uname']);
//$channel = $this->firstOrCreateChannelByUser($user);
if (!$this->exists(json_encode($newRows))) {
$channel = $this->getChannel($newRows['Email']);
if ($channel) {
$videoCategory = $this->firstOrCreateCategoryByName($newRows['Category'] ?? '');
$asin = $this->firstOrCreateASIN($newRows['ASIN-$']);
$types = [];
if ($newRows['Sponsored']) {
array_push($types, StudioPlusVideo::TYPE_SPONSORED);
}
if ($newRows['Reach Out']) {
array_push($types, StudioPlusVideo::TYPE_REACH_OUT);
}
$status = StudioPlusVideo::STATUS_INTERNAL_PUBLISHED;
if (str_contains($newRows['Status'], 'Published') && !empty($newRows['URL'])) {
$status = StudioPlusVideo::STATUS_PUBLISHED;
}
else if (str_contains($newRows['Status'], 'Rejected')) {
$status = StudioPlusVideo::STATUS_REJECTED;
}
else if (str_contains($newRows['Status'], 'Review')) {
$status = StudioPlusVideo::STATUS_EDITED;
}
$created_at = Carbon::createFromFormat('M-d-Y H:i:s', $newRows['Created'] . ' ' . Carbon::now()->format('H:i:s'))->format('Y-m-d H:i:s');
$updated_at = Carbon::createFromFormat('M-d-Y H:i:s', $newRows['Edit'] . ' ' . Carbon::now()->format('H:i:s'))->format('Y-m-d H:i:s');
$video = $channel->videos()->updateOrCreate(
[
'studio_plus_category_id' => $videoCategory->id,
'video_url' => $newRows['Video'],
'original_video_url' => $newRows['Video'],
'types' => $types,
'studio_plus_asin_id' => $asin->id,
'asin' => $newRows['ASIN'],
'product_name' => $newRows['Prod'],
'amazon_url' => empty($newRows['URL']) ? NULL : $newRows['URL'],
'created_at' => $created_at,
'updated_at' => $updated_at,
],
[
'status' => $status,
'visibility' => StudioPlusVideo::VISIBILITY_TYPE_PUBLIC,
'title' => $newRows['ASIN'],
'upload_status' => StudioPlusVideo::UPLOAD_STATUS_COMPLETE,
]
);
$this->createThumbnail($video, $newRows['Image']);
StudioPlusVideoMeta::create([
'studioplus_video_id' => $video->id,
'name' => 'is_old',
'value' => 'true'
]);
StudioPlusVideoMeta::create([
'studioplus_video_id' => $video->id,
'name' => 'raw_data',
'value' => json_encode($newRows)
]);
}
else {
Log::info('No channel found');
Log::info($newRows);
$temp_filename = Str::random() . '.dat';
Storage::put("CreatorStudio/temp/import/orphan/$temp_filename", json_encode($newRows));
}
}
else {
Log::info('Video already exists');
Log::info($newRows);
$temp_filename = Str::random() . '.dat';
Storage::put("CreatorStudio/temp/import/duplicates/$temp_filename", json_encode($newRows));
}
}
DB::commit();
} catch (\Exception $ex) {
DB::rollBack();
logger($ex->getMessage());
}
}
private function exists($raw_data)
{
$meta = StudioPlusVideoMeta::where('name', 'raw_data')->where('value', $raw_data)->first();
if ($meta) {
return true;
}
return false;
}
private function getChannel($email)
{
$user = User::where('email', $email)->first();
if (!$user) {
$user = User::find(316);
}
if ($user) {
$channel = StudioPlusChannel::where('user_id', $user->id)->first();
if ($channel) {
return $channel;
}
}
return null;
}
private function firstOrCreateUserByEmail(string $email, string $name): User
{
$explodedName = explode(' ', $name);
$firstName = $explodedName[0];
$lastName = $explodedName[1] ?: '';
$role = $this->getDefaultRole();
$user = User::query()
->firstOrCreate(
[
'email' => $email
],
[
'first_name' => $firstName,
'last_name' => $lastName,
'role_id' => $role->id
]
);
Staff::query()
->firstOrCreate(
[
'user_id' => $user->id
]
);
return $user;
}
private function getDefaultRole(): Role
{
return Role::query()
->where('type', 'staff')
->first();
}
private function firstOrCreateChannelByUser(User $user): StudioPlusChannel
{
return StudioPlusChannel::query()
->firstOrCreate(
[
'user_id' => $user->id
],
[
'name' => Str::random(30)
]
);
}
private function firstOrCreateCategoryByName(string|null $name = ''): StudioPlusCategory
{
return StudioPlusCategory::query()
->firstOrCreate(
[
'name' => $name ?: 'N/A'
],
[
'user_id' => 1
]
);
}
private function firstOrCreateASIN(string|null $asin = null): StudioPlusAsin
{
if (!$asin) {
return StudioPlusAsin::query()
->where('min_range', 0)
->first();
}
if (Str::contains($asin, 'to')) {
$newASIN = explode(' to ', Str::replace('$', '', $asin));
$studioPlusAsin = StudioPlusAsin::query()
->where('min_range', '>=', $newASIN[0])
->where('max_range', '<=', $newASIN[1])
->first();
return $studioPlusAsin
? $studioPlusAsin
: StudioPlusAsin::query()
->where('min_range', 0)
->first();
}
$newASIN = preg_replace('/[^0-9]/i', '', $asin);
$studioPlusAsin = StudioPlusAsin::query()
->where('min_range', $newASIN[0])
->first();
return $studioPlusAsin
? $studioPlusAsin
: StudioPlusAsin::query()
->where('min_range', 0)
->first();
}
private function createThumbnail(StudioPlusVideo $studioPlusVideo, string|null $image = ''): StudioPlusThumbnail | null
{
if (!$image) return null;
$fileName = Str::afterLast($image, '/');
$thumbnailUrl = Str::after($image, 'wticreatorhub/');
return $studioPlusVideo->thumbnails()->create(
[
'filename' => $fileName,
'thumbnail_url' => $thumbnailUrl,
'is_active' => TRUE
]
);
}
}