VideoTask.php
13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
<?php
/**
* Created by PhpStorm.
* User: zhl
* Date: 2024/02/26
* Time: 10:13
*/
namespace App\Console\Commands\KeywordInVideo;
use App\Console\Commands\Model;
use App\Console\Commands\TaskSub;
use App\Models\Com\KeywordVideoTask;
use App\Models\Com\KeywordVideoTaskLog;
use App\Models\Domain\DomainInfo;
use App\Models\Product\Keyword;
use App\Models\Product\KeywordRelated;
use App\Models\Product\Product;
use App\Services\ProjectServer;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class VideoTask extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'video_task';
/**
* The console command description.
*
* @var string
*/
protected $description = '视频推广任务';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* @var int 最大子任务
*/
public $max_sub_task = 200;
public $max_num = 49000;
/**
* @return bool
*/
public function handle()
{
Log::info('开始视频推广任务');
$number = KeywordVideoTaskLog::getMonthVideoNum();
if($number >= $this->max_num){
Log::info('当月以达到最大视频生成数,任务执行数:' . $number);
return true;
}
$this->createSubTask($number);
$this->sendSubTask();
Log::info('结束视频推广任务');
return true;
}
/**
* 创建子任务
* TODO 获取需要生成子任务的项目,获取项目中未生成视频的关键词,通过关键词生成初始化子任务
* @return bool
*/
public function createSubTask($number)
{
$sub_task_num = $this->max_sub_task;
while (true) {
if ($sub_task_num <= 0){
break;
}
if($number >= $this->max_num){
break;
}
$task_project = KeywordVideoTask::where(['status' => KeywordVideoTask::STATUS_OPEN])->orderBy('sort', 'desc')->orderBy('id', 'desc')->first();
if (empty($task_project)){
break;
}
echo '开始,项目id:'.$task_project->project_id.PHP_EOL;
$domainModel = new DomainInfo();
$domainInfo = $domainModel->read(['project_id'=>$task_project->project_id]);
if($domainInfo === false){
$task_project->status = KeywordVideoTask::STATUS_CLOSE;
$task_project->save();
continue;
}
ProjectServer::useProject($task_project->project_id);
if(!empty($task_project->keywords)){
$keywords = explode(',',trim(',',$task_project->keywords));
}
$keyword = $this->getProjectKeyword($task_project->number,$keywords ?? []);
// 已经没有需要生成视频的关键词
if (!$keyword) {
$task_project->status = KeywordVideoTask::STATUS_CLOSE;
$task_project->save();
continue;
}
$logo_bg = $this->getImage($domainInfo);
foreach ($keyword as $val) {
$log = KeywordVideoTaskLog::where(['project_id' => $task_project->project_id, 'keyword_id' => $val->id , 'result_status'=>'200'])->first();
if ($log){
continue;
}
$keywordInfo = $this->getKeywordImage($val->id,$task_project->project_id,$domainInfo['domain']);
if(!empty($keywordInfo['product_list'])){
if(!empty($task_project->logo_img)){
$logo_bg['logo'] = $task_project->logo_img;
}
$array = [
'project_id' => $task_project->project_id,
'keyword_id' => $val->id,
'keyword' => $val->title,
'data' => json_encode(['url' => $keywordInfo['url'],'title' => $keywordInfo['title'],
'description' => $keywordInfo['keyword_content'], 'images' => $keywordInfo['product_list'],
'keywords' => $keywordInfo['keyword_list'], 'logo_bg' => $logo_bg , 'template_data' => $task_project->template_data]),
'status' => KeywordVideoTaskLog::STATUS_INIT,
'updated_at' => date('Y-m-d H:i:s'),
'created_at' => date('Y-m-d H:i:s'),
];
$rs = KeywordVideoTaskLog::insert($array);
if($rs && ($sub_task_num > 0)){
$sub_task_num--;
}
}
}
Cache::put('video_keyword_number_month',$number + count($keyword),3600);
$task_project->status = KeywordVideoTask::STATUS_CLOSE;
$task_project->save();
}
return true;
}
/**
* 发送子任务
* @return bool
*/
public function sendSubTask()
{
$subTask = KeywordVideoTaskLog::where(['status' => KeywordVideoTaskLog::STATUS_INIT])->orderBy('id', 'asc')->get();
if ($subTask->isEmpty()){
return true;
}
foreach ($subTask as $val) {
$valData = json_decode($val->data,true);
$task_id = 'v6-' . uniqid();
$data = [
'project_data' => [
'tag_url' => $valData['url'],
'title' => $valData['title'],
'keywords' => $valData['keywords'],
'description' => $valData['description'],
'images' => $valData['images'],
'logo'=> $valData['logo_bg']['logo'] ?? '',
'bg'=> $valData['logo_bg']['bg'] ?? '',
'template_id'=> ((array)$valData['template_data'])['template_id'] ?? '',
],
'task_id' => $task_id,
'callback_url' => env('APP_URL') . '/api/video_task_callback',
'is_ytb'=>false,
'other_language_subtitle'=>false
];
$result = Http::post('http://216.250.255.116:7866/create_task', $data);//todo::小天的接口
$res_json = json_decode($result,true);
$val->task_id = $task_id;
$val->status = KeywordVideoTaskLog::STATUS_ERROR;
if(isset($res_json['code']) && ($res_json['code'] == 200)){
$val->status = KeywordVideoTaskLog::STATUS_RUNNING;
}
$val->result_info = $result;
$val->save();
}
return true;
}
/**
* 获取未生成页面的关键词
* @param $number
* @return mixed
*/
public function getProjectKeyword($number,$keywords = [])
{
$keyword_id = Keyword::where('video', null)->whereIn("title", $keywords)->whereNull('deleted_at')
->where('route', 'not like', '%-tag')->whereNotNull('keyword_content')->inRandomOrder()->take($number)->pluck('id')->toArray();
$need = $number - count($keyword_id);
if ($need > 0) {
$keyword_arr_id = Keyword::where('video', null)->where('route', 'not like', '%-tag')->whereNull('deleted_at')
->whereNotNull('keyword_content')->whereNotIn('id', $keyword_id)->orderBy('id','asc')->inRandomOrder()->take($need)->pluck('id')->toArray();
}
$keyword_arr_id = array_merge($keyword_id, $keyword_arr_id);
$keyword = Keyword::whereIn("id", $keyword_arr_id)->get();
return $keyword;
}
/**
* 获取需要处理的任务
* @return int
*/
public function getTaskProject()
{
// $task_project = Model::where(['status' => Model::STATUS_OPEN])->orderBy('sort', 'desc')->first();
$project_id = 110;
return $project_id;
}
/**
* 根据关键字获取产品主图
* @param $keyword_id
* @param $project_id
* @param $domain
* @return array
*/
public function getKeywordImage($keyword_id,$project_id,$domain){
$keywordModel = new Keyword();
$keywordInfo = $keywordModel->read(['id'=>$keyword_id]);
// TODO 当内容太多时,生成视频过长, 尽量保证生成视频30秒左右, 所以需要控制文案内容长度
$content = $keywordInfo['keyword_content'];
$content_array = explode(" ", $content);
if (count($content_array) > 80) {
$content_array = preg_split("/[,,。]/u", $content);
$tmp = '';
foreach ($content_array as $val) {
$tmp .= $val . '.';
$tmp_array = explode(' ', $tmp);
if (count($tmp_array) > 60) {
$content = $tmp;
break;
}
}
}
//TODO::所有产品
$thumb = $this->getRecommendAndHotProducts($keyword_id);
$keyword_arr = Keyword::where("project_id",$project_id)->where("status",1)->inRandomOrder()->take(10)->pluck('title')->toArray();
$data = [
'url'=> 'https://' . $domain.'/'.$keywordInfo['route'],
'title'=>$keywordInfo['title'],
'keyword_title'=>$keywordInfo['keyword_title'],
'keyword_content'=>$content,
'product_list'=>$thumb ?? [],
'keyword_list'=>$keyword_arr ?? []
];
return $data;
}
/**
* 关键词聚合页-推荐&热门产品
*/
public function getRecommendAndHotProducts($keyword_id): ?array
{
$productIds = [];
$productsQuery = Product::where("status",1)->where("keyword_id","like","%,".$keyword_id.",%")->limit(13)->get();
if (count($productsQuery) > 0){
foreach ($productsQuery as $item){
$productIds[] = $item->id;
}
if (count($productIds) < 13){
$product_all_id = Product::where('thumb','!=',null)->whereNotIn('id', $productIds)->where("status",Product::STATUS_ON)->inRandomOrder()->take(20 - count($productIds))->pluck('id')->toArray();
if(empty($product_all_id)){
$randomData = [];
}else{
$randomData = Product::whereIn("id", $product_all_id)->orderByRaw(DB::raw("FIELD(id, " . implode(',', $product_all_id) . ")"))->get();
}
$products = $productsQuery->merge($randomData);
}else{
$products = $productsQuery;
}
}else{
$product_all_id = Product::where('thumb','!=',null)->where("status",Product::STATUS_ON)->inRandomOrder()->take(20)->pluck('id')->toArray();
if(empty($product_all_id)){
$products = [];
}else{
$products = Product::whereIn("id", $product_all_id)->orderByRaw(DB::raw("FIELD(id, " . implode(',', $product_all_id) . ")"))->get();
}
}
$data = [];
if (!empty($products)){
foreach ($products as $item){
if(empty($item->thumb) || ($item->thumb['url'] == "")){
continue;
}
if(count($data) > 13){
break;
}
$keyword_ids = implode(',',$item->keyword_id);
$keyword_video_ids = implode(',',$item->keyword_video_id);
if (strpos(','.$keyword_ids.',', ','.$keyword_id.',') === false) {
if(strpos(','.$keyword_video_ids.',', ','.$keyword_id.',') === false){
//不包含
$productModel = new Product();
$keyword_video_ids = !empty($keyword_video_ids) ? ','.$keyword_video_ids.',' : ',' ;
$keyword_video_id_str = $keyword_video_ids . $keyword_id.',';
$productModel->edit(['keyword_video_id'=>$keyword_video_id_str],['id'=>$item->id]);
KeywordRelated::saveRelated($item->id,$keyword_video_ids,2);
}
}
$data[] = ['url'=>getImageUrl($item->thumb['url']),'title'=>$item->title];
}
}
return $data;
}
/**
* 获取图片
* @param $domainInfo
* @return array
*/
public function getImage($domainInfo){
$logo = $bg = '';
try {
$dom = file_get_html('https://'.$domainInfo['domain'].'/');
$logoDom = $dom->find('.logo', 0);
if ($logoDom) {
$logoDomImg = $logoDom->find("img",0);
if($logoDomImg != null){
$logo = $logoDomImg->src;
}
}
$elements = $dom->find('.section-banner-wrap-block');
if (count($elements) >= 2) {
foreach ($elements as $v){
$image = $v->find('img', 0);
if($image != null){
break;
}
}
} else {
$image = $dom->find('.section-banner-wrap-block',0);
if($image != null){
$image = $image->find('img', 0);
}else{
$image = null;
}
}
if($image != null){
$bg = $image->src;
}
$dom->clear();
} catch (\Exception $e) {
Log::error('file_get_html: ' . $domainInfo['domain'] . ', error message: ' . $e->getMessage());
}
return ['logo' => $logo, 'bg' => $bg];
}
}