Esempio n. 1
0
def wttr(location, request):
    """
    Main rendering function, it processes incoming weather queries.
    Depending on user agent it returns output in HTML or ANSI format.

    Incoming data:
        request.args
        request.headers
        request.remote_addr
        request.referrer
        request.query_string
    """
    def _wrap_response(response_text, html_output):
        response = make_response(response_text)
        response.mimetype = 'text/html' if html_output else 'text/plain'
        return response

    if is_location_blocked(location):
        return ""

    ip_addr = client_ip_address(request)

    try:
        LIMITS.check_ip(ip_addr)
    except RuntimeError as exception:
        return str(exception)

    png_filename = None
    if location is not None and location.lower().endswith(".png"):
        png_filename = location
        location = location[:-4]

    lang = get_answer_language(request)
    query = parse_query.parse_query(request.args)
    html_output = get_output_format(request, query)
    user_agent = request.headers.get('User-Agent', '').lower()

    if location in PLAIN_TEXT_PAGES:
        help_ = show_text_file(location, lang)
        if html_output:
            return _wrap_response(render_template('index.html', body=help_),
                                  html_output)
        return _wrap_response(help_, html_output)

    if location and ':' in location:
        location = cyclic_location_selection(location, query.get('period', 1))

    orig_location = location

    if not png_filename:
        location, override_location_name, full_address, country, query_source_location = \
                location_processing(location, ip_addr)

        us_ip = query_source_location[
            1] == 'United States' and 'slack' not in user_agent
        query = parse_query.metric_or_imperial(query, lang, us_ip=us_ip)

        # logging query
        orig_location_utf8 = (orig_location or "").encode('utf-8')
        location_utf8 = location.encode('utf-8')
        use_imperial = query.get('use_imperial', False)
        log(" ".join(
            map(str, [
                ip_addr, user_agent, orig_location_utf8, location_utf8,
                use_imperial, lang
            ])))

        if country and location != NOT_FOUND_LOCATION:
            location = "%s,%s" % (location, country)

    # We are ready to return the answer
    try:
        if 'format' in query:
            return _wrap_response(
                wttr_line(location, override_location_name, query, lang),
                html_output)

        if png_filename:
            options = {'lang': lang, 'location': location}
            options.update(query)

            cached_png_file = wttrin_png.make_wttr_in_png(png_filename,
                                                          options=options)
            response = make_response(
                send_file(cached_png_file,
                          attachment_filename=png_filename,
                          mimetype='image/png'))
            for key, value in {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0',
            }.items():
                response.headers[key] = value

            # Trying to disable github caching
            return response

        if location.lower() == 'moon' or location.lower().startswith('moon@'):
            output = get_moon(location,
                              html=html_output,
                              lang=lang,
                              query=query)
        else:
            output = get_wetter(
                location,
                ip_addr,
                html=html_output,
                lang=lang,
                query=query,
                location_name=override_location_name,
                full_address=full_address,
                url=request.url,
            )

        if query.get('days', '3') != '0' and not query.get('no-follow-line'):
            if html_output:
                output = add_buttons(output)
            else:
                #output += '\n' + get_message('NEW_FEATURE', lang).encode('utf-8')
                output += '\n' + get_message('FOLLOW_ME',
                                             lang).encode('utf-8') + '\n'

        return _wrap_response(output, html_output)

    except RuntimeError as exception:
        if 'Malformed response' in str(exception) \
                or 'API key has reached calls per day allowed limit' in str(exception):
            if html_output:
                return _wrap_response(MALFORMED_RESPONSE_HTML_PAGE,
                                      html_output)
            return _wrap_response(
                get_message('CAPACITY_LIMIT_REACHED', lang).encode('utf-8'),
                html_output)
        logging.error("Exception has occured", exc_info=1)
        return "ERROR"
Esempio n. 2
0
        help_ = show_text_file(location, lang)
        if html_output:
            return render_template('index.html', body=help_)
        return help_

    if location and ':' in location:
        location = cyclic_location_selection(location, query.get('period', 1))

    orig_location = location

    location, override_location_name, full_address, country, query_source_location = \
            location_processing(location, ip_addr)

    us_ip = query_source_location[
        1] == 'United States' and 'slack' not in user_agent
    query = parse_query.metric_or_imperial(query, lang, us_ip=us_ip)

    # logging query
    orig_location_utf8 = (orig_location or "").encode('utf-8')
    location_utf8 = location.encode('utf-8')
    use_imperial = query.get('use_imperial', False)
    log(" ".join(
        map(str, [
            ip_addr, user_agent, orig_location_utf8, location_utf8,
            use_imperial, lang
        ])))

    if country and location != NOT_FOUND_LOCATION:
        location = "%s,%s" % (location, country)

    # We are ready to return the answer
Esempio n. 3
0
def parse_request(location, request, query, fast_mode=False):
    """Parse request and provided extended information for the query,
    including location data, language, output format, view, etc.

    Incoming data:

        `location`              location name extracted from the query url
        `request.args`
        `request.headers`
        `request.remote_addr`
        `request.referrer`
        `request.query_string`
        `query`                 parsed command line arguments

    Parameters priorities (from low to high):

        * HTTP-header
        * Domain name
        * URL
        * Filename

    Return: dictionary with parsed parameters
    """

    if location and location.startswith("b_"):
        result = parse_query.deserialize(location)
        result["request_url"] = request.url
        if result:
            return result

    png_filename = None
    if location is not None and location.lower().endswith(".png"):
        png_filename = location
        location = location[:-4]
    if location and ':' in location and location[0] != ":":
        location = _cyclic_location_selection(location, query.get('period', 1))

    parsed_query = {
        'ip_addr': _client_ip_address(request),
        'user_agent': request.headers.get('User-Agent', '').lower(),
        'request_url': request.url,
    }

    if png_filename:
        parsed_query["png_filename"] = png_filename
        parsed_query.update(parse_query.parse_wttrin_png_name(png_filename))

    lang, _view = get_answer_language_and_view(request)

    parsed_query["view"] = parsed_query.get("view", query.get("view", _view))
    parsed_query["location"] = parsed_query.get("location", location)
    parsed_query["orig_location"] = parsed_query["location"]
    parsed_query["lang"] = parsed_query.get("lang", lang)

    parsed_query["html_output"] = get_output_format(query, parsed_query)

    if not fast_mode:  # not png_filename and not fast_mode:
        location, override_location_name, full_address, country, query_source_location = \
                location_processing(parsed_query["location"], parsed_query["ip_addr"])

        us_ip = query_source_location[1] == 'United States' \
                and 'slack' not in parsed_query['user_agent']
        query = parse_query.metric_or_imperial(query, lang, us_ip=us_ip)

        if country and location != NOT_FOUND_LOCATION:
            location = "%s,%s" % (location, country)

        parsed_query.update({
            'location': location,
            'override_location_name': override_location_name,
            'full_address': full_address,
            'country': country,
            'query_source_location': query_source_location
        })

    parsed_query.update(query)
    return parsed_query