scripts.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. """
  2. Copyright © 2022 Noah Vogt <noah@noahvogt.com>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. """
  14. import sys
  15. from os import path, listdir
  16. from subprocess import Popen
  17. from shlex import split
  18. from time import sleep
  19. from re import match
  20. from pyautogui import keyDown, keyUp
  21. from PyQt5.QtWidgets import ( # pylint: disable=no-name-in-module
  22. QApplication,
  23. QMessageBox,
  24. )
  25. from PyQt5.QtWidgets import ( # pylint: disable=no-name-in-module
  26. QDialog,
  27. )
  28. from PyQt5.QtCore import QTimer # pylint: disable=no-name-in-module
  29. from utils import (
  30. log,
  31. error_msg,
  32. get_yyyy_mm_dd_date,
  33. expand_dir,
  34. )
  35. from input import (
  36. validate_cd_record_config,
  37. RadioButtonDialog,
  38. InfoMsgBox,
  39. )
  40. from os_agnostic import get_cd_drives, eject_drive
  41. import config as const
  42. def make_sure_file_exists(cachefile: str) -> None:
  43. if not path.isfile(cachefile):
  44. try:
  45. with open(
  46. cachefile, mode="w+", encoding="utf-8-sig"
  47. ) as file_creator:
  48. file_creator.write("")
  49. except (FileNotFoundError, PermissionError, IOError) as error:
  50. error_msg(
  51. "Failed to create file in '{}'. Reason: {}".format(
  52. cachefile, error
  53. )
  54. )
  55. def choose_right_cd_drive(drives: list) -> str:
  56. if len(drives) != 1:
  57. log("Warning: More than one cd drive found", color="yellow")
  58. if (
  59. const.CD_RECORD_PREFERED_DRIVE in drives
  60. and const.CD_RECORD_PREFERED_DRIVE != ""
  61. ):
  62. return const.CD_RECORD_PREFERED_DRIVE
  63. dialog = RadioButtonDialog(drives, "Choose a CD to Burn")
  64. if dialog.exec_() == QDialog.Accepted:
  65. print(f"Dialog accepted: {dialog.chosen}")
  66. return dialog.chosen
  67. log("Warning: Choosing first cd drive...", color="yellow")
  68. return drives[0]
  69. def get_burn_cmd(cd_drive: str, yyyy_mm_dd, padded_zfill_num: str) -> str:
  70. cue_sheet_path = path.join(
  71. expand_dir(const.CD_RECORD_OUTPUT_BASEDIR),
  72. yyyy_mm_dd,
  73. f"sheet-{padded_zfill_num}.cue",
  74. )
  75. return (
  76. f"cdrecord -pad dev={cd_drive} -dao -swab -text -audio "
  77. + f"-cuefile='{cue_sheet_path}'"
  78. )
  79. def switch_to_song(song_number: int) -> None:
  80. if song_number > const.OBS_MIN_SUBDIRS:
  81. song_number = 1
  82. log("sending hotkey to switch to scene {}".format(song_number), "cyan")
  83. scene_switch_hotkey = list(const.OBS_SWITCH_TO_SCENE_HOTKEY_PREFIX)
  84. scene_switch_hotkey.append("f{}".format(song_number))
  85. safe_send_hotkey(scene_switch_hotkey)
  86. log("sending hotkey to transition to scene {}".format(song_number), "cyan")
  87. safe_send_hotkey(const.OBS_TRANSITION_HOTKEY)
  88. create_cachfile_for_song(song_number)
  89. def safe_send_hotkey(hotkey: list, sleep_time=0.1) -> None:
  90. for key in hotkey:
  91. keyDown(key)
  92. sleep(sleep_time)
  93. for key in hotkey:
  94. keyUp(key)
  95. def create_cachfile_for_song(song) -> None:
  96. log("writing song {} to cachefile...".format(song))
  97. try:
  98. with open(
  99. const.NEXTSONG_CACHE_FILE, mode="w", encoding="utf-8-sig"
  100. ) as file_writer:
  101. file_writer.write(get_yyyy_mm_dd_date() + "\n")
  102. file_writer.write(str(song) + "\n")
  103. except (FileNotFoundError, PermissionError, IOError) as error:
  104. error_msg(
  105. "Failed to write to cachefile '{}'. Reason: {}".format(
  106. const.NEXTSONG_CACHE_FILE, error
  107. )
  108. )
  109. def mark_end_of_recording(cachefile_content: list) -> None:
  110. cachefile = expand_dir(const.CD_RECORD_CACHEFILE)
  111. log("marking end of recording...")
  112. try:
  113. with open(cachefile, mode="w+", encoding="utf-8-sig") as file_writer:
  114. file_writer.write(cachefile_content[0].strip() + "\n")
  115. file_writer.write("9001\n")
  116. file_writer.write(cachefile_content[2].strip() + "\n")
  117. file_writer.write(cachefile_content[3].strip() + "\n")
  118. file_writer.write(cachefile_content[4].strip() + "\n")
  119. file_writer.write(cachefile_content[5].strip() + "\n")
  120. except (FileNotFoundError, PermissionError, IOError) as error:
  121. error_msg(
  122. "Failed to write to cachefile '{}'. Reason: {}".format(
  123. cachefile, error
  124. )
  125. )
  126. def is_valid_cd_record_checkfile(
  127. cachefile_content: list, yyyy_mm_dd: str
  128. ) -> bool:
  129. return (
  130. len(cachefile_content) == 6
  131. # YYYY-MM-DD
  132. and bool(match(r"[0-9]{4}-[0-9]{2}-[0-9]{2}$", cachefile_content[0]))
  133. # last set marker
  134. and bool(match(r"^[0-9][0-9]?$", cachefile_content[1]))
  135. # pid of ffmpeg recording instance
  136. and bool(match(r"^[0-9]+$", cachefile_content[2]))
  137. # unix milis @ recording start
  138. and bool(match(r"^[0-9]+$", cachefile_content[3]))
  139. # unix milis @ last track
  140. and bool(match(r"^[0-9]+$", cachefile_content[4]))
  141. # cd number
  142. and bool(match(r"^[0-9]+$", cachefile_content[5]))
  143. # date matches today
  144. and cachefile_content[0].strip() == yyyy_mm_dd
  145. )
  146. class CDBurnerGUI:
  147. def __init__(self, cd_drive: str, yyyy_mm_dd: str, cd_num: str):
  148. self.app = QApplication([])
  149. self.drive = cd_drive
  150. self.yyyy_mm_dd = yyyy_mm_dd
  151. self.cd_num = cd_num
  152. self.exit_code = 1
  153. self.show_burning_msg_box()
  154. self.start_burn_subprocess()
  155. self.app.exec_()
  156. def burning_successful(self) -> bool:
  157. if self.exit_code == 0:
  158. return True
  159. return False
  160. def show_burning_msg_box(self):
  161. self.message_box = QMessageBox()
  162. self.message_box.setWindowTitle("Info")
  163. self.message_box.setText("Burning CD...")
  164. self.message_box.setInformativeText(
  165. "Please wait for a few minutes. You can close this Window, as "
  166. + "there will spawn another window after the operation is "
  167. + "finished."
  168. )
  169. self.message_box.show()
  170. def start_burn_subprocess(self):
  171. process = Popen(
  172. split(get_burn_cmd(self.drive, self.yyyy_mm_dd, self.cd_num))
  173. )
  174. while process.poll() is None:
  175. QApplication.processEvents()
  176. self.message_box.accept()
  177. # Yeah this is hacky but it doesn't work when calling quit directly
  178. QTimer.singleShot(0, self.app.quit)
  179. self.exit_code = process.returncode
  180. def burn_cds_of_day(yyyy_mm_dd: str) -> None:
  181. validate_cd_record_config()
  182. make_sure_file_exists(const.CD_RECORD_CACHEFILE)
  183. try:
  184. target_dir = path.join(
  185. expand_dir(const.CD_RECORD_OUTPUT_BASEDIR), yyyy_mm_dd
  186. )
  187. if not path.isfile(target_dir):
  188. exit_as_no_cds_found(target_dir)
  189. target_files = sorted(listdir(target_dir))
  190. cue_sheets = []
  191. for file in target_files:
  192. if file.endswith(".cue") and len(file) == 17:
  193. cue_sheets.append(file)
  194. if not target_files:
  195. exit_as_no_cds_found(target_dir)
  196. if len(cue_sheets) == 1:
  197. burn_and_eject_cd(yyyy_mm_dd, "0000001")
  198. else:
  199. for num, file in enumerate(cue_sheets):
  200. log(f"file found: {file}")
  201. except (FileNotFoundError, PermissionError, IOError):
  202. InfoMsgBox(
  203. QMessageBox.Critical,
  204. "Error",
  205. "Error: Could not access directory: "
  206. + f"'{const.CD_RECORD_OUTPUT_BASEDIR}'",
  207. )
  208. sys.exit(1)
  209. def exit_as_no_cds_found(target_dir):
  210. InfoMsgBox(
  211. QMessageBox.Critical,
  212. "Error",
  213. f"Error: Did not find any CD's in: {target_dir}.",
  214. )
  215. sys.exit(1)
  216. def burn_and_eject_cd(yyyy_mm_dd: str, padded_cd_num: str) -> None:
  217. cd_drives = get_cd_drives()
  218. if not cd_drives:
  219. InfoMsgBox(
  220. QMessageBox.Critical,
  221. "Error",
  222. "Error: Could not find a CD-ROM. Please try again",
  223. )
  224. sys.exit(1)
  225. drive = choose_right_cd_drive(cd_drives)
  226. burn_success = CDBurnerGUI(
  227. drive, yyyy_mm_dd, padded_cd_num
  228. ).burning_successful()
  229. if burn_success:
  230. InfoMsgBox(QMessageBox.Info, "Info", "Successfully burned CD.")
  231. else:
  232. InfoMsgBox(QMessageBox.Critical, "Error", "Error: Failed to burn CD.")
  233. eject_drive(drive)