forked from rjayroso/haystack-link-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
haystack.py
215 lines (171 loc) · 6.32 KB
/
haystack.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
"""
HAYSTACK
Author: Royce Ayroso-Ong
Licence: MIT Licence
Description: Haystack checks through a file for broken links
"""
from multiprocessing.dummy import Pool # support for parallelization
from multiprocessing import cpu_count # get cpu thread count
import argparse # parsing command line arguments
import sys # command line arguments
import re # regex for urls
import requests # url validating
from termcolor import colored # colored terminal text
flag = '--all' # to be used for flag options
def find_urls(filename):
"""Finds URLs within the file provided in the paramter.
Args:
filename (file): a file that can be read.
Returns:
list: a list containing unique URLs.
"""
regex = (
"(?:(?:https?|ftp)://)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]"
)
urls = re.findall(
regex, filename
) # uses regex to search for http(s) links in the file
urls = list(dict.fromkeys(urls)) # removes duplicate links
return urls
def ignore_urls(searchurls, ignoreurls):
"""Removes URLs that are common to both lists,
given a list of URLs and another list of URLs to ignore.
Args:
searchurls (list): initial list of URLs to remove from.
ignoreurls (list): a list of URLs to remove from searchurls.
Returns:
list: a list containing URLs that were not found in ignoreurls.
"""
# finds the common elements between the two lists and gets rid of them
finalurls = list(set(searchurls) ^ set(ignoreurls))
return finalurls
def check_url(url):
"""Sends a request to the URL in the parameter and prints the status code.
Args:
url (string): a string containing the URL to be checked.
"""
try: # get status code
request = requests.head(url, timeout=3)
status = request.status_code
except KeyboardInterrupt: # must include to be able to stop the program while it is running
sys.exit()
except Exception:
if flag == "--all":
print_colored("Unknown link: {}".format(url), "yellow")
else:
if status in range(200, 299) and flag in ("--good", "--all"):
print_colored("Valid link ({}): {} ".format(status, url), "green")
elif status in range(400, 599) and flag in ("--bad", "--all"):
print_colored("Bad link ({}): {} ".format(status, url), "red")
elif flag == "--all":
print_colored("Unknown link: {} ".format(url), "yellow")
return status
def print_colored(message, color):
"""Prints colored the specified text in the chosen color.
Args:
message (string): a string containing the message to be printed in color.
color (string): a string containing the color to print the message in.
"""
# using term color to print string in specified color
print(colored(message, color))
def parse_json(url, data):
# parse an array of json objects
searchurls = []
for item in data:
linktocheck = url + '/' + item["id"]
searchurls.append(linktocheck)
return searchurls
def initialize_parser():
"""Initializes the command line arguments.
Returns:
argparse.ArgumentParser: a argparse parser containing the initialized arguments.
"""
# initialize argparse arguments and return the main parser
init_parser = argparse.ArgumentParser(
prog="Haystack",
description="These are common Haystack commands used in various situations:",
)
init_parser.add_argument(
"-v",
"--version",
action="version",
help="display installed version",
version="%(prog)s version 3.0",
)
init_parser.add_argument(
"-f", "--file", help="search through a file for broken links", dest="searchfile"
)
parser.add_argument(
'-u', '--url', help='search through a web link for broken links', dest='url'
)
init_parser.add_argument(
"-i", "--ignore", help="file that contains urls to ignore", dest="ignorefile"
)
# optional flags for file processing, default is --all, only one flag can be present at a time
flag_group = init_parser.add_mutually_exclusive_group()
flag_group.add_argument(
"--all",
help="displays all links",
action="store_const",
const="--all",
default="--all",
dest="flag",
)
flag_group.add_argument(
"--good",
help="displays good links",
action="store_const",
const="--good",
dest="flag",
)
flag_group.add_argument(
"--bad",
help="displays bad links",
action="store_const",
const="--bad",
dest="flag",
)
return init_parser
def main(searchfile, ignorefile, url):
"""The main method of haystack.py, contains the main flow of the program.
Args:
searchfile (file): a file containing all the URLs to validate.
ignorefile (file): a file containing all the URLs to ignore.
"""
try: # read from file
if url:
r = requests.get(url, timeout=3)
data = r.json()
print(data)
searchurls = parse_json(url, data)
elif searchfile:
with open(searchfile, 'r') as search:
searchurls = find_urls(search.read())
# if user is using the ignore options
if ignorefile:
with open(ignorefile, 'r') as ignore:
ignoreurls = find_urls(ignore.read())
searchurls = ignore_urls(searchurls, ignoreurls)
except OSError as err: # error opening file
print("Error opening file: {0}".format(err))
return 1
else: # success opening file
print("Haystack is processing the file")
pool = Pool(cpu_count()) # Using 5 Thread pool
pool.map(
check_url, searchurls
) # Returns an iterator that applies function to every item of iterable
pool.close()
pool.join()
# Using '+' operator to connect with each sentence to print
print("Haystack has finished processing the file")
return 0
if __name__ == "__main__":
parser = initialize_parser()
args = parser.parse_args()
if args.searchfile or args.url:
flag = args.flag
main(args.searchfile, args.ignorefile, args.url)
else:
parser.print_help(sys.stderr)
sys.exit(0)