"""
FeedFinder
==============

Tries to find feeds for
a given URL.

This is essentially a rewrite
of feedfinder.py,
originally by Mark Pilgrim
and Aaron Swartz.

Credits from the original:
Abe Fettig for a patch to sort Syndic8 feeds by popularity
Also Jason Diamond, Brian Lalor for bug reporting and patches

Original is located at:
    http://www.aaronsw.com/2002/feedfinder/

How it works:
    0. At every step, feeds are minimally verified to make sure they are really feeds.
    1. If the URI points to a feed, it is simply returned; otherwise
       the page is downloaded and the real fun begins.
    2. Feeds pointed to by LINK tags in the header of the page (autodiscovery)
    3. <A> links to feeds on the same server ending in ".rss", ".rdf", ".xml", or
       ".atom"
    4. <A> links to feeds on the same server containing "rss", "rdf", "xml", or "atom"
    5. Try some guesses about common places for feeds (index.xml, atom.xml, etc.).
    6. <A> links to feeds on external servers ending in ".rss", ".rdf", ".xml", or
       ".atom"
    7. <A> links to feeds on external servers containing "rss", "rdf", "xml", or "atom"

Copyright:
    2002-2004: Mark Pilgrim
    2006: Aaron Swartz
    2013: Francis Tseng
"""

# Python 2.7 support.
try:
    from urllib import request, parse
except ImportError:
    import urllib2 as request
    import urllib.parse as parse

import lxml.html
import chardet

def feeds(url):
    """
    Tries to find feeds
    for a given URL.
    """

    url = _full_url(url)
    data = _get(url)

    # Check if the url is a feed.
    if _is_feed(url):
        return [url]

    # Try to get feed links from markup.
    try:
        feed_links = [link for link in _get_feed_links(data, url) if _is_feed(link)]
    except:
        feed_links = []
    if feed_links:
        return feed_links

    # Try 'a' links.
    try:
        links = _get_a_links(data)
    except:
        links = []

    if links:
        # Filter to only local links.
        local_links = [link for link in links if link.startswith(url)]

        # Try to find feed links.
        feed_links.extend(_filter_feed_links(local_links))

        # If still nothing has been found...
        if not feed_links:
            # Try to find feed-looking links.
            feed_links.extend(_filter_feedish_links(local_links))

    # If still nothing has been found...
    if not feed_links:
        # BRUTE FORCE IT!
        guesses = [
                'atom.xml',     # Blogger, TypePad
                'index.atom',   # MoveableType
                'index.rdf',    # MoveableType
                'rss.xml',      # Dave Winer/Manila
                'index.xml',    # MoveableType
                'index.rss',    # Slash
                'feed'          # WordPress
        ]
        tries = [parse.urljoin(url, g) for g in guesses]
        feed_links.extend([link for link in tries if _is_feed(link)])