cd.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 os
  13. from utils import log, CustomException
  14. if os.name == "nt":
  15. # pylint: disable=import-error
  16. import wmi # pyright: ignore
  17. import ctypes
  18. else:
  19. from pycdio import DRIVER_DEVICE
  20. from cdio import (
  21. get_devices,
  22. DriverUnsupportedError,
  23. DeviceException,
  24. )
  25. def get_cd_drives() -> list[str]:
  26. if os.name == "nt":
  27. c = wmi.WMI()
  28. cd_drives = []
  29. for cd in c.Win32_CDROMDrive():
  30. cd_drives.append(cd.Drive)
  31. # pylint: disable=possibly-used-before-assignment
  32. else:
  33. raw_cd_drives = get_devices(DRIVER_DEVICE)
  34. cd_drives = []
  35. for cd in raw_cd_drives:
  36. cd_drives.append(str(cd.get_device()))
  37. return cd_drives
  38. # pylint: disable=possibly-used-before-assignment
  39. def eject_drive(drive: str) -> None: # pyright: ignore
  40. if os.name == "nt":
  41. ctypes.windll.WINMM.mciSendStringW(
  42. f"open {drive} type cdaudio alias d_drive", None, 0, None
  43. )
  44. ctypes.windll.WINMM.mciSendStringW(
  45. "set d_drive door open", None, 0, None
  46. )
  47. else:
  48. try:
  49. raw_drives = get_devices(DRIVER_DEVICE)
  50. drive_ejected = False
  51. for cd in raw_drives:
  52. if str(cd.get_device()) == drive:
  53. drive.eject_media() # pyright: ignore
  54. drive_ejected = True
  55. if not drive_ejected:
  56. raise CustomException(f"Drive {drive} not found")
  57. # pylint: disable=possibly-used-before-assignment
  58. except (DriverUnsupportedError, DeviceException, CustomException):
  59. log(f"Eject of CD-ROM drive {drive} failed") # pyright: ignore