YoutubeService.php 11 KB

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