fetcher.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import json
  2. import requests
  3. import os
  4. import subprocess
  5. import typing
  6. import threading
  7. import time
  8. class song:
  9. def __init__(self, json_song) -> None:
  10. self.__url = json_song["url"]
  11. self.__artist = json_song["artist"]
  12. self.__title = json_song["title"]
  13. @property
  14. def url(self) -> str:
  15. return self.__url
  16. @property
  17. def artist(self) -> str:
  18. return self.__artist
  19. @property
  20. def title(self) -> str:
  21. return self.__title
  22. def seg_finder(mlst: typing.List[str]):
  23. for i in mlst:
  24. if i[:3] == "seg":
  25. yield i
  26. def the_fetcher(m_subj: song, number):
  27. global counter
  28. global thread_count
  29. start = time.time()
  30. root_url = m_subj.url.split("index.m3u8")[0]
  31. inc_name = root_url.split("/")[-2]
  32. os.mkdir("music/" + inc_name)
  33. f = open("music/" + inc_name + "/" + "index.m3u8", "wb")
  34. m3u8 = requests.get(m_subj.url).content
  35. f.write(m3u8)
  36. f.close()
  37. m3u8 = list(seg_finder(str(m3u8).split("\\n")[:-1]))
  38. m3u8.sort()
  39. for i in m3u8:
  40. f = open("music/" + inc_name + "/" + i, "wb")
  41. f.write(requests.get(root_url + i).content)
  42. f.close()
  43. prc = subprocess.Popen(
  44. f'ffmpeg -protocol_whitelist file,http,https,tcp,tls,crypto -allowed_extensions ALL -i music/{inc_name}/index.m3u8 -metadata title="{m_subj.title}" -metadata artist="{m_subj.artist}" -metadata track={number} music/"{m_subj.title} - {m_subj.artist}".mp3 &> /dev/null && rm -r music/{inc_name}',
  45. shell=True,
  46. )
  47. prc.wait()
  48. print(
  49. f"Process number {number} ({m_subj.title} - {m_subj.artist}) is done in {time.time() - start}s"
  50. )
  51. counter -= 1
  52. locker.acquire()
  53. thread_count -= 1
  54. locker.release()
  55. inp = open("music_info.json", "r+")
  56. m_seq = [song(i) for i in json.load(inp)]
  57. m_seq.reverse()
  58. counter = len(m_seq)
  59. endway = counter
  60. locker = threading.Lock()
  61. thread_count = 0
  62. glb_start = time.time()
  63. i = 0
  64. while i < endway:
  65. locker.acquire()
  66. if thread_count >= 8:
  67. locker.release()
  68. else:
  69. i += 1
  70. thread_count += 1
  71. locker.release()
  72. thread = threading.Thread(target=the_fetcher, args=(m_seq.pop(), i))
  73. thread.start()
  74. while counter != 0:
  75. pass
  76. print(f"Program is done in {(time.time() - glb_start)}s")