YoutubeService.php 11 KB

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