scripts.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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
  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) -> str:
  70. cue_sheet_path = path.join(
  71. expand_dir(const.CD_RECORD_OUTPUT_BASEDIR), yyyy_mm_dd, "sheet.cue"
  72. )
  73. return (
  74. f"cdrecord -pad dev={cd_drive} -dao -swab -text -audio "
  75. + f"-cuefile={cue_sheet_path}"
  76. )
  77. def switch_to_song(song_number: int) -> None:
  78. if song_number > const.OBS_MIN_SUBDIRS:
  79. song_number = 1
  80. log("sending hotkey to switch to scene {}".format(song_number), "cyan")
  81. scene_switch_hotkey = list(const.OBS_SWITCH_TO_SCENE_HOTKEY_PREFIX)
  82. scene_switch_hotkey.append("f{}".format(song_number))
  83. safe_send_hotkey(scene_switch_hotkey)
  84. log("sending hotkey to transition to scene {}".format(song_number), "cyan")
  85. safe_send_hotkey(const.OBS_TRANSITION_HOTKEY)
  86. create_cachfile_for_song(song_number)
  87. def safe_send_hotkey(hotkey: list, sleep_time=0.1) -> None:
  88. for key in hotkey:
  89. keyDown(key)
  90. sleep(sleep_time)
  91. for key in hotkey:
  92. keyUp(key)
  93. def create_cachfile_for_song(song) -> None:
  94. log("writing song {} to cachefile...".format(song))
  95. try:
  96. with open(
  97. const.NEXTSONG_CACHE_FILE, mode="w", encoding="utf-8-sig"
  98. ) as file_writer:
  99. file_writer.write(get_yyyy_mm_dd_date() + "\n")
  100. file_writer.write(str(song) + "\n")
  101. except (FileNotFoundError, PermissionError, IOError) as error:
  102. error_msg(
  103. "Failed to write to cachefile '{}'. Reason: {}".format(
  104. const.NEXTSONG_CACHE_FILE, error
  105. )
  106. )
  107. def is_valid_cd_record_checkfile(
  108. cachefile_content: list, yyyy_mm_dd: str
  109. ) -> bool:
  110. return (
  111. len(cachefile_content) == 5
  112. # YYYY-MM-DD
  113. and bool(match(r"[0-9]{4}-[0-9]{2}-[0-9]{2}$", cachefile_content[0]))
  114. # last marker
  115. and bool(match(r"^[0-9]+$", cachefile_content[1]))
  116. # pid of ffmpeg recording instance
  117. and bool(match(r"^[0-9]+$", cachefile_content[2]))
  118. # unix milis @ recording start
  119. and bool(match(r"^[0-9]+$", cachefile_content[3]))
  120. # unix milis @ last track
  121. and bool(match(r"^[0-9]+$", cachefile_content[4]))
  122. # date matches today
  123. and cachefile_content[0].strip() == yyyy_mm_dd
  124. )
  125. class CDBurnerGUI:
  126. def __init__(self, cd_drive: str, yyyy_mm_dd: str):
  127. self.app = QApplication([])
  128. self.drive = cd_drive
  129. self.yyyy_mm_dd = yyyy_mm_dd
  130. self.exit_code = 1
  131. self.show_burning_msg_box()
  132. self.start_burn_subprocess()
  133. self.app.exec_()
  134. def burning_successful(self) -> bool:
  135. if self.exit_code == 0:
  136. return True
  137. return False
  138. def show_burning_msg_box(self):
  139. self.message_box = QMessageBox()
  140. self.message_box.setWindowTitle("Info")
  141. self.message_box.setText("Burning CD...")
  142. self.message_box.setInformativeText(
  143. "Please wait for a few minutes. You can close this Window, as "
  144. + "there will spawn another window after the operation is "
  145. + "finished."
  146. )
  147. self.message_box.show()
  148. def start_burn_subprocess(self):
  149. process = Popen(split(get_burn_cmd(self.drive, self.yyyy_mm_dd)))
  150. while process.poll() is None:
  151. QApplication.processEvents()
  152. self.message_box.accept()
  153. # Yeah this is hacky but it doesn't work when calling quit directly
  154. QTimer.singleShot(0, self.app.quit)
  155. self.exit_code = process.returncode
  156. def burn_cd_of_day(yyyy_mm_dd: str) -> None:
  157. validate_cd_record_config()
  158. make_sure_file_exists(const.CD_RECORD_CACHEFILE)
  159. cd_drives = get_cd_drives()
  160. if not cd_drives:
  161. InfoMsgBox(
  162. QMessageBox.Critical,
  163. "Error",
  164. "Error: Could not find a CD-ROM. Please try again",
  165. )
  166. sys.exit(1)
  167. drive = choose_right_cd_drive(cd_drives)
  168. burn_success = CDBurnerGUI(drive, yyyy_mm_dd).burning_successful()
  169. if burn_success:
  170. InfoMsgBox(QMessageBox.Info, "Info", "Successfully burned CD.")
  171. else:
  172. InfoMsgBox(QMessageBox.Critical, "Error", "Error: Failed to burn CD.")
  173. eject_drive(drive)