# coding=utf-8
"""Output formatters."""
from __future__ import print_function
import functools
import json
from xml.dom.minidom import parseString
import ansimarkup
import click
import colorama
from dicttoxml import dicttoxml
from jinja2 import Environment, PackageLoader
JINJA2_ENV = Environment(loader=PackageLoader("greynoise.cli"))
colorama.init()
ANSI_MARKUP = ansimarkup.AnsiMarkup(
tags={
"header": ansimarkup.parse("<bold>"),
"key": ansimarkup.parse("<blue>"),
"value": ansimarkup.parse("<green>"),
"noise": ansimarkup.parse("<light-yellow>"),
"not-noise": ansimarkup.parse("<dim>"),
"malicious": ansimarkup.parse("<light-red>"),
"unknown": ansimarkup.parse("<dim>"),
"benign": ansimarkup.parse("<light-green>"),
}
)
[docs]def colored_output(function):
"""Decorator that converts ansi markup into ansi escape sequences.
:param function: Function that will return text using ansi markup.
:type function: callable
:returns: Wrapped function that converts markup into escape sequences.
:rtype: callable
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
output = function(*args, **kwargs)
return ANSI_MARKUP(output)
return wrapper
[docs]def get_location(metadata):
"""Get location from ip context metadata."""
city = metadata["city"]
country = metadata["country"]
country_code = metadata["country_code"]
location = []
if city:
location.append("{},".format(city))
if country:
location.append(country)
if country_code:
location.append("({})".format(country_code))
return " ".join(location)
[docs]@colored_output
def ip_context_formatter(results, verbose):
"""Convert IP context result into human-readable text."""
for ip_context in results:
if "seen" in ip_context and ip_context["seen"]:
metadata = ip_context["metadata"]
metadata["location"] = get_location(metadata)
template = JINJA2_ENV.get_template("ip_context.txt.j2")
return template.render(results=results, verbose=verbose)
FORMATTERS = {
"json": json_formatter,
"xml": xml_formatter,
"txt": {
"ip": ip_context_formatter,
"quick": ip_quick_check_formatter,
"query": gnql_query_formatter,
"stats": gnql_stats_formatter,
},
}