YoutubeService.php 11 KB

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