# Path: rophako/utils.py
# def remote_addr():
#     """Retrieve the end user's remote IP address. If the site is configured
#     to honor X-Forwarded-For and this header is present, it's returned."""
#     if Config.security.use_forwarded_for:
#         return request.access_route[0]
#     return request.remote_addr
# 
# def pretty_time(time_format, unix):
#     """Pretty-print a time stamp."""
#     tz   = pytz.timezone(Config.site.timezone)
#     date = datetime.datetime.fromtimestamp(unix, pytz.utc)
#     return date.astimezone(tz).strftime(time_format)
# 
# def server_name():
#     """Get the server's hostname."""
#     urlparts = list(urlparse.urlparse(request.url_root))
#     return urlparts[1]
# 
# def handle_exception(error):
#     """Send an e-mail to the site admin when an exception occurs."""
#     if current_app.config.get("DEBUG"):
#         print(traceback.format_exc())
#         raise
# 
#     import rophako.jsondb as JsonDB
# 
#     # Don't spam too many e-mails in a short time frame.
#     cache = JsonDB.get_cache("exception_catcher")
#     if cache:
#         last_exception = int(cache)
#         if int(time.time()) - last_exception < 120:
#             # Only one e-mail per 2 minutes, minimum
#             logger.error("RAPID EXCEPTIONS, DROPPING")
#             return
#     JsonDB.set_cache("exception_catcher", int(time.time()))
# 
#     username = "anonymous"
#     try:
#         if hasattr(g, "info") and "session" in g.info and "username" in g.info["session"]:
#             username = g.info["session"]["username"]
#     except:
#         pass
# 
#     # Get the timestamp.
#     timestamp = time.ctime(time.time())
# 
#     # Exception's traceback.
#     error = str(error.__class__.__name__) + ": " + str(error)
#     stacktrace = error + "\n\n" \
#         + "==== Start Traceback ====\n" \
#         + traceback.format_exc() \
#         + "==== End Traceback ====\n\n" \
#         + "Request Information\n" \
#         + "-------------------\n" \
#         + "Address: " + remote_addr() + "\n" \
#         + "User Agent: " + request.user_agent.string + "\n" \
#         + "Referrer: " + request.referrer
# 
#     # Construct the subject and message
#     subject = "Internal Server Error on {} - {} - {}".format(
#         Config.site.site_name,
#         username,
#         timestamp,
#     )
#     message = "{} has experienced an exception on the route: {}".format(
#         username,
#         request.path,
#     )
#     message += "\n\n" + stacktrace
# 
#     # Send the e-mail.
#     send_email(
#         to=Config.site.notify_address,
#         subject=subject,
#         message=message,
#     )


import time
import requests
import rophako.jsondb as JsonDB
from rophako.utils import (remote_addr, pretty_time, server_name,
    handle_exception)

            # Update with their IP?
            if not cookie and not addr in db:
                db[addr] = time.time()
                JsonDB.commit(dbfile, db)

            # Store the copy.
            values[key] = len(db.keys())

    # Log their HTTP referrer.
    referrer = "1"
    if request.referrer:
        # Branch and check this.
        referrer = log_referrer(request, request.referrer)
        if not referrer:
            # Wasn't a valid referrer.
            referrer = "1"

    # Set their tracking cookie.
    if not cookie:
        cookie = referrer
        session["tracking"] = cookie

    return values


def log_referrer(request, link):
    """Double check the referring URL."""

    # Ignore if same domain.

# Path: rophako/utils.py
# def remote_addr():
#     """Retrieve the end user's remote IP address. If the site is configured
#     to honor X-Forwarded-For and this header is present, it's returned."""
#     if Config.security.use_forwarded_for:
#         return request.access_route[0]
#     return request.remote_addr
# 
# def pretty_time(time_format, unix):
#     """Pretty-print a time stamp."""
#     tz   = pytz.timezone(Config.site.timezone)
#     date = datetime.datetime.fromtimestamp(unix, pytz.utc)
#     return date.astimezone(tz).strftime(time_format)
# 
# def server_name():
#     """Get the server's hostname."""
#     urlparts = list(urlparse.urlparse(request.url_root))
#     return urlparts[1]
# 
# def handle_exception(error):
#     """Send an e-mail to the site admin when an exception occurs."""
#     if current_app.config.get("DEBUG"):
#         print(traceback.format_exc())
#         raise
# 
#     import rophako.jsondb as JsonDB
# 
#     # Don't spam too many e-mails in a short time frame.
#     cache = JsonDB.get_cache("exception_catcher")
#     if cache:
#         last_exception = int(cache)
#         if int(time.time()) - last_exception < 120:
#             # Only one e-mail per 2 minutes, minimum
#             logger.error("RAPID EXCEPTIONS, DROPPING")
#             return
#     JsonDB.set_cache("exception_catcher", int(time.time()))
# 
#     username = "anonymous"
#     try:
#         if hasattr(g, "info") and "session" in g.info and "username" in g.info["session"]:
#             username = g.info["session"]["username"]
#     except:
#         pass
# 
#     # Get the timestamp.
#     timestamp = time.ctime(time.time())
# 
#     # Exception's traceback.
#     error = str(error.__class__.__name__) + ": " + str(error)
#     stacktrace = error + "\n\n" \
#         + "==== Start Traceback ====\n" \
#         + traceback.format_exc() \
#         + "==== End Traceback ====\n\n" \
#         + "Request Information\n" \
#         + "-------------------\n" \
#         + "Address: " + remote_addr() + "\n" \
#         + "User Agent: " + request.user_agent.string + "\n" \
#         + "Referrer: " + request.referrer
# 
#     # Construct the subject and message
#     subject = "Internal Server Error on {} - {} - {}".format(
#         Config.site.site_name,
#         username,
#         timestamp,
#     )
#     message = "{} has experienced an exception on the route: {}".format(
#         username,
#         request.path,
#     )
#     message += "\n\n" + stacktrace
# 
#     # Send the e-mail.
#     send_email(
#         to=Config.site.notify_address,
#         subject=subject,
#         message=message,
#     )


# Path: rophako/model/tracking.py
import time
import requests
import rophako.jsondb as JsonDB
from rophako.utils import (remote_addr, pretty_time, server_name,
    handle_exception)


            # Update with their IP?
            if not cookie and not addr in db:
                db[addr] = time.time()
                JsonDB.commit(dbfile, db)

            # Store the copy.
            values[key] = len(db.keys())

    # Log their HTTP referrer.
    referrer = "1"
    if request.referrer:
        # Branch and check this.
        referrer = log_referrer(request, request.referrer)
        if not referrer:
            # Wasn't a valid referrer.
            referrer = "1"

    # Set their tracking cookie.
    if not cookie:
        cookie = referrer
        session["tracking"] = cookie

    return values


def log_referrer(request, link):
    """Double check the referring URL."""

    # Ignore if same domain.

    hostname = server_name()