forked from cyberblackhole/stack-dump
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackDump.py
More file actions
178 lines (155 loc) · 7.87 KB
/
stackDump.py
File metadata and controls
178 lines (155 loc) · 7.87 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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from requests import get
from os import environ
from sys import exit
from datetime import datetime
from math import ceil
import json
from html import unescape
from argparse import ArgumentParser, RawTextHelpFormatter
try:
from naryal2580.style import info, fetchFormattedTime, uline, bold, italic, \
dim, blue, yellow, rst, bad, coolExit
except ImportError:
print("Install missing package with `pip3 install -r ./requirements.txt`", end='\n\n')
exit(1)
__version__ = 0.7
banner = '''
____ _ _ ____
/ ___|| |_ __ _ ___| | __ | _ \ _ _ _ __ ___ _ __
\___ \| __/ _` |/ __| |/ / | | | | | | | '_ ` _ \| '_ \\
___) | || (_| | (__| < | |_| | |_| | | | | | | |_) |
|____/ \__\__,_|\___|_|\_\ |____/ \__,_|_| |_| |_| .__/
|_| v{}'''.format(
__version__
)[1:]
print(banner)
try:
if environ['STACK_API_KEY']:
api_key = environ['STACK_API_KEY']
except KeyError:
print(bad("Please Export API key `export STACK_API_KEY='your_key_here'`\n check https://stackapps.com/apps/oauth/register for more details"), end='\n\n')
coolExit(1)
try:
stack_sites = json.load(open('stackSites.json'))
except:
print(bad("Problem with opening stackSites.json File"), end='\n\n')
coolExit(1)
def printResult(keyword, title, link, site, quota):
colorOut = '{}{}{}> {}{}{} {}{}{}{} | {}{}{} [{}{}{}]'.format(
uline,
keyword,
rst,
bold,
title,
rst,
italic,
blue,
link,
rst,
dim,
result_site,
rst,
yellow,
quota_status,
rst
)
print(colorOut, end='\n\n')
def get_request_limit(key):
url = "https://api.stackexchange.com/2.2/sites?page=1&pagesize=10&key={}".\
format(key)
res = get(url)
quota_remaining = quota_max = 0
if res.status_code == 200:
json_data = json.loads(res.content)
quota_remaining, quota_max = json_data['quota_remaining'], \
json_data['quota_max']
return quota_remaining, quota_max
if __name__ == '__main__':
parser = ArgumentParser(
description='StackDump', epilog='''Example: stackdump -k "example"\n''',
formatter_class=RawTextHelpFormatter)
requiredparser = parser.add_argument_group('required arguments')
requiredparser.add_argument('-k', '--keyword', help="Keyword to lookup",
type=str, dest="keyword", required=True)
requiredparser.add_argument('-l', '--limit', type=int, dest="limit",
help="Limit Results per Stack Site: min:10")
args = parser.parse_args()
print(info('Started [at] {}'.format(datetime.now())), end='\n\n')
apilink = "https://api.stackexchange.com/2.2/search/advanced"
if args.keyword:
page=1
pagesize = 10
if args.limit:
if args.limit >= 10 and args.limit <= 1000:
maxpages = ceil(float(args.limit/10))
print(maxpages)
else:
print(bad("--limit where 10>=limit<=1000"), end='\n\n')
coolExit(1)
else:
maxpages=100
try:
site_itr_total = len(stack_sites['top_stack_sites'])
site_itr_current = 0
for site in stack_sites['top_stack_sites']:
site_itr_current += 1
quota_remaining, quota_max = get_request_limit(api_key)
keyword_name = args.keyword
page=1
while quota_remaining > 0:
query_string = '?page={}&pagesize={}&order=asc&sort=relevance&q={}&site={}&key={}'.format(
page, pagesize, keyword_name, site, api_key)
url = apilink + query_string
response = get(url)
quota_remaining, quota_max = get_request_limit(api_key)
page += 1
json_data = json.loads(response.content)
if 'items' in json_data:
result_items = json_data['items']
if len(result_items) > 0:
for item in result_items:
link = unescape(str(item['link']))
quota_status = str(quota_remaining)+"/"+str(
quota_max
)
title = unescape(str(item['title']))
result_site = '{}({}/{})'.format(
site,
site_itr_current,
site_itr_total
)
printResult(keyword_name, title, link, site,
quota_status)
else:
quota_status = str(quota_remaining)+"/"+str(
quota_max
)
result_site = '{}({}/{})'.format(
site,
site_itr_current,
site_itr_total
)
printResult(keyword_name, "None", "None", site,
quota_status)
break
else:
quota_remaining, quota_max = get_request_limit(api_key)
quota_status = str(quota_remaining)+"/"+str(quota_max)
result_site = '{}({}/{})'.format(
site,
site_itr_current,
site_itr_total
)
printResult(keyword_name, "None", "None", site,
quota_status)
break
if page == maxpages + 1:
print("max")
break
if quota_remaining == 0:
print(bad('Error -> API Quota Exaushed'), end='\n\n')
except KeyboardInterrupt:
print(bad("Interupt Received"), end='\n\n')
coolExit(1)