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.

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