YoutubeService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <?php
  2. namespace App\Services\Smm;
  3. use App\Services\Contracts\SmmPlatformInterface;
  4. use Carbon\Carbon;
  5. use Google_Client;
  6. use Google_Service_YouTube;
  7. use Google_Service_YouTube_Video;
  8. use Google_Service_YouTube_VideoSnippet;
  9. use Google_Service_YouTube_VideoStatus;
  10. use Google_Http_MediaFileUpload;
  11. use Illuminate\Http\Request;
  12. use OSS\OssClient;
  13. use OSS\Core\OssException;
  14. use Illuminate\Support\Facades\Log;
  15. class YoutubeService implements SmmPlatformInterface
  16. {
  17. protected Google_Client $client;
  18. protected string $redirectUri;
  19. protected array $configData;
  20. public function __construct(array $configData)
  21. {
  22. $this->configData = $configData;
  23. $this->client = new Google_Client();
  24. $this->client->setClientId(env('SSM_YOUTUBE_CLIENT_ID'));
  25. $this->client->setClientSecret(env('SSM_YOUTUBE_CLIENT_SECRET'));
  26. $this->client->setRedirectUri(env('DIST_SITE_URL').'/dist/callback/youtube');
  27. $this->client->setScopes([
  28. Google_Service_YouTube::YOUTUBE_UPLOAD,
  29. Google_Service_YouTube::YOUTUBE,
  30. Google_Service_YouTube::YOUTUBE_FORCE_SSL,
  31. Google_Service_YouTube::YOUTUBE_READONLY,
  32. Google_Service_YouTube::YOUTUBEPARTNER,
  33. Google_Service_YouTube::YOUTUBEPARTNER_CHANNEL_AUDIT
  34. ]);
  35. $this->client->setAccessType('offline');
  36. $this->client->setPrompt('consent');
  37. $this->client->setDeveloperKey(env('SSM_YOUTUBE_DEV_KEY'));
  38. }
  39. public function login()
  40. {
  41. try {
  42. return ['status' => true, 'data' => ['url' => $this->client->createAuthUrl()]];
  43. } catch (\Exception $e) {
  44. return ['status' => false, 'data' => 'Failed to generate login URL: '.$e->getMessage()];
  45. }
  46. }
  47. public function loginCallback(Request $request)
  48. {
  49. try {
  50. $code = $request->input('code');
  51. if (!$code) {
  52. return ['status' => false, 'data' => 'Authorization code not found'];
  53. }
  54. $token = $this->client->fetchAccessTokenWithAuthCode($code);
  55. if (isset($token['error'])) {
  56. return ['status' => false, 'data' => $token['error_description'] ?? 'Failed to exchange authorization code'];
  57. }
  58. $this->client->setAccessToken($token);
  59. $youtube = new Google_Service_YouTube($this->client);
  60. $channelResponse = $youtube->channels->listChannels('snippet', ['mine' => true]);
  61. return [
  62. 'status' => true,
  63. 'data' => [
  64. 'accessToken' => $token['access_token'],
  65. 'refreshToken' => $token['refresh_token'] ?? '',
  66. 'accessToken_expiresAt' => Carbon::now()->addSeconds($token['expires_in']),
  67. 'userName' => $channelResponse->items[0]->snippet->title ?? '',
  68. 'userId' => $channelResponse->items[0]->id ?? '',
  69. ]
  70. ];
  71. } catch (\Exception $e) {
  72. return ['status' => false, 'data' => $e->getMessage()];
  73. }
  74. }
  75. public function postImage($message, $imagePaths, $accessToken)
  76. {
  77. return [
  78. 'status' => false,
  79. 'data' => 'YouTube API does not support image-only posts'
  80. ];
  81. }
  82. public function postVideo($message, $videoPath, $accessToken)
  83. {
  84. Log::info('YouTube 开始发布视频帖子');
  85. /*
  86. $ossPath = ltrim(parse_url($videoPath, PHP_URL_PATH), '/');
  87. $fileSize = $this->getOssFileSize($ossPath);
  88. if ($fileSize['status'] === false) {
  89. return ['status' => false, 'data' => $fileSize['data']];
  90. }*/
  91. $backup_field1 = $this->configData['postData']['backup_field1'] ?? '';
  92. $backup_field1 = json_decode($backup_field1, true);
  93. $title = $backup_field1['yutube_title'] ?? '';
  94. $category = $backup_field1['yutube_category'] ?? '';
  95. $videoPath = toStoragePath($videoPath);
  96. // 处理 OAuth 回调
  97. $this->client->setAccessToken($accessToken);
  98. // 初始化 YouTube 服务
  99. $youtube = new Google_Service_YouTube($this->client);
  100. try {
  101. // 定义视频元数据
  102. $snippetData = [
  103. 'title' => $title,
  104. 'description' => $message,
  105. 'tags' => [],
  106. 'categoryId' => $category // 人物与博客
  107. ];
  108. Log::info('YouTube 定义视频元数据'.json_encode($snippetData));
  109. $snippet = new Google_Service_YouTube_VideoSnippet();
  110. $snippet->setTitle($snippetData['title']);
  111. $snippet->setDescription($snippetData['description']);
  112. $snippet->setTags($snippetData['tags']);//'test', 'api'
  113. $snippet->setCategoryId($snippetData['categoryId']); // 人物与博客
  114. // 设置视频状态
  115. $status = new Google_Service_YouTube_VideoStatus();
  116. $status->setPrivacyStatus('public'); // public, private, unlisted
  117. $status->setMadeForKids(true);// 是否为儿童视频
  118. // 创建视频对象
  119. $video = new Google_Service_YouTube_Video();
  120. $video->setSnippet($snippet);
  121. $video->setStatus($status);
  122. // 上传视频
  123. $this->client->setDefer(true);
  124. $insertRequest = $youtube->videos->insert('snippet,status', $video);
  125. Log::info('YouTube 分块上传视频');
  126. $media = new Google_Http_MediaFileUpload(
  127. $this->client,
  128. $insertRequest,
  129. 'video/*',
  130. null,
  131. true,
  132. 2 * 1048576 // 分块大小 2MB
  133. );
  134. $media->setFileSize(filesize($videoPath)); // 替换为视频文件路径
  135. $status = false;
  136. $handle = fopen($videoPath, 'rb');
  137. while (!$status && !feof($handle)) {
  138. $chunk = fread($handle, 2 * 1048576);
  139. $status = $media->nextChunk($chunk);
  140. }
  141. fclose($handle);
  142. $this->client->setDefer(false);
  143. //echo "Video uploaded: " . $status['id'];
  144. Log::info('视频上传成功: '.$status['id']);
  145. return ['status' => true,
  146. 'data' => [
  147. 'responseIds' => [$status['id']],
  148. ]];
  149. } catch (Google_Service_Exception $e) {
  150. return ['status' => false, 'data' => $e->getMessage()];
  151. } catch (Google_Exception $e) {
  152. return ['status' => false, 'data' => $e->getMessage()];
  153. }
  154. }
  155. public function getVideoCategories($regionCode = 'US')
  156. {
  157. try {
  158. $youtube = new Google_Service_YouTube($this->client);
  159. $response = $youtube->videoCategories->listVideoCategories('snippet', [
  160. 'regionCode' => $regionCode
  161. ]);
  162. $categories = [];
  163. foreach ($response->items as $category) {
  164. if ($category->snippet->assignable) {
  165. $categories[$category->id] = $category->snippet->title;
  166. }
  167. }
  168. return [
  169. 'status' => true,
  170. 'data' => $categories
  171. ];
  172. } catch (\Google_Service_Exception $e) {
  173. $error = json_decode($e->getMessage(), true)['error']['message'] ?? $e->getMessage();
  174. return ['status' => false, 'data' => $error];
  175. }
  176. }
  177. public function getComments($postId)
  178. {
  179. try {
  180. $youtube = new Google_Service_YouTube($this->client);
  181. $response = $youtube->commentThreads->listCommentThreads('snippet', [
  182. 'videoId' => $postId,
  183. 'maxResults' => 100
  184. ]);
  185. $comments = [];
  186. foreach ($response->items as $item) {
  187. $comment = $item->snippet->topLevelComment->snippet;
  188. $comments[] = [
  189. 'id' => $item->id,
  190. 'text' => $comment->textDisplay,
  191. 'author' => $comment->authorDisplayName,
  192. 'createdAt' => $comment->publishedAt
  193. ];
  194. }
  195. return ['status' => true, 'data' => $comments];
  196. } catch (\Exception $e) {
  197. Log::error('YouTube get comments error: '.$e->getMessage());
  198. return ['status' => false, 'error' => $e->getMessage()];
  199. }
  200. }
  201. public function replyToComment($commentId)
  202. {
  203. $text = '';
  204. try {
  205. $youtube = new Google_Service_YouTube($this->client);
  206. $commentSnippet = new \Google_Service_YouTube_CommentSnippet();
  207. $commentSnippet->setTextOriginal($text);
  208. $commentSnippet->setParentId($commentId);
  209. $comment = new \Google_Service_YouTube_Comment();
  210. $comment->setSnippet($commentSnippet);
  211. $response = $youtube->comments->insert('snippet', $comment);
  212. return [
  213. 'status' => true,
  214. 'data' => [
  215. 'commentId' => $response->getId(),
  216. 'text' => $text
  217. ]
  218. ];
  219. } catch (\Exception $e) {
  220. Log::error('YouTube reply error: '.$e->getMessage());
  221. return ['status' => false, 'error' => $e->getMessage()];
  222. }
  223. }
  224. public function deleteComment($commentId)
  225. {
  226. try {
  227. $youtube = new Google_Service_YouTube($this->client);
  228. $youtube->comments->delete($commentId);
  229. return ['status' => true];
  230. } catch (\Exception $e) {
  231. Log::error('YouTube delete comment error: '.$e->getMessage());
  232. return ['status' => false, 'error' => $e->getMessage()];
  233. }
  234. }
  235. public function refreshToken($refreshToken)
  236. {
  237. try {
  238. $this->client->refreshToken($refreshToken);
  239. return $this->client->getAccessToken();
  240. } catch (\Exception $e) {
  241. Log::error('YouTube refresh token error: '.$e->getMessage());
  242. return ['error' => $e->getMessage()];
  243. }
  244. }
  245. public function refreshAccessToken($refreshToken)
  246. {
  247. try {
  248. $newToken = $this->client->fetchAccessTokenWithRefreshToken($refreshToken);
  249. return [
  250. 'status' => true,
  251. 'data' => [
  252. 'access_token' => $newToken['access_token'],
  253. 'expires_at' => Carbon::now()->addSeconds($newToken['expires_in']),
  254. 'refresh_token' => $newToken['refresh_token'],
  255. ]
  256. ];
  257. } catch (\Exception $e) {
  258. return ['status' => false, 'error' => 'Failed to refresh access token: '.$e->getMessage()];
  259. }
  260. }
  261. /*
  262. * 返回oss文件大小 (字节)
  263. * $pathName : 'path/to/your/file.txt'
  264. */
  265. /*
  266. public function getOssFileSize($pathName)
  267. {
  268. // 配置信息
  269. $accessKeyId = env('OSS_ACCESS_KEY_ID');
  270. $accessKeySecret = env('OSS_ACCESS_KEY_SECRET');
  271. $endpoint = env('OSS_ENDPOINT'); // 替换为你的 Region Endpoint
  272. $bucketName = env('OSS_BUCKET');
  273. $objectName = $pathName; // OSS 文件路径
  274. try {
  275. // 创建 OssClient 实例
  276. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  277. // 获取文件元数据
  278. $metadata = $ossClient->headObject($bucketName, $objectName);
  279. // 从元数据中获取文件大小(字节)
  280. $fileSize = $metadata['content-length'];
  281. return ['status' => true, 'data' => $fileSize];
  282. } catch (OssException $e) {
  283. // 错误处理
  284. return ['status' => false, 'data' => $e->getMessage()];
  285. }
  286. }
  287. */
  288. }