def episode_torrents(eid):
    episode = index.Episode.get({"id": eid})
    nyaa = Nyaa(episode.aid)
    torrents = nyaa.find_episode(episode.epno)

    from urllib.parse import quote

    links = ['<a href="/download/episode/{}">{}</a>'.format(quote(link), title) for (link, title) in torrents]

    return "</br>".join(links)
    def handleSubscription(self, subscription):
        if not subscription.anime:
            return False
        print('handling', subscription.anime)

        aid = subscription.anime.id
        nyaa = Nyaa(aid)
        group = nyaa.get_groups()[0][0]
        # gotta wait for groups to be available 8D
        if not group:
            return False
        # F**K THE CONFIG
        qualities = ['720p', '480p', '']

        for episode in subscription.anime.episodes:
            if episode.download:
                # if theres an entry for this episode in the download table, skip it
                continue

            if episode.files:
                found = False
                for file in episode.files:
                    if isfile(file.path):
                        # set the found flag is we find a valid file
                        found = True
                    else:
                        # delete any invalid looking rows
                        with session_scope() as session:
                            session.delete(file)
                if found:
                    # if we found a valid file for this episode, skip it
                    continue

            # get all the available torrents for this episode
            available = nyaa.find_episode(episode.epno)
            if len(available):
                # TODO have group/quality preference/order to pick the right one
                # and download the one we want if there was any
                chosen = None
                for quality in qualities:
                    for torrent in available:
                        title = torrent[0].lower()
                        good = group.lower() in title and quality in title
                        if good:
                            chosen = torrent
                            break
                    if chosen:
                        break
                if chosen:
                    Nyaa.download_torrent(chosen, eid=episode.id)
def download_episode(path):
    Nyaa.download_torrent(path)
    return redirect(request.referrer)