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.

210 lines
6.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. import ntpath
  14. import yaml
  15. from pathlib import Path
  16. config_path = Path(__file__).parent / './config.yaml'
  17. with config_path.open() as file:
  18. config = yaml.load(file, Loader=yaml.FullLoader)
  19. try:
  20. if sys.argv[1] and os.path.exists(sys.argv[1]):
  21. ROOT_PATH = sys.argv[1]
  22. print('Root path for downloaded streams: ' + ROOT_PATH)
  23. else:
  24. print('destination path does not exist')
  25. sys.exit()
  26. except IndexError:
  27. print('Script needs a valid destination path for recorded videos as argument')
  28. print('For example: \ndemotape.py /path/to/videos')
  29. sys.exit()
  30. def timestamp():
  31. dateTimeObj = datetime.now()
  32. return '[ ' + dateTimeObj.strftime("%F %H:%M:%S.%f") + ' ] '
  33. def generate_channellist():
  34. channels = []
  35. districts = range(1, 23 + 1) # districts of vienna
  36. for district_num in districts:
  37. # district_str = str(district_num)
  38. district_str_lz = str(district_num).zfill(2) # leading zero
  39. channel = {
  40. 'name': '1' + district_str_lz + '0', # 1010 - 1230
  41. 'url': 'https://stream.wien.gv.at/live/ngrp:bv' + district_str_lz + '.stream_all/playlist.m3u8'
  42. }
  43. channels.append(channel)
  44. print('channels:')
  45. for channel in channels:
  46. print(channel['name'] + ' ' + channel['url'])
  47. return channels
  48. def check_stream(url):
  49. playlist = m3u8.load(url)
  50. try:
  51. if playlist.data['playlists']:
  52. # has active live stream
  53. return True
  54. else:
  55. # no livestream
  56. return False
  57. except (ValueError, KeyError):
  58. print('some connection error or so')
  59. class MyLogger(object):
  60. def debug(self, msg):
  61. #pass
  62. print(msg)
  63. def warning(self, msg):
  64. #pass
  65. print(msg)
  66. def error(self, msg):
  67. print(msg)
  68. def my_ytdl_hook(d):
  69. if d['status'] == 'finished':
  70. print(timestamp() + 'Done downloading!')
  71. else:
  72. print(timestamp() + 'sth went wrong' + d['status'])
  73. print(d)
  74. def download_stream(channel, dest_path):
  75. print('download_stream')
  76. ytdl_opts = {
  77. 'logger': MyLogger(),
  78. 'outtmpl': dest_path,
  79. 'format': 'bestaudio/best',
  80. # 'recodevideo': 'mp4',
  81. # 'postprocessors': [{
  82. # 'key': 'FFmpegVideoConvertor',
  83. # 'preferedformat': 'mp4',
  84. # 'preferredquality': '25',
  85. # }],
  86. # should just stop after a few retries and start again instead of hanging in the loop of trying to download
  87. 'retries': 3,
  88. 'fragment-retries': 3,
  89. 'progress_hooks': [my_ytdl_hook]
  90. }
  91. ytdl = youtube_dl.YoutubeDL(ytdl_opts)
  92. try:
  93. print(timestamp() + " Downloading: " + channel['url'])
  94. ytdl.download([channel['url']])
  95. except (youtube_dl.utils.DownloadError) as e:
  96. print(timestamp() + " Download error: " + str(e))
  97. except (youtube_dl.utils.SameFileError) as e:
  98. print("Download error: " + str(e))
  99. except (UnicodeDecodeError) as e:
  100. print("UnicodeDecodeError: " + str(e))
  101. def process_channel(channel):
  102. #print('entered function process_channel with ' + channel['name'])
  103. while True:
  104. print(timestamp() + ' checking ' + channel['name'])
  105. if check_stream(channel['url']):
  106. print(channel['name'] + ': stream online! Downloading ...')
  107. dest_dir = ROOT_PATH + '/' + channel['name'] +'/'
  108. # create directory if it doesn't exist
  109. if not os.path.exists(dest_dir):
  110. print('creating directory ' + dest_dir)
  111. os.makedirs(dest_dir)
  112. dest_path = get_destpath(channel) # dirctory + filename
  113. download_stream(channel, dest_path) # also converts video
  114. print(timestamp() + " Uploading video " + dest_path)
  115. upload_video(dest_path)
  116. else:
  117. waitingtime = random.randint(50,60)
  118. time.sleep(waitingtime)
  119. print('end processing ' + channel['name'] + ' ... (shouldn\'t happen!)')
  120. def upload_video(videofile_path):
  121. print('uploading %s' % (videofile_path))
  122. credentials = config['webdav']['username'] + ':' + config['webdav']['password']
  123. webdav_baseurl = config['webdav']['base_url']
  124. filename = ntpath.basename(videofile_path)
  125. webdav_url = webdav_baseurl + filename
  126. try:
  127. # Upload to cloud using webdav
  128. result = os.system('curl -L -u %s -T "%s" "%s"' % (credentials, videofile_path, webdav_url))
  129. if result == 0: # exit code
  130. delete_video(videofile_path)
  131. return true
  132. except:
  133. print('Error while uploading %s to %s' % (file, webdav_url))
  134. def delete_video(file):
  135. try:
  136. os.system('rm -rf "%s"' % (file))
  137. return true
  138. except:
  139. print('Error while deleting %s' % (file))
  140. def get_destpath(channel):
  141. now = datetime.now() # current date and time
  142. dest_dir = ROOT_PATH + '/' + channel['name'] +'/'
  143. dest_filename = channel['name'] + "_" + now.strftime("%Y-%m-%d--%H.%M.%S") + '.mp4'
  144. return dest_dir + dest_filename
  145. def main():
  146. channels = generate_channellist()
  147. with concurrent.futures.ThreadPoolExecutor(max_workers=23) as executor:
  148. future_to_channel = {executor.submit(process_channel, channel): channel for channel in channels}
  149. for future in concurrent.futures.as_completed(future_to_channel):
  150. channel = future_to_channel[future]
  151. try:
  152. data = future.result()
  153. except Exception as exc:
  154. print('%r generated an exception: %s' % (channel, exc))
  155. else:
  156. print('%r page is %d bytes' % (channel, len(data)))
  157. print('end main (this shouldn\'t happen!)')
  158. main()
  159. #test_channel = {
  160. # 'name': 'Test Channel',
  161. # 'url': 'https://1000338copo-app2749759488.r53.cdn.tv1.eu/1000518lf/1000338copo/live/app2749759488/w2928771075/live247.smil/playlist.m3u8'
  162. # }
  163. #download_stream(test_channel)