You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

165 lines
4.2 KiB

  1. # demotape.py checks regulary the webstreams of all district parlaments
  2. # in Vienna. If a webstream is online, it gets recorded into seperate
  3. # directories per district.
  4. import os
  5. import sys
  6. import time
  7. from datetime import datetime
  8. import random
  9. import m3u8
  10. import youtube_dl
  11. import asyncio
  12. import concurrent.futures
  13. try:
  14. if sys.argv[1] and os.path.exists(sys.argv[1]):
  15. ROOT_PATH = sys.argv[1]
  16. print('Root path for downloaded streams: ' + ROOT_PATH)
  17. else:
  18. print('destination path does not exist')
  19. sys.exit()
  20. except IndexError:
  21. print('Script needs a valid destination path for recorded videos as argument')
  22. print('For example: \ndemotape.py /path/to/videos')
  23. sys.exit()
  24. def generate_channellist():
  25. channels = []
  26. districts = range(1, 23 + 1) # districts of vienna
  27. for district_num in districts:
  28. district_str = str(district_num)
  29. district_str_lz = str(district_num).zfill(2) # leading zero
  30. channel = {
  31. 'name': district_str+'. Bezirk',
  32. 'url': 'https://stream.wien.gv.at/live/ngrp:bv' + district_str_lz + '.stream_all/playlist.m3u8'
  33. }
  34. channels.append(channel)
  35. return channels
  36. def check_stream(url):
  37. playlist = m3u8.load(url)
  38. try:
  39. if playlist.data['playlists']:
  40. # has active live stream
  41. return True
  42. else:
  43. # no livestream
  44. return False
  45. except (ValueError, KeyError):
  46. print('some connection error or so')
  47. class MyLogger(object):
  48. def debug(self, msg):
  49. #pass
  50. print(msg)
  51. def warning(self, msg):
  52. #pass
  53. print(msg)
  54. def error(self, msg):
  55. print(msg)
  56. def my_ytdl_hook(d):
  57. if d['status'] == 'finished':
  58. print('Done downloading!')
  59. print(d)
  60. def download_stream(channel):
  61. now = datetime.now() # current date and time
  62. dest_dir = ROOT_PATH + '/' + channel['name'] +'/'
  63. dest_filename = now.strftime("%Y-%m-%d--%H.%M.%S") + '.mp4'
  64. # create directory if it doesn't exist
  65. if not os.path.exists(dest_dir):
  66. print('creating directory ' + dest_dir)
  67. os.makedirs(dest_dir)
  68. dest = dest_dir + dest_filename
  69. ytdl_opts = {
  70. 'logger': MyLogger(),
  71. 'outtmpl': dest,
  72. 'format': 'bestaudio/best',
  73. 'recodevideo': 'mp4',
  74. 'progress_hooks': [my_ytdl_hook],
  75. }
  76. ytdl = youtube_dl.YoutubeDL(ytdl_opts)
  77. try:
  78. ytdl.download([channel['url']])
  79. except (youtube_dl.utils.DownloadError) as e:
  80. print("Download error: " + str(e))
  81. except (youtube_dl.utils.SameFileError) as e:
  82. print("Download error: " + str(e))
  83. except (UnicodeDecodeError) as e:
  84. print("UnicodeDecodeError: " + str(e))
  85. def process_channel(channel):
  86. #print('entered function process_channel with ' + channel['name'])
  87. while True:
  88. #print('checking ' + channel['name'])
  89. if check_stream(channel['url']):
  90. print(channel['name'] + ': stream online! Downloading ...')
  91. download_stream(channel)
  92. else:
  93. # print(channel['name'] + ': stream offline')
  94. # wait between checks
  95. waitingtime = random.randint(20,30)
  96. time.sleep(waitingtime)
  97. print('end processing ' + channel['name'] + ' ... (shouldn\'t happen!)')
  98. def main():
  99. channels = generate_channellist()
  100. with concurrent.futures.ThreadPoolExecutor(max_workers=23) as executor:
  101. future_to_channel = {executor.submit(process_channel, channel): channel for channel in channels}
  102. for future in concurrent.futures.as_completed(future_to_channel):
  103. channel = future_to_channel[future]
  104. try:
  105. data = future.result()
  106. except Exception as exc:
  107. print('%r generated an exception: %s' % (channel, exc))
  108. else:
  109. print('%r page is %d bytes' % (channel, len(data)))
  110. print('end main (this shouldn\'t happen!)')
  111. main()
  112. #test_channel = {
  113. # 'name': 'Test Channel',
  114. # 'url': 'https://1000338copo-app2749759488.r53.cdn.tv1.eu/1000518lf/1000338copo/live/app2749759488/w2928771075/live247.smil/playlist.m3u8'
  115. # }
  116. #download_stream(test_channel)