episoder-0.7.0/0000755000175000017500000000000012226654723014123 5ustar stefanstefan00000000000000episoder-0.7.0/extras/0000755000175000017500000000000012226654723015431 5ustar stefanstefan00000000000000episoder-0.7.0/extras/episoder_helper_epguides.awk0000644000175000017500000001066312165703760023177 0ustar stefanstefan00000000000000# episoder epguides.com parser helper # # Copyright (C) 2006-2013 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . /.*/ { # Some files don't have proper linebreaks - they'll have and # on the same line titleStart = index($0, "") + 8; titlePart = substr($0, titleStart); titleEnd = index($0, "(a Titles "); set_show(substr($0, titleStart, titleEnd - titleStart - 1)); } /^<h1>/ { sub(/<h1><a href=\".*\">/, "", $0) sub(/<\/a><\/h1>/, "", $0) # remove ^M gsub(/\015/, "", $0) set_show($0) } /aired from:/ { pos = match($0, /___/) if (pos == 0) { running="No" } } function set_show(showName) { gsub("'", "''", showName) print "- title: '" showName "'" >> output print " episodes:" >> output printf "%s... ", showName } /^• Season/ { # remove ^M gsub(/\015/, "", $3) # Some files come with bullets before the season number season = $3 if (season == "") { season = 0 } } /^<a name='latest' id='latest' \/>• Season/ { # remove ^M gsub(/\015/, "", $6) # Some files come with bullets before the season number and an anchor # before the bullet season = $6 if (season == "") { season = 0 } } /^Season/ { # Most, however, don't # remove ^M gsub(/\015/, "", $2) season = $2 if (season == "") { season = 0 } } /^<a href="guide.shtml#[0-9].*Series/ { pos = match($0, /guide.shtml#([0-9]+.*">)/) season = substr($0, pos + RLENGTH) pos = match(season, /[^0-9]/) season = substr(season, 0, pos - 1) } /^[0-9]+/ { # A data file format used for shows like Eureka totalep = $1 epnum = substr($0, index($0, "-")+1, 2) if (epnum < 10) { epnum = 0 substr(epnum, 2, 1) } prodnum = substr($0, 16, 9) gsub(/^ */, "", prodnum) gsub(/ *$/, "", prodnum) pos = match($0, /([1-3]?[0-9]\/[A-Z][a-z][a-z]\/[0-9][0-9]) /) epdate = substr($0, pos, RLENGTH) gsub(/ *$/, "", epdate) gsub(/\//, " ", epdate) eptitle = substr($0, 40) pos = index(eptitle, ">") # remove recap and trailer links from html sub(/<span class='recap'.*<\/span>/, "", eptitle) sub(/<span class='Trailers'.*<\/span>/, "", eptitle) # remove href and trailing </a> sub(/<a.*href=['"].*['"]>/, "", eptitle) sub(/<\/a>/, "", eptitle) # remove trailing white spaces gsub(/[ \t\f\n\r\v]*$/, "", eptitle) show_episode(show, totalep, season, epnum, prodnum, epdate, eptitle) } /^ *[0-9]+\./ { totalep = substr ($1, 0, index($1, ".")) gsub (/\.$/, "", totalep) epnum = substr($0, index($0, "-")+1, 2) if (epnum < 10) { epnum = 0 substr(epnum, 2, 1) } prodnum = substr($0, 16, 9) gsub(/^ */, "", prodnum) gsub(/ *$/, "", prodnum) pos = match($0, /([1-3]?[0-9] [A-Z][a-z][a-z] [0-9][0-9]) /) epdate = substr($0, pos, RLENGTH) gsub(/ *$/, "", epdate) eptitle = substr($0, 40) pos = index(eptitle, ">") # remove recap and trailer links from html sub(/<span class='recap'.*<\/span>/, "", eptitle) sub(/<span class='Trailers'.*<\/span>/, "", eptitle) # remove href and trailing </a> sub(/<a.*href=['"].*['"]>/, "", eptitle) sub(/<\/a>/, "", eptitle) # remove trailing white spaces gsub(/[ \t\f\n\r\v]*$/, "", eptitle) show_episode(show, totalep, season, epnum, prodnum, epdate, eptitle) } BEGIN { IGNORECASE = 1 season = 0 running = "Yes" } END { print " running: " running >> output if (dropped == 0) { dropped="0" } if (kept == 0) { kept="0" } printf "Kept %s, dropped %s.\n", kept, dropped } function show_episode(show, totalep, season, epnum, prodnum, epdate, eptitle) { if (epdate == "") { dropped++ return } command = "date +%Y-%m-%d -d '" epdate "'" command | getline airdate close(command) gsub("'", "''", eptitle) print " - title: '" eptitle "'" >> output print " season: " season >> output print " episode: " epnum >> output print " airdate: " airdate >> output print " prodnum: '" prodnum "'" >> output print " totalepnum: " totalep >> output kept++ } �����������������������������������������������������������������������������episoder-0.7.0/pyepisoder/��������������������������������������������������������������������������0000755�0001750�0001750�00000000000�12226654723�016306� 5����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/pyepisoder/__init__.py���������������������������������������������������������������0000644�0001750�0001750�00000000000�12165430034�020372� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/pyepisoder/episode.py����������������������������������������������������������������0000644�0001750�0001750�00000004147�12220423772�020306� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# episoder, http://code.ott.net/projects/episoder # # Copyright (C) 2004-2013 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class Episode(object): def __init__(self, show, name, season, episode, date, prodnum, total): self._show = show self.title = name self.season = int(season) self.episode = int(episode) self.airdate = date self.prodnum = str(prodnum) self.total = int(total) self.show_id = self._show.show_id def setAirDate(self, airdate): # meh, hack to make sure that we actually get a date object airdate.isoformat() self.__airdate = airdate def getAirDate(self): return self.__airdate def _setSeason(self, season): self._season = int(season) def _getSeason(self): return self._season def _setEpisode(self, episode): self._episode = int(episode) def _getEpisode(self): return self._episode def _setTotal(self, total): self._total = int(total) def _getTotal(self): return self._total def __str__(self): return "%s %dx%02d: %s" % (self._show.name, self.season, self.episode, self.title) def __eq__(self, other): return (self.show_id == other.show_id and self.season == other.season and self.episode == other.episode) def _getShow(self): return self._show def _setShow(self, show): self._show = show show.show_id = show.show_id airdate = property(getAirDate, setAirDate) season = property(_getSeason, _setSeason) episode = property(_getEpisode, _setEpisode) total = property(_getTotal, _setTotal) show = property(_getShow, _setShow) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/pyepisoder/episoder.py���������������������������������������������������������������0000644�0001750�0001750�00000017262�12221435015�020464� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# episoder, http://code.ott.net/projects/episoder # # Copyright (C) 2004-2013 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from datetime import date, timedelta from sqlalchemy import Boolean, Column, Date, DateTime, ForeignKey, Integer from sqlalchemy import MetaData, Sequence, Table, Text from sqlalchemy import create_engine, or_, and_ from sqlalchemy.orm import clear_mappers, create_session, mapper, relation import logging from episode import Episode from plugins import parser_for version='0.7.0' class DataStore(object): def __init__(self, path): self.logger = logging.getLogger('DataStore') if path.find('://') > -1: engine = create_engine(path, convert_unicode=True) else: engine = create_engine('sqlite:///%s' % path) self.conn = engine.connect() self.metadata = MetaData() self.metadata.bind = engine self.session = create_session(bind=engine) self.session.begin() self._initdb() def __str__(self): return 'DataStore(%s)' % self.conn def clear(self): episodes = self.session.query(Episode).all() for episode in episodes: self.session.delete(episode) self.session.flush() def update(self): result = self.meta.select().execute() meta = {} for key in result: meta[key[0]] = key[1] if not 'schema' in meta: meta['schema'] = '1' self.logger.debug('Found v%s schema' % meta['schema']) if meta['schema'] == '-1': self.logger.debug('Automatic schema updates disabled') return if meta['schema'] < '3': self.logger.info('Updating database schema') self.episodes.drop() self.shows.drop() self._initdb() self.session.commit() self.session.begin() insert = self.meta.insert().values(key='schema', value=3) self.conn.execute(insert) def _initdb(self): clear_mappers() self.shows = Table('shows', self.metadata, Column('show_id', Integer, Sequence('shows_show_id_seq'), primary_key=True), Column('show_name', Text), Column('url', Text, unique=True), Column('updated', DateTime), Column('enabled', Boolean), Column('status', Integer, default=Show.RUNNING), extend_existing=True) showmapper = mapper(Show, self.shows, properties={ 'name': self.shows.c.show_name, 'episodes': relation(Episode, backref='show', cascade='all') }) self.meta = Table('meta', self.metadata, Column('key', Text, primary_key=True), Column('value', Text), extend_existing=True) self.episodes = Table('episodes', self.metadata, Column('show_id', ForeignKey('shows.show_id'), primary_key=True), Column('num', Integer, primary_key=True), Column('airdate', Date), Column('season', Integer, primary_key=True), Column('title', Text), Column('totalnum', Integer), Column('prodnum', Text), extend_existing=True) episodemapper = mapper(Episode, self.episodes, properties={ 'title': self.episodes.c.title, 'season': self.episodes.c.season, 'episode': self.episodes.c.num, 'airdate': self.episodes.c.airdate, 'prodnum': self.episodes.c.prodnum, 'total': self.episodes.c.totalnum }) self.metadata.create_all() def getExpiredShows(self): today = date.today() deltaRunning = timedelta(2) # 2 days deltaSuspended = timedelta(7) # 1 week deltaNotRunning = timedelta(14) # 2 weeks shows = self.session.query(Show).filter(or_( and_( Show.enabled == True, Show.status == Show.RUNNING, Show.updated < today - deltaRunning ), and_( Show.enabled == True, Show.status == Show.SUSPENDED, Show.updated < today - deltaSuspended ), and_( Show.enabled == True, Show.status == Show.ENDED, Show.updated < today - deltaNotRunning ) )) return shows.all() def getEnabledShows(self): shows = self.session.query(Show).filter(Show.enabled == True) return shows.all() def getShowByUrl(self, url): shows = self.session.query(Show).filter(Show.url == url) if shows.count() < 1: return None return shows.first() def getShowById(self, id): shows = self.session.query(Show).filter(Show.show_id == id) if shows.count() < 1: return None return shows.first() def addShow(self, show): show = self.session.merge(show) self.session.flush() return show def removeShow(self, id): shows = self.session.query(Show).filter(Show.show_id == id) if shows.count() < 1: self.logger.error('No such show') return self.session.delete(shows.first()) self.session.flush() def getShows(self): select = self.shows.select() result = select.execute() shows = [] for show in result: shows.append(show) return shows def addEpisode(self, episode): self.session.merge(episode) self.session.flush() def getEpisodes(self, basedate=date.today(), n_days=0): shows = [] episodes = [] enddate = basedate + timedelta(n_days) data = self.session.query(Episode).add_entity(Show). \ select_from(self.episodes.join(self.shows)). \ filter(Episode.airdate >= basedate). \ filter(Episode.airdate <= enddate). \ order_by(Episode.airdate) for row in data: (episode, show) = row episode.show = show if show in shows: show = shows[shows.index(show)] else: shows.append(show) episodes.append(episode) return episodes def search(self, search): shows = [] episodes = [] data = self.session.query(Episode).add_entity(Show). \ select_from(self.episodes.join(self.shows)). \ filter(or_( \ Episode.title.like('%%%s%%' % search), Show.name.like('%%%s%%' % search))). \ order_by(Episode.airdate) for row in data: (episode, show) = row episode.show = show if show in shows: show = shows[shows.index(show)] else: shows.append(show) episodes.append(episode) return episodes def commit(self): self.session.commit() self.session.begin() def rollback(self): self.session.rollback() self.session.begin() def removeBefore(self, date, show=None): episodes = self.session.query(Episode).filter( Episode.airdate < date) if show: episodes = episodes.filter( Episode.show_id == show.show_id) for episode in episodes: self.session.delete(episode) self.commit() class Show(object): RUNNING = 1 SUSPENDED = 2 ENDED = 3 def __init__(self, name, id=-1, url='', updated=date(1970, 1, 1)): self.name = name self.url = url self.updated = updated self.status = Show.RUNNING self.episodes = [] self.enabled = True def addEpisode(self, episode): self.episodes.append(episode) def setRunning(self): self.status = Show.RUNNING def setSuspended(self): self.status = Show.SUSPENDED def setEnded(self): self.status = Show.ENDED def update(self, store, args): parser = parser_for(self.url) if not parser: raise RuntimeError('No parser found for %s' % self.url) if 'agent' in args: parser.user_agent = args.agent parser.parse(self, store, args) def removeEpisodesBefore(self, store, date): logging.debug('Removing episodes from before %s' % date) store.removeBefore(date, show=self) def __str__(self): return 'Show("%s")' % self.name def __eq__(self, other): return (self.name == other.name and self.url == other.url) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/pyepisoder/plugins.py����������������������������������������������������������������0000644�0001750�0001750�00000017704�12221435654�020345� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# episoder, http://code.ott.net/projects/episoder # # Copyright (C) 2004-2013 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import re import os import yaml import pyepisoder import time import logging import urllib2 import tempfile from datetime import date, datetime, timedelta from tvdb_api import BaseUI, Tvdb, tvdb_shownotfound from BeautifulSoup import BeautifulSoup from episode import Episode def parser_for(url): parsers = [ TVDB, EpguidesParser, TVComDummyParser ] for parser in parsers: if parser.accept(url): return parser() return None class TVDB(object): def __init__(self): self.logger = logging.getLogger('TVDB') self.latest = 0 def __str__(self): return 'TheTVDB.com parser' @staticmethod def accept(url): return url.isdigit() def parse(self, show, store, args): self.show = show self.store = store if show.url.isdigit(): id = int(show.url) else: self.logger.error('%s is not a valid TVDB show id' % show.url) return tv = Tvdb(apikey=args.tvdb_key) try: data = tv[id] except tvdb_shownotfound: self.logger.error('Show %s not found' % id) return self.show.name = data.data.get('seriesname') self.show.updated = datetime.now() for (idx, season) in data.items(): for (epidx, episode) in season.items(): self.__addEpisode(episode) now = int(time.time()) age = now - self.latest # 31536000 seconds -> 1 year # 2419200 seconds -> 4 weeks if age > 31536000: self.show.setEnded() elif age > 2419200: self.show.setSuspended() else: self.show.setRunning() self.store.commit() def __addEpisode(self, episode): name = episode.get('episodename') season = episode.get('seasonnumber', 0) num = episode.get('episodenumber', 0) airdate = episode.get('firstaired') if not airdate: self.logger.debug('Throwing away episode %s' % num) return airdate = time.strptime(airdate, '%Y-%m-%d') airdate = datetime(airdate.tm_year, airdate.tm_mon, airdate.tm_mday).date() self.latest = max(self.latest, int(airdate.strftime('%s'))) prodcode = episode.get('productioncode') abs_number = episode.get('absolute_number', 0) # can be None which is bad if not abs_number: abs_number = 0 self.logger.debug('Found episode %s' % name) e = Episode(self.show, name, season, num, airdate, prodcode, abs_number) self.store.addEpisode(e) @staticmethod def lookup(text): result = [] class search(BaseUI): def selectSeries(self, allSeries): result.extend(allSeries) return BaseUI.selectSeries(self, allSeries) db = Tvdb(custom_ui=search) db[text] return result class EpguidesParser(object): def __init__(self): self.logger = logging.getLogger('EpguidesParser') dirname = os.path.dirname(pyepisoder.__file__) prefix = os.path.join(dirname, '..') self.awkfile = os.path.join(prefix, 'extras', 'episoder_helper_epguides.awk') self.awk = '/usr/bin/awk' self.user_agent = None self.url = '' def __str__(self): return 'epguides.com parser' @staticmethod def accept(url): exp = 'http://(www.)?epguides.com/.*' return re.match(exp, url) def parse(self, show, store, _): self.show = show BeautifulSoup.CDATA_CONTENT_ELEMENTS = () try: webdata = self._fetchPage(self.show.url) except Exception, e: self.logger.error("Error fetching %s: %s" % (self.show.url, e)) return self.parseFile(webdata, store) os.unlink(webdata) def parseFile(self, file, store): self.store = store yamlfile = self._runAwk(file) data = self._readYaml(yamlfile) self.store.commit() os.unlink(yamlfile) def _fetchPage(self, url): self.logger.info('Fetching ' + url) headers = {} if (self.user_agent): headers['User-Agent'] = self.user_agent request = urllib2.Request(url, None, headers) result = urllib2.urlopen(request) (fd, name) = tempfile.mkstemp() file = os.fdopen(fd, 'w') file.write(result.read()) file.close() self.logger.debug("Stored in %s" % name) return name def _runAwk(self, webdata): yamlfile = tempfile.mktemp() logfile = tempfile.mktemp() cleanwebdata = tempfile.mktemp() self.logger.info('Parsing data') self.logger.debug('Calling iconv') cmd = 'iconv -c -f utf8 -t iso-8859-1 %s >%s' % (webdata, cleanwebdata) if os.system(cmd) != 0: self.logger.debug('iconv failed, ignoring') self.logger.debug('Calling AWK') cmd = 'LC_CTYPE=UTF-8 %s -f %s output=%s %s >%s 2>&1' % ( self.awk, self.awkfile, yamlfile, cleanwebdata, logfile) if os.system(cmd) != 0: raise Exception("Error running %s" % cmd) file = open(logfile) self.logger.debug(file.read().strip()) file.close() os.unlink(cleanwebdata) os.unlink(logfile) return yamlfile def _readYaml(self, yamlfile): self.logger.debug('Reading YAML') file = open(yamlfile) data = yaml.load(file.read().decode('iso8859-1')) file.close() show_data = data[0] if not 'title' in show_data or not show_data['title']: self.logger.warning('Show has no title, aborting') self.store.rollback() return title = show_data['title'] self.show.name = title if show_data['running']: self.show.setRunning() else: self.show.setEnded() self.show.updated = datetime.now() self.logger.debug('Got show "%s"', title) if not 'episodes' in show_data or not show_data['episodes']: self.logger.warning('Show has no episodes, aborting') self.store.rollback() return episodes = show_data['episodes'] for episode in episodes: self.logger.debug('Found episode %s' % episode['title']) self.store.addEpisode(Episode(self.show, episode['title'], episode['season'], episode['episode'], episode['airdate'], episode['prodnum'], episode['totalepnum'] )) class TVComDummyParser(object): def __str__(self): return 'dummy tv.com parser to detect old urls (DO NOT USE)' @staticmethod def accept(url): exp = 'http://(www.)?tv.com/.*' return re.match(exp, url) def parse(self, source, _, __): logging.error("The url %s is no longer supported" % source.url) class ConsoleRenderer(object): def __init__(self, format, dateformat): self.logger = logging.getLogger('ConsoleRenderer') self.format = format self.dateformat = dateformat def _render(self, episode, color, endColor): string = self.format airdate = episode.airdate.strftime(self.dateformat) string = string.replace('%airdate', airdate) string = string.replace('%show', episode.show.name) string = string.replace('%season', str(episode.season)) string = string.replace('%epnum', "%02d" % episode.episode) string = string.replace('%eptitle', unicode(episode.title)) string = string.replace('%totalep', str(episode.total)) string = string.replace('%prodnum', str(episode.prodnum)) print ("%s%s%s" % (color, string.encode('utf8'), endColor)) def render(self, episodes, color=True): today = date.today() yesterday = today - timedelta(1) tomorrow = today + timedelta(1) if color: red = '\033[31;1m' cyan = '\033[36;1m' grey = '\033[30;0m' green = '\033[32;1m' yellow = '\033[33;1m' else: red = '' cyan = '' grey = '' green = '' yellow = '' for episode in episodes: if episode.airdate == yesterday: color = red elif episode.airdate == today: color = yellow elif episode.airdate == tomorrow: color = green elif episode.airdate > tomorrow: color = cyan else: color = grey self._render(episode, color, grey) ������������������������������������������������������������episoder-0.7.0/test/��������������������������������������������������������������������������������0000755�0001750�0001750�00000000000�12226654723�015102� 5����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/test/test.py�������������������������������������������������������������������������0000755�0001750�0001750�00000035631�12170143437�016437� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # -*- coding: utf8 -*- import os import shutil import logging import unittest import tempfile import datetime import pyepisoder.episoder as episoder import pyepisoder.plugins as plugins class DataStoreTest(unittest.TestCase): def setUp(self): self.path = tempfile.mktemp() self.store = episoder.DataStore(self.path) def tearDown(self): os.unlink(self.path) def testGetShowByUrl(self): show1 = episoder.Show('test show', url='a') show2 = episoder.Show('test show 2', url='b') self.store.addShow(show1) self.store.addShow(show2) self.assertEqual(show1, self.store.getShowByUrl('a')) self.assertEqual(show2, self.store.getShowByUrl('b')) self.assertEqual(None, self.store.getShowByUrl('c')) def testAddShow(self): show = episoder.Show('test show', url='http://test.show') show = self.store.addShow(show) self.store.commit() id = show.show_id self.assertTrue(id > 0, "id is %d, must be > 0" % id) shows = self.store.getShows() self.assertEqual(1, len(shows)) self.assertEqual(id, shows[0].show_id) self.assertEqual('test show', shows[0].show_name) show2 = episoder.Show('moo show', url='http://test.show.2') show2 = self.store.addShow(show2) id2 = show2.show_id self.store.commit() shows = self.store.getShows() self.assertNotEqual(id, id2) self.assertEqual(2, len(shows)) ids = [] for show in shows: ids.append(show.show_id) self.assertTrue(id2 in ids) showA = episoder.Show('showA', url='urlA') showB = episoder.Show('showA', url='urlB') showC = episoder.Show('showB', url='urlB') self.store.addShow(showA) self.store.commit() self.assertEqual(3, len(self.store.getShows())) self.store.addShow(showB) self.store.commit() self.assertEqual(4, len(self.store.getShows())) try: self.store.addShow(showC) self.store.commit() self.assertTrue(false) except Exception: pass def testAddEpisode(self): show = episoder.Show('some show', url='foo') show = self.store.addShow(show) self.store.commit() episode1 = episoder.Episode(show, 'Some episode', 3, 10, datetime.date.today(), 'FOO', 30) episode2 = episoder.Episode(show, 'No episode', 3, 12, datetime.date.today(), 'FOO', 32) self.store.addEpisode(episode1) self.store.addEpisode(episode2) self.store.commit() episodes = self.store.getEpisodes() self.assertTrue(episode1 in episodes) self.assertTrue(episode2 in episodes) def testSearch(self): show = episoder.Show('some show') show = self.store.addShow(show) episode1 = episoder.Episode(show, 'first episode', 3, 10, datetime.date.today(), 'FOO', 30) episode2 = episoder.Episode(show, 'Second episode', 3, 12, datetime.date.today(), 'FOO', 32) self.store.addEpisode(episode1) self.store.addEpisode(episode2) self.store.commit() episodes = self.store.search('first') self.assertTrue(episode1 in episodes) self.assertFalse(episode2 in episodes) episodes = self.store.search('second') self.assertFalse(episode1 in episodes) self.assertTrue(episode2 in episodes) episodes = self.store.search('episode') self.assertTrue(episode1 in episodes) self.assertTrue(episode2 in episodes) episodes = self.store.search('some show') self.assertTrue(episode1 in episodes) self.assertTrue(episode2 in episodes) def testRemoveShow(self): show1 = episoder.Show('random show', url='z') show2 = episoder.Show('other show', url='x') show1 = self.store.addShow(show1) show2 = self.store.addShow(show2) self.store.commit() now = datetime.date.today() episode1 = episoder.Episode(show1, 'first', 1, 1, now, 'x', 1) episode2 = episoder.Episode(show1, 'second', 1, 2, now, 'x', 1) episode3 = episoder.Episode(show2, 'first', 1, 1, now, 'x', 1) self.store.addEpisode(episode1) self.store.addEpisode(episode2) self.store.addEpisode(episode3) self.store.commit() episodes = self.store.getEpisodes() self.assertEquals(3, len(episodes)) self.store.removeShow(show1.show_id) self.store.commit() episodes = self.store.getEpisodes() self.assertEquals(1, len(episodes)) self.assertEquals(episode3, episodes[0]) def testRollback(self): show = episoder.Show('some show') show = self.store.addShow(show) self.store.commit() episode1 = episoder.Episode(show, 'first episode', 3, 10, datetime.date.today(), 'FOO', 30) episode2 = episoder.Episode(show, 'Second episode', 3, 12, datetime.date.today(), 'FOO', 32) self.store.addEpisode(episode1) self.store.rollback() self.store.addEpisode(episode2) self.store.commit() episodes = self.store.getEpisodes() self.assertFalse(episode1 in episodes) self.assertTrue(episode2 in episodes) def testGetEpisodes(self): show = episoder.Show('some show') show = self.store.addShow(show) today = datetime.date.today() yesterday = today - datetime.timedelta(1) before = yesterday - datetime.timedelta(1) tomorrow = today + datetime.timedelta(1) episode1 = episoder.Episode(show, 'episode1', 1, 1, before, 'x', 1) episode2 = episoder.Episode(show, 'episode2', 1, 2, yesterday, 'x', 2) episode3 = episoder.Episode(show, 'episode3', 1, 3, today, 'x', 3) episode4 = episoder.Episode(show, 'episode4', 1, 4, tomorrow, 'x', 4) self.store.addEpisode(episode1) self.store.addEpisode(episode2) self.store.addEpisode(episode3) self.store.addEpisode(episode4) episodes = self.store.getEpisodes(basedate = before, n_days=1) self.assertTrue(episode1 in episodes) self.assertTrue(episode2 in episodes) self.assertFalse(episode3 in episodes) self.assertFalse(episode4 in episodes) episodes = self.store.getEpisodes(basedate = before, n_days=0) self.assertTrue(episode1 in episodes) self.assertFalse(episode2 in episodes) self.assertFalse(episode3 in episodes) self.assertFalse(episode4 in episodes) episodes = self.store.getEpisodes(basedate = today, n_days=0) self.assertFalse(episode1 in episodes) self.assertFalse(episode2 in episodes) self.assertTrue(episode3 in episodes) self.assertFalse(episode4 in episodes) episodes = self.store.getEpisodes(basedate = yesterday,n_days=2) self.assertFalse(episode1 in episodes) self.assertTrue(episode2 in episodes) self.assertTrue(episode3 in episodes) self.assertTrue(episode4 in episodes) def testRemoveBefore(self): show = episoder.Show('some show') show = self.store.addShow(show) today = datetime.date.today() yesterday = today - datetime.timedelta(1) before = yesterday - datetime.timedelta(1) tomorrow = today + datetime.timedelta(1) episode1 = episoder.Episode(show, 'episode1', 1, 1, before, 'x', 1) episode2 = episoder.Episode(show, 'episode2', 1, 2, yesterday, 'x', 2) episode3 = episoder.Episode(show, 'episode3', 1, 3, today, 'x', 3) episode4 = episoder.Episode(show, 'episode4', 1, 4, tomorrow, 'x', 4) self.store.addEpisode(episode1) self.store.addEpisode(episode2) self.store.addEpisode(episode3) self.store.addEpisode(episode4) episodes = self.store.getEpisodes(basedate = before, n_days=10) self.assertTrue(episode1 in episodes) self.assertTrue(episode2 in episodes) self.assertTrue(episode3 in episodes) self.assertTrue(episode4 in episodes) self.store.removeBefore(today) episodes = self.store.getEpisodes(basedate = before, n_days=10) self.assertFalse(episode1 in episodes) self.assertFalse(episode2 in episodes) self.assertTrue(episode3 in episodes) self.assertTrue(episode4 in episodes) def testRemoveBeforeWithShow(self): show1 = episoder.Show('some show', url='a') show1 = self.store.addShow(show1) show2 = episoder.Show('some other show', url='b') show2 = self.store.addShow(show2) today = datetime.date.today() yesterday = today - datetime.timedelta(1) episode1 = episoder.Episode(show1, 'episode1', 1, 1, yesterday, 'x', 1) episode2 = episoder.Episode(show1, 'episode1', 1, 2, yesterday, 'x', 1) episode3 = episoder.Episode(show2, 'episode1', 1, 2, yesterday, 'x', 1) self.store.addEpisode(episode1) self.store.addEpisode(episode2) self.store.addEpisode(episode3) self.store.removeBefore(today, show=show1) episodes = self.store.getEpisodes(basedate = yesterday, n_days=10) self.assertEquals(1, len(episodes)) def testDuplicateEpisodes(self): today = datetime.date.today() show = episoder.Show('some show') show = self.store.addShow(show) self.assertEqual(0, len(self.store.getEpisodes())) episode1 = episoder.Episode(show, 'e', 1, 1, today, 'x', 1) episode2 = episoder.Episode(show, 'f', 1, 1, today, 'x', 1) self.store.addEpisode(episode1) self.store.addEpisode(episode1) episodes = self.store.getEpisodes() self.assertEqual(1, len(episodes)) self.assertEquals('e', episodes[0].title) self.store.addEpisode(episode2) episodes = self.store.getEpisodes() self.assertEqual(1, len(episodes)) self.assertEquals('f', episodes[0].title) def testClear(self): today = datetime.date.today() show = episoder.Show('some show', url='urlX') show = self.store.addShow(show) self.assertEqual(0, len(self.store.getEpisodes())) episode1 = episoder.Episode(show, 'e', 1, 1, today, 'x', 1) episode2 = episoder.Episode(show, 'e', 1, 2, today, 'x', 1) episode3 = episoder.Episode(show, 'e', 1, 3, today, 'x', 1) episode4 = episoder.Episode(show, 'e', 1, 3, today, 'x', 1) episode5 = episoder.Episode(show, 'e', 1, 4, today, 'x', 1) self.store.addEpisode(episode1) self.store.addEpisode(episode2) self.store.addEpisode(episode3) self.store.commit() self.assertEqual(3, len(self.store.getEpisodes())) self.store.clear() self.assertEqual(0, len(self.store.getEpisodes())) self.store.addEpisode(episode4) self.store.addEpisode(episode5) self.assertEqual(2, len(self.store.getEpisodes())) class ShowTest(unittest.TestCase): def setUp(self): self.path = tempfile.mktemp() self.store = episoder.DataStore(self.path) self.show = episoder.Show('A', url='a') self.show = self.store.addShow(self.show) def tearDown(self): os.unlink(self.path) def testRemoveEpisodesBefore(self): now = datetime.date.today() then = now - datetime.timedelta(3) show2 = episoder.Show('B', url='b') show2 = self.store.addShow(show2) episode1 = episoder.Episode(self.show, 'e', 1, 1, now, 'x', 1) episode2 = episoder.Episode(self.show, 'e', 1, 2, then, 'x', 1) episode3 = episoder.Episode(show2, 'e', 1, 3, now, 'x', 1) episode4 = episoder.Episode(show2, 'e', 1, 4, then, 'x', 1) self.store.addEpisode(episode1) self.store.addEpisode(episode2) self.store.addEpisode(episode3) self.store.addEpisode(episode4) self.store.commit() episodes = self.store.getEpisodes(basedate = then, n_days=10) self.assertEqual(4, len(episodes)) show2.removeEpisodesBefore(self.store, now) episodes = self.store.getEpisodes(basedate = then, n_days=10) self.assertEqual(3, len(episodes)) self.show.removeEpisodesBefore(self.store, now) episodes = self.store.getEpisodes(basedate = then, n_days=10) self.assertEqual(2, len(episodes)) class testEpguidesParser(unittest.TestCase): def setUp(self): self.path = tempfile.mktemp() self.store = episoder.DataStore(self.path) self.parser = plugins.EpguidesParser() self.parser.awkfile = 'extras/episoder_helper_epguides.awk' def tearDown(self): os.unlink(self.path) def _accept(self, url): return self.parser.accept(url) def _parse(self, file): show = self.store.getShowByUrl(file) if not show: show = episoder.Show(name='', url=file) show = self.store.addShow(show) self.parser.show = show self.parser.parseFile(file, self.store) def testAccept(self): self.assertTrue(self._accept('http://www.epguides.com/Lost')) self.assertFalse(self._accept('http://epguides2.com/Lost')) self.assertFalse(self._accept('http://www.tv.com/Lost')) def testParseFile(self): then = datetime.date(1970, 1, 1) self.assertEquals(0, len(self.store.getEpisodes())) self._parse('test/testdata/epguides_lost.html') self.store.commit() self.assertEquals(102, len(self.store.getEpisodes(then, 99999))) show = self.store.getShowByUrl( 'test/testdata/epguides_lost.html') self.assertEquals('Lost', show.name) self.assertEquals(episoder.Show.RUNNING, show.status) self._parse('test/testdata/epguides_lost.html') self.store.commit() self.assertEquals(102, len(self.store.getEpisodes(then, 99999))) self.store.clear() self.assertEquals(0, len(self.store.getEpisodes())) self._parse('test/testdata/epguides_bsg.html') self.assertEquals(74, len(self.store.getEpisodes(then, 99999))) def testEpguidesFormat2(self): # Another format then = datetime.date(1970, 1, 1) self.assertEquals(0, len(self.store.getEpisodes())) self._parse('test/testdata/epguides_eureka.html') episodes = self.store.getEpisodes(then, 99999) self.assertEquals(43, len(episodes)) self.assertEquals('Best in Faux', episodes[27].title) def testEpguidesFormat3(self): # Yet another format then = datetime.date(1970, 1, 1) self._parse('test/testdata/epguides_midsomer_murders.html') episodes = self.store.getEpisodes(then, 99999) episode = episodes[1] self.assertEquals(1, episode.season) self.assertEquals(1, episode.episode) def testEpguidesRemoveIllegalChars(self): # This one contains an illegal character somewhere then = datetime.date(1970, 1, 1) self._parse('test/testdata/epguides_american_idol.html') episodes = self.store.getEpisodes(then, 99999) self.assertEquals('Pride Goeth Before The Fro', episodes[10].title) def testEpguidesMissingSeasonNumber(self): # This one lacks a season number somewhere then = datetime.date(1970, 1, 1) self._parse('test/testdata/epguides_48_hours_mistery.html') episodes = self.store.getEpisodes(then, 99999) self.assertEquals(31, len(episodes)) def testEpguidesEndedShow(self): # This one is no longer on the air then = datetime.date(1970, 1, 1) self._parse('test/testdata/epguides_kr2008.html') show = self.store.getShowByUrl( 'test/testdata/epguides_kr2008.html') self.assertEquals(episoder.Show.ENDED, show.status) def testEpguidesEncoding(self): # This one has funny characters then = datetime.date(1970, 1, 1) self._parse('test/testdata/epguides_buzzcocks.html') episodes = self.store.getEpisodes(then, 99999) episode = episodes[20] self.assertEquals( 'ZoĆ« Ball, Louis Eliot, Graham Norton, Keith Duffy', episodes[20].title.encode('utf8')) def testEpguidesWithAnchor(self): # This one has an anchor tag before the bullet for season 6 then = datetime.date(1970, 1, 1) self._parse('test/testdata/epguides_futurama.html') episodes = self.store.getEpisodes(then, 99999) episode = episodes.pop() self.assertEquals(6, episode.season) def testEpguidesWithTrailerAndRecap(self): # This one has [Trailer] and [Recap] in episode titles then = datetime.date(1970, 1, 1) self._parse('test/testdata/epguides_house.html') episodes = self.store.getEpisodes(then, 99999) episode = episodes[len(episodes) - 3] self.assertEquals('Unwritten', episode.title) episode = episodes[len(episodes) - 2] self.assertEquals('Massage Therapy', episode.title) if __name__ == '__main__': unittest.main() �������������������������������������������������������������������������������������������������������episoder-0.7.0/AUTHORS������������������������������������������������������������������������������0000644�0001750�0001750�00000000037�12165430034�015160� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Stefan Ott <stefan at ott net> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/CHANGELOG����������������������������������������������������������������������������0000644�0001750�0001750�00000014543�12226645537�015347� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������== v0.7.0 (14 Oct 2013) == * Added support for TheTVDB.com * Removed support for tv.com * Changed command-line arguments. See the man page for details * Removed the ability to specify shows in the configuration file * Reorganized the command line options. Check the documentation for details * Updated the epguides.com parser to ignore trailer links in episode names * Fixed some more encoding issues in the console renderer * Changed license to GPLv3 == v0.6.5 (6 Oct 2010) == * Updated the epguides.com parser to ignore links to trailers in episode names == v0.6.4 (25 Jun 2010) == * Filter javascript from tv.com pages because it confuses beautifulsoup 3.1 == v0.6.3 (23 Jun 2010) == * The epguides parser now properly reads the season number for more shows == v0.6.2 (08 Nov 2009) == * Updated tv.com parser (show names need to be lower-case now!) * Added -S option to specify a show id for (forced) updates == v0.6.1 (26 Aug 2009) == * Episoder can now talk to any database supported by sqlalchemy (see README) * Tell awk to process utf8 (for epguides parser) * Catch (and properly log) some more HTTP exceptions == v0.6.0 (8 Aug 2009) == * Episoder now keeps a persistent database of shows and episodes * Added new options (-L, -a, -r, -E, -D) to manage the database * The parsers now know whether a show is still running or not * Active (currently running) shows are updated every two days * Inactive (ended) shows are updated every two weeks * The new -B command overrides those intervals and forces an update * Show names can no longer be overridden in the configuration file * Don't report an error when no sources are defined in the config file * The tv.com parser now also accepts urls containing '!', '+' or '%' * The -d option now also accepts the number of days instead of a fixed date * Documentation updated == v0.5.3 (26 Jul 2009) == * Added support for another epguides formatting style (used eg. for "Eureka") * Added option to suppress colors in console output * Added a filter to remove invalid characters from epguides content * Fixed some other parsing issues in the epguides parser * Improved compatibility with older python versions == v0.5.2 (30 Jun 2009) == * Reworked parts of the code to improve compatibility with older libraries * Fixed some encoding issues in the console renderer == v0.5.1 (23 Jun 2009) == * Thanks to Philip Douglass for his bug reports and patches * The epguides parser now properly closes all file handles and works with mawk * The tv.com parser would crash on missing production/season/episode numbers * The tv.com parser now accepts urls that contain a dash * Switched to using sqlalchemy to access the database * Properly implemented the user-agent configuration option * Removed old FAQ * Fixed some text encoding issues * Small fixes to the man page == v0.5.0 (18 May 2009) == * Rewrote the whole thing in python * Wrote a brand new tv.com parser * Small fixes in the epguides.com parser * Parsed data is now stored in an sqlite3 database == v0.4.7 (24 Feb 2007) == * Fixed a parsing issue introduced with 0.4.6 == v0.4.6 (24 Feb 2007) == * Discovered yet another formatting possibility on epguides.com (used for instance for the show "Midsomer Murders") and adapted the parser accordingly * Slightly updated the man page == v0.4.5 (23 Jan 2007) == * Fixed some epguides parser issues == v0.4.4 (19 Nov 2006) == * Fixed the -i option when building the database (did the exact opposite of what it was supposed to do) == v0.4.3 (24 Oct 2006) == * We now actually honor the -i option when building the database * Added the possibility to override a show's name in the config file. This was needed for the new webisoder, a web-based episoder. Find out more about it at http://www.webisoder.net/ * Oops, forgot to update episoder's version number in the last release... * Fixed a bug in the new epguides.com parser which would not drop episodes without a date == v0.4.2 (21 Oct 2006) == * Don't ignore the config file passed with -c anymore when building the db * Added parser for epguides.com (closes #38) == v0.4.1 (20 Apr 2006) == * Did some minor internal changes to get episoder to work on non-linux systems * Removed long options * Hotfix for the tv.com website changes == v0.4.0 (3 Dec 2005) == * Re-organized options: -vv is now -w, -rc is now -c (or --rc), -nd is gone (use --nodate), -sa is gone (use -s and --nodate instead), -i is gone (see below) * Search is now alway case-insensitive * If no action is specified, episoder now defaults to showlist * Removed the tvtome dummy plugin == v0.3.0 (9 Aug 2005) == * Majeed Goldrick joined the project * Moved parts of the website to sourceforge * Removed a 1024-episodes-limit in sortlist * Added search options * Switched to awk to remove old episodes (>600 times faster) * Switched to awk for tv.com parsing (>10 times faster) * Removed the debian files from the main distribution * Added a couple of tests == v0.2.5 (19 Jul 2005) == * Fixed an alignment problem in showlist (closes #25) * Fixed a date-calculation issue in showlist (closes #23) * Fixed a documentation mistake about the format string (closes #21) * Added support for nun-numeric episode numbers (closes #24) == v0.2.4 (19 Jul 2005) == * Re-arranged the code to remove a 3-episodes-limit in showlist (closes #19) * Added command line option to specify the number of days to show (closes #20) * Brought back season-episode information in the tvcom plugin (closes #15) * Added the possibility to customize the output format (closes #16) * Added a small FAQ * Thanks to Majeed Goldrick for all the bug reports and feature suggestions * Cosmetic changes == v0.2.3 (23 Jun 2005) == * The tvcom plugin now uses the new "All Seasons" link * Cosmetic changes == v0.2.2 (17 Jun 2005) == * Added LICENSE file * install.sh now correctly changes the EPISODER_HOME value * Small fixes in the verbose output * Created tvcom plugin * Replaced all functionality from the tvtome plugin with a warning * Now all the available modules are actually loaded * Some minor changes in the man page == v0.2.1 (4 Jan 2005) == * The tvtome plugin now understands UNAIRED episodes * Improved the builddb script's debug output * Fixed an issue that would print errors for shows with no upcoming episodes * The debian files are now part of the main distribution == v0.2.0 (13 Sep 2004) == * Initial public release �������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/COPYING������������������������������������������������������������������������������0000644�0001750�0001750�00000104513�10642030347�015150� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/README�������������������������������������������������������������������������������0000644�0001750�0001750�00000001205�12221162173�014765� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������== Purpose == episoder is a tool to tell you about new episodes of your favourite TV shows. == Installation == * Run 'easy_install episoder-0.7.0.tar.gz' * Create a cron job to have your database rebuilt once a day * Add "episoder" to your ~/.bashrc, ~/.bash_profile, /etc/bash.bashrc or /etc/profile if you want to see your upcoming shows every time you start a shell. Consult the bash docs to find out which file you want to use. == Configuration == See "man episoder" == Contact == If you find any bugs or have any idea on how to improve this tool, please use the bug tracker on our website at http://code.ott.net/projects/episoder �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/episoder�����������������������������������������������������������������������������0000755�0001750�0001750�00000022522�12221160252�015646� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # episoder, http://code.ott.net/projects/episoder # # Copyright (C) 2004-2013 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging from argparse import ArgumentParser from datetime import date, timedelta from os import environ, path from re import match from sys import exit, stderr from traceback import print_exc from pyepisoder.episoder import DataStore, Show, version from pyepisoder.plugins import ConsoleRenderer, TVDB, parser_for def update(args): store = DataStore(args.datafile) store.update() if args.show: show = store.getShowById(args.show) if not show: logging.error('Show #%d not found' % args.show) return shows = [show] elif args.force: shows = store.getEnabledShows() else: shows = store.getExpiredShows() for show in shows: try: show.update(store, args) except: logging.error('Error parsing %s' % show) print_exc() store.rollback() if not args.nodate: basedate = args.date show.removeEpisodesBefore(store, basedate) if not shows: logging.info('None of your shows need to be updated') def add(args): url = args.show store = DataStore(args.datafile) store.update() show = store.getShowByUrl(url) if show: stderr.write('A show with that url/id already exists\n') return if not parser_for(url): stderr.write('Invalid show url/id: %s\n' % url) return show = Show('Unknown Show', url=url) store.addShow(show) store.commit() def remove(args): id = args.show store = DataStore(args.datafile) store.update() store.removeShow(id) store.commit() def set_show_enabled(store, id, enabled): show = store.getShowById(id) if not show: stderr.write('There is no show with that ID\n') return show.enabled = enabled store.commit() def enable(args): store = DataStore(args.datafile) store.update() set_show_enabled(store, args.show, True) def disable(args): store = DataStore(args.datafile) store.update() set_show_enabled(store, args.show, False) def shows(args): store = DataStore(args.datafile) store.update() shows = store.getShows() statusStrings = ['?Invalid', 'Running', 'Suspended', 'Ended' ] enabledStrings = ['Disabled', 'Enabled'] for show in shows: status = show.status print '[%4d] %s' % (show.show_id, show.url) print ' %s, %s, %s' % (show.show_name, statusStrings[status], enabledStrings[show.enabled]) print ' Last update: %s' % (show.updated) def episodes(args): store = DataStore(args.datafile) renderer = ConsoleRenderer(args.format, args.dateformat) if args.nodate: startdate = date(1900, 1, 1) n_days = 109500 # should be fine until late 21xx :) else: startdate = args.date n_days = args.days if args.search: episodes = store.search(args.search) else: episodes = store.getEpisodes(startdate, n_days) renderer.render(episodes, not args.nocolor) def search(args): search = args.keyword try: res = TVDB.lookup(search) print "ID\tName\n-------\t--------------------" for x in res: print "%s\t%s" % (x['seriesid'], x['seriesname']) except: print 'Nothing found' def parseArgs(): yesterday = date.today() - timedelta(1) parser = ArgumentParser() subparsers = parser.add_subparsers(help='commands') # OPTIONS FOR ADDING SHOWS parser_add = subparsers.add_parser('add', help='Add a show') parser_add.add_argument('show', action='store', help='the show to add (TVDV ID or epguides.com URL)') parser_add.set_defaults(func=add) # OPTIONS FOR REMOVING SHOWS parser_remove = subparsers.add_parser('remove', help='Remove a show from the database') parser_remove.add_argument('show', action='store', type=int, help='the show ID to remove') parser_remove.set_defaults(func=remove) # OPTIONS FOR ENABLING SHOWS parser_enable = subparsers.add_parser('enable', help='Enable updates for a show') parser_enable.add_argument('show', action='store', type=int, help='the show ID to enable updates for') parser_enable.set_defaults(func=enable) # OPTIONS FOR DISABLING SHOWS parser_disable = subparsers.add_parser('disable', help='Disable updates for a show') parser_disable.add_argument('show', action='store', type=int, help='the show ID to disable updates for') parser_disable.set_defaults(func=disable) # OPTIONS FOR SHOWING EPISODES parser_list = subparsers.add_parser('list', help='Show upcoming episodes') parser_list.add_argument('-C', '--nocolor', action='store_true', help="don't use colors") parser_list.add_argument('-d', metavar='YYYY-MM-DD|n', dest='date', default = yesterday.strftime('%Y-%m-%d'), help='only show episodes prior to this date or n days back') parser_list.add_argument('-n', '--days', type=int, default=2, help='number of future days to show (default: 2)') parser_list.add_argument('-i', '--nodate', action='store_true', help="ignore date, show all episodes") parser_list.add_argument('-s', dest='search', help='search episodes') parser_list.set_defaults(func=episodes) # OPTIONS FOR SEARCHING SHOWS parser_search = subparsers.add_parser('search', help='Find shows on TVDB') parser_search.add_argument('keyword', action='store', help='search string') parser_search.set_defaults(func=search) # OPTIONS FOR LISTING SHOWS parser_shows = subparsers.add_parser('shows', help='List shows in the database') parser_shows.set_defaults(func=shows) # OPTIONS FOR DATABASE UPDATE parser_update = subparsers.add_parser('update', help='Update the database') parser_update.add_argument('-d', metavar='YYYY-MM-DD|n', dest='date', default = yesterday.strftime('%Y-%m-%d'), help='remove episodes prior to this date or n days back') parser_update.add_argument('-f', '--force', action='store_true', help='force-update the database, disregard last update time') parser_update.add_argument('-i', '--nodate', action='store_true', help="ignore date, don't remove old episodes") parser_update.add_argument('-s', '--show', metavar='id', type=int, help='only update the show with this id') parser_update.set_defaults(func=update) # GLOBAL OPTIONS group = parser.add_mutually_exclusive_group() parser.add_argument('-c', metavar='file', action='store', default=path.join(environ['HOME'], '.episoder'), help='use configuration from file') group.add_argument('-v', '--verbose', action='store_true', help='verbose operation') group.add_argument('-d', '--debug', action='store_true', help='debug (very verbose) operation') parser.add_argument('-l', metavar='file', dest='logfile', action='store', help='log to file instead of stdout') parser.add_argument('-V', '--version', action='version', version='episoder %s' % version, help='show version information') args = parser.parse_args() # turn our date string into a proper date object if hasattr(args, 'date'): if args.date.isdigit(): daysback = int(args.date) args.date = date.today() - timedelta(daysback) elif match('^[0-9]{4}(-[0-9]{2}){2}$', args.date): d = args.date.split('-') args.date = date(int(d[0]), int(d[1]), int(d[2])) else: parser.error('%s: Wrong date format' % args.date) # configure the logger loglevel = logging.WARNING if args.verbose: loglevel = logging.INFO if args.debug: loglevel = logging.DEBUG if args.logfile: logging.basicConfig(level=loglevel, filename=args.logfile) else: logging.basicConfig(level=loglevel) return args def loadConfig(args): rcfile = args.c config = {} try: rc = open(rcfile) except IOError, e: stderr.write('%s: %s\n' % (rcfile, e.strerror)) exit(2) except Exception, e: stderr.write('%s\n' % e) exit(2) for line in rc: line = line.strip() if line.startswith('data='): (_, config['datafile']) = line.split('=') elif line.startswith('format='): (_, config['format']) = line.split('=') elif line.startswith('dateformat='): (_, config['dateformat']) = line.split('=') elif line.startswith('agent='): (_, config['agent']) = line.split('=') elif line.startswith('src='): logging.warn('Specifying shows in the configuration ' 'file is no longer supported.') rc.close() for key in config: logging.debug('%s=%s' % (key, config.get(key))) args.agent = config.get('agent', 'episoder/' + version) args.datafile = config.get('datafile', path.join(environ['HOME'], '.episodes')) args.dateformat = config.get('dateformat', '%a, %b %d, %Y') args.format = config.get('format', '%airdate %show %seasonx%epnum') args.tvdb_key = config.get('tvdb_key', '8F15287C4B23B36E') logging.info('Loaded rcfile') def main(): args = parseArgs() loadConfig(args) if path.exists(args.datafile): file = open(args.datafile) if file.read(6) != 'SQLite': stderr.write('episoder found an old data file at ' + '%s. You have to delete ' % args.datafile + 'that file before episoder can proceed.\n') exit(4) file.close() args.func(args) if __name__ == '__main__': main() ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/episoder.1���������������������������������������������������������������������������0000644�0001750�0001750�00000016133�12221161054�016004� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.TH EPISODER 1 .SH NAME episoder \- TV show episode reminder. .SH SYNOPSIS .B episoder [global options] [command] [command-specific options] .SH COPYRIGHT episoder is Copyright (C) 2004-2013 by Stefan Ott .SH DESCRIPTION episoder is a tool to tell you about new episodes of your favourite TV shows .SH GLOBAL OPTIONS .TP .B \-h Show help and quit. .TP .B \-c \fIFILE\fR Use \fIFILE\fR for configuration values. By default ~/.episoder is used. .TP .B \-v, \-\-verbose Enable verbose operation. .TP .B \-d, \-\-debug Enable debug (very verbose) operation. .TP .B \-l \fIFILE\fR Log to \fIFILE\fR instead of stdout. .TP .B \-V, \-\-version Show program version and quit. .SH COMMANDS .SS Add Shows .B episoder [options] .B add \fISHOW\fR .PP This adds a \fISHOW\fR to episoder's database. You can either specify a URL from epguides.com or a show ID from TheTVDB.com. Note that this won't fetch any episodes or meta data about the show, to do this you will need to .B update your database. .SS Find Shows on TheTVDB.com .B episoder [options] .B search \fI"search terms"\fR .PP Rather than visiting their web site you can use episoder to search TheTVDB.com. This command will show you a list of all shows that match your \fIsearch terms\fR along with their IDs -- you will need to know these to .B add shows to the database. .SS List Shows .B episoder [options] .B shows .PP List all shows in episoder's database. The output contains information on the show's URL or TVDB ID, name, current state and the time of the last update. .SS Remove Shows .B episoder [options] .B remove \fISHOW\fR .PP This removes a \fISHOW\fR from episoder's database. Please specify the \fIshow id\fR as shown by the .B shows command. .SS Disable Updates .B episoder [options] .B disable \fISHOW\fR .PP By default, any show that is added to episoder's database is included when the database is updated. If however you would like to disable updates for a certain show, this is how you do it. .PP Please specify the \fIshow id\fR as shown by the .B shows command. .SS Enable Updates .B episoder [options] .B enable \fISHOW\fR .PP Use this to re-enable updates for a show that has previously been \fIdisabled\fR. Please specify the \fIshow id\fR as shown by the .B shows command. .SS Update the Database .B episoder [options] .B update [update-options] .PP Update the episoder database. This will fetch the list of known episodes for all shows that are currently in the database (unless they have been disabled). .PP The update command knows the following extra options: .TP .B \-d \fIDATE\fR All episodes that are older than \fIDATE\fR will be removed from the database after the update. You can either specify an absolute date as \fIYYYY-MM-DD\fR or a relative date by passing the number of days back. The default value is 2, i.e. all episodes more than two days old will be removed. .TP .B \-f, \-\-force Update the database regardless of the time of the last update. By default episoder uses these update intervals: .RS .PP * 2 days for shows that are currently running. .PP * 1 week for shows that are currently paused. .PP * 2 weeks for shows that have ended. .RE .TP .B \-i, \-\-nodate Don't remove any old episodes, regardless of their date. .TP .B \-s, \-\-show \fIID\fR Only update the show with this \fIID\fR (as shown by the .B shows command), regardless of the last update time and whether or not updates are currently enabled for this show. .TP Note that the \fB-d\fP and \fB-i\fP options cannot be combined and that \fB-f\fP has no effect when using \fB-s\fP. .SS List Episodes in the Database .B episoder [options] .B list [list-options] .PP Show upcoming episodes. Before running this you should update the database to make sure that your list of episodes is up-to-date. .PP The list command knows the following extra options: .TP .B \-C, \-\-nocolor Don't use colors in the list of episodes. By default, episodes will be colored to indicate the air date relative to the current date: .RS .PP * Episodes from the distant past are colored gray .PP * Yesterday's episodes are colored red .PP * Today's episodes are colored yellow .PP * Tomorrow's episodes are colored green .PP * Future episodes are colored cyan .RE .TP .B \-d \fIDATE\fR Only show episodes that air prior to \fIDATE\fR. You can either specify an absolute date as \fIYYYY-MM-DD\fR or a relative date by passing the number of days back. The default is to hide all episodes that aired before yesterday. .TP .B \-n \fIDAYS\fB, \-\-days \fIDAYS\fR The number of days to show. Any episodes that are more than \fIDAYS\fR days in the future will be hidden. The default value is 2. Note that this value is relative to the \fIDATE\fR specified with the .B \-d option. .TP .B \-i, \-\-nodate Show all episodes regardless of their date. .TP .B \-s \fISEARCH\fR Search for \fISEARCH\fR in show and episode names. .SH EXAMPLES Find a show on TheTVDB.com: .IP .B episoder search dexter .IP The output will look like this: .IP .nf ID Name ------- -------------------- 79349 Dexter .fi .TP Add a show: .IP .B episoder add 79349 .TP List all currently added shows: .IP .B episoder shows .IP The output will look like this: .IP [ 1] 79349 Dexter, Running, Enabled Last update: 1970-01-01 00:00:00 .TP Fetch all episodes for Dexter regardless of the air date and enable debugging output: .IP .B episoder -d update -s 1 -i .TP List all episodes from October 2012: .IP .B episoder list -d 2012-10-01 -n 31 .SH CONFIG FILE .LP The configuration file contains default settings for episoder. .TP .B agent=foo Set the user-agent string to be used when fetching data. This is only used for shows on epguides.com. .TP .B data=/path/to/file Path to episoder's data file. If, instead of a file, you supply a database url (as expected by sqlalchemy, eg. 'mysql://localhost/episoder'), episoder is going to use that database for storage instead. .TP .B format=unquoted format string This allows you to customize episoder's output. Available fields are: .PP %airdate The episode's airdate as YYYY-MM-DD %show Name of the show %season Current season %epnum Episode's number in season %eptitle Title of the episode %totalep Episode's total number %prodnum Production number .br If undefined, the default value of .B %airdate %show %seasonx%epnum (eg. "2005-07-29 Monk 4x04") is used. .TP .B dateformat=unquoted string describing the format Here you can define the date format you'd like to be used for the output. To get a list of all possible fields, see .BR date(1). The default is %a, %b %d, %Y .TP .B tvdb_key=KEY Use your own TVDB API \fIKEY\fR instead of episoder's built-in default key. This is recommended if you use episoder on a larger scale. See http://thetvdb.com/?tab=apiregister for more details. .SH CRON .LP You might want to have your episode database rebuilt on a regular basis (i.e. daily). The easiest way to achieve this is with a simple cron job: .PP crontab \-l > crontab echo "40 5 * * * episoder update" >> crontab crontab crontab .SH FILES .B ~/.episoder - default configuration file .br .B ~/.episodes - default data file .SH AUTHOR This manual page was written by Stefan Ott �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/home.episoder������������������������������������������������������������������������0000644�0001750�0001750�00000001343�12226645424�016606� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Datafile #data=/home/stefan/.episodes # User agent to be used for epguides.com #agent=Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0) # Output format # Currently available fields are (last column: example values): # # %airdate The episode's airdate Sun, Apr 04, 2005 # %show Name of the show Monk # %season Current season 3 # %epnum Episode's number in season 16 # %eptitle Title of the episode Mr. Monk and the kid # %totalep Episode's total number 45 # %prodnum Production number T-3015 # # Default value: %airdate %show %seasonx%epnum #format=%airdate %show %seasonx%epnum - %eptitle # Your favourite dateformat as used by the date command (see `man date`) #dateformat=%a, %b %d, %Y ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/setup.py�����������������������������������������������������������������������������0000644�0001750�0001750�00000002557�12226654720�015643� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python from distutils.core import setup from os import path # files to install files = [] # man page manpage = 'episoder.1' files.append((path.join('man', 'man1'), ['episoder.1'])) # awk parser awkfile = path.join('extras', 'episoder_helper_epguides.awk') files.append(('extras', [awkfile])) # documentation for file in [ 'AUTHORS', 'CHANGELOG', 'COPYING', 'README' ]: files.append((path.join('doc', 'episoder'), [file])) files.append((path.join('doc', 'episoder', 'examples'), [ 'home.episoder' ])) setup( name = 'episoder', version = '0.7.0', license = 'GPLv3', description = 'TV episode notifier', author = 'Stefan Ott', author_email = 'stefan@ott.net', url = 'http://code.ott.net/projects/episoder', packages = [ 'pyepisoder' ], scripts = [ 'episoder' ], long_description = 'episoder is a tool to tell you about new episodes of your favourite TV shows', data_files = files, install_requires = [ 'beautifulsoup', 'pyyaml', 'argparse', 'sqlalchemy>=0.7', 'tvdb_api' ], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Multimedia :: Video' ] ) �������������������������������������������������������������������������������������������������������������������������������������������������episoder-0.7.0/PKG-INFO�����������������������������������������������������������������������������0000644�0001750�0001750�00000001275�12226654723�015225� 0����������������������������������������������������������������������������������������������������ustar �stefan��������������������������stefan��������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Metadata-Version: 1.1 Name: episoder Version: 0.7.0 Summary: TV episode notifier Home-page: http://code.ott.net/projects/episoder Author: Stefan Ott Author-email: stefan@ott.net License: GPLv3 Description: episoder is a tool to tell you about new episodes of your favourite TV shows Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: End Users/Desktop Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Multimedia :: Video �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������