GetVideoData.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Libraries\TikTokScraper;
  4. use App\Models\TikTokUser;
  5. use App\Models\TikTokVideo;
  6. use Carbon\Carbon;
  7. use Illuminate\Console\Command;
  8. use Illuminate\Support\Facades\Log;
  9. class GetVideoData extends Command
  10. {
  11. /**
  12. * The name and signature of the console command.
  13. *
  14. * @var string
  15. */
  16. protected $signature = 'tiktok:getvideos {--f|file= : File that contains list of user-video pairings, in JSON format}';
  17. /**
  18. * The console command description.
  19. *
  20. * @var string
  21. */
  22. protected $description = 'Fetches video information, given in the specified file. File should be in JSON format.';
  23. /**
  24. * Create a new command instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct()
  29. {
  30. parent::__construct();
  31. }
  32. /**
  33. * Execute the console command.
  34. *
  35. * @return mixed
  36. */
  37. public function handle()
  38. {
  39. $file = $this->option('file');
  40. if (!file_exists($file)) {
  41. $this->error("File $file doesn't exist. Check the filename provided, and try again.");
  42. exit(1);
  43. }
  44. $scraper = new TikTokScraper();
  45. try {
  46. $videos = json_decode(file_get_contents($file));
  47. } catch (\Exception $e) {
  48. $this->error("There was an error parsing video information: {$e->getMessage()}");
  49. exit(1);
  50. }
  51. foreach($videos as $video) {
  52. $scraper->get("https://www.tiktok.com/@{$video->user}/video/{$video->video}");
  53. try {
  54. $videoData = $scraper->extractVideoData();
  55. $videoTikTok = TikTokVideo::where(['video_id' => $video->video])->first();
  56. if (empty($videoTikTok)) {
  57. $videoTikTok = new TikTokVideo;
  58. }
  59. $videoTikTok->video_id = $video->video;
  60. $videoTikTok->username = $video->user ?? null;
  61. $videoTikTok->url = @array_shift($videoData->itemInfos->video->urls) ?? null;
  62. $videoTikTok->duration = $videoData->itemInfos->video->videoMeta->duration ?? 0;
  63. $videoTikTok->uploaded = Carbon::createFromTimestamp($videoData->itemInfos->createTime)
  64. ->toDateTimeString() ?? null;
  65. $videoTikTok->description = $videoData->itemInfos->text ?? null;
  66. $videoTikTok->plays = $videoData->itemInfos->playCount ?? 0;
  67. $videoTikTok->shares = $videoData->itemInfos->shareCount ?? 0;
  68. $videoTikTok->likes = $videoData->itemInfos->diggCount ?? 0;
  69. $videoTikTok->comments = $videoData->itemInfos->commentCount ?? 0;
  70. $videoTikTok->save();
  71. } catch (\Exception $e) {
  72. Log::error("Error extracting video data: {$e->getMessage()}");
  73. }
  74. }
  75. }
  76. }