| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293 | <?php/** * Created by PhpStorm. * User: Administrator * Date: 2019/4/18 0018 * Time: 16:27 */namespace App\Http\Logics\Admin;use App\Http\Models\Article;use App\Http\Models\ArticleSiteKeep;use App\Http\Models\SiteInfo;use App\Jobs\TranArticle;use App\Libs\Ssh;use App\Libs\Translate;use DirkGroenen\Pinterest\Pinterest;use Illuminate\Database\Eloquent\Collection;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Log;use GuzzleHttp\Client;use GuzzleHttp\Pool;use GuzzleHttp\Psr7\Response;use Lightit\LinkedinShare\Facades\LinkedinShare;class ArticleLogic{    public function amountRule($words)    {        return round(($words / 300) * 10, 2);    }    public function autoTranslate(Collection $articles)    {        $translate = new Translate;        $successNum = 0;        foreach ($articles as $item) {            $content = html_entity_decode(strip_tags($item->content));            $result = json_decode($translate->request($content), true);            if (empty($result['translation'][0])) {                Log::info(var_export($result, 1));                continue;            }            $item->translate_content = $result['translation'][0];            $item->save();            $successNum++;        }        return response()->json(['message' => $successNum . '篇翻译完成']);    }    public function save($validated, $id)    {        $validated['status'] = Article::STATUS_PENDING; //默认待翻译        if (!empty($validated['translator_id'])) {            if ($validated['translator_id'] == Article::INSIDER) { //如果是内部人员yingyingli                $validated['status'] = Article::STATUS_PASSED; //已通过            } elseif ($validated['translator_id'] == Article::IS_EXPIRED) {                $validated['expired_at'] = date('Y-m-d H:i:s', strtotime('+20 year'));                $validated['status'] = Article::STATUS_TRANSLATING; //翻译中            } else {                $validated['expired_at'] = date('Y-m-d H:i:s', strtotime('+1 day'));                $validated['status'] = Article::STATUS_TRANSLATING; //翻译中            }        }        if ($id > 0) { //编辑            $article = Article::query()->where(['id' => $id])->first();            if (!$article) return response()->json(['message' => '数据不存在']);            $article->update($validated);        } else { //添加//            $client = new Client;//            $response = $client->post('http://translate.api.yinqingli.net/translate/translate', [//                'form_params' => [//                    'q' => $validated['content'],//                    'source' => 'zh-CN',//                    'target' => 'en'//                ],//                'timeout' => 0//            ]);//            $result = json_decode($response->getBody()->getContents(), true);////            $validated['translate_content'] = $result['data']['translations'][0]['translatedText'] ?? '';//            $validated['translate_words'] = !empty($validated['translate_content']) ? word_count($validated['translate_content']) : 0;            $translate = new Translate;            $result = json_decode($translate->request($validated['title']), true);            if (!empty($result['translation'][0])) {                $validated['translate_title'] = $result['translation'][0];                $validated['init_tran_title'] = $validated['translate_title'];            }            $validated['creator_id'] = Auth::id();            $article = Article::query()->create($validated);            TranArticle::dispatch($article->id, $validated['content'])->onQueue('translate');        }        ArticleSiteKeep::query()->where(['user_id' => Auth::id()])->update(['site_id' => $article->id ?? 0]);        return response()->json(['message' => '操作成功']);    }    protected function sendImage($targetBaseDir, $fullSrc)    {        $path = substr($fullSrc, 1);        $originTruePath = public_path($path);        if (file_exists($originTruePath)) {            $targetTruePath = $targetBaseDir . $path;            Ssh::mkdir(dirname($targetTruePath));            try {                Ssh::send($originTruePath, $targetTruePath);            } catch (\Throwable $throwable) {                Log::alert(var_export($throwable->getMessage(), 1));            }        }    }    public function sync($validated, $site, $server)    {        $articles = Article::query()->whereIn('id', $validated['article_ids'])->get();        $siteInfo = SiteInfo::query()->select(['is_upload_thumb'])->where(['site_id' => $site->id])->first();        if (!empty($siteInfo->is_upload_thumb)) {            $failList = [];            foreach ($articles as $ac) {                if (empty($ac->thumb)) {                    $failList[] = $ac->cn_title;                }            }            if ($failList) {                return response()->json(['message' => '站点设置缩略图 不能为空' . implode("|", $failList)], 400);            }        }        try {            Ssh::factory($server->server_ip, $server->server_user_name, $server->server_passwd);        } catch (\Throwable $throwable) {            Log::alert(var_export($throwable->getMessage(), 1));            return response()->json(['message' => '用户名密码验证失败'], 400);        }        $targetBaseDir = $site->code_dir ? sprintf('%s/wwwroot/', $site->code_dir)            : sprintf('/repo/%s/wwwroot/', $site->domain);        Log::info($targetBaseDir);        if (!Ssh::dir_exists($targetBaseDir)) {            return response()->json(['message' => '站点服务器目录不存在'], 400);        }        $requestData = [];        $articles->each(function ($article, $inx) use ($validated, $targetBaseDir, &$requestData) {            //<img src="http://build.cn/storage/uploads/image/2019/05/29/26cf238774423b482241baf35e39b774.jpg" >            if (strpos($article->translate_content, '<img') !== false) {                preg_match_all('/<img.*?src="(.*?)".*?>/i', $article->translate_content, $matches);                $imgList = [];                array_walk($matches[1], function ($val) use (&$imgList) {                    $imgList[] = $val;                });                array_walk($imgList, function ($fullSrc) use ($targetBaseDir) {                    $this->sendImage($targetBaseDir, $fullSrc);                });            }            //http://build.cn/storage/201905/jpg/VnhVz2B4eigmihZo6AKb7MMz8F5TM9EF9A1sswVe.jpeg            if ($article->thumb) {                $this->sendImage($targetBaseDir, $article->thumb);            }            $publishTime = strtotime('+' . ($validated['release_interval'] * $inx) . ' day', strtotime($validated['release_at']));            $requestData[$inx]['form_params'] = [                'lang' => 'en',//                'thumb' => preg_replace(sprintf('/%s/i', $url), '', $article->thumb),                'thumb' => $article->thumb,                'parent_id' => $validated['remote_content_id'],                'tpl_id' => $validated['template_id'],                'title' => htmlspecialchars($article->translate_title),                'uri' => $article->translate_title2,                'is_freeze_url' => 1,//                'content' => preg_replace_callback(sprintf('/(src=.)%s/i', $url), function ($matches) {//                    return $matches[1];//                }, $article->content),//                'content' => preg_replace_callback(sprintf('/(src=.)%s/i', $url), function ($matches) {//                    return $matches[1];//                }, $article->content),                'content' => $article->translate_content,                'is_enabled' => 1,                'publish_time' => $publishTime            ];            /** @var \App\Http\Models\Article $article * */            $article->update([                'sync_at' => date('Y-m-d H:i:s'),                'publish_at' => date('Y-m-d H:i:s', $publishTime)            ]);        });        $this->concurrentRequest($requestData, $site->api_url, $articles);//        Article::query()->whereIn('id', $validated['article_ids'])->update(['sync_at' => date('Y-m-d H:i:s')]);        return response()->json(['message' => '操作成功']);    }    protected function concurrentRequest($requestData, $apiUrl, Collection $articles)    {        $client = new Client([            'verify' => false,            'timeout' => 10        ]); //并发请求链接地址        $requests = function () use ($client, $requestData, $apiUrl) {            foreach ($requestData as $item) {                if (empty($item))                    continue;                yield new \GuzzleHttp\Psr7\Request(                    'POST',                    ($apiUrl . 'content/sync'),                    ['Content-type' => 'application/x-www-form-urlencoded'],                    http_build_query($item['form_params'])                );            }        };        $results = [];        $pool = new Pool($client, $requests(), [            'concurrency' => 5, //同时并发抓取几个            'fulfilled' => function (Response $response, $index) use (&$results) {                $content = $response->getBody()->getContents();                $content = trim($content, "\xEF\xBB\xBF");                $ret = json_decode($content, true);                if (!empty($ret['id'])) {                    $results[$index] = $ret['id'];                }            },            'rejected' => function (\Throwable $throwable, $index) {                Log::error(var_export($throwable->getMessage(), 1));            },        ]);        $promise = $pool->promise();        $promise->wait();        foreach ($articles as $key => $article) {            foreach ($results as $inx => $val) {                if ($key == $inx) {                    $article->update(['remote_content_id' => $val]);                    break;                }            }        }    }    public function pin()    {        $pin = new Pinterest(config('services.pinterest.client_id'), config('services.pinterest.client_secret'));        $pin->auth->setOAuthToken('AsityC1Rl6-kSqfwD98akYNaj5gxFatL7qHFJjNF8JCvpODAwAu6ADAAAUegRfKs6higoeEAAAAA');        try {            $pin->pins->create([                "note" => "Test board from API",                "image_url" => "http://admin.yinqingli.com/storage/201906/jpg/1Q987Ryl6mdPFhJljhy5O1EhPol9M79dSVFbGnod.jpeg",                "board" => "hinaqin/api-demo"            ]);        } catch (\Throwable $throwable) {            Log::warning(var_export($throwable->getMessage(), 1));            return false;        }        return true;    }    public function linkedIn($content)    {        $text = str_replace('<br/>', PHP_EOL, html_entity_decode(strip_tags($content, '<br/>')));//        $text = $content;        $token = 'AQUOiNxK2Fn0fEwbqCzeo26xT-CFp_DO57GJ1Hqf9XoD1zezGa1knRuENJyu7RtJTjQhSS3UZ_winzcHsxHxm_nWE0pJUclmN21BMsTmiYnqA_i2mjo8l26ZjZ0Y0Qn2umh0aGqt5XGVw9_YY5HkHmy_5JUjGQb7SMpdEO1mobEyb9CK0L5-jPcLAfmwLDRrap3KeeOIdu3i8EgPKzJG8dNqmcsbHuA1Gnq3WX1kXtBtKmnd1KzPxGbQSK9-V_txzz3VhdsRs6CFqoZrWdZjcxngkN26etQg6cG58Il1f7W7PVS8SKjpyC6rzIAEN9ee00dp3EvyfckcJDZTtYbojr-HUnmw_Q';        try {            LinkedinShare::shareTemp($token, 'http://admin.yinqingli.com/storage/201906/jpg/1Q987Ryl6mdPFhJljhy5O1EhPol9M79dSVFbGnod.jpeg', $text, 'accessToken');        } catch (\Throwable $throwable) {            Log::warning(var_export($throwable->getMessage(), 1));            return false;        }        return true;    }}
 |