forked from i-am-fyre/Scraper-Discord-Notification
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_lib.py
More file actions
443 lines (347 loc) · 13.7 KB
/
task_lib.py
File metadata and controls
443 lines (347 loc) · 13.7 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
"""
"""
import os
import yaml
import collections
import subprocess
import re
import creator_utils_lib as creator
import cron_lib as cronlib
import logger_lib as log
minute="minute"
hour="hour"
day="day"
class Task:
yaml_tag = None
def __init__(self, **kwargs):
self.name = kwargs.get("name", "New Task")
self.enabled = kwargs.get("enabled", True)
self.frequency = kwargs.get("frequency", 15)
self.frequency_unit = kwargs.get("frequency_unit", "minutes")
self.source_ids = kwargs.get("source_ids", [])
self.notif_agent_ids = kwargs.get("notif_agent_ids", [])
self.include = kwargs.get("include", [])
self.exclude = kwargs.get("exclude", [])
def set_frequency(freq, unit):
self.frequency = freq
self.frequency_unit = unit
def yaml(self):
return yaml.dump(self.__dict)
@staticmethod
def load(data):
values = data
#print(values)
if "exclude" in values:
exclude = values["exclude"]
else:
exclude = []
return Task(**data)
def matches_freq(self, time, unit):
return time == self.frequency and unit[:1] == self.frequency_unit[:1]
def load_tasks(file):
if not os.path.exists(file):
open(file, "w+")
with open(file, "r") as stream:
tasks_yaml = yaml.safe_load(stream)
tasks = []
if tasks_yaml is not None:
for t in tasks_yaml:
tasks.append(Task.load(t))
return tasks
def list_tasks_in_file(file):
list_tasks(load_tasks(file))
def list_tasks(tasks):
i = 0
for t in tasks:
print (f"[{i}]")
print_task(t)
i = i+1
def save(tasks, file, preserve_comments=True):
if preserve_comments:
# preserve comments in file
with open(file, "r") as stream:
filestream = stream.read()
match = re.findall("([#][^\n]*[\n]|[#][\n])", filestream)
with open(file, "w") as stream:
if preserve_comments and match:
for m in match:
stream.write(m)
yaml.dump(tasks, stream, default_flow_style=False, sort_keys=False)
def append_task_to_file(task, file):
tasks = load_tasks(file)
tasks.append(task)
save_tasks(tasks, file)
def delete_task_from_file(index, file):
tasks = load_tasks(file)
if index < 0 or index >= len(tasks):
log.error_print(f"tasklib.delete_task_from_file: Invalid index: {index}")
return
del(tasks[index])
save_tasks(tasks, file)
def print_task(task):
print(f"""Name: {task.name}
Source ids: {task.source_ids}
Frequency: {task.frequency} {task.frequency_unit}
Url: {task.url}
Include: {task.include}
Exclude: {task.exclude}
""")
# <-- don't output yaml class tags
def noop(self, *args, **kw):
pass
yaml.emitter.Emitter.process_tag = noop
# --------------------------------------->
if __name__ == "__main__":
t = load_tasks("tasks.yaml")
save_tasks(t, "tasks.yaml", "tasks.yaml")
def task_creator(cur_tasks, sources, notif_agents, file, edit_task=None):
from main import dry_run, prime_task
while True:
t = {}
if edit_task:
e = edit_task
old_task_name = e.name
t["name"] = e.name
t["freq"] = e.frequency
t["frequ"] = e.frequency_unit
t["sources"] = e.source_ids
if len(e.include) == 0 or e.include[0] == "":
t["include"] = ""
else:
t["include"] = ",".join(e.include)
if len(e.exclude) == 0 or e.exclude[0] == "":
t["exclude"] = ""
else:
t["exclude"] = ",".join(e.exclude)
t["notif_agents"] = e.notif_agent_ids
while True:
t["name"] = creator.prompt_string("Name", default=t.get("name", None))
t["freq"] = creator.prompt_num("Frequency", default=t.get("freq", 15))
t["frequ"] = creator.prompt_options("Frequency Unit", ["minutes", "hours"], default=t.get("frequ", "minutes"))
t["sources"] = create_task_add_sources(sources, default=t.get("sources", None))
t["include"] = creator.prompt_string("Include [list seperated by commas]", allow_empty=True, default=t.get("include", None))
t["exclude"] = creator.prompt_string("exclude [list seperated by commas]", allow_empty=True, default=t.get("exclude", None))
t["notif_agents"] = create_task_add_notif_agents(notif_agents, default=t.get("notif_agents", None))
print()
print(f"Name: {t['name']}")
print(f"Frequency: {t['freq']} {t['frequ']}")
print(f"Sources")
print(f"----------------------------")
for s in t["sources"]:
print(f"{sources[s].name}")
print("-----------------------------")
print(f"Include: {t['include']}")
print(f"Exclude: {t['exclude']}")
task = Task(
name = t["name"],
frequency = t["freq"],
frequency_unit = t["frequ"],
source_ids = t["sources"],
include = t["include"].split(","),
exclude = t["include"].split(","),
notif_agent_ids = t["notif_agents"]
)
while True:
confirm = creator.prompt_options("Choose an option", ["save", "edit", "dryrun", "quit"])
if confirm == "quit":
if creator.yes_no("Quit without saving?", "n") == "y":
return
else:
continue
elif confirm == "dryrun":
if creator.yes_no("Execute dry run?", "y"):
log.debug_print("Executing dry run...")
dry_run(task)
continue
else:
break
if confirm == "save":
break
elif confirm == "edit":
continue
if edit_task is None:
cur_tasks.append(task)
else:
e = edit_task
e.name = t["name"]
e.frequency = t["freq"]
e.frequency_unit = t["frequ"]
e.source_ids = t["sources"]
e.include = t["include"].split(",")
e.exclude = t["include"].split(",")
e.notif_agent_ids = t["notif_agents"]
task = edit_task
save(cur_tasks, file)
"""
if creator.yes_no("Test this task with a dry run", "y") == "y":
while True:
dry_run(task)
confirm = creator.yes_no("Do you want to go back and edit this task")
if confirm == "y":
continue
elif confirm == "n":
break
"""
if creator.yes_no("Prime this task?", "y") == "y":
recent = creator.prompt_num("How many of the latest ads do you want notified?", default="3")
prime_task (task, recent_ads=int(recent))
if not cronlib.exists(task.frequency, task.frequency_unit):
if creator.yes_no(f"Add cronjob for '{task.frequency} {task.frequency_unit}'", "y"):
cronlib.clear()
for t in cur_tasks:
if not cronlib.exists(t.frequency, task.frequency_unit):
cronlib.add(task.frequency, task.frequency_unit)
else:
print (f"Cronjob already exists for '{task.frequency} {task.frequency_unit}'... skipping")
print ("Done!")
return
def create_task_add_sources(sources_dict, default=None):
default_str = ""
if default is not None:
first = True
for s in default:
if not s in sources_dict:
continue
if first:
default_str = f"[{sources_dict[s].name}"
first = False
else:
default_str = f"{default_str}, {sources_dict[s].name}"
default_str = f" {default_str}]"
add_sources = []
if len(sources_dict) == 0:
log.error_print(f"No sources found. Please add a source ")
return
sources_list = list(sources_dict.values())
remaining_sources = sources_list.copy()
while len(remaining_sources) > 0:
i = 0
for s in remaining_sources:
print(f"{i} - {s.name}")
i = i + 1
choices = "0"
if len(remaining_sources) > 1:
choices = f"0-{len(remaining_sources) - 1}"
if len(add_sources) > 0:
print("r - reset")
print("d - done")
if default is None or len(add_sources) > 0:
source_index_str = input(f"Source [{choices}]: ")
else:
source_index_str = input(f"Source [{choices}]:{default_str} ")
if default is not None and source_index_str == "" and len(add_sources) == 0:
return default
if len(remaining_sources) == 0 and source_index_str == "":
add_sources.append(remaining_sources[source_index])
break
if len(add_sources):
if source_index_str == "d":
break
elif source_index_str == "r":
print ("Resetting...")
remaining_sources = sources_list.copy()
add_sources = []
if re.match("[0-9]+$", source_index_str):
source_index = int(source_index_str)
if source_index >= 0 and source_index < len(sources_list):
add_sources.append(remaining_sources[source_index])
del(remaining_sources[source_index])
confirm = creator.yes_no("Add another?", "y")
if confirm == "n":
break
result = []
for s in add_sources:
result.append(s.id)
return result
def create_task_add_notif_agents(notif_agents_dict, default=None):
default_str = ""
if default is not None:
first = True
for s in default:
if not s in notif_agents_dict:
continue
if first:
default_str = f"[{notif_agents_dict[s].name}"
first = False
else:
default_str = f"{default_str}, {notif_agents_dict[s].name}"
default_str = f" {default_str}]"
add_notif_agents = []
if len(notif_agents_dict) == 0:
log.error_print(f"No notif_agents found. Please add a notif_agent ")
return
notif_agents_list = list(notif_agents_dict.values())
remaining_notif_agents = notif_agents_list.copy()
while len(remaining_notif_agents) > 0:
i = 0
for s in remaining_notif_agents:
print(f"{i} - {s.name}")
i = i + 1
choices = "0"
if len(remaining_notif_agents) > 1:
choices = f"0-{len(remaining_notif_agents) - 1}"
if len(add_notif_agents) > 0:
print("r - reset")
print("d - done")
if default is None or len(add_notif_agents) > 0:
notif_agent_index_str = input(f"notif_agent [{choices}]: ")
else:
notif_agent_index_str = input(f"notif_agent [{choices}]:{default_str} ")
if default is not None and notif_agent_index_str == "" and len(add_notif_agents) == 0:
return default
if len(remaining_notif_agents) == 0 and notif_agent_index_str == "":
add_notif_agents.append(remaining_notif_agents[notif_agent_index])
break
if len(add_notif_agents):
if notif_agent_index_str == "d":
break
elif notif_agent_index_str == "r":
print ("Resetting...")
remaining_notif_agents = notif_agents_list.copy()
add_notif_agents = []
if re.match("[0-9]+$", notif_agent_index_str):
notif_agent_index = int(notif_agent_index_str)
if notif_agent_index >= 0 and notif_agent_index < len(notif_agents_list):
add_notif_agents.append(remaining_notif_agents[notif_agent_index])
del(remaining_notif_agents[notif_agent_index])
confirm = creator.yes_no("Add another?", "y")
if confirm == "n":
break
result = []
for s in add_notif_agents:
result.append(s.id)
return result
def create_task(cur_tasks, sources, notif_agents, file):
if len(sources) == 0:
log.error_print("No sources found. Please add a source before creating a task")
return
if len(notif_agents) == 0:
log.error_print("No notification agents found. Please add a notification agent before creating a task")
return
creator.print_title("Add Task")
task_creator(cur_tasks, sources, notif_agents, file, edit_task=None)
def edit_task(cur_tasks, sources, notif_agents, file):
creator.print_title("Edit Task")
task = creator.prompt_complex_list("Choose a task", cur_tasks, "name", extra_options=["d"], extra_options_desc=["done"])
if task == "d":
return
else:
task_creator(cur_tasks, sources, notif_agents, file, task)
def delete_task(tasks_list, file):
creator.print_title("Delete Task")
while True:
for i in range(len(tasks_list)):
print(f"{i} - {tasks_list[i].name}")
print("s - save")
print("q - quit without saving")
tnum_str = creator.prompt_string("Delete task")
if tnum_str == "s":
save(tasks_list, file)
return
elif tnum_str == "q":
return
if re.match("[0-9]+$", tnum_str):
tnum = int(tnum_str)
if tnum >= 0 and tnum < len(tasks_list):
if creator.yes_no(f"Are you sure you want to delete {tasks_list[tnum].name}") == "y":
del tasks_list[tnum]