cDownloader.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import argparse
  2. import codecs
  3. import datetime
  4. import json
  5. import logging
  6. import os.path
  7. import threading
  8. from socket import error as SocketError
  9. from socket import timeout
  10. from ssl import SSLError
  11. from urllib2 import URLError
  12. import cLogger, cComments
  13. import sys, os, time
  14. from httplib import HTTPException
  15. from instagram_private_api_extensions import live
  16. class NoBroadcastException(Exception):
  17. pass
  18. def main(apiArg, recordArg):
  19. global api
  20. global record
  21. global isRecording
  22. global currentDate
  23. global currentTime
  24. global broadcast
  25. global mpd_url
  26. currentTime = str(int(time.time()))
  27. currentDate = time.strftime("%Y%m%d")
  28. isRecording = False
  29. api = apiArg
  30. record = recordArg
  31. getUserInfo(record)
  32. def recordStream(broadcast):
  33. try:
  34. def check_status():
  35. printStatus()
  36. return heartbeat_info['broadcast_status'] not in ['active', 'interrupted']
  37. mpd_url = (broadcast.get('dash_manifest')
  38. or broadcast.get('dash_abr_playback_url')
  39. or broadcast['dash_playback_url'])
  40. outputDir = '{}_{}_{}_{}_downloads/'.format(currentDate ,record, broadcast['id'], currentTime)
  41. dl = live.Downloader(
  42. mpd=mpd_url,
  43. output_dir=outputDir,
  44. user_agent=api.user_agent,
  45. max_connection_error_retry=2,
  46. duplicate_etag_retry=60,
  47. callback_check=check_status,
  48. mpd_download_timeout=10,
  49. download_timeout=10)
  50. except Exception as e:
  51. cLogger.log('[E] Could not start recording broadcast: ' + str(e), "RED")
  52. cLogger.seperator("GREEN")
  53. sys.exit(0)
  54. try:
  55. viewers = broadcast.get('viewer_count', 0)
  56. started_mins, started_secs = divmod((int(time.time()) - broadcast['published_time']), 60)
  57. started_label = '%d minutes and ' % started_mins
  58. if started_secs:
  59. started_label += '%d seconds' % started_secs
  60. cLogger.log('[I] Starting broadcast recording:', "GREEN")
  61. last_stream = open("last_stream.html", "w")
  62. last_stream.write('<b>Username:</b> {}<br><b>MPD URL:</b> <a href="{}">LINK</a><br><b>Viewers:</b> {}<br><b>Missing:</b> {}'
  63. .format(record, mpd_url, str(int(viewers)), started_label))
  64. last_stream.close()
  65. cLogger.log('[I] Username : ' + record, "GREEN")
  66. cLogger.log('[I] MPD URL : ' + mpd_url, "GREEN")
  67. printStatus(api, broadcast)
  68. cLogger.log('[I] Recording broadcast...', "GREEN")
  69. dl.run()
  70. stitchVideo(dl, broadcast)
  71. except KeyboardInterrupt:
  72. cLogger.log('', "GREEN")
  73. cLogger.log('[I] Aborting broadcast recording...', "GREEN")
  74. if not dl.is_aborted:
  75. dl.stop()
  76. stitchVideo(dl, broadcast)
  77. def stitchVideo(dl, broadcast):
  78. isRecording = False
  79. cLogger.log('[I] Stitching downloaded files into video...', "GREEN")
  80. output_file = '{}_{}_{}_{}.mp4'.format(currentDate ,record, broadcast['id'], currentTime)
  81. dl.stitch(output_file, cleartempfiles=False)
  82. cLogger.log('[I] Successfully stitched downloaded files!', "GREEN")
  83. cLogger.seperator("GREEN")
  84. sys.exit(0)
  85. def getUserInfo(record):
  86. try:
  87. user_res = api.username_info(record)
  88. user_id = user_res['user']['pk']
  89. getBroadcast(user_id)
  90. except Exception as e:
  91. cLogger.log('[E] Could not get user info: ' + str(e), "RED")
  92. cLogger.seperator("GREEN")
  93. sys.exit(0)
  94. def getBroadcast(user_id):
  95. try:
  96. cLogger.log('[I] Checking broadcast for "' + record + '"...', "GREEN")
  97. broadcast = api.user_broadcast(user_id)
  98. if (broadcast is None):
  99. raise NoBroadcastException('No broadcast available.')
  100. else:
  101. recordStream(broadcast)
  102. except NoBroadcastException as e:
  103. cLogger.log('[W] ' + str(e), "YELLOW")
  104. cLogger.seperator("GREEN")
  105. sys.exit(0)
  106. except Exception as e:
  107. if (e.__name__ is not NoBroadcastException):
  108. cLogger.log('[E] Could not get broadcast info: ' + str(e), "RED")
  109. cLogger.seperator("GREEN")
  110. sys.exit(0)
  111. def printStatus(api, broadcast):
  112. heartbeat_info = api.broadcast_heartbeat_and_viewercount(broadcast['id'])
  113. viewers = broadcast.get('viewer_count', 0)
  114. started_mins, started_secs = divmod((int(time.time()) - broadcast['published_time']), 60)
  115. started_label = '%d minutes and ' % started_mins
  116. if started_secs:
  117. started_label += '%d seconds' % started_secs
  118. cLogger.log('[I] Viewers : ' + str(int(viewers)) + " watching", "GREEN")
  119. cLogger.log('[I] Airing time : ' + started_label, "GREEN")
  120. cLogger.log('[I] Status : ' + heartbeat_info['broadcast_status'].title(), "GREEN")
  121. cLogger.log('', "GREEN")