選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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