radio-save.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #!/usr/bin/env python3
  2. from requests import get
  3. from time import time
  4. from sys import argv
  5. from datetime import datetime
  6. from os import popen
  7. if len(argv) > 1:
  8. if argv[1] == 'xwave':
  9. stream_url = 'http://ns319459.ip-91-121-67.eu:8000'
  10. elif argv[1] == 'ifm1':
  11. stream_url = 'http://radio.intergalactic.fm:80/1'
  12. elif argv[1] == 'ifm2':
  13. stream_url = 'http://radio.intergalactic.fm:80/2'
  14. elif argv[1] == 'ifm3':
  15. stream_url = 'http://radio.intergalactic.fm:80/3'
  16. elif (argv[1].split(':')[0] == 'http') or (argv[1].split(':')[0] == 'https'):
  17. stream_url = argv[1]
  18. else:
  19. print('invalid stream:', argv[1])
  20. exit()
  21. else:
  22. print('must provide a stream as the only argument')
  23. exit()
  24. def rip():
  25. r = ''
  26. while not r:
  27. try:
  28. r = get(stream_url, headers={'Icy-MetaData': '1'}, stream=True, timeout=10)
  29. except:
  30. print('there was a problem connecting to the stream')
  31. metaint = int(r.headers['icy-metaint'])
  32. bitrate = int(r.headers['icy-br'].split(', ')[0])
  33. stream_buffer = bytearray()
  34. stream_byte_counter = 0
  35. extension = 'mp3'
  36. mp3_file_name = ''
  37. sec_save_interval = 15
  38. bytes_per_second = (bitrate * 1024) / 8
  39. mp3_write_chunk_size = bytes_per_second * sec_save_interval
  40. all_current_headers = ''
  41. for key, value in r.headers.items():
  42. this_header_string = key + ' : ' + value
  43. all_current_headers += this_header_string + '\n'
  44. header_file_name = str(int(time())) + ' ' + 'headers' + '.' + 'txt'
  45. with open(header_file_name, "w") as headerf:
  46. headerf.write(all_current_headers)
  47. print(all_current_headers)
  48. while True:
  49. for mp3_chunk in r.iter_content(chunk_size=metaint):
  50. stream_buffer.extend(mp3_chunk)
  51. stream_byte_counter += metaint
  52. time_now = str(datetime.now()).split('.')[0]
  53. columns = int(popen('stty size', 'r').read().split()[1])
  54. name_size = columns - 19 - 10 - 4
  55. pstr = time_now # 19 chars
  56. pstr += " "
  57. pstr += mp3_file_name[0:name_size]
  58. pstr += " "
  59. pstr += str(stream_byte_counter) # assume this is 10 chars
  60. pstr += " "
  61. pstr += str(int(stream_byte_counter / bytes_per_second)) # 4chars
  62. print(pstr, end='\r')
  63. break
  64. for metalen_byte in r.iter_content(chunk_size=1):
  65. metalen = int.from_bytes(metalen_byte, 'little') * 16
  66. break
  67. if mp3_file_name and (len(stream_buffer) >= mp3_write_chunk_size):
  68. with open(mp3_file_name, 'ab') as f:
  69. f.write(stream_buffer)
  70. stream_buffer = bytearray()
  71. if metalen > 0:
  72. if mp3_file_name:
  73. with open(mp3_file_name, 'ab') as f:
  74. f.write(stream_buffer)
  75. stream_buffer = bytearray()
  76. with open("logfile.txt", "a") as logf:
  77. logf.write(mp3_file_name + '\n')
  78. for meta_chunk in r.iter_content(chunk_size=metalen):
  79. stream_title = meta_chunk.decode().split("StreamTitle='")[1].rsplit("';")[0]
  80. title_change_time = str(int(time()))
  81. mp3_file_name = title_change_time + ' ' + stream_title + '.' + extension
  82. mp3_file_name = mp3_file_name.replace('/', '\u2215').replace('\0', '')
  83. print()
  84. stream_byte_counter = 0
  85. break
  86. #rip()
  87. if __name__ == '__main__':
  88. while True:
  89. try:
  90. rip()
  91. except KeyboardInterrupt:
  92. print()
  93. exit()
  94. except:
  95. print("error with rip()")
  96. pass