scripts.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. SheetAndPreviewChooser,
  40. )
  41. from os_agnostic import get_cd_drives, eject_drive
  42. import config as const
  43. def make_sure_file_exists(cachefile: str) -> None:
  44. if not path.isfile(cachefile):
  45. try:
  46. with open(
  47. cachefile, mode="w+", encoding="utf-8-sig"
  48. ) as file_creator:
  49. file_creator.write("")
  50. except (FileNotFoundError, PermissionError, IOError) as error:
  51. error_msg(
  52. "Failed to create file in '{}'. Reason: {}".format(
  53. cachefile, error
  54. )
  55. )
  56. def choose_right_cd_drive(drives: list) -> str:
  57. if len(drives) != 1:
  58. log("Warning: More than one cd drive found", color="yellow")
  59. if (
  60. const.CD_RECORD_PREFERED_DRIVE in drives
  61. and const.CD_RECORD_PREFERED_DRIVE != ""
  62. ):
  63. return const.CD_RECORD_PREFERED_DRIVE
  64. dialog = RadioButtonDialog(drives, "Choose a CD to Burn")
  65. if dialog.exec_() == QDialog.Accepted:
  66. print(f"Dialog accepted: {dialog.chosen_sheets}")
  67. return dialog.chosen_sheets
  68. log("Warning: Choosing first cd drive...", color="yellow")
  69. return drives[0]
  70. def get_burn_cmd(cd_drive: str, yyyy_mm_dd, padded_zfill_num: str) -> str:
  71. cue_sheet_path = path.join(
  72. expand_dir(const.CD_RECORD_OUTPUT_BASEDIR),
  73. yyyy_mm_dd,
  74. f"sheet-{padded_zfill_num}.cue",
  75. )
  76. return (
  77. f"cdrecord -pad dev={cd_drive} -dao -swab -text -audio "
  78. + f"-cuefile='{cue_sheet_path}'"
  79. )
  80. def switch_to_song(song_number: int) -> None:
  81. if song_number > const.OBS_MIN_SUBDIRS:
  82. song_number = 1
  83. log("sending hotkey to switch to scene {}".format(song_number), "cyan")
  84. scene_switch_hotkey = list(const.OBS_SWITCH_TO_SCENE_HOTKEY_PREFIX)
  85. scene_switch_hotkey.append("f{}".format(song_number))
  86. safe_send_hotkey(scene_switch_hotkey)
  87. log("sending hotkey to transition to scene {}".format(song_number), "cyan")
  88. safe_send_hotkey(const.OBS_TRANSITION_HOTKEY)
  89. create_cachfile_for_song(song_number)
  90. def safe_send_hotkey(hotkey: list, sleep_time=0.1) -> None:
  91. for key in hotkey:
  92. keyDown(key)
  93. sleep(sleep_time)
  94. for key in hotkey:
  95. keyUp(key)
  96. def create_cachfile_for_song(song) -> None:
  97. log("writing song {} to cachefile...".format(song))
  98. try:
  99. with open(
  100. const.NEXTSONG_CACHE_FILE, mode="w", encoding="utf-8-sig"
  101. ) as file_writer:
  102. file_writer.write(get_yyyy_mm_dd_date() + "\n")
  103. file_writer.write(str(song) + "\n")
  104. except (FileNotFoundError, PermissionError, IOError) as error:
  105. error_msg(
  106. "Failed to write to cachefile '{}'. Reason: {}".format(
  107. const.NEXTSONG_CACHE_FILE, error
  108. )
  109. )
  110. def mark_end_of_recording(cachefile_content: list) -> None:
  111. cachefile = expand_dir(const.CD_RECORD_CACHEFILE)
  112. log("marking end of recording...")
  113. try:
  114. with open(cachefile, mode="w+", encoding="utf-8-sig") as file_writer:
  115. file_writer.write(cachefile_content[0].strip() + "\n")
  116. file_writer.write("9001\n")
  117. file_writer.write(cachefile_content[2].strip() + "\n")
  118. file_writer.write(cachefile_content[3].strip() + "\n")
  119. file_writer.write(cachefile_content[4].strip() + "\n")
  120. file_writer.write(cachefile_content[5].strip() + "\n")
  121. except (FileNotFoundError, PermissionError, IOError) as error:
  122. error_msg(
  123. "Failed to write to cachefile '{}'. Reason: {}".format(
  124. cachefile, error
  125. )
  126. )
  127. def is_valid_cd_record_checkfile(
  128. cachefile_content: list, yyyy_mm_dd: str
  129. ) -> bool:
  130. return (
  131. len(cachefile_content) == 6
  132. # YYYY-MM-DD
  133. and bool(match(r"[0-9]{4}-[0-9]{2}-[0-9]{2}$", cachefile_content[0]))
  134. # last set marker
  135. and bool(match(r"^[0-9][0-9]?$", cachefile_content[1]))
  136. # pid of ffmpeg recording instance
  137. and bool(match(r"^[0-9]+$", cachefile_content[2]))
  138. # unix milis @ recording start
  139. and bool(match(r"^[0-9]+$", cachefile_content[3]))
  140. # unix milis @ last track
  141. and bool(match(r"^[0-9]+$", cachefile_content[4]))
  142. # cd number
  143. and bool(match(r"^[0-9]+$", cachefile_content[5]))
  144. # date matches today
  145. and cachefile_content[0].strip() == yyyy_mm_dd
  146. )
  147. class CDBurnerGUI:
  148. def __init__(self, cd_drive: str, yyyy_mm_dd: str, cd_num: str):
  149. self.app = QApplication([])
  150. self.drive = cd_drive
  151. self.yyyy_mm_dd = yyyy_mm_dd
  152. self.cd_num = cd_num
  153. self.exit_code = 1
  154. self.show_burning_msg_box()
  155. self.start_burn_subprocess()
  156. self.app.exec_()
  157. def burning_successful(self) -> bool:
  158. if self.exit_code == 0:
  159. return True
  160. return False
  161. def show_burning_msg_box(self):
  162. self.message_box = QMessageBox()
  163. self.message_box.setWindowTitle("Info")
  164. self.message_box.setText("Burning CD...")
  165. self.message_box.setInformativeText(
  166. "Please wait for a few minutes. You can close this Window, as "
  167. + "there will spawn another window after the operation is "
  168. + "finished."
  169. )
  170. self.message_box.show()
  171. def start_burn_subprocess(self):
  172. process = Popen(
  173. split(get_burn_cmd(self.drive, self.yyyy_mm_dd, self.cd_num))
  174. )
  175. while process.poll() is None:
  176. QApplication.processEvents()
  177. self.message_box.accept()
  178. # Yeah this is hacky but it doesn't work when calling quit directly
  179. QTimer.singleShot(0, self.app.quit)
  180. self.exit_code = process.returncode
  181. def burn_cds_of_day(yyyy_mm_dd: str) -> None:
  182. validate_cd_record_config()
  183. make_sure_file_exists(const.CD_RECORD_CACHEFILE)
  184. try:
  185. target_dir = path.join(
  186. expand_dir(const.CD_RECORD_OUTPUT_BASEDIR), yyyy_mm_dd
  187. )
  188. if not path.isdir(target_dir):
  189. exit_as_no_cds_found(target_dir)
  190. target_files = sorted(listdir(target_dir))
  191. cue_sheets = []
  192. for file in target_files:
  193. if is_legal_sheet_filename(file):
  194. cue_sheets.append(file)
  195. if not target_files:
  196. exit_as_no_cds_found(target_dir)
  197. if len(cue_sheets) == 1:
  198. burn_and_eject_cd(
  199. yyyy_mm_dd, "1".zfill(const.CD_RECORD_FILENAME_ZFILL)
  200. )
  201. else:
  202. app = QApplication([])
  203. dialog = SheetAndPreviewChooser(
  204. target_dir, cue_sheets, f"Preview CD's for {yyyy_mm_dd}"
  205. )
  206. if dialog.exec_() == QDialog.Accepted:
  207. if not dialog.chosen_sheets:
  208. sys.exit(0)
  209. log(f"Burning CD's from sheets: {dialog.chosen_sheets}")
  210. for sheet in dialog.chosen_sheets:
  211. del app # pyright: ignore
  212. burn_and_eject_cd(
  213. yyyy_mm_dd, get_padded_cd_num_from_sheet_filename(sheet)
  214. )
  215. except (FileNotFoundError, PermissionError, IOError):
  216. InfoMsgBox(
  217. QMessageBox.Critical,
  218. "Error",
  219. "Error: Could not access directory: "
  220. + f"'{const.CD_RECORD_OUTPUT_BASEDIR}'",
  221. )
  222. sys.exit(1)
  223. def exit_as_no_cds_found(target_dir):
  224. InfoMsgBox(
  225. QMessageBox.Critical,
  226. "Error",
  227. f"Error: Did not find any CD's in: {target_dir}.",
  228. )
  229. sys.exit(1)
  230. def is_legal_sheet_filename(filename: str) -> bool:
  231. return bool(match(r"^sheet-[0-9]+\.cue", filename)) and len(filename) == 17
  232. def get_padded_cd_num_from_sheet_filename(filename: str) -> str:
  233. if not is_legal_sheet_filename(filename):
  234. InfoMsgBox(
  235. QMessageBox.Critical,
  236. "Error",
  237. f"Error: filename '{filename}' in illegal format",
  238. )
  239. sys.exit(1)
  240. return filename[6:13]
  241. def burn_and_eject_cd(yyyy_mm_dd: str, padded_cd_num: str) -> None:
  242. cd_drives = get_cd_drives()
  243. if not cd_drives:
  244. InfoMsgBox(
  245. QMessageBox.Critical,
  246. "Error",
  247. "Error: Could not find a CD-ROM. Please try again",
  248. )
  249. sys.exit(1)
  250. drive = choose_right_cd_drive(cd_drives)
  251. burn_success = CDBurnerGUI(
  252. drive, yyyy_mm_dd, padded_cd_num
  253. ).burning_successful()
  254. if burn_success:
  255. InfoMsgBox(QMessageBox.Info, "Info", "Successfully burned CD.")
  256. else:
  257. InfoMsgBox(QMessageBox.Critical, "Error", "Error: Failed to burn CD.")
  258. eject_drive(drive)