-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathscript_server.py
423 lines (316 loc) · 12.5 KB
/
script_server.py
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
"""
Starts flask server at the specified location.
Access through:
ip:port/run?url=.... etc.
Examples:
http://127.0.0.1:3000/run?url=https://google.com&crawler_data={"crawler":"StealthRequestsCrawler","name":"StealthRequestsCrawler","settings": {"timeout_s":20}}
http://127.0.0.1:3000/run?url=https://google.com&crawler_data={"crawler":"SeleniumChromeFull","name":"SeleniumChromeFull","settings": {"timeout_s":50, "driver_executable" : "/usr/bin/chromedriver"}}
http://127.0.0.1:3000/run?url=https://google.com&crawler_data={"crawler":"ScriptCrawler","name":"CrawleeScript","settings": {"timeout_s":50, "script" : "poetry run python crawleebeautifulsoup.py"}}
http://127.0.0.1:3000/run?url=https://google.com&crawler_data={"crawler":"ScriptCrawler","name":"CrawleeScript","settings": {"timeout_s":50, "script" : "poetry run python crawleebeautifulsoup.py", "remote-server" : "http://127.0.0.1:3000"}}
"""
from pathlib import Path
from flask import Flask, request, jsonify
import json
import html
import subprocess
import argparse
from datetime import datetime
from rsshistory import webtools
app = Flask(__name__)
# should contain tuples of datetime, URL, properties
url_history = []
history_length = 200
def get_html(body):
html = """<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
{}
</body>
</html>
""".format(body)
return html
def get_crawler_config():
path = Path("init_browser_setup.json")
if path.exists():
print("Reading configuration from file")
with path.open("r") as file:
config = json.load(file)
for index, item in enumerate(config):
config[index]["crawler"] = webtools.WebConfig.get_crawler_from_string(item["crawler"])
return config
else:
print("Reading configuration from webtools")
return webtools.WebConfig.get_init_crawler_config()
def find_response(input_url):
for datetime, url, all_properties in reversed(url_history):
if input_url == url and all_properties:
return all_properties
def run_webtools_url(url, remote_server, crawler_data, full):
page_url = webtools.Url(url)
options = page_url.get_init_page_options()
if crawler_data:
if "crawler" in crawler_data:
crawler_data["crawler"] = webtools.WebConfig.get_crawler_from_string(crawler_data["crawler"])
if crawler_data["settings"] is None:
crawler_data["settings"] = {}
crawler_data["settings"]["remote-server"] = remote_server
options.mode_mapping = [crawler_data]
if "name" in crawler_data:
config = get_crawler_config()
for item in config:
if crawler_data["name"] == item["name"]:
crawler_data = item
if crawler_data["settings"] is None:
crawler_data["settings"] = {}
crawler_data["settings"]["remote-server"] = remote_server
options.mode_mapping = [crawler_data]
page_url = webtools.Url(url, page_options=options)
response = page_url.get_response()
all_properties = page_url.get_properties(full=True)
if full:
page_url = webtools.Url.get_type(url)
additional = append_properties(page_url)
all_properties.append({"name" : "Social", "data" : additional})
return all_properties
def run_cmd_url(url, remote_server):
output_file = Path("storage") / "out.txt"
remote_server = remote_server + "/set"
# TODO timeout
command = ["poetry", "run", "python", "crawleebeautifulsoup.py", "--url", url, "--remote-server", remote_server]
try:
# Run the command using subprocess
result = subprocess.run(
command,
#shell=True,
text=True,
capture_output=True,
check=True
)
output = result.stdout
error = result.stderr
return jsonify({
"success": True,
"output": output,
"error": error
})
except subprocess.CalledProcessError as e:
# Handle command errors
return jsonify({
"success": False,
"output": e.stdout,
"error": e.stderr,
"return_code": e.returncode
})
except Exception as e:
# Handle general errors
return jsonify({
"success": False,
"error": str(e)
})
@app.route('/info')
def info():
text = """
<h1>Crawlers</h1>
"""
config = get_crawler_config()
for item in config:
name = item["name"]
crawler = item["crawler"]
settings = item["settings"]
text += "<div>Name:{} Crawler:{} Settings:{}</div>".format(name, crawler.__name__, settings)
return get_html(text)
@app.route('/infoj')
def infoj():
text = """
<h1>Crawlers</h1>
"""
properties = []
config = get_crawler_config()
for item in config:
item["crawler"] = item["crawler"].__name__
properties.append(item)
return jsonify(properties)
@app.route('/')
def home():
text = """
<h1>Available commands</h1>
<div><a href="/info">Info</a></div>
<div><a href="/infoj">Info JSON</a></div>
<div><a href="/history">History</a></div>
<div><a href="/run">Crawl</a></div>
<div><a href="/social">Social</a></div>
"""
return get_html(text)
@app.route('/history')
def history():
text = ""
if len(url_history) == 0:
return "<div>No history yet!</div>"
text += "<h1>Url history</h1>"
for datetime, url, all_properties in url_history:
text += "<h2>{} {}</h2>".format(datetime, url)
contents = all_properties[1]["data"]["Contents"]
status_code = all_properties[3]["data"]["status_code"]
charset = all_properties[3]["data"]["Charset"]
content_length = all_properties[3]["data"]["Content-Length"]
content_type = all_properties[3]["data"]["Content-Type"]
text += "<div>Status code:{} charset:{} Content-Type:{} Content-Length{}</div>".format(status_code, charset, content_type, content_length)
# text += "<div>{}</div>".format(html.escape(str(all_properties)))
return get_html(text)
@app.route('/set', methods=['POST'])
def set_response():
data = request.json
if not data or 'Contents' not in data:
return jsonify({"success": False, "error": "Missing 'Contents'"}), 400
# url = data['url']
url = data['request_url']
contents = data['Contents']
headers = data['Headers']
status_code = data['status_code']
print("Received data about {}".format(url))
response = {}
if headers and "Charset" in headers:
response["Charset"] = headers["Charset"]
else:
response["Charset"] = None
if headers and "Content-Length" in headers:
response["Content-Length"] = headers["Content-Length"]
else:
response["Content-Length"] = None
if headers and "Content-Type" in headers:
response["Content-Type"] = headers["Content-Type"]
else:
response["Content-Type"] = None
response["status_code"] = status_code
all_properties = []
all_properties.append({})
all_properties.append({"name": "Contents", "data" : {"Contents" : contents}})
all_properties.append({})
all_properties.append({"name" : "Response", "data" : response})
all_properties.append({"name" : "Headers", "data" : headers})
if len(url_history) > history_length:
url_history.pop(0)
url_history.append( (datetime.now(), url, all_properties) )
return jsonify({"success": True, "received": contents})
@app.route('/find', methods=['GET'])
def find_request():
url = request.args.get('url')
all_properties = find_response(url)
if not all_properties:
return jsonify({
"success": False,
"error": "No properties found"
}), 400
return jsonify(all_properties)
def append_properties(handler):
json_obj = {}
if type(handler) == webtools.Url.youtube_video_handler:
code = handler.get_video_code()
h = webtools.ReturnDislike(code)
json_obj["thumbs_up"] = h.get_thumbs_up()
json_obj["thumbs_down"] = h.get_thumbs_down()
json_obj["view_count"] = h.get_view_count()
json_obj["rating"] = h.get_rating()
json_obj["upvote_ratio"] = h.get_upvote_ratio()
json_obj["upvote_view_ratio"] = h.get_upvote_view_ratio()
elif type(handler) == webtools.HtmlPage:
reddit = webtools.RedditUrlHandler(handler.url)
github = webtools.GitHubUrlHandler(handler.url)
if reddit.is_handled_by():
handler_data = reddit.get_json_data()
if handler_data and "thumbs_up" in handler_data:
json_obj["thumbs_up"] = handler_data["thumbs_up"]
if handler_data and "thumbs_down" in handler_data:
json_obj["thumbs_down"] = handler_data["thumbs_down"]
if handler_data and "upvote_ratio" in handler_data:
json_obj["upvote_ratio"] = handler_data["upvote_ratio"]
if handler_data and "upvote_view_ratio" in handler_data:
json_obj["upvote_view_ratio"] = handler_data["upvote_view_ratio"]
elif github.is_handled_by():
handler_data = github.get_json_data()
if handler_data and "thumbs_up" in handler_data:
json_obj["thumbs_up"] = handler_data["thumbs_up"]
if handler_data and "thumbs_down" in handler_data:
json_obj["thumbs_down"] = handler_data["thumbs_down"]
if handler_data and "upvote_ratio" in handler_data:
json_obj["upvote_ratio"] = handler_data["upvote_ratio"]
if handler_data and "upvote_view_ratio" in handler_data:
json_obj["upvote_view_ratio"] = handler_data["upvote_view_ratio"]
return json_obj
@app.route('/run', methods=['GET'])
def run_command():
url = request.args.get('url')
crawler_data = request.args.get('crawler_data')
crawler = request.args.get('crawler')
name = request.args.get('name')
full = request.args.get('full')
if not url:
return jsonify({
"success": False,
"error": "No url provided"
}), 400
parsed_crawler_data = None
if crawler_data:
try:
parsed_crawler_data = json.loads(crawler_data)
except json.JSONDecodeError as E:
print(str(E))
if parsed_crawler_data is None:
parsed_crawler_data = {}
if crawler:
parsed_crawler_data["crawler"] = crawler
if name:
parsed_crawler_data["name"] = name
if "settings" not in parsed_crawler_data:
parsed_crawler_data["settings"] = {}
remote_server = f"http://{request.host}"
parsed_crawler_data["settings"]["remote_server"] = remote_server
print("Running:{}, with:{} at:{}".format(url, parsed_crawler_data, remote_server))
all_properties = run_webtools_url(url, remote_server, parsed_crawler_data, full)
#all_properties = None
#run_cmd_url(url, remote_server)
if all_properties:
if len(url_history) > history_length:
url_history.pop(0)
url_history.append( (datetime.now(), url, all_properties) )
else:
all_properties = find_response(url)
if not all_properties:
return jsonify({
"success": False,
"error": "No properties found"
}), 400
return jsonify(all_properties)
@app.route('/social', methods=['GET'])
def get_social():
url = request.args.get('url')
if not url:
return jsonify({
"success": False,
"error": "No url provided"
}), 400
page_url = webtools.Url.get_type(url)
additional = append_properties(page_url)
return jsonify(additional)
class CommandLineParser(object):
"""
Headers can only be passed by input binary file
"""
def parse(self):
self.parser = argparse.ArgumentParser(description="Remote server options")
self.parser.add_argument(
"--port", default=3000, type=int, help="Port number to be used"
)
self.parser.add_argument(
"-l", "--history-length", default=200, type=int, help="Length of history"
)
self.parser.add_argument("--host", default="0.0.0.0", help="Host")
self.args = self.parser.parse_args()
if __name__ == '__main__':
p = CommandLineParser()
p.parse()
history_length = p.args.history_length
app.run(debug=True, host=p.args.host, port=p.args.port, threaded=True)