How to update youtube annalytics to all previously registered youtube channels

Viewed 14

I have a web app in which the users can register and connect their youtube channels. Next in the registration process I collect all the information I can get from youtube data api and youtube analytics and reporting api (with scopes and access tokens) and store it in the database. I show that info on their dashboards. I also display that info in the admin panel for the administrators to see. The problem is, how can I refresh that info, lets say, once a day? I've tried with the access token but i get error 403 Forbidden message. I want to update the info to all of the registered youtube accounts, this is the function I use to update all but its not working (In the bellow script, i send $code as a variable and the function is called on the redirect URI)

    $youtube_channels = YouTubeChannels::get();
    $key = env('NEW_YOUTUBE_API_KEY');
    foreach($youtube_channels as $youtube_channel) {
        $yt_channel_statistics = Http::get('https://www.googleapis.com/youtube/v3/channels', [
            'part' => 'statistics,snippet',
            'id' =>  $youtube_channel->youtube_channel_id,
            'key' => $key
        ]);

        $yt_channel_statistics_json = $yt_channel_statistics->json();

        $update_yt = YouTubeChannels::where('youtube_channel_id', $youtube_channel->youtube_channel_id)->first();

        if($update_yt != null) {
            $update_yt->channel_name = $yt_channel_statistics_json['items'][0]['snippet']['title'];
            $update_yt->channel_subscribers = $yt_channel_statistics_json['items'][0]['statistics']['subscriberCount'];
            $update_yt->channel_total_views = $yt_channel_statistics_json['items'][0]['statistics']['viewCount'];
            $update_yt->channel_videos_count = $yt_channel_statistics_json['items'][0]['statistics']['videoCount'];
            $update_yt->save();
        }

        //test
        $baseUrl = 'https://www.googleapis.com/youtube/v3/';
        $apiKey = env('NEW_YOUTUBE_API_KEY');
        $channelId = $youtube_channel->youtube_channel_id;

        $params = [
            'id'=> $channelId,
            'part'=> 'contentDetails',
            'key'=> $apiKey
        ];
        $url = $baseUrl . 'channels?' . http_build_query($params);
        $json = json_decode(file_get_contents($url), true);

        $playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];

        $params = [
            'part'=> 'snippet',
            'playlistId' => $playlist,
            'maxResults'=> '50',
            'key'=> $apiKey
        ];
        $url = $baseUrl . 'playlistItems?' . http_build_query($params);
        $json = json_decode(file_get_contents($url), true);

        $videos = [];
        foreach($json['items'] as $video)
            $videos[] = $video['snippet']['resourceId']['videoId'];

        while(isset($json['nextPageToken'])){
            $nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
            $json = json_decode(file_get_contents($nextUrl), true);
            foreach($json['items'] as $video)
                $videos[] = $video['snippet']['resourceId']['videoId'];
        }

        $video_ids_string = collect($videos)->implode(',');
        //
        //endtest

        //new test
        //
        $params = [
            'part'=> 'snippet,contentDetails,statistics,status',
            'id' => $video_ids_string,
            'key'=> $apiKey
        ];
        $url = $baseUrl . 'videos?' . http_build_query($params);
        $json = json_decode(file_get_contents($url), true);

        $videos_infos = $json;

        //
        YouTubeVideos::where('youtube_channel_id', $youtube_channel->id)->delete();
        foreach ($videos as $video){

            foreach($videos_infos['items'] as $info){

                if ($info['id'] == $video) {

                    if($info['status']['privacyStatus'] == 'public') {
                        $youtube_video = new YouTubeVideos();

                        // if (!$live_error) {
                        //     foreach ($live_videos as $live) {
                        //         if ($live->youtube_id == $video) {
                        //             $youtube_video->was_live = true;
                        //         }
                        //     }
                        // }

                        // dd($video);
                        $youtube_video->youtube_channel_id = $youtube_channel->id;
                        $youtube_video->yt_video_id = $video;
                        $youtube_video->yt_video_title = $info['snippet']['title'];
                        $youtube_video->yt_video_description = $info['snippet']['description'];
                        $youtube_video->yt_video_published_at = Carbon::parse($info['snippet']['publishedAt']);
                        if(isset($info['snippet']['defaultAudioLanguage'])) {
                            $youtube_video->yt_video_default_audio_language = $info['snippet']['defaultAudioLanguage'];
                        } else {
                            $youtube_video->yt_video_default_audio_language = '';
                        }
                        
                        if (strcmp($info['contentDetails']['caption'], 'true') == 0) {
                            $youtube_video->is_video_captioned = true;
                        } else {
                            $youtube_video->is_video_captioned = false;
                        }
                        $youtube_video->yt_video_definition = $info['contentDetails']['definition'];

                        $youtube_video->yt_video_dislike_count = 0;
                        $youtube_video->yt_video_like_count = $info['statistics']['likeCount'];
                        $youtube_video->yt_video_views_count = $info['statistics']['viewCount'];

                        //proba type of views
                        //
                        $client = new Google_Client();
                        try{
                            $client->setAuthConfig(storage_path('app'.DIRECTORY_SEPARATOR. 'json'. DIRECTORY_SEPARATOR.'client_secret.json'));
                        }catch (\Google\Exception $e){
                            dd($e->getMessage());
                        }

                        // $client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/youtube.readonly']);
                        $client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL,GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, GOOGLE_SERVICE_YOUTUBE::YOUTUBEPARTNER,'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly']);

                        $client->setRedirectUri(env('APP_URL') . '/get_access_token_yt_test');

                        // offline access will give you both an access and refresh token so that
                        // your app can refresh the access token without user interaction.
                        $client->setAccessType('offline');

                        // Using "consent" ensures that your application always receives a refresh token.
                        // If you are not using offline access, you can omit this.
                        $client->setPrompt("consent");
                        $client->setApprovalPrompt('force');
                        $client->setIncludeGrantedScopes(true);   // incremental auth

                        if (!isset($code)){
                            $auth_url = $client->createAuthUrl();
                            return redirect()->away($auth_url)->send();
                        }else{
                            if($code != null) {
                                $client->fetchAccessTokenWithAuthCode($code);
                                $client->setAccessToken($client->getAccessToken());
                                session()->push('refresh_token_youtube', $client->getRefreshToken());
                                session()->save();
                            }
                        }

                        $service = new Google_Service_YouTube($client);
                        $analytics = new Google_Service_YouTubeAnalytics($client);


                        $typeOfViews = $analytics->reports->query([
                            'ids' => 'channel==' . $youtube_channel->youtube_channel_id,
                            'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
                            'endDate' => Carbon::today()->format('Y-m-d'),
                            'metrics' => 'views',
                            'dimensions' => 'liveOrOnDemand',
                            'filters' => 'video=='.$video
                        ]);


                        foreach ($typeOfViews as $viewType) {
                            if ($viewType[0] == 'ON_DEMAND') {
                                $youtube_video->yt_video_on_demand_views_count = $viewType[1];
                            } else if ($viewType[0] == 'LIVE') {
                                $youtube_video->yt_video_live_views_count = $viewType[1];
                            }
                        }

                        $watch_times = $analytics->reports->query([
                            'ids' => 'channel=='.$youtube_channel->youtube_channel_id,
                            'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
                            'endDate' => Carbon::today()->format('Y-m-d'),
                            'metrics' => 'estimatedMinutesWatched',
                            'dimensions' => 'day',
                            'filters' => 'video=='.$video
                        ]);

                        // //update quotas
                        // // self::update_quotas(1);


                        $total = 0;
                        foreach ($watch_times as $watch_time){
                            $total += $watch_time[1];
                        }
                        $youtube_video->estimated_minutes_watch_time = $total;

                        $youtube_video->save();

                        //zacuvuva captions
                        $xmlString = file_get_contents("https://video.google.com/timedtext?type=list&v=" . $video);
                        $xmlObject = simplexml_load_string($xmlString);
                        $json = json_encode($xmlObject);
                        $phpArray = json_decode($json, true);


                        if (isset($phpArray['track'])) {
                            foreach ($phpArray['track'] as $array) {
                                $yt_video_captions = new YouTubeVideosCaptions();
                                $yt_video_captions->youtube_video_id = $youtube_video->id;
                                $yt_video_captions->language = $array['lang_code'];
                                $yt_video_captions->save();
                            }
                        }

                        //zacuvuva tags
                        if(isset($info['snippet']['tags'])) {
                            if ($info['snippet']['tags'] != null) {
                                foreach ($info['snippet']['tags'] as $tag) {
                                    $youtube_video_tags = new YouTubeVideosTags();
                                    $youtube_video_tags->youtube_video_id = $youtube_video->id;
                                    $youtube_video_tags->tag = $tag;
                                    $youtube_video_tags->save();
                                }
                            }  
                        }
                        

                        if ($youtube_video->is_video_captioned) {
                            $captions = YouTubeVideosCaptions::where('youtube_video_id', $youtube_video->id)->get();
                            foreach ($captions as $caption) {
                                $video_id = YouTubeVideos::where('id', $caption->youtube_video_id)->first();

                                $client->authorize();

                                $fp = fopen('../storage/app/captions/' . $caption->id . '.xml', 'w');

                                $xmlString = file_get_contents("http://video.google.com/timedtext?type=track&v=" . $video_id['yt_video_id'] . "&id=0&lang=" . $caption['language']);

                                fwrite($fp, $xmlString);
                                fclose($fp);
                            }
                        }

                        echo 'done';
                    }

                    
                }
            }

        }
        // Command::line('Youtube videos updated');
        //

        //
        //end new test
    }
}
0 Answers
Related