'Search for entries on RarBG'

@plugin.internet(log)
def search(self, task, entry, config):

    categories = config.get(u'category', u'all')
    if (not isinstance(categories, list)):
        categories = [categories]
    categories = [(c if isinstance(c, int) else CATEGORIES[c]) for c in categories]
    category_url_fragment = u';'.join((str(c) for c in categories))
    entries = set()
    params = {u'mode': u'search', u'ranked': int(config[u'ranked']), u'min_seeders': config[u'min_seeders'], u'min_leechers': config[u'min_leechers'], u'sort': config[u'sorted_by'], u'category': category_url_fragment, u'format': u'json_extended', u'app_id': u'flexget'}
    for search_string in entry.get(u'search_strings', [entry[u'title']]):
        params.pop(u'search_string', None)
        params.pop(u'search_imdb', None)
        params.pop(u'search_tvdb', None)
        if (entry.get(u'movie_name') and entry.get(u'imdb_id')):
            params[u'search_imdb'] = entry.get(u'imdb_id')
        else:
            query = normalize_scene(search_string)
            query_url_fragment = query.encode(u'utf8')
            params[u'search_string'] = query_url_fragment
            if config[u'use_tvdb']:
                plugin.get_plugin_by_name(u'thetvdb_lookup').instance.lazy_series_lookup(entry, u'en')
                params[u'search_tvdb'] = entry.get(u'tvdb_id')
                log.debug(u'Using    tvdb    id    %s', entry.get(u'tvdb_id'))
        response = self.get(params=params)
        if (not response):
            continue
        if (response.get(u'error_code') in [10, 20]):
            searched_string = (params.get(u'search_string') or u'imdb={0}'.format(params.get(u'search_imdb')) or u'tvdb={0}'.format(params.get(u'tvdb_id')))
            log.debug(u'No    results    found    for    %s.    Message    from    rarbg:    %s', searched_string, response.get(u'error'))
            continue
        elif response.get(u'error'):
            log.error(u'Error    code    %s:    %s', response.get(u'error_code'), response.get(u'error'))
            continue
        else:
            for result in response.get(u'torrent_results'):
                e = Entry()
                e[u'title'] = result.get(u'title')
                e[u'url'] = result.get(u'download')
                e[u'torrent_seeds'] = int(result.get(u'seeders'))
                e[u'torrent_leeches'] = int(result.get(u'leechers'))
                e[u'content_size'] = ((int(result.get(u'size')) / 1024) / 1024)
                episode_info = result.get(u'episode_info')
                if episode_info:
                    e[u'imdb_id'] = episode_info.get(u'imdb')
                    e[u'tvdb_id'] = episode_info.get(u'tvdb')
                    e[u'tvrage_id'] = episode_info.get(u'tvrage')
                entries.add(e)
    return entries
