-
-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathapp.py
More file actions
3159 lines (2608 loc) · 110 KB
/
app.py
File metadata and controls
3159 lines (2608 loc) · 110 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import builtins
import hmac
import datetime
import json
import time
import markupsafe
import re
import subprocess
import tempfile
import zipfile
import base64
import gzip
import ipaddress
import hashlib
from io import StringIO
from contextlib import redirect_stdout
import random
import string
import xmltodict
from json2xml import json2xml
from json2xml.utils import readfromstring
from ioc_finder import find_iocs
from dateutil.parser import parse as dateutil_parser
from google.auth import crypt
from google.auth import jwt
import py7zr
import pyzipper
import rarfile
import requests
import tarfile
import binascii
import struct
import paramiko
import concurrent.futures
import multiprocessing
#from walkoff_app_sdk.app_base import AppBase
from shuffle_sdk import AppBase
# Override exit(), sys.exit, and os._exit
# sys.exit() can be caught, meaning we can have a custom handler for it
builtins.exit = sys.exit
os.exit = sys.exit
os._exit = sys.exit
class Tools(AppBase):
__version__ = "1.2.0"
app_name = (
"Shuffle Tools" # this needs to match "name" in api.yaml for WALKOFF to work
)
def __init__(self, redis, logger, console_logger=None):
"""
Each app should have this __init__ to set up Redis and logging.
:param redis:
:param logger:
:param console_logger:
"""
self.cache_update_buffer = []
self.shared_cache = {}
super().__init__(redis, logger, console_logger)
def router(self):
return "This action should be skipped"
def base64_conversion(self, string, operation):
if operation == "encode":
# Try JSON decoding
try:
string = json.dumps(json.loads(string))
except:
pass
encoded_bytes = base64.b64encode(str(string).encode("utf-8"))
encoded_string = str(encoded_bytes, "utf-8")
return encoded_string
elif operation == "to image":
# Decode the base64 into an image and upload it as a file
decoded_bytes = base64.b64decode(string)
# Make the bytes into unicode escaped bytes
# UnicodeDecodeError - 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
try:
decoded_bytes = str(decoded_bytes, "utf-8")
except:
pass
filename = "base64_image.png"
file = {
"filename": filename,
"data": decoded_bytes,
}
fileret = self.set_files([file])
value = {"success": True, "filename": filename, "file_id": fileret}
if len(fileret) == 1:
value = {"success": True, "filename": filename, "file_id": fileret[0]}
return value
elif operation == "decode":
if "-" in string:
string = string.replace("-", "+", -1)
if "_" in string:
string = string.replace("_", "/", -1)
# Fix padding
if len(string) % 4 != 0:
string += "=" * (4 - len(string) % 4)
# For loop this. It's stupid.
decoded_bytes = ""
try:
decoded_bytes = base64.b64decode(string)
except Exception as e:
return json.dumps({
"success": False,
"reason": "Invalid Base64 - %s" % e,
})
#if "incorrect padding" in str(e).lower():
# try:
# decoded_bytes = base64.b64decode(string + "=")
# except Exception as e:
# if "incorrect padding" in str(e).lower():
# try:
# decoded_bytes = base64.b64decode(string + "==")
# except Exception as e:
# if "incorrect padding" in str(e).lower():
# try:
# decoded_bytes = base64.b64decode(string + "===")
# except Exception as e:
# if "incorrect padding" in str(e).lower():
# return "Invalid Base64"
try:
decoded_bytes = str(decoded_bytes, "utf-8")
except:
pass
# Check if json
try:
decoded_bytes = json.loads(decoded_bytes)
except:
pass
return decoded_bytes
return {
"success": False,
"reason": "Invalid operation",
}
def parse_list_internal(self, input_list):
if isinstance(input_list, list):
input_list = ",".join(input_list)
try:
input_list = json.loads(input_list)
if isinstance(input_list, list):
input_list = ",".join(input_list)
else:
return json.dumps(input_list)
except:
pass
input_list = input_list.replace(", ", ",", -1)
return input_list
# This is an SMS function of Shuffle
def send_sms_shuffle(self, apikey, phone_numbers, body):
phone_numbers = self.parse_list_internal(phone_numbers)
targets = [phone_numbers]
if ", " in phone_numbers:
targets = phone_numbers.split(", ")
elif "," in phone_numbers:
targets = phone_numbers.split(",")
data = {"numbers": targets, "body": body}
url = "https://shuffler.io/api/v1/functions/sendsms"
headers = {"Authorization": "Bearer %s" % apikey}
return requests.post(url, headers=headers, json=data, verify=False).text
# This is an email function of Shuffle
def send_email_shuffle(self, apikey, recipients, subject, body, attachments=""):
recipients = self.parse_list_internal(recipients)
targets = [recipients]
if ", " in recipients:
targets = recipients.split(", ")
elif "," in recipients:
targets = recipients.split(",")
data = {
"targets": targets,
"subject": subject,
"body": body,
"type": "alert",
"email_app": True,
}
# Read the attachments
if attachments != None and len(attachments) > 0:
try:
attachments = parse_list(attachments, splitter=",")
files = []
for item in attachments:
new_file = self.get_file(file_ids)
files.append(new_file)
data["attachments"] = files
except Exception as e:
pass
url = "https://shuffler.io/functions/sendmail"
headers = {"Authorization": "Bearer %s" % apikey}
return requests.post(url, headers=headers, json=data).text
def repeat_back_to_me(self, call):
return call
def dedup_and_merge(self, key, value, timeout, set_skipped=True):
timeout = int(timeout)
key = str(key)
set_skipped = True
if str(set_skipped).lower() == "false":
set_skipped = False
else:
set_skipped = True
cachekey = "dedup-%s" % (key)
response = {
"success": False,
"datastore_key": cachekey,
"info": "All keys from the last %d seconds with the key '%s' have been merged. The result was set to SKIPPED in all other actions." % (timeout, key),
"timeout": timeout,
"original_value": value,
"all_values": [],
}
found_cache = self.get_cache(cachekey)
if found_cache["success"] == True and len(found_cache["value"]) > 0:
if "value" in found_cache:
if not str(found_cache["value"]).startswith("["):
found_cache["value"] = [found_cache["value"]]
else:
try:
found_cache["value"] = json.loads(found_cache["value"])
except Exception as e:
self.logger.info("[ERROR] Failed parsing JSON: %s" % e)
else:
found_cache["value"] = []
found_cache["value"].append(value)
if "created" in found_cache:
if found_cache["created"] + timeout + 3 < time.time():
set_skipped = False
response["success"] = True
response["all_values"] = found_cache["value"]
self.delete_cache(cachekey)
return json.dumps(response)
else:
self.logger.info("Dedup-key is already handled in another workflow with timeout %d" % timeout)
self.set_cache(cachekey, json.dumps(found_cache["value"]))
if set_skipped == True:
self.action_result["status"] = "SKIPPED"
self.action_result["result"] = json.dumps({
"status": False,
"reason": "Dedup-key is already handled in another workflow with timeout %d" % timeout,
})
self.send_result(self.action_result, {"Authorization": "Bearer %s" % self.authorization}, "/api/v1/streams")
return found_cache
parsedvalue = [value]
resp = self.set_cache(cachekey, json.dumps(parsedvalue))
self.logger.info("Sleeping for %d seconds while waiting for cache to fill up elsewhere" % timeout)
time.sleep(timeout)
found_cache = self.get_cache(cachekey)
response["success"] = True
response["all_values"] = found_cache["value"]
self.delete_cache(cachekey)
return json.dumps(response)
# https://github.com/fhightower/ioc-finder
def parse_file_ioc(self, file_ids, input_type="all"):
def parse(data):
try:
iocs = find_iocs(str(data))
newarray = []
for key, value in iocs.items():
if input_type != "all":
if key not in input_type:
continue
if len(value) > 0:
for item in value:
if isinstance(value, dict):
for subkey, subvalue in value.items():
if len(subvalue) > 0:
for subitem in subvalue:
data = {
"data": subitem,
"data_type": "%s_%s" % (key[:-1], subkey),
}
if data not in newarray:
newarray.append(data)
else:
data = {"data": item, "data_type": key[:-1]}
if data not in newarray:
newarray.append(data)
for item in newarray:
if "ip" in item["data_type"]:
item["data_type"] = "ip"
return {"success": True, "items": newarray}
except Exception as excp:
return {"success": False, "message": "{}".format(excp)}
if input_type == "":
input_type = "all"
else:
input_type = input_type.split(",")
# Parse file_ids if it's a JSON list string like '["id1", "id2"]'
try:
file_ids = json.loads(file_ids)
except (json.JSONDecodeError, TypeError):
file_ids = file_ids
return_value = None
if type(file_ids) == str:
return_value = parse(self.get_file(file_ids)["data"])
elif type(file_ids) == list and type(file_ids[0]) == str:
return_value = [
parse(self.get_file(file_id)["data"]) for file_id in file_ids
]
elif (
type(file_ids) == list
and type(file_ids[0]) == list
and type(file_ids[0][0]) == str
):
return_value = [
[parse(self.get_file(file_id2)["data"]) for file_id2 in file_id]
for file_id in file_ids
]
else:
return "Invalid input"
return return_value
def parse_list(self, items, splitter="\n"):
# Check if it's already a list first
try:
newlist = json.loads(items)
if isinstance(newlist, list):
return newlist
except Exception as e:
self.logger.info("[WARNING] Parse error - fallback: %s" % e)
if splitter == "":
splitter = "\n"
splititems = items.split(splitter)
return str(splititems)
def get_length(self, item):
if item.startswith("[") and item.endswith("]"):
try:
item = item.replace("'", '"', -1)
item = json.loads(item)
except json.decoder.JSONDecodeError as e:
self.logger.info("Parse error: %s" % e)
return str(len(item))
def set_json_key(self, json_object, key, value):
if isinstance(json_object, str):
try:
json_object = json.loads(json_object)
except json.decoder.JSONDecodeError as e:
return {
"success": False,
"reason": "Item is not valid JSON"
}
if isinstance(json_object, list):
if len(json_object) == 1:
json_object = json_object[0]
else:
return {
"success": False,
"reason": "Item is valid JSON, but can't handle lists. Use .#"
}
#if not isinstance(json_object, object):
# return {
# "success": False,
# "reason": "Item is not valid JSON (2)"
# }
if isinstance(value, str):
try:
value = json.loads(value)
except json.decoder.JSONDecodeError as e:
pass
# Handle JSON paths
if "." in key:
base_object = json.loads(json.dumps(json_object))
#base_object.output.recipients.notificationEndpointIds = ...
keys = key.split(".")
if len(keys) >= 1:
first_object = keys[0]
# Walk the nested keys and set the value
current = base_object
for subkey in keys[:-1]:
if subkey not in current:
current[subkey] = {}
current = current[subkey]
current[keys[-1]] = value
json_object = base_object
#json_object[first_object] = base_object
else:
json_object[key] = value
return json_object
def delete_json_keys(self, json_object, keys):
keys = self.parse_list_internal(keys)
splitdata = [keys]
if ", " in keys:
splitdata = keys.split(", ")
elif "," in keys:
splitdata = keys.split(",")
for key in splitdata:
key = key.strip()
try:
del json_object[key]
except:
self.logger.info(f"[ERROR] Key {key} doesn't exist")
return json_object
def replace_value(self, input_data, translate_from, translate_to, else_value=""):
splitdata = [translate_from]
if ", " in translate_from:
splitdata = translate_from.split(", ")
elif "," in translate_from:
splitdata = translate_from.split(",")
if isinstance(input_data, list) or isinstance(input_data, dict):
input_data = json.dumps(input_data)
to_return = input_data
if isinstance(input_data, str):
found = False
for item in splitdata:
item = item.strip()
if item in input_data:
input_data = input_data.replace(item, translate_to)
found = True
if not found and len(else_value) > 0:
input_data = else_value
if input_data.lower() == "false":
return False
elif input_data.lower() == "true":
return True
return input_data
def replace_value_from_dictionary(self, input_data, mapping, default_value=""):
if isinstance(mapping, str):
try:
mapping = json.loads(mapping)
except json.decoder.JSONDecodeError as e:
return {
"success": False,
"reason": "Mapping is not valid JSON: %s" % e,
}
for key, value in mapping.items():
try:
input_data = input_data.replace(key, str(value), -1)
except:
self.logger.info(f"Failed mapping output data for key {key}")
return input_data
# Changed with 1.1.0 to run with different returns
def regex_capture_group(self, input_data, regex):
try:
returnvalues = {
"success": True,
}
matches = re.findall(regex, input_data)
found = False
for item in matches:
if isinstance(item, str):
found = True
name = "group_0"
try:
returnvalues[name].append(item)
except:
returnvalues[name] = [item]
else:
for i in range(0, len(item)):
found = True
name = "group_%d" % i
try:
returnvalues[name].append(item[i])
except:
returnvalues[name] = [item[i]]
returnvalues["found"] = found
return returnvalues
except re.error as e:
return {
"success": False,
"reason": "Bad regex pattern: %s" % e,
}
def regex_replace(
self, input_data, regex, replace_string="", ignore_case="False"
):
if ignore_case.lower().strip() == "true":
return re.sub(regex, replace_string, input_data, flags=re.IGNORECASE)
else:
return re.sub(regex, replace_string, input_data)
def execute_python(self, code):
if len(code) == 36 and "-" in code:
filedata = self.get_file(code)
if filedata["success"] == False:
return {
"success": False,
"message": f"Failed to get file for ID {code}",
}
if ".py" not in filedata["filename"]:
return {
"success": False,
"message": f"Filename needs to contain .py",
}
# Sandboxed execution: fresh subprocess with globals (self, singul, shuffle)
# preserved inside the worker. See sandbox_worker.py execute_python().
try:
result = self.run_python_sandboxed(code)
if result.get("success"):
return {
"success": True,
"message": result.get("result", ""),
}
else:
return {
"success": False,
"message": result.get("error", "Unknown error"),
}
except Exception as e:
return {
"success": False,
"message": f"Exception: {e}",
}
def execute_bash(self, code, shuffle_input):
# Sandboxed execution: fresh subprocess with clean env, resource limits.
# See sandbox_worker.py execute_bash().
try:
result = self.run_bash_sandboxed(code, shuffle_input=shuffle_input)
if result.get("success"):
return result.get("result", "")
else:
self.logger.info(f"[ERROR] FAILED to run bash command {code}!")
return result.get("error", "")
except Exception as e:
self.logger.info(f"[ERROR] FAILED to run bash command {code}: {e}")
return ""
# Check if wildcardstring is in all_ips and support * as wildcard
def check_wildcard(self, wildcardstring, matching_string):
wildcardstring = str(wildcardstring.lower())
if wildcardstring in str(matching_string).lower():
return True
else:
wildcardstring = wildcardstring.replace(".", "\\.")
wildcardstring = wildcardstring.replace("*", ".*")
if re.match(wildcardstring, str(matching_string).lower()):
return True
return False
def preload_cache(self, key):
org_id = self.full_execution["workflow"]["execution_org"]["id"]
url = f"{self.url}/api/v1/orgs/{org_id}/get_cache"
data = {
"workflow_id": self.full_execution["workflow"]["id"],
"execution_id": self.current_execution_id,
"authorization": self.authorization,
"org_id": org_id,
"key": key,
}
get_response = requests.post(url, json=data, verify=False)
response_data = get_response.json()
if "value" in response_data:
raw_value = response_data["value"]
if isinstance(raw_value, str):
try:
parsed = json.loads(raw_value)
except json.JSONDecodeError:
parsed = [raw_value]
else:
parsed = raw_value
if not isinstance(parsed, list):
parsed = [parsed]
response_data["value"] = parsed
return get_response.json()
def update_cache(self, key):
org_id = self.full_execution["workflow"]["execution_org"]["id"]
url = f"{self.url}/api/v1/orgs/{org_id}/set_cache"
data = {
"workflow_id": self.full_execution["workflow"]["id"],
"execution_id": self.current_execution_id,
"authorization": self.authorization,
"org_id": org_id,
"key": key,
"value": json.dumps(self.shared_cache["value"]),
}
get_response = requests.post(url, json=data, verify=False)
self.cache_update_buffer = []
return get_response.json()
def filter_list(self, input_list, field, check, value, opposite):
# Remove hashtags on the fly
# E.g. #.fieldname or .#.fieldname
flip = False
if str(opposite).lower() == "true":
flip = True
try:
#input_list = eval(input_list) # nosec
input_list = json.loads(input_list)
except Exception:
try:
input_list = input_list.replace("'", '"', -1)
input_list = json.loads(input_list)
except Exception:
self.logger.info("[WARNING] Error parsing string to array. Continuing anyway.")
# Workaround D:
if not isinstance(input_list, list):
return {
"success": False,
"reason": "Error: input isnt a list. Please use conditions instead if using JSON.",
"valid": [],
"invalid": [],
}
input_list = [input_list]
if str(value).lower() == "null" or str(value).lower() == "none":
value = "none"
found_items = []
new_list = []
failed_list = []
for item in input_list:
try:
try:
item = json.loads(item)
except Exception:
pass
# Support for nested dict key
tmp = item
if field and field.strip() != "":
for subfield in field.split("."):
tmp = tmp[subfield]
if isinstance(tmp, dict) or isinstance(tmp, list):
try:
tmp = json.dumps(tmp)
except json.decoder.JSONDecodeError as e:
pass
# EQUALS JUST FOR STR
if check == "equals":
# Mostly for bools
# value = tmp.lower()
if str(tmp).lower() == str(value).lower():
new_list.append(item)
else:
failed_list.append(item)
elif check == "equals any of":
value = self.parse_list_internal(value)
checklist = value.split(",")
found = False
for subcheck in checklist:
subcheck = str(subcheck).strip()
#ext.lower().strip() == value.lower().strip()
if type(tmp) == list and subcheck in tmp:
new_list.append(item)
found = True
break
elif type(tmp) == str and tmp == subcheck:
new_list.append(item)
found = True
break
elif type(tmp) == int and str(tmp) == subcheck:
new_list.append(item)
found = True
break
else:
if str(tmp) == str(subcheck):
new_list.append(item)
found = True
break
if not found:
failed_list.append(item)
# IS EMPTY FOR STR OR LISTS
elif check == "is empty":
if str(tmp) == "[]":
tmp = []
if str(tmp) == "{}":
tmp = []
if type(tmp) == list and len(tmp) == 0:
new_list.append(item)
elif type(tmp) == str and not tmp:
new_list.append(item)
else:
failed_list.append(item)
# STARTS WITH = FOR STR OR [0] FOR LIST
elif check == "starts with":
if type(tmp) == list and tmp[0] == value:
new_list.append(item)
elif type(tmp) == str and tmp.startswith(value):
new_list.append(item)
else:
failed_list.append(item)
# ENDS WITH = FOR STR OR [-1] FOR LIST
elif check == "ends with":
if type(tmp) == list and tmp[-1] == value:
new_list.append(item)
elif type(tmp) == str and tmp.endswith(value):
new_list.append(item)
else:
failed_list.append(item)
# CONTAINS FIND FOR LIST AND IN FOR STR
elif check == "contains":
#if str(value).lower() in str(tmp).lower():
if str(value).lower() in str(tmp).lower() or self.check_wildcard(value, tmp):
new_list.append(item)
else:
failed_list.append(item)
elif check == "contains any of":
value = self.parse_list_internal(value)
checklist = value.split(",")
found = False
for checker in checklist:
if str(checker).lower() in str(tmp).lower() or self.check_wildcard(checker, tmp):
new_list.append(item)
found = True
break
if not found:
failed_list.append(item)
# CONTAINS FIND FOR LIST AND IN FOR STR
elif check == "field is unique":
if tmp.lower() not in found_items:
new_list.append(item)
found_items.append(tmp.lower())
else:
failed_list.append(item)
# CONTAINS FIND FOR LIST AND IN FOR STR
elif check == "larger than":
list_set = False
try:
if str(tmp).isdigit() and str(value).isdigit():
if int(tmp) > int(value):
new_list.append(item)
list_set = True
except AttributeError as e:
pass
try:
value = len(json.loads(value))
except Exception as e:
pass
try:
# Check if it's a list in autocast and if so, check the length
if len(json.loads(tmp)) > int(value):
new_list.append(item)
list_set = True
except Exception as e:
pass
if not list_set:
failed_list.append(item)
elif check == "less than":
# Old
#if int(tmp) < int(value):
# new_list.append(item)
#else:
# failed_list.append(item)
list_set = False
try:
if str(tmp).isdigit() and str(value).isdigit():
if int(tmp) < int(value):
new_list.append(item)
list_set = True
except AttributeError as e:
pass
try:
value = len(json.loads(value))
except Exception as e:
pass
try:
# Check if it's a list in autocast and if so, check the length
if len(json.loads(tmp)) < int(value):
new_list.append(item)
list_set = True
except Exception as e:
pass
if not list_set:
failed_list.append(item)
elif check == "in cache key":
if item == input_list[0]:
self.shared_cache = self.preload_cache(key=value)
ret = self.check_cache_contains(value, tmp, "true")
if ret["success"] == True and ret["found"] == True:
new_list.append(item)
else:
failed_list.append(item)
if len(self.cache_update_buffer) > 400 or (item == input_list[-1] and len(self.cache_update_buffer) > 0):
self.update_cache(value)
#return {
# "success": True,
# "found": False,
# "key": key,
# "value": new_value,
#}
# SINGLE ITEM COULD BE A FILE OR A LIST OF FILES
elif check == "files by extension":
if type(tmp) == list:
file_list = []
for file_id in tmp:
filedata = self.get_file(file_id)
_, ext = os.path.splitext(filedata["filename"])
if (ext.lower().strip() == value.lower().strip()):
file_list.append(file_id)
# else:
# failed_list.append(file_id)
tmp = item
if field and field.strip() != "":
for subfield in field.split(".")[:-1]:
tmp = tmp[subfield]
tmp[field.split(".")[-1]] = file_list
new_list.append(item)
else:
new_list = file_list
# else:
# failed_list = file_list
elif type(tmp) == str:
filedata = self.get_file(tmp)
_, ext = os.path.splitext(filedata["filename"])
if ext.lower().strip() == value.lower().strip():
new_list.append(item)
else:
failed_list.append(item)
except Exception as e:
failed_list.append(item)
# return
if flip:
tmplist = new_list
new_list = failed_list
failed_list = tmplist
try:
data ={
"success": True,
"valid": new_list,
"invalid": failed_list,
}
return json.dumps(data)
# new_list = json.dumps(new_list)
except json.decoder.JSONDecodeError as e:
return json.dumps(
{
"success": False,
"reason": "Failed parsing filter list output" + e,
}
)
return new_list
#def multi_list_filter(self, input_list, field, check, value):
# input_list = input_list.replace("'", '"', -1)
# input_list = json.loads(input_list)
# fieldsplit = field.split(",")
# if ", " in field:
# fieldsplit = field.split(", ")
# valuesplit = value.split(",")
# if ", " in value:
# valuesplit = value.split(", ")
# checksplit = check.split(",")
# if ", " in check:
# checksplit = check.split(", ")
# new_list = []
# for list_item in input_list:
# list_item = json.loads(list_item)
# index = 0
# for check in checksplit:
# if check == "equals":
# self.logger.info(
# "Checking %s vs %s"