()
| 56 | print('\n'.join(log)) |
| 57 | |
| 58 | def main(): |
| 59 | youtube_api_key = load_youtube_api_key() |
| 60 | |
| 61 | parser = optparse.OptionParser('usage%prog -f <target_file>') |
| 62 | parser.add_option('-f', dest='input_file', type='string', help='specify input file') |
| 63 | (options, args) = parser.parse_args() |
| 64 | input_file = options.input_file |
| 65 | |
| 66 | log = [] |
| 67 | |
| 68 | number_of_lines = get_number_of_lines(input_file) |
| 69 | with open(input_file, 'r+') as f: |
| 70 | data = f.read() |
| 71 | new_data = [] |
| 72 | for i, line in enumerate(data.split('\n'), 1): |
| 73 | print('Parsing line: ' + str(i) + ' of ' + str(number_of_lines)) |
| 74 | # FIXME: Assumes that no two videos have the exact same length |
| 75 | has_been_added_earlier = re.findall('\[\d\d:\d\d:\d\d\]', line) |
| 76 | if has_been_added_earlier: |
| 77 | new_data.append(line) |
| 78 | else: |
| 79 | youtube_match = re.findall('http[s]?://www.youtube.com/watch\?v\=[a-zA-Z0-9_-]+', line) |
| 80 | if youtube_match: |
| 81 | link = youtube_match[0] |
| 82 | video_id = parse_qs(link.split('?')[1]).get('v') |
| 83 | try: |
| 84 | r = requests.get('https://www.googleapis.com/youtube/v3/videos?key=' + youtube_api_key + '&part=contentDetails&id=' + video_id) |
| 85 | except: |
| 86 | log.append('The request to the youtube API went wrong. Video id: ' + video_id + '. Youtube api key: ' + youtube_api_key + '.') |
| 87 | duration = get_duration(r.json()) |
| 88 | new_line = re.split('(\))', line) |
| 89 | new_line[1] += print_duration(duration) |
| 90 | new_data.append(''.join(new_line)) |
| 91 | print(''.join(new_line)) |
| 92 | else: |
| 93 | new_data.append(line) |
| 94 | f.seek(0) # set file cursor to start of file |
| 95 | f.write('\n'.join(new_data)) |
| 96 | handle_log(log) |
| 97 | |
| 98 | if __name__ == '__main__': |
| 99 | main() |
no test coverage detected