Ejemplo n.º 1
0
def _response(parsed_query, query, fast_mode=False):
    """Create response text based on `parsed_query` and `query` data.
    If `fast_mode` is True, process only requests that can
    be handled very fast (cached and static files).
    """

    answer = None
    cache_signature = cache.get_signature(parsed_query["user_agent"],
                                          parsed_query["request_url"],
                                          parsed_query["ip_addr"],
                                          parsed_query["lang"])
    answer = cache.get(cache_signature)

    if parsed_query['orig_location'] in PLAIN_TEXT_PAGES:
        answer = show_text_file(parsed_query['orig_location'],
                                parsed_query['lang'])
        if parsed_query['html_output']:
            answer = render_template('index.html', body=answer)

    if answer or fast_mode:
        return answer

    # at this point, we could not handle the query fast,
    # so we handle it with all available logic
    loc = (parsed_query['orig_location'] or "").lower()
    if parsed_query.get("view"):
        if not parsed_query.get("location"):
            parsed_query["location"] = loc

        output = wttr_line(query, parsed_query)
    elif loc == 'moon' or loc.startswith('moon@'):
        output = get_moon(parsed_query)
    else:
        output = get_wetter(parsed_query)

    if parsed_query.get('png_filename'):
        if parsed_query.get("view") != "v3":
            # originally it was just a usual function call,
            # but it was a blocking call, so it was moved
            # to separate threads:
            #
            #    output = fmt.png.render_ansi(
            #        output, options=parsed_query)
            result = TASKS.spawn(fmt.png.render_ansi,
                                 cache._update_answer(output),
                                 options=parsed_query)
            output = result.get()
    else:
        if query.get('days', '3') != '0' \
            and not query.get('no-follow-line') \
            and ((parsed_query.get("view") or "v2")[:2] in ["v2", "v3"]):
            if parsed_query['html_output']:
                output = add_buttons(output)
            else:
                message = get_message('FOLLOW_ME', parsed_query['lang'])
                if parsed_query.get('no-terminal', False):
                    message = remove_ansi(message)
                output += '\n' + message + '\n'

    return cache.store(cache_signature, output)
Ejemplo n.º 2
0
def _wego_postprocessing(location, parsed_query, stdout):
    full_address = parsed_query['full_address']
    lang = parsed_query['lang']

    if 'days' in parsed_query:
        if parsed_query['days'] == '0':
            stdout = "\n".join(stdout.splitlines()[:7]) + "\n"
        if parsed_query['days'] == '1':
            stdout = "\n".join(stdout.splitlines()[:17]) + "\n"
        if parsed_query['days'] == '2':
            stdout = "\n".join(stdout.splitlines()[:27]) + "\n"


    first = stdout.splitlines()[0]
    rest = stdout.splitlines()[1:]
    if parsed_query.get('no-caption', False):
        if ':' in first:
            first = first.split(":", 1)[1]
            stdout = "\n".join([first.strip()] + rest) + "\n"

    if parsed_query.get('no-terminal', False):
        stdout = remove_ansi(stdout)

    if parsed_query.get('no-city', False):
        stdout = "\n".join(stdout.splitlines()[2:]) + "\n"

    if full_address \
        and parsed_query.get('format', 'txt') != 'png' \
        and (not parsed_query.get('no-city')
             and not parsed_query.get('no-caption')
             and not parsed_query.get('days') == '0'):
        line = "%s: %s [%s]\n" % (
            get_message('LOCATION', lang),
            full_address,
            location)
        stdout += line

    if parsed_query.get('padding', False):
        lines = [x.rstrip() for x in stdout.splitlines()]
        max_l = max(len(remove_ansi(x)) for x in lines)
        last_line = " "*max_l + "   .\n"
        stdout = " \n" + "\n".join("  %s  " %x for x in lines) + "\n" + last_line

    return first, stdout
Ejemplo n.º 3
0
def get_moon(parsed_query):

    location = parsed_query['orig_location']
    html = parsed_query['html_output']
    lang = parsed_query['lang']
    hemisphere = parsed_query['hemisphere']

    date = None
    if '@' in location:
        date = location[location.index('@') + 1:]
        location = location[:location.index('@')]

    cmd = [globals.PYPHOON]
    if lang:
        cmd += ["-l", lang]

    if not hemisphere:
        cmd += ["-s", "south"]

    if date:
        try:
            dateutil.parser.parse(date)
        except Exception as e:
            print("ERROR: %s" % e)
        else:
            cmd += [date]

    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    stdout = p.communicate()[0]
    stdout = stdout.decode("utf-8")

    if parsed_query.get('no-terminal', False):
        stdout = globals.remove_ansi(stdout)

    if html:
        p = Popen(
            ["bash", globals.ANSI2HTML, "--palette=solarized", "--bg=dark"],
            stdin=PIPE,
            stdout=PIPE,
            stderr=PIPE)
        stdout, stderr = p.communicate(stdout.encode("utf-8"))
        stdout = stdout.decode("utf-8")
        stderr = stderr.decode("utf-8")
        if p.returncode != 0:
            globals.error(stdout + stderr)

    return stdout
Ejemplo n.º 4
0
def main(query, parsed_query, data):
    parsed_query["locale"] = "en_US"

    location = parsed_query["location"]
    html_output = parsed_query["html_output"]

    geo_data = get_geodata(location)
    if data is None:
        data_parsed = get_data(parsed_query)
    else:
        data_parsed = data

    if html_output:
        parsed_query["text"] = "no"
        filename = "b_" + parse_query.serialize(parsed_query) + ".png"
        output = """
<html>
<head>
<title>Weather report for {orig_location}</title>
<link rel="stylesheet" type="text/css" href="/files/style.css" />
</head>
<body>
  <img src="/{filename}" width="592" height="532"/>
<pre>
{textual_information}
</pre>
</body>
</html>
""".format(filename=filename,
           orig_location=parsed_query["orig_location"],
           textual_information=textual_information(data_parsed,
                                                   geo_data,
                                                   parsed_query,
                                                   html_output=True))
    else:
        output = generate_panel(data_parsed, geo_data, parsed_query)
        if query.get("text") != "no" and parsed_query.get("text") != "no":
            output += textual_information(data_parsed, geo_data, parsed_query)
        if parsed_query.get('no-terminal', False):
            output = remove_ansi(output)
    return output