win-planner 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,167 @@
1
+ """
2
+ win_planner — регистрация задач в Планировщике задач Windows.
3
+
4
+ API:
5
+ task_create(name=..., run_filepath=..., highest_available=..., description=...)
6
+ task_update(name=..., run_filepath=..., highest_available=..., description=..., new_name=...)
7
+
8
+ Триггер фиксирован: запуск при входе пользователя в систему.
9
+ Для задач с highest_available=True сам скрипт должен работать от администратора.
10
+ """
11
+
12
+ import os
13
+ import ctypes
14
+ from datetime import datetime
15
+
16
+ __version__ = "1.0.0"
17
+ __all__ = ["task_create", "task_update"]
18
+
19
+ try:
20
+ import pythoncom
21
+ from win32com.client import Dispatch
22
+ from win32com.taskscheduler.taskscheduler import (
23
+ TASK_TRIGGER_LOGON,
24
+ TASK_ACTION_EXEC,
25
+ TASK_LOGON_INTERACTIVE_TOKEN,
26
+ TASK_CREATE_OR_UPDATE,
27
+ )
28
+ _COM_OK = True
29
+ except ImportError:
30
+ _COM_OK = False
31
+
32
+
33
+ def _is_admin() -> bool:
34
+ try:
35
+ return bool(ctypes.windll.shell32.IsUserAnAdmin())
36
+ except Exception:
37
+ return False
38
+
39
+
40
+ def _service():
41
+ """Подключение к службе Планировщика задач."""
42
+ if not _COM_OK:
43
+ raise RuntimeError("Установите pywin32: pip install pywin32")
44
+ pythoncom.CoInitialize()
45
+ svc = Dispatch("Schedule.Service")
46
+ svc.Connect()
47
+ return svc
48
+
49
+
50
+ def _new_definition(svc, run_filepath: str, highest_available: bool, description: str):
51
+ """Собирает определение задачи из четырёх атрибутов."""
52
+ td = svc.NewTask(0)
53
+
54
+ # Описание
55
+ td.RegistrationInfo.Description = description
56
+ try:
57
+ td.RegistrationInfo.Author = os.getlogin()
58
+ except OSError:
59
+ pass
60
+
61
+ # Права запуска: RunLevel 1 = HIGHEST (наивысшие доступные), 0 = LIMITED
62
+ td.Principal.LogonType = TASK_LOGON_INTERACTIVE_TOKEN
63
+ td.Principal.RunLevel = 1 if highest_available else 0
64
+
65
+ # Настройки
66
+ td.Settings.StartWhenAvailable = True
67
+ td.Settings.AllowStartIfOnBatteries = True
68
+ td.Settings.StopIfGoingOnBatteries = False
69
+
70
+ # Триггер — при входе пользователя
71
+ td.Triggers.Create(TASK_TRIGGER_LOGON)
72
+
73
+ # Действие — запуск файла
74
+ action = td.Actions.Create(TASK_ACTION_EXEC)
75
+ action.Path = run_filepath
76
+
77
+ return td
78
+
79
+
80
+ def _validate(name: str, run_filepath: str):
81
+ if not name or not name.strip():
82
+ raise ValueError("name не может быть пустым")
83
+ if "\\" in name or "/" in name:
84
+ raise ValueError("name не должен содержать '\\' или '/'")
85
+ if not os.path.isfile(run_filepath):
86
+ raise FileNotFoundError(f"Файл не найден: {run_filepath}")
87
+
88
+
89
+ def task_create(name: str,
90
+ run_filepath: str,
91
+ highest_available: bool = True,
92
+ description: str = "") -> dict:
93
+ """
94
+ Регистрирует задачу в Планировщике задач Windows.
95
+
96
+ Параметры:
97
+ name — кастомное имя задачи;
98
+ run_filepath — путь к exe/скрипту;
99
+ highest_available — запуск с наивысшими доступными правами;
100
+ description — описание задачи.
101
+ """
102
+ _validate(name, run_filepath)
103
+
104
+ svc = _service()
105
+ td = _new_definition(svc, run_filepath, highest_available, description)
106
+ svc.GetFolder("\\").RegisterTaskDefinition(
107
+ name, td, TASK_CREATE_OR_UPDATE, None, None, TASK_LOGON_INTERACTIVE_TOKEN
108
+ )
109
+ return {
110
+ "name": name,
111
+ "run_filepath": run_filepath,
112
+ "highest_available": highest_available,
113
+ "description": description,
114
+ "registered_at": datetime.now().isoformat(timespec="seconds"),
115
+ }
116
+
117
+
118
+ def task_update(name: str,
119
+ run_filepath: str | None = None,
120
+ highest_available: bool | None = None,
121
+ description: str | None = None,
122
+ new_name: str | None = None) -> dict:
123
+ """
124
+ Изменяет атрибуты уже созданной задачи.
125
+
126
+ Передайте только то, что нужно поменять:
127
+ run_filepath — новый путь к файлу;
128
+ highest_available — новое значение прав запуска;
129
+ description — новое описание;
130
+ new_name — переименовать задачу.
131
+
132
+ Не переданные параметры остаются прежними.
133
+ """
134
+ svc = _service()
135
+ try:
136
+ task = svc.GetFolder("\\").GetTask(name)
137
+ td = task.Definition
138
+ except Exception as exc:
139
+ raise LookupError(f"Задача '{name}' не найдена") from exc
140
+
141
+ if new_name:
142
+ _validate(new_name, "C:\\Windows\\System32") # проверяем только имя
143
+ if run_filepath is not None and not os.path.isfile(run_filepath):
144
+ raise FileNotFoundError(f"Файл не найден: {run_filepath}")
145
+
146
+ # Меняем только переданные атрибуты
147
+ if description is not None:
148
+ td.RegistrationInfo.Description = description
149
+ if highest_available is not None:
150
+ td.Principal.RunLevel = 1 if highest_available else 0
151
+ if run_filepath is not None:
152
+ td.Actions.Item(1).Path = run_filepath
153
+
154
+ target = new_name if new_name else name
155
+ svc.GetFolder("\\").RegisterTaskDefinition(
156
+ target, td, TASK_CREATE_OR_UPDATE, None, None, TASK_LOGON_INTERACTIVE_TOKEN
157
+ )
158
+ if new_name and new_name != name:
159
+ svc.GetFolder("\\").DeleteTask(name, 0)
160
+
161
+ return {
162
+ "name": target,
163
+ "run_filepath": td.Actions.Item(1).Path,
164
+ "highest_available": td.Principal.RunLevel == 1,
165
+ "description": td.RegistrationInfo.Description,
166
+ "updated_at": datetime.now().isoformat(timespec="seconds"),
167
+ }
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: win_planner
3
+ Version: 1.0.0
4
+ Summary: Регистрация задач в Планировщике задач Windows с наивысшими доступными правами и кастомным именем
5
+ Author: bogpolt
6
+ Classifier: Operating System :: Microsoft :: Windows
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.8
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: pywin32; platform_system == "Windows"
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: requires-dist
22
+ Dynamic: requires-python
23
+ Dynamic: summary
24
+
25
+ Библеотека для планировщика
@@ -0,0 +1,5 @@
1
+ win_planner/__init__.py,sha256=33CwNodw6kTc2AVRYMStzLYkeGbujcco-l8JZvcy4qA,6223
2
+ win_planner-1.0.0.dist-info/METADATA,sha256=2UuyX5dK1mUgIHD-7tRt7IFNR2JNJrDAyeSGQOg_8Mk,1012
3
+ win_planner-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ win_planner-1.0.0.dist-info/top_level.txt,sha256=Ahk_Hjv91sBXDFT4LA7tyL0jKiTxdEkUDACW6dCh4r4,12
5
+ win_planner-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ win_planner