UserSyncIMJob.php 2.02 KB
<?php

namespace App\Jobs;

use App\Helpers\IMHelper;
use App\Models\User;
use App\Models\UserTag;
use App\Support\JsonAttributeCast;
use App\Support\Model;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class UserSyncIMJob implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public User $user;

    public int $tries = 3;

    /**
     * @param \App\Models\User $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function uniqueId(): string
    {
        return 'updateIm:' . $this->user->getKey();
    }


    /**
     * @throws \Exception
     */
    public function handle(): void
    {
        $result = IMHelper::updateSingleAccountInfo($this->user->getKey(), [
            ['Tag' => 'Tag_Profile_IM_Image', 'Value' => $this->user->getAttribute('avatar')],
            ['Tag' => 'Tag_Profile_IM_Nick', 'Value' => json_encode([
                'chat_mode' => $this->user->getAttribute('chat_mode'),
                'nickName'  => $this->user->getAttribute('nick_name'),
                'identity'  => $this->user->getAttribute('identity'),
                'userTag'   => $this->getUserTag(),
            ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)]
        ]);

        if ($result->json('ActionStatus') !== 'OK') {
            $this->release(1);
            Log::warning(__CLASS__, ['key' => $this->user->getKey(), 'result' => $result->json()]);
        }
    }

    /**
     * @return \App\Support\Model|null
     */
    protected function getUserTag(): ?Model
    {
        return UserTag::withCasts(['frame' => JsonAttributeCast::class])
            ->whereKey($this->user->getAttribute('user_tag_id'))
            ->where('status', 1)
            ->first(['id', 'name', 'icon', 'frame']);
    }
}