-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
86 lines (58 loc) · 2.81 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from datetime import timedelta
import re
import os
from googleapiclient.discovery import build, HttpError
def main():
#api credentials from https://console.cloud.google.com/apis/credentials/
api_key = os.environ.get('YOUTUBE_API_KEY')
youtubeService = build('youtube', 'v3',developerKey = api_key)
totalVideoSeconds = 0
#to seprate the hours minutes and seconds from the output of videoResponse
hoursPattern = re.compile(r'(\d+)H')
minutesPattern = re.compile(r'(\d+)M')
secondsPattern = re.compile(r'(\d+)S')
nextPageToken = None
while True:
playlistRequest = youtubeService.playlistItems().list(
#to be used with playlistItems service request
part = 'contentDetails',
#id is for the playlist id unlike the channelId which is clearly for the channel id
playlistId = 'PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-', #ARCH studio Rhino Tutorials
maxResults = 50,
pageToken = nextPageToken
)
try:
playlistResponse = playlistRequest.execute()
videoIds =[]
for item in playlistResponse['items']:
videoIds.append(item['contentDetails']['videoId'])
videoRequest = youtubeService.videos().list(
part = 'contentDetails',
id = ','.join(videoIds)
)
videoResponse = videoRequest.execute()
for item in videoResponse['items']:
videoDuration = item['contentDetails']['duration']
hours = hoursPattern.search(videoDuration)
minutes = minutesPattern.search(videoDuration)
seconds = secondsPattern.search(videoDuration)
hours = int(hours.group(1)) if hours else 0
minutes = int(minutes.group(1)) if minutes else 0
seconds = int(seconds.group(1)) if seconds else 0
videoSeconds = timedelta(
hours = hours,
minutes = minutes,
seconds = seconds
).total_seconds()
totalVideoSeconds += videoSeconds
totalVideoSeconds = int(totalVideoSeconds)
minutes, seconds = divmod(totalVideoSeconds, 60)
hours, minutes = divmod(minutes, 60)
nextPageToken = playlistResponse.get('nextPageToken')
if not nextPageToken:
break
except HttpError as e:
print('Error response status code : {0}, reason : {1}'.format(e.status_code, e.error_details))
print (f'Total Playlist duration is {hours} Hours {minutes} Minutes {seconds} Seconds.' )
if __name__ == "__main__":
main()