1111import logging
1212
1313class Api ():
14- """A python interface into the Nightfall API"""
14+ """A python interface for the Nightfall API.
15+
16+ .. data:: MAX_PAYLOAD_SIZE
17+
18+ Maximum payload size that the Nightfall API will accept
19+
20+ .. data:: MAX_NUM_ITEMS
21+
22+ Maximum number of items that the Nightfall API will accept
23+ """
24+ MAX_PAYLOAD_SIZE = 450_000
25+ MAX_NUM_ITEMS = 50_000
1526
1627 def __init__ (self , token , condition_set ):
1728 """Instantiate a new nightfall.Api object.
@@ -27,26 +38,73 @@ def __init__(self, token, condition_set):
2738 'x-api-key' : self .token
2839 }
2940
41+ def make_payloads (self , data ):
42+ """Turn a list of strings into a list of acceptable payloads.
43+
44+ Creates chunks based on the MAX_PAYLOAD_SIZE and MAX_NUM_ITEMS
45+ constants.
46+
47+ :param data: list of string
48+ :returns: list of list of strings
49+ """
50+ cur_chunk_bytes = 0
51+ cur_chunk = []
52+ chunks = []
53+
54+ for i in data :
55+ if cur_chunk_bytes + len (i ) >= self .MAX_PAYLOAD_SIZE or \
56+ len (cur_chunk ) >= self .MAX_NUM_ITEMS :
57+ chunks .append (cur_chunk )
58+
59+ cur_chunk_bytes = len (i )
60+
61+ if len (i ) < self .MAX_PAYLOAD_SIZE :
62+ cur_chunk = [i ]
63+ else :
64+ cur_chunk = []
65+ for i in range (0 , len (i ), self .MAX_PAYLOAD_SIZE ):
66+ chunks .append ([i [i :i + self .MAX_PAYLOAD_SIZE ]])
67+
68+ else :
69+ cur_chunk .append (i )
70+ cur_chunk_bytes += len (i )
71+ if cur_chunk :
72+ chunks .append (cur_chunk )
73+
74+ return chunks
75+
76+
3077 def scan (self , data ):
31- """Scan a piece of data with Nightfall.
78+ """Scan lists of data with Nightfall.
79+
80+ This method will convert the list of strings into chunks if necessary
81+ and then makes one or more requests to the Nightfall API to scan the
82+ data.
3283
33- :param data: Data to scan.
84+ :param data: list of strings to scan.
3485 :type data: list
86+
87+ :returns: list of list of resposes for items in payload.
3588 """
36- payload = {
37- 'payload' : data ,
38- 'config' : {
39- 'conditionSetUUID' : self .condition_set
89+ responses = []
90+
91+ for i in self .make_payloads (data ):
92+ payload = {
93+ 'payload' : i ,
94+ 'config' : {
95+ 'conditionSetUUID' : self .condition_set
96+ }
4097 }
41- }
4298
43- response = requests .post (
44- url = self ._url ,
45- headers = self ._headers ,
46- data = json .dumps (payload )
47- )
48- response .raise_for_status ()
99+ response = requests .post (
100+ url = self ._url ,
101+ headers = self ._headers ,
102+ data = json .dumps (payload )
103+ )
104+ response .raise_for_status ()
105+ responses += response .json ()
49106
50- return response
107+ return responses
108+
51109
52110
0 commit comments