switch.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # Copyright © 2024 Noah Vogt <noah@noahvogt.com>
  2. # This program is free software: you can redistribute it and/or modify
  3. # it under the terms of the GNU General Public License as published by
  4. # the Free Software Foundation, either version 3 of the License, or
  5. # (at your option) any later version.
  6. # This program is distributed in the hope that it will be useful,
  7. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. # GNU General Public License for more details.
  10. # You should have received a copy of the GNU General Public License
  11. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  12. import sys
  13. from re import match
  14. from enum import Enum
  15. from PyQt5.QtWidgets import ( # pylint: disable=no-name-in-module
  16. QApplication,
  17. QMessageBox,
  18. )
  19. from utils import (
  20. log,
  21. get_yyyy_mm_dd_date,
  22. expand_dir,
  23. InfoMsgBox,
  24. )
  25. from input import get_cachefile_content
  26. import config as const
  27. from .obs import change_to_song_scene
  28. class SongDirection(Enum):
  29. PREVIOUS = "previous"
  30. NEXT = "next"
  31. def cycle_to_song_direction(song_direction: SongDirection):
  32. cachefile_content = get_cachefile_content(const.NEXTSONG_CACHE_FILE)
  33. if song_direction == SongDirection.PREVIOUS:
  34. step = -1
  35. else:
  36. step = 1
  37. if (
  38. not (
  39. len(cachefile_content) == 2
  40. and match(r"[0-9]{4}-[0-9]{2}-[0-9]{2}$", cachefile_content[0])
  41. and match(r"^[0-9]+$", cachefile_content[1])
  42. )
  43. or cachefile_content[0].strip() != get_yyyy_mm_dd_date()
  44. ):
  45. switch_to_song(1)
  46. else:
  47. switch_to_song(int(cachefile_content[1]) + step)
  48. def switch_to_song(song_number: int) -> None:
  49. if song_number > const.OBS_MIN_SUBDIRS:
  50. song_number = 1
  51. if song_number < 1:
  52. song_number = const.OBS_MIN_SUBDIRS
  53. change_to_song_scene(song_number)
  54. create_cachfile_for_song(song_number)
  55. def create_cachfile_for_song(song) -> None:
  56. log("writing song {} to cachefile...".format(song))
  57. cachefile = expand_dir(const.NEXTSONG_CACHE_FILE)
  58. try:
  59. with open(cachefile, mode="w", encoding="utf-8-sig") as file_writer:
  60. file_writer.write(get_yyyy_mm_dd_date() + "\n")
  61. file_writer.write(str(song) + "\n")
  62. except (FileNotFoundError, PermissionError, IOError) as error:
  63. app = QApplication
  64. InfoMsgBox(
  65. QMessageBox.Critical,
  66. "Error",
  67. "Failed to write to cachefile '{}'. Reason: {}".format(
  68. cachefile, error
  69. ),
  70. )
  71. del app
  72. sys.exit(1)