Example #1
0
 def __init__(self, directory):
     self.logger = logging.getLogger('tvlazy')
     if( not directory ):
         self.logger.error('Should have been given directory')
         return
     # Collect the series name
     self.seriesname = os.path.basename(directory)
     # Collect seasons
     self.seasons = {} # Create empty seasons container
     self.directory = directory
     subdir = os.listdir(self.directory)
     season_re = re.compile(self.season_regex, re.IGNORECASE)
     for season in subdir:
         if os.path.isdir(os.path.join(self.directory, season)):
             self.logger.debug('Found a season %s' % season)
             season_mat = season_re.match(season)
             if( season_mat ):
                 self.logger.debug('Season number %s' % season_mat.group(1))
                 season_num = str(season_mat.group(1))
                 season_path = os.path.join(self.directory, season)
                 self.seasons[season_num] = { 'directory': season_path,
                                             'text': season,
                                             'episodes': {} }
                 # Collect Episodes
                 season_eps = os.listdir(season_path)
                 t = SeriesParser(self.seriesname, identified_by='ep')
                 for ep in season_eps:
                     ep_path = os.path.join(season_path, ep)
                     try: 
                         t.parse(ep)
                     except: 
                         print ep
                     if( t.valid ):
                         new_ep = TvEpisode(ep_path, t.name, t.episode, t.season, t.quality)
                         self.seasons[season_num]['episodes'][new_ep.epNumber()] = new_ep
Example #2
0
def controller():
    opt = optparse.OptionParser(description="does stuff for tv",
    								prog="tvlazy",
    								version="3.14",
    								usage="%prog directory ")
    opt.add_option('--clientip', '-c',
                action = 'store',
                help='Client ip address of transmission client',
                default='192.168.1.109')
    opt.add_option('--clientport', '-p',
                action = 'store',
                help='Client port of transmission client',
                default='9091')
    # Clean-up options
    opt.add_option('--cleanup', '-C',
                action = 'store_true',
                help='Set this flag if you want to clean up old torrents',
                default=False)
    opt.add_option('--ratio', '-r',
                action = 'store',
                help='Ratio after which to delete torrents if positive. \
                    If negative ratio before to delete torrents',
                default='3')
    opt.add_option('--old', '-o',
                action = 'store',
                help='Time in days after which to delete torrents',
                default=40)
    # Sort torrent
    opt.add_option('--tv_sort', '-v',
                action = 'store',
                help='Sort tv eps to this location',
                default='')
    opt.add_option('--movie_sort', '-m',
                action = 'store',
                help='Sort movies to this location',
                default='')
    # Maintain New-list
    opt.add_option('--new_list', '-n',
                action = 'store',
                help='Maintain a newlist of the newest 50 videos in \
                    at this location chronological order',
                default='')
    opt.add_option('--test', '-t',
                action = 'store_true',
                help='Test config etc.. no changes made',
                default=False)
	
    options, arguments = opt.parse_args()
    if len(arguments) < 0:
    	opt.print_help()
    	return
    TEST = options.test

    # Setting up logging
    logger = logging.getLogger('tvlazy')
    logger.setLevel(logging.INFO)
    #fh = logging.FileHandler('spam.log')
    #fh.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    #fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    #logger.addHandler(fh)
    logger.addHandler(ch)

    # Connect to client and create the collection
    tc = transmissionrpc.Client(address=options.clientip, port=options.clientport)
    torrentlist = tc.list()
    tvcol = TvCollection("/home/andrew/TvShows/")
    
    # New movies/tveps list
    newtv = []
    newmovie = []

    if( options.tv_sort != '' ):
        # find tv series
        series = tvcol.getSeries()
        for tor in torrentlist:
            torrent = tc.info(tor)[tor]
            if( int(torrent.progress) == int(100) ): 
                # See if it matches our collection
                for s in series:
                    t = SeriesParser(s)
                    try: 
                        t.parse(torrent.name) 
                    except: 
                        logger.error("Tried to parse but failed %s" % torrent.name)
                    if( t.valid ):
                        ep = TorrentTvEpisode(t.name, t.episode, t.season, t.quality, torrent.files())
                        tvcol.addEpisode(ep)
                        newtv.append(ep)
        return

    if( options.cleanup ):
        cleanupOldTorrents(tc, int(options.ratio), options.old);
        return
    
    newtv.append(ep)
    MAX_NEW_LIST = 10
    logger.error('newtv {} newlist {}'.format(newtv, newlist))
    if( options.new_list != '' ):
        # Get current new list
        newlinks = os.listdir(options.new_list)
        newlinks = [(os.lstat(os.path.join(options.new_list, n)).st_ctime,
            n) for n in newlinks]
        newlinks.sort() # Ascending
        if(len(newtv) > 0):
            # Remove old 
            dellinks = []
            if((len(newlinks)+len(newtv)) > MAX_NEW_LIST):
                dellinks = newlinks[(len(newlinks)+len(newtv)) - MAX_NEW_LIST:]
                logger.erro('old links {}'.format(dellinks))
                for d in delinks:
                    print d
                    os.remove(os.path.join(options.new_list, d))
            # Add new
            for ep in newtv:
                src = "%s" % ep.location
                dst = "%s/%s-s%02d%02d" % (options.new_list, ep.series,
                    int(ep.season), int(ep.ep))
                os.symlink(src, dst)
                logger.error( '{}->{}'.format(src, dst))

    if( options.tv_sort or options.movie_sort ):
        # Get environment variables
        try:
            torr_id = os.environ['TR_TORRENT_ID']
            torr_dir = os.environ['TR_TORRENT_DIR']
            torr_name = os.environ['TR_TORRENT_NAME']
        except KeyError:
            torr_id = 1
            logger.error("No torrent info")
        torr = tc.info(torr_id)[torr_id]
        # Do we need to extract any files?
        for f in torr.files():
            print f
        return