Skip to content

Instantly share code, notes, and snippets.

@aslakr
Last active March 16, 2019 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aslakr/453c1861aa910bc20fd322727e19e5b8 to your computer and use it in GitHub Desktop.
Save aslakr/453c1861aa910bc20fd322727e19e5b8 to your computer and use it in GitHub Desktop.
Python for creating a RewriteMap
#!/usr/bin/env python3
import libravatar
import requests
from furl import furl
import os
import sys
import argparse
p = argparse.ArgumentParser()
p.add_argument(
"-i",
"--infile",
type=argparse.FileType("r"),
default=sys.stdin,
help="Input one email adress pr line",
)
p.add_argument(
"-o",
"--outfile",
type=argparse.FileType("w"),
default=sys.stdout,
help="Output result fitting for a Apache RewriteMap",
)
a = p.parse_args()
for em in a.infile.read().splitlines():
# Get libravatar_url, default to 404 with added query for
# not using gravatarproxy and redirect if no libravatar
# au = avatarurl
try:
au = furl(libravatar.libravatar_url(email=em, https=True, default="404")).add(
args={"gravatarproxy": "n", "gravatarredirect": "n"}
)
ah = libravatar.parse_user_identity(email=em, openid=None)[0]
except Exception:
pass
# Follow redirects
aur = requests.head(au.url, allow_redirects=True)
# If no libravatar, check if a gravatar exist
if aur.status_code == 404:
au = furl("https://www.gravatar.com/avatar/").add(path=ah, args={"d": "404"})
aur = requests.head(au, allow_redirects=True)
# If http = 200, (not e.g. 404) output result
if aur.status_code == 200:
# Remove query
au = furl(aur.url).remove(query=True).url
# Output result fitting for
# <https://httpd.apache.org/docs/current/rewrite/rewritemap.html#txt>
# -> mailmd5hash avatarurl # mail
a.outfile.write(" ".join([ah, au]) + " # " + em + os.linesep)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment