| 1 |
#!/usr/bin/env python3 |
| 2 |
import configparser |
| 3 |
import json |
| 4 |
import logging |
| 5 |
import os |
| 6 |
import pathlib |
| 7 |
import sys |
| 8 |
import time |
| 9 |
from datetime import datetime |
| 10 |
|
| 11 |
import requests |
| 12 |
from requests.auth import HTTPBasicAuth |
| 13 |
|
| 14 |
logging.basicConfig() |
| 15 |
|
| 16 |
log = logging.getLogger(__name__) |
| 17 |
log.setLevel(logging.DEBUG) |
| 18 |
|
| 19 |
DEFAULT_AVATAR = "https://upload.wikimedia.org/wikipedia/commons/5/5f/Err-logo.png" |
| 20 |
BLACKLISTED = [] |
| 21 |
|
| 22 |
user_cache = {} |
| 23 |
plugins = {} |
| 24 |
|
| 25 |
|
| 26 |
def get_auth(): |
| 27 |
"""Get auth creds from Github Token |
| 28 |
|
| 29 |
token is generated from the personal tokens in github |
| 30 |
""" |
| 31 |
token_file = pathlib.Path("token") |
| 32 |
token_env = os.getenv("ERRBOT_REPOS_TOKEN") |
| 33 |
|
| 34 |
if token_file.is_file(): |
| 35 |
try: |
| 36 |
token_info = open("token", "r").read() |
| 37 |
except ValueError: |
| 38 |
log.fatal( |
| 39 |
"Token file cannot be properly read, should be of the form username:token" |
| 40 |
) |
| 41 |
sys.exit(-1) |
| 42 |
elif token_env: |
| 43 |
token_info = token_env |
| 44 |
else: |
| 45 |
msg = "No 'token' file or environment variable 'ERROBOT_REPOS_TOKEN' found." |
| 46 |
log.fatal(msg) |
| 47 |
sys.exit(-1) |
| 48 |
|
| 49 |
try: |
| 50 |
user, token = token_info.strip().split(":") |
| 51 |
except ValueError: |
| 52 |
msg = "Token file cannot be properly read, should be of the form username:token" |
| 53 |
log.fatal(msg) |
| 54 |
sys.exit(-1) |
| 55 |
|
| 56 |
auth = HTTPBasicAuth(user, token) |
| 57 |
return auth |
| 58 |
|
| 59 |
|
| 60 |
AUTH = get_auth() |
| 61 |
|
| 62 |
|
| 63 |
def add_blacklisted(repo): |
| 64 |
with open("blacklisted.txt", "a") as f: |
| 65 |
f.write(repo) |
| 66 |
f.write("\n") |
| 67 |
|
| 68 |
|
| 69 |
def save_plugins(): |
| 70 |
with open("repos.json", "w") as f: |
| 71 |
json.dump(plugins, f, indent=2, separators=(",", ": ")) |
| 72 |
|
| 73 |
|
| 74 |
def get_avatar_url(repo): |
| 75 |
username = repo.split("/")[0] |
| 76 |
if username in user_cache: |
| 77 |
user = user_cache[username] |
| 78 |
else: |
| 79 |
user_res = requests.get("https://api.github.com/users/" + username, auth=AUTH) |
| 80 |
user = user_res.json() |
| 81 |
if "avatar_url" in user: # don't pollute the presistent cache |
| 82 |
user_cache[username] = user |
| 83 |
with open("user_cache", "w") as f: |
| 84 |
f.write(repr(user_cache)) |
| 85 |
rate_limit(user_res) |
| 86 |
return user["avatar_url"] if "avatar_url" in user else DEFAULT_AVATAR |
| 87 |
|
| 88 |
|
| 89 |
def rate_limit(resp): |
| 90 |
""" |
| 91 |
Wait enough to be in the budget for this request. |
| 92 |
:param resp: the http response from github |
| 93 |
:return: |
| 94 |
""" |
| 95 |
if "X-RateLimit-Remaining" not in resp.headers: |
| 96 |
log.info("No rate limit detected. Hum along...") |
| 97 |
return |
| 98 |
remain = int(resp.headers["X-RateLimit-Remaining"]) |
| 99 |
limit = int(resp.headers["X-RateLimit-Limit"]) |
| 100 |
log.info("Rate limiter: %s allowed out of %d", remain, limit) |
| 101 |
if remain > 1: # margin by one request |
| 102 |
return |
| 103 |
reset = int(resp.headers["X-RateLimit-Reset"]) |
| 104 |
ts = datetime.fromtimestamp(reset) |
| 105 |
delay = (ts - datetime.now()).total_seconds() |
| 106 |
log.info("Hit rate limit. Have to wait for %d seconds", delay) |
| 107 |
if delay < 0: # time drift |
| 108 |
delay = 2 |
| 109 |
time.sleep(delay) |
| 110 |
|
| 111 |
|
| 112 |
def parse_date(gh_date: str) -> datetime: |
| 113 |
return datetime.strptime(gh_date, "%Y-%m-%dT%H:%M:%SZ") |
| 114 |
|
| 115 |
|
| 116 |
def check_repo(repo): |
| 117 |
repo_name = repo.get("full_name", None) |
| 118 |
if repo_name is None: |
| 119 |
log.error("No name in %s", repo) |
| 120 |
log.debug("Checking %s...", repo_name) |
| 121 |
code_resp = requests.get( |
| 122 |
"https://api.github.com/search/code?q=extension:plug+repo:%s" % repo_name, |
| 123 |
auth=AUTH, |
| 124 |
) |
| 125 |
if code_resp.status_code != 200: |
| 126 |
log.error( |
| 127 |
"Error getting https://api.github.com/search/code?q=extension:plug+repo:%s", |
| 128 |
repo_name, |
| 129 |
) |
| 130 |
log.error("code %d", code_resp.status_code) |
| 131 |
log.error("content %s", code_resp.text) |
| 132 |
|
| 133 |
return |
| 134 |
plug_items = code_resp.json()["items"] |
| 135 |
if not plug_items: |
| 136 |
log.debug("No plugin found in %s, blacklisting it.", repo_name) |
| 137 |
add_blacklisted(repo_name) |
| 138 |
return |
| 139 |
owner = repo["owner"] |
| 140 |
avatar_url = owner["avatar_url"] if "avatar_url" in owner else DEFAULT_AVATAR |
| 141 |
|
| 142 |
days_old = (datetime.now() - parse_date(repo["updated_at"])).days |
| 143 |
score = ( |
| 144 |
repo["stargazers_count"] |
| 145 |
+ repo["watchers_count"] * 2 |
| 146 |
+ repo["forks_count"] |
| 147 |
- days_old / 25 |
| 148 |
) |
| 149 |
|
| 150 |
for plug in plug_items: |
| 151 |
plugfile_resp = requests.get( |
| 152 |
"https://raw.githubusercontent.com/%s/master/%s" % (repo_name, plug["path"]) |
| 153 |
) |
| 154 |
log.debug("Found a plugin:") |
| 155 |
log.debug("Repo: %s", repo_name) |
| 156 |
log.debug("File: %s", plug["path"]) |
| 157 |
parser = configparser.ConfigParser() |
| 158 |
try: |
| 159 |
parser.read_string(plugfile_resp.text) |
| 160 |
|
| 161 |
name = parser["Core"]["Name"] |
| 162 |
log.debug("Name: %s", name) |
| 163 |
|
| 164 |
if "Documentation" in parser and "Description" in parser["Documentation"]: |
| 165 |
doc = parser["Documentation"]["Description"] |
| 166 |
log.debug("Documentation: %s", doc) |
| 167 |
else: |
| 168 |
doc = "" |
| 169 |
|
| 170 |
if "Python" in parser: |
| 171 |
python = parser["Python"]["Version"] |
| 172 |
log.debug("Python Version: %s", python) |
| 173 |
else: |
| 174 |
python = "2" |
| 175 |
|
| 176 |
plugin = { |
| 177 |
"path": plug["path"], |
| 178 |
"repo": repo["html_url"], |
| 179 |
"documentation": doc, |
| 180 |
"name": name, |
| 181 |
"python": python, |
| 182 |
"avatar_url": avatar_url, |
| 183 |
"score": score, |
| 184 |
} |
| 185 |
|
| 186 |
repo_entry = plugins.get(repo_name, {}) |
| 187 |
repo_entry[name] = plugin |
| 188 |
plugins[repo_name] = repo_entry |
| 189 |
log.debug("Catalog added plugin %s.", plugin["name"]) |
| 190 |
except: |
| 191 |
log.error("Invalid syntax in %s, skipping...", plug["path"]) |
| 192 |
continue |
| 193 |
|
| 194 |
rate_limit(plugfile_resp) |
| 195 |
|
| 196 |
save_plugins() |
| 197 |
rate_limit(code_resp) |
| 198 |
|
| 199 |
|
| 200 |
def find_plugins(query): |
| 201 |
url = ( |
| 202 |
"https://api.github.com/search/repositories?q=%s+in:name+language:python&sort=stars&order=desc" |
| 203 |
% query |
| 204 |
) |
| 205 |
while True: |
| 206 |
repo_resp = requests.get(url, auth=AUTH) |
| 207 |
repo_json = repo_resp.json() |
| 208 |
if repo_json.get("message", None) == "Bad credentials": |
| 209 |
log.error("Invalid credentials, check your token file, see README.") |
| 210 |
sys.exit(-1) |
| 211 |
log.debug( |
| 212 |
"Repo reqs before ratelimit %s/%s", |
| 213 |
repo_resp.headers["X-RateLimit-Remaining"], |
| 214 |
repo_resp.headers["X-RateLimit-Limit"], |
| 215 |
) |
| 216 |
if "message" in repo_json and repo_json["message"].startswith( |
| 217 |
"API rate limit exceeded for" |
| 218 |
): |
| 219 |
log.error("API rate limit hit anyway ... wait for 30s") |
| 220 |
time.sleep(30) |
| 221 |
continue |
| 222 |
items = repo_json["items"] |
| 223 |
|
| 224 |
for repo in items: |
| 225 |
if repo["full_name"] in BLACKLISTED: |
| 226 |
log.debug("Skipping %s.", repo) |
| 227 |
continue |
| 228 |
check_repo(repo) |
| 229 |
if "next" not in repo_resp.links: |
| 230 |
break |
| 231 |
url = repo_resp.links["next"]["url"] |
| 232 |
log.debug("Next url: %s", url) |
| 233 |
rate_limit(repo_resp) |
| 234 |
|
| 235 |
|
| 236 |
def main(): |
| 237 |
find_plugins("err") |
| 238 |
# Those are found by global search only available on github UI: |
| 239 |
# https://github.com/search?l=&q=Documentation+extension%3Aplug&ref=advsearch&type=Code&utf8=%E2%9C%93 |
| 240 |
url = "https://api.github.com/repos/%s" |
| 241 |
with open("extras.txt", "r") as extras: |
| 242 |
for repo_name in extras: |
| 243 |
repo_name = repo_name.strip() |
| 244 |
repo_resp = requests.get(url % repo_name, auth=AUTH) |
| 245 |
repo = repo_resp.json() |
| 246 |
if repo.get("message", None) == "Bad credentials": |
| 247 |
log.error("Invalid credentials, check your token file, see README.") |
| 248 |
sys.exit(-1) |
| 249 |
if "message" in repo and repo["message"].startswith( |
| 250 |
"API rate limit exceeded for" |
| 251 |
): |
| 252 |
log.error("API rate limit hit anyway ... wait for 30s") |
| 253 |
time.sleep(30) |
| 254 |
continue |
| 255 |
if "message" in repo and repo["message"].startswith("Not Found"): |
| 256 |
log.error("%s not found.", repo_name) |
| 257 |
else: |
| 258 |
check_repo(repo) |
| 259 |
rate_limit(repo_resp) |
| 260 |
|
| 261 |
|
| 262 |
if __name__ == "__main__": |
| 263 |
try: |
| 264 |
with open("user_cache", "r") as f: |
| 265 |
user_cache = eval(f.read()) |
| 266 |
except FileNotFoundError: |
| 267 |
# File doesn't exist, so we continue on |
| 268 |
log.info("No user cache existing, will be generating it for the first time.") |
| 269 |
|
| 270 |
try: |
| 271 |
with open("blacklisted.txt", "r") as f: |
| 272 |
BLACKLISTED = [line.strip() for line in f.readlines()] |
| 273 |
except FileNotFoundError: |
| 274 |
log.info("No blacklisted.txt found, no plugins will be blacklisted.") |
| 275 |
|
| 276 |
main() |