def channel(self, data): hits = data['data']['Airings'] for i in hits: item = Hits(self.plugin, i).item if item.get('id'): self.items.add_item(item) date = self.plugin.epg_date() prev_date = self.plugin.get_prev_day(date) self.items.add_item( { 'mode': 'epg', 'title': self.plugin.get_string(30103), 'plot': self.plugin.get_string(30103), 'id': date.strftime(self.plugin.date_format), 'params': prev_date.strftime(self.plugin.date_format) } ) self.items.add_item( { 'mode': 'sports', 'title': self.plugin.get_string(30101), 'plot': self.plugin.get_string(30102) } ) self.items.add_item( { 'mode': 'events', 'title': self.plugin.get_string(30104), 'plot': self.plugin.get_string(30104) } ) self.items.list_items(sort=True)
def channel(data): from hits import Hits hits = data['data']['Airings'] for i in hits: item = Hits(i).item if item.get('id'): items.add(item) date = epg_date() prev_date = get_prev_day(date) items.add({ 'mode': 'epg', 'title': getString(30103), 'plot': getString(30103), 'id': date.strftime(date_format), 'params': prev_date.strftime(date_format) }) items.add({ 'mode': 'sports', 'title': getString(30101), 'plot': getString(30102) }) items.add({ 'mode': 'events', 'title': getString(30104), 'plot': getString(30104) }) items.list(sort=True)
def video(self, data, id_): sport_id = 'sport_{0}'.format(id_) hits = data['data'][sport_id]['hits'] for i in hits: hit = i['hit'] item = Hits(self.plugin, hit).item if item.get('id'): self.items.add_item(item) self.items.list_items()
def video(data, id): from hits import Hits sport_id = 'sport_{0}'.format(id) hits = data['data'][sport_id]['hits'] for i in hits: hit = i['hit'] item = Hits(hit).item if item.get('id'): items.add(item) items.list()
def epg(data, prev_date, date): from resources import resources from hits import Hits def date_item(params, id): return { 'mode': 'epg', 'title': '%s (%s)' % (resources(id.strftime('%A')), id.strftime(date_format)), 'plot': '%s (%s)' % (resources(epg_date(date).strftime('%A')), epg_date(date).strftime(date_format)), 'id': id.strftime(date_format), 'params': params.strftime(date_format), 'cm': cm } update = False if date == epg_date().strftime(date_format) else True cm = Context().epg_date() items.add(date_item(get_prev_day(epg_date(prev_date)), epg_date(prev_date))) hits = data['data']['Airings']['hits'] for i in reversed(hits): hit = i['hit'] items.add(Hits(hit, epg=True).item) items.add(date_item(epg_date(date), get_next_day(epg_date(date)))) items.list(upd=update)
def Query(self, query, index='', comment=''): """Processes the query as Sphinx normally would. If specified, parse the query, retrieve the hits and compute the facets. """ # first let's parse the query if possible if self.query_parser and isinstance(query, basestring): query = self.query_parser.Parse(query) self.query = query # check the default index index = index or self.default_index # let's perform a normal query results = SphinxClient.Query(self, getattr(query, 'sphinx', query), index, comment) # let's fetch the hits from the DB if possible if self.db_fetch and results and results['total_found']: self.hits = self.db_fetch.Fetch(results) else: self.hits = Hits(results) # let's compute the facets if possible if self.facets and results and results['total_found']: self.facets.Compute(query) # keep expected return of SphinxClient return self.hits
def epg(data, prev_date, date): from resources import resources from hits import Hits def date_item(params, _id): return { 'mode': 'epg', 'title': '{0} {1}'.format(resources(_id.strftime('%A')), _id.strftime(date_format)), 'plot': '{0} {1}'.format(resources(epg_date(date).strftime('%A')), epg_date(date).strftime(date_format)), 'id': _id.strftime(date_format), 'params': params.strftime(date_format), 'cm': cm } update = False if date == epg_date().strftime(date_format) else True cm = Context().epg_date() items.add(date_item(get_prev_day(epg_date(prev_date)), epg_date(prev_date))) hits = data['data']['Airings'] hits = sorted(hits, key=lambda k: k.get('startDate')) for i in hits: items.add(Hits(i, epg=True).item) items.add(date_item(epg_date(date), get_next_day(epg_date(date)))) items.list(upd=update)
def event(data): from hits import Hits media = data['data']['EventPageByContentId']['media'] for m in media: hits = m['videos'] for i in hits: items.add(Hits(i, event=True).item) items.list()
def __init__(self, name, from_file, start, airdates, name_matcher, sources, condition, rules): self.name = name self.from_file = from_file self.start = start self.name_matcher = name_matcher self.sources = sources self.condition = condition self.rules = rules self.airdates = airdates self.hits = Hits(self)
def __init__(self): """Creates a sphinx client but with all of fSphinx additional functionalities. """ # the possible options self.query_parser = None self.default_index = '*' self.db_fetch = None self.cache = None self.sort_mode_options = [] # the returned results self.query = '' self.hits = Hits() self.facets = FacetGroup() SphinxClient.__init__(self)
def AttachDBFetch(self, db_fetch): """Attach a DBFetch object to retrieve hits from the database. """ self.db_fetch = db_fetch self.hits = Hits()
class Show: "TV Show" def __init__(self, name, from_file, start, airdates, name_matcher, sources, condition, rules): self.name = name self.from_file = from_file self.start = start self.name_matcher = name_matcher self.sources = sources self.condition = condition self.rules = rules self.airdates = airdates self.hits = Hits(self) @staticmethod def from_file(filename): try: j = json.load(open(filename, 'r')) except IOError as e: print "Error opening show:", e return None name = j['name'] start = numbering_from_str(j['start']) airdates = dict((start.from_str(e), datetime.strptime(d, "%Y/%m/%d").date()) for e, d in j.get('airdates', {}).iteritems()) name_matcher = NameMatcher(j.get('match', { 'name': name })) sources = [] for source_name, source_params in j['sources'].iteritems(): params = config.source(source_name) params.update(source_params) source = get_source(source_name, params) if source: sources.append(source) condition = j.get('condition', config.condition) rules = list(flatten(config.bind_rules(j.get('rules')))) if not rules: rules = [config.rule('default')] return Show(name, filename, start, airdates, name_matcher, sources, condition, rules) def expand(self, w): return expand(w, { 'name': self.name, 'number': str(self.hits.current) }) def update_airdates(self): "Update airdates" airdates = dict(self.airdates) airdates.update(self.hits.airdates) if self.hits.current not in airdates: log.verbose("No airdate for '%s' (%s)" % (self.name, self.hits.current)) # TODO too crowded if isinstance(self.hits.current, SeasonEpisodeNumbering): log.verbose("Updating airdates for '%s'" % self.name) self.hits.airdates = dict(get_next_episodes(self.name, self.hits.current)) elif isinstance(self.hits.current, DateNumbering): log.verbose("Updating airdates for '%s'" % self.name) self.hits.airdates = dict(get_all_episodes_after_airdate(self.name, self.hits.current)) def get_airdate(self, episode): return self.hits.airdates.get(episode, self.airdates.get(episode)) def get_episodes_after(self, episode): airdates = dict(self.airdates) airdates.update(self.hits.airdates) airdates = sorted(airdates.iteritems(), lambda e1, e2: e1[0].__cmp__(e2[0])) is_before = (lambda e: episode > e[0]) nearest = list(dropwhile(is_before, airdates)) return nearest[0] if nearest else (None, None) def search_by_episode(self, episode): "Search all torrents corresponding to this episode" torrents = set() for source in self.sources: try: log.verbose("Searching for '%s' (%s) on %s" % (self.name, episode, source.name)) for t in source.search(self): if not t.satisfy(self.condition): continue t = self.is_hit(t, episode) if t: torrents.add(t) except Exception as e: print "Error while searching for (%s, %s, %s):" % (self.name, episode, source.name), type(e), e return torrents def is_hit(self, torrent, episode): "Determine if this torrent is related to this episode" torrent.episode = episode.recognize(self, torrent.name) if torrent.episode: torrent.next_episode = torrent.episode.next() return torrent return None def search(self): "Search torrents and update all hits corresponding to the current episode" self.update_airdates() airdate = self.get_airdate(self.hits.current) if not airdate: log.verbose("%s (%s) doesn't have an air date" % (self.name, self.hits.current)) # Try to determine if there is still an episode which airs after episode, airdate = self.get_episodes_after(self.hits.current) if episode: self.hits.current = episode if airdate and airdate >= date.today(): log.verbose("%s (%s) will air on %s" % (self.name, self.hits.current, airdate)) else: torrents = self.search_by_episode(self.hits.current) log.log(0 if len(torrents) else 1, "%d torrent(s) found for '%s' (%s)" % (len(torrents), self.name, self.hits.current)) if torrents: torrents = [t.merge(self.hits.torrent(self.hits.current, t)) for t in torrents] self.hits.torrents(self.hits.current, torrents) self.hits.save() def best_candidate(self): "Return the best torrent for the current episode" torrents = self.hits.torrents(self.hits.current) # Discard failed download torrents = [t for t in torrents if t.get('failed_download', 0) < 3 and t.satisfy(self.condition)] if torrents: for rule in self.rules: filtered_torrents = rule.filter_sort(self, torrents) if filtered_torrents: log.info("'%s' (%s): %d torrents" % (self.name, self.hits.current, len(filtered_torrents))) log.info(" - Best: %(name)s %(seeds)s/%(leechs)s from %(source)s\n - %(url)s" % filtered_torrents[0].__dict__) return filtered_torrents[0] log.verbose("'%s' (%s): No torrent" % (self.name, self.hits.current)) return None def download(self): "Download the best torrent for the current episode" torrent = self.best_candidate() if not torrent: return log.info(" - Downloading %s" % torrent.url) try: req = fetch(torrent.url) with open(config.torrents_dir + '/' + torrent.name + '.torrent', 'wb') as f: f.write(req.read()) except Exception as e: torrent.failed_download = torrent.get('failed_download', 0) + 1 print " - Failed for the %d time(s) [%s, %s]" % (torrent.failed_download, type(e), e) self.hits.save() return guessed_next = numbering_from_str(torrent.next_episode) next, _ = self.get_episodes_after(guessed_next) self.hits.current = next if next else guessed_next log.info(" - Current episode is now %s" % self.hits.current) torrent.downloaded = True self.hits.save() def info(self): self.best_candidate() def reset(self, episode): episode = numbering_from_str(episode) if episode else self.start log.info("Resetting '%s' to '%s'" % (self.name, episode)) self.hits = Hits.empty(self, episode) self.hits.save()
def reset(self, episode): episode = numbering_from_str(episode) if episode else self.start log.info("Resetting '%s' to '%s'" % (self.name, episode)) self.hits = Hits.empty(self, episode) self.hits.save()