fix imports of mygpo.couch
[mygpo.git] / mygpo / directory / search.py
blobd8c261762c91a70369cef7fa43269937ad689c04
1 from mygpo.core.models import Podcast, PodcastGroup
2 from mygpo.utils import is_url
3 from mygpo.couch import get_main_database
4 from mygpo.data.feeddownloader import update_podcasts
5 from mygpo.api.sanitizing import sanitize_url
8 def search_wrapper(result):
9 doc = result['doc']
10 if doc['doc_type'] == 'Podcast':
11 p = Podcast.wrap(doc)
12 elif doc['doc_type'] == 'PodcastGroup':
13 p = PodcastGroup.wrap(doc)
14 p._id = result['id']
15 return p
18 def search_podcasts(q, limit=20, skip=0):
20 if is_url(q):
21 url = sanitize_url(q)
23 podcast = Podcast.for_url(url, create=True)
25 if not podcast.title:
26 update_podcasts([podcast])
28 podcast = Podcast.for_url(url)
30 return [podcast], 1
33 db = get_main_database()
35 #FIXME current couchdbkit can't parse responses for multi-query searches
36 q = q.replace(',', '')
38 res = db.search('podcasts/search', wrapper=search_wrapper,
39 include_docs=True, limit=limit, skip=skip, q=q,
40 sort='\\subscribers<int>')
42 #FIXME: return empty results in case of search backend error
43 try:
44 return list(res), res.total_rows
45 except:
46 return [], 0