YoutubeService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. // 创建视频对象
  118. $video = new Google_Service_YouTube_Video();
  119. $video->setSnippet($snippet);
  120. $video->setStatus($status);
  121. // 上传视频
  122. $this->client->setDefer(true);
  123. $insertRequest = $youtube->videos->insert('snippet,status', $video);
  124. Log::info('YouTube 分块上传视频');
  125. $media = new Google_Http_MediaFileUpload(
  126. $this->client,
  127. $insertRequest,
  128. 'video/*',
  129. null,
  130. true,
  131. 2 * 1048576 // 分块大小 2MB
  132. );
  133. $media->setFileSize(filesize($videoPath)); // 替换为视频文件路径
  134. $status = false;
  135. $handle = fopen($videoPath, 'rb');
  136. while (!$status && !feof($handle)) {
  137. $chunk = fread($handle, 2 * 1048576);
  138. $status = $media->nextChunk($chunk);
  139. }
  140. fclose($handle);
  141. $this->client->setDefer(false);
  142. //echo "Video uploaded: " . $status['id'];
  143. Log::info('视频上传成功: '.$status['id']);
  144. return ['status' => true,
  145. 'data' => [
  146. 'responseIds' => [$status['id']],
  147. ]];
  148. } catch (Google_Service_Exception $e) {
  149. return ['status' => false, 'data' => $e->getMessage()];
  150. } catch (Google_Exception $e) {
  151. return ['status' => false, 'data' => $e->getMessage()];
  152. }
  153. }
  154. public function getVideoCategories($regionCode = 'US')
  155. {
  156. try {
  157. $youtube = new Google_Service_YouTube($this->client);
  158. $response = $youtube->videoCategories->listVideoCategories('snippet', [
  159. 'regionCode' => $regionCode
  160. ]);
  161. $categories = [];
  162. foreach ($response->items as $category) {
  163. if ($category->snippet->assignable) {
  164. $categories[$category->id] = $category->snippet->title;
  165. }
  166. }
  167. return [
  168. 'status' => true,
  169. 'data' => $categories
  170. ];
  171. } catch (\Google_Service_Exception $e) {
  172. $error = json_decode($e->getMessage(), true)['error']['message'] ?? $e->getMessage();
  173. return ['status' => false, 'data' => $error];
  174. }
  175. }
  176. public function getComments($postId)
  177. {
  178. try {
  179. $youtube = new Google_Service_YouTube($this->client);
  180. $response = $youtube->commentThreads->listCommentThreads('snippet', [
  181. 'videoId' => $postId,
  182. 'maxResults' => 100
  183. ]);
  184. $comments = [];
  185. foreach ($response->items as $item) {
  186. $comment = $item->snippet->topLevelComment->snippet;
  187. $comments[] = [
  188. 'id' => $item->id,
  189. 'text' => $comment->textDisplay,
  190. 'author' => $comment->authorDisplayName,
  191. 'createdAt' => $comment->publishedAt
  192. ];
  193. }
  194. return ['status' => true, 'data' => $comments];
  195. } catch (\Exception $e) {
  196. Log::error('YouTube get comments error: '.$e->getMessage());
  197. return ['status' => false, 'error' => $e->getMessage()];
  198. }
  199. }
  200. public function replyToComment($commentId)
  201. {
  202. $text = '';
  203. try {
  204. $youtube = new Google_Service_YouTube($this->client);
  205. $commentSnippet = new \Google_Service_YouTube_CommentSnippet();
  206. $commentSnippet->setTextOriginal($text);
  207. $commentSnippet->setParentId($commentId);
  208. $comment = new \Google_Service_YouTube_Comment();
  209. $comment->setSnippet($commentSnippet);
  210. $response = $youtube->comments->insert('snippet', $comment);
  211. return [
  212. 'status' => true,
  213. 'data' => [
  214. 'commentId' => $response->getId(),
  215. 'text' => $text
  216. ]
  217. ];
  218. } catch (\Exception $e) {
  219. Log::error('YouTube reply error: '.$e->getMessage());
  220. return ['status' => false, 'error' => $e->getMessage()];
  221. }
  222. }
  223. public function deleteComment($commentId)
  224. {
  225. try {
  226. $youtube = new Google_Service_YouTube($this->client);
  227. $youtube->comments->delete($commentId);
  228. return ['status' => true];
  229. } catch (\Exception $e) {
  230. Log::error('YouTube delete comment error: '.$e->getMessage());
  231. return ['status' => false, 'error' => $e->getMessage()];
  232. }
  233. }
  234. public function refreshToken($refreshToken)
  235. {
  236. try {
  237. $this->client->refreshToken($refreshToken);
  238. return $this->client->getAccessToken();
  239. } catch (\Exception $e) {
  240. Log::error('YouTube refresh token error: '.$e->getMessage());
  241. return ['error' => $e->getMessage()];
  242. }
  243. }
  244. public function refreshAccessToken($refreshToken)
  245. {
  246. try {
  247. $newToken = $this->client->fetchAccessTokenWithRefreshToken($refreshToken);
  248. return [
  249. 'status' => true,
  250. 'data' => [
  251. 'access_token' => $newToken['access_token'],
  252. 'expires_at' => Carbon::now()->addSeconds($newToken['expires_in']),
  253. 'refresh_token' => $newToken['refresh_token'],
  254. ]
  255. ];
  256. } catch (\Exception $e) {
  257. return ['status' => false, 'error' => 'Failed to refresh access token: '.$e->getMessage()];
  258. }
  259. }
  260. /*
  261. * 返回oss文件大小 (字节)
  262. * $pathName : 'path/to/your/file.txt'
  263. */
  264. /*
  265. public function getOssFileSize($pathName)
  266. {
  267. // 配置信息
  268. $accessKeyId = env('OSS_ACCESS_KEY_ID');
  269. $accessKeySecret = env('OSS_ACCESS_KEY_SECRET');
  270. $endpoint = env('OSS_ENDPOINT'); // 替换为你的 Region Endpoint
  271. $bucketName = env('OSS_BUCKET');
  272. $objectName = $pathName; // OSS 文件路径
  273. try {
  274. // 创建 OssClient 实例
  275. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  276. // 获取文件元数据
  277. $metadata = $ossClient->headObject($bucketName, $objectName);
  278. // 从元数据中获取文件大小(字节)
  279. $fileSize = $metadata['content-length'];
  280. return ['status' => true, 'data' => $fileSize];
  281. } catch (OssException $e) {
  282. // 错误处理
  283. return ['status' => false, 'data' => $e->getMessage()];
  284. }
  285. }
  286. */
  287. }