-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathactions_service.py
More file actions
413 lines (364 loc) · 14.3 KB
/
actions_service.py
File metadata and controls
413 lines (364 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import os
import uuid
from json import dumps
from typing import Any, Dict, Optional, Tuple
from .._config import Config
from .._execution_context import ExecutionContext
from .._folder_context import FolderContext
from .._utils import Endpoint, RequestSpec
from .._utils.constants import (
ENV_TENANT_ID,
HEADER_FOLDER_KEY,
HEADER_FOLDER_PATH,
HEADER_TENANT_ID,
)
from ..models import Action, ActionSchema
from ._base_service import BaseService
def _create_spec(
data: Optional[Dict[str, Any]],
action_schema: Optional[ActionSchema],
title: str,
app_key: str = "",
app_version: int = -1,
app_folder_key: str = "",
app_folder_path: str = "",
) -> RequestSpec:
field_list = []
outcome_list = []
if action_schema:
if action_schema.inputs:
for input_field in action_schema.inputs:
field_name = input_field.name
field_list.append(
{
"Id": input_field.key,
"Name": field_name,
"Title": field_name,
"Type": "Fact",
"Value": data.get(field_name, "") if data is not None else "",
}
)
if action_schema.outputs:
for output_field in action_schema.outputs:
field_name = output_field.name
field_list.append(
{
"Id": output_field.key,
"Name": field_name,
"Title": field_name,
"Type": "Fact",
"Value": "",
}
)
if action_schema.in_outs:
for inout_field in action_schema.in_outs:
field_name = inout_field.name
field_list.append(
{
"Id": inout_field.key,
"Name": field_name,
"Title": field_name,
"Type": "Fact",
"Value": data.get(field_name, "") if data is not None else "",
}
)
if action_schema.outcomes:
for outcome in action_schema.outcomes:
outcome_list.append(
{
"Id": action_schema.key,
"Name": outcome.name,
"Title": outcome.name,
"Type": "Action.Http",
"IsPrimary": True,
}
)
return RequestSpec(
method="POST",
endpoint=Endpoint("/orchestrator_/tasks/AppTasks/CreateAppTask"),
content=dumps(
{
"appId": app_key,
"appVersion": app_version,
"title": title,
"data": data if data is not None else {},
"actionableMessageMetaData": {
"fieldSet": {
"id": str(uuid.uuid4()),
"fields": field_list,
}
if len(field_list) != 0
else {},
"actionSet": {
"id": str(uuid.uuid4()),
"actions": outcome_list,
}
if len(outcome_list) != 0
else {},
}
if action_schema is not None
else {},
}
),
headers=folder_headers(app_folder_key, app_folder_path),
)
def _retrieve_action_spec(
action_key: str, app_folder_key: str, app_folder_path: str
) -> RequestSpec:
return RequestSpec(
method="GET",
endpoint=Endpoint("/orchestrator_/tasks/GenericTasks/GetTaskDataByKey"),
params={"taskKey": action_key},
headers=folder_headers(app_folder_key, app_folder_path),
)
def _assign_task_spec(task_key: str, assignee: str) -> RequestSpec:
return RequestSpec(
method="POST",
endpoint=Endpoint(
"/orchestrator_/odata/Tasks/UiPath.Server.Configuration.OData.AssignTasks"
),
content=dumps(
{"taskAssignments": [{"taskId": task_key, "UserNameOrEmail": assignee}]}
),
)
def _retrieve_app_key_spec(app_name: str) -> RequestSpec:
tenant_id = os.getenv(ENV_TENANT_ID, None)
if not tenant_id:
raise Exception(f"{ENV_TENANT_ID} env var is not set")
return RequestSpec(
method="GET",
endpoint=Endpoint("/apps_/default/api/v1/default/deployed-action-apps-schemas"),
params={"search": app_name},
headers={HEADER_TENANT_ID: tenant_id},
)
def folder_headers(app_folder_key: str, app_folder_path: str) -> Dict[str, str]:
headers = {}
if app_folder_key:
headers[HEADER_FOLDER_KEY] = app_folder_key
elif app_folder_path:
headers[HEADER_FOLDER_PATH] = app_folder_path
return headers
class ActionsService(FolderContext, BaseService):
"""Service for managing UiPath Actions.
Actions are task-based automation components that can be integrated into
applications and processes. They represent discrete units of work that can
be triggered and monitored through the UiPath API.
This service provides methods to create and retrieve actions, supporting
both app-specific and generic actions. It inherits folder context management
capabilities from FolderContext.
Reference: https://docs.uipath.com/automation-cloud/docs/actions
"""
def __init__(self, config: Config, execution_context: ExecutionContext) -> None:
"""Initializes the ActionsService with configuration and execution context.
Args:
config: The configuration object containing API settings
execution_context: The execution context for the service
"""
super().__init__(config=config, execution_context=execution_context)
async def create_async(
self,
title: str,
data: Optional[Dict[str, Any]] = None,
*,
app_name: str = "",
app_key: str = "",
app_folder_path: str = "",
app_folder_key: str = "",
app_version: int = -1,
assignee: str = "",
) -> Action:
"""Creates a new action asynchronously.
This method creates a new action task in UiPath Orchestrator. The action can be
either app-specific (using app_name or app_key) or a generic action.
Args:
title: The title of the action
data: Optional dictionary containing input data for the action
app_name: The name of the application (if creating an app-specific action)
app_key: The key of the application (if creating an app-specific action)
app_folder_path: Optional folder path for the action
app_folder_key: Optional folder key for the action
app_version: The version of the application
assignee: Optional username or email to assign the task to
Returns:
Action: The created action object
Raises:
Exception: If neither app_name nor app_key is provided for app-specific actions
"""
(key, action_schema) = (
(app_key, None)
if app_key
else await self.__get_app_key_and_schema_async(app_name)
)
spec = _create_spec(
title=title,
data=data,
app_key=key,
app_version=app_version,
action_schema=action_schema,
app_folder_key=app_folder_key,
app_folder_path=app_folder_path,
)
response = await self.request_async(
spec.method, spec.endpoint, content=spec.content, headers=spec.headers
)
json_response = response.json()
if assignee:
spec = _assign_task_spec(json_response["id"], assignee)
await self.request_async(spec.method, spec.endpoint, content=spec.content)
return Action.model_validate(json_response)
def create(
self,
title: str,
data: Optional[Dict[str, Any]] = None,
*,
app_name: str = "",
app_key: str = "",
app_folder_path: str = "",
app_folder_key: str = "",
app_version: int = -1,
assignee: str = "",
) -> Action:
"""Creates a new action synchronously.
This method creates a new action task in UiPath Orchestrator. The action can be
either app-specific (using app_name or app_key) or a generic action.
Args:
title: The title of the action
data: Optional dictionary containing input data for the action
app_name: The name of the application (if creating an app-specific action)
app_key: The key of the application (if creating an app-specific action)
app_folder_path: Optional folder path for the action
app_folder_key: Optional folder key for the action
app_version: The version of the application
assignee: Optional username or email to assign the task to
Returns:
Action: The created action object
Raises:
Exception: If neither app_name nor app_key is provided for app-specific actions
"""
(key, action_schema) = (
(app_key, None) if app_key else self.__get_app_key_and_schema(app_name)
)
spec = _create_spec(
title=title,
data=data,
app_key=key,
app_version=app_version,
action_schema=action_schema,
app_folder_key=app_folder_key,
app_folder_path=app_folder_path,
)
response = self.request(
spec.method, spec.endpoint, content=spec.content, headers=spec.headers
)
json_response = response.json()
if assignee:
spec = _assign_task_spec(json_response["id"], assignee)
self.request(spec.method, spec.endpoint, content=spec.content)
return Action.model_validate(json_response)
def retrieve(
self, action_key: str, app_folder_path: str = "", app_folder_key: str = ""
) -> Action:
"""Retrieves an action by its key synchronously.
Args:
action_key: The unique identifier of the action to retrieve
app_folder_path: Optional folder path for the action
app_folder_key: Optional folder key for the action
Returns:
Action: The retrieved action object
"""
spec = _retrieve_action_spec(
action_key=action_key,
app_folder_key=app_folder_key,
app_folder_path=app_folder_path,
)
response = self.request(
spec.method, spec.endpoint, params=spec.params, headers=spec.headers
)
return Action.model_validate(response.json())
async def retrieve_async(
self, action_key: str, app_folder_path: str = "", app_folder_key: str = ""
) -> Action:
"""Retrieves an action by its key asynchronously.
Args:
action_key: The unique identifier of the action to retrieve
app_folder_path: Optional folder path for the action
app_folder_key: Optional folder key for the action
Returns:
Action: The retrieved action object
"""
spec = _retrieve_action_spec(
action_key=action_key,
app_folder_key=app_folder_key,
app_folder_path=app_folder_path,
)
response = await self.request_async(
spec.method, spec.endpoint, params=spec.params, headers=spec.headers
)
return Action.model_validate(response.json())
async def __get_app_key_and_schema_async(
self, app_name: str
) -> Tuple[str, Optional[ActionSchema]]:
"""Retrieves an application's key and schema asynchronously.
Args:
app_name: The name of the application to retrieve
Returns:
Tuple[str, Optional[ActionSchema]]: A tuple containing the application key and schema
Raises:
Exception: If app_name is not provided
"""
if not app_name:
raise Exception("appName or appKey is required")
spec = _retrieve_app_key_spec(app_name=app_name)
response = await self.request_org_scope_async(
spec.method, spec.endpoint, params=spec.params, headers=spec.headers
)
try:
deployed_app = response.json()["deployed"][0]
action_schema = deployed_app["actionSchema"]
deployed_app_key = deployed_app["systemName"]
except (KeyError, IndexError):
raise Exception("Action app not found") from None
try:
return (
deployed_app_key,
ActionSchema(
key=action_schema["key"],
in_outs=action_schema["inOuts"],
inputs=action_schema["inputs"],
outputs=action_schema["outputs"],
outcomes=action_schema["outcomes"],
),
)
except KeyError:
raise Exception("Failed to deserialize action schema") from KeyError
def __get_app_key_and_schema(
self, app_name: str
) -> Tuple[str, Optional[ActionSchema]]:
if not app_name:
raise Exception("appName or appKey is required")
spec = _retrieve_app_key_spec(app_name=app_name)
response = self.request_org_scope(
spec.method, spec.endpoint, params=spec.params, headers=spec.headers
)
try:
deployed_app = response.json()["deployed"][0]
action_schema = deployed_app["actionSchema"]
deployed_app_key = deployed_app["systemName"]
except (KeyError, IndexError):
raise Exception("Action app not found") from None
try:
return (
deployed_app_key,
ActionSchema(
key=action_schema["key"],
in_outs=action_schema["inOuts"],
inputs=action_schema["inputs"],
outputs=action_schema["outputs"],
outcomes=action_schema["outcomes"],
),
)
except KeyError:
raise Exception("Failed to deserialize action schema") from KeyError
@property
def custom_headers(self) -> Dict[str, str]:
return self.folder_headers