Beispiel #1
0
def opensub_initiate():
    """OpenSubtitles initiation for use

    Login to OpenSubtitles using API to retrieve a token
    for identifying movies.

    Failure results in a null token.
    Network errors are caused to service unavailability, or DNS problems

    Args:
        None

    Returns:
        token(str): Authentication Token for OpenSubtitles
        None: if token cannot be validated

    Raises:
        None
    """
    try:
        # login to opensub using API
        sub = OpenSubtitles()
        token = sub.login(OpenSubKey.get_solo().uid, OpenSubKey.get_solo().key)
        if not token:
            # return sub
            print 'null token'
            log.error('open sub null token')
            return
        return sub
    except ProtocolError as e:
        # most likely network error or API server error
        print "E: " + str(e)
    except AssertionError:
        print 'Failed to authenticate opensubtitles login.'
    except ProtocolError as e:
        """
        TODO: gaierror:
            [Errno 8] nodename nor servname provided, or not known
        """
        if e.errcode == 503:
            # ProtocolError - 503 Service Unavailable
            print 'Check network connection and try again.'
        log.error('open sub error occured')
        log.error(traceback.format_exc())
    except Exception:
        log.error('open sub error occured')
        log.error(traceback.format_exc())
Beispiel #2
0
def setup(request):
    """Setup for first-use
    """
    if not request.POST:
        log.info('served setup page')
        return render(
            request,
            'hdd_indexer/setup.html',
            {
                'RegistrationKey': RegistrationKey.get_solo().key,
                'hdd_name': HDDName.get_solo().name,
                'hdd_root': HDDRoot.get_solo().path,
                'movie_folder': MovieFolder.get_solo().relpath,
                'opensub_id': OpenSubKey.get_solo().uid,
                'opensub_key': OpenSubKey.get_solo().key,
                'tmdb_key': TMDbKey.get_solo().key,
                'error': False,
                'err_msg': '',
            }
        )

    error = False
    err_msg = 'Validation errors have been found: '
    log.info('POST: preferences and settings in setup')
    # validations
    # registration key
    registration_key = request.POST.get('ID', '')
    if registration_key:
        # make sure that it is valid registration key
        registration_key_db = RegistrationKey.get_solo()
        registration_key_db.key = registration_key
        registration_key_db.save()
        log.info('registration key = %s saved to db' % registration_key)
    else:
        pass

    # hdd name
    hdd_name = request.POST.get('HDDName', '')
    pattern = re.compile(r'^[0-9a-zA-z_-]+$')
    if pattern.match(hdd_name):
        hdd_name_db = HDDName.get_solo()
        hdd_name_db.name = hdd_name
        hdd_name_db.save()
        log.info('hdd_name: %s saved to db' % hdd_name)
    else:
        error = True
        err_msg = ' '.join(((err_msg, 'HDD Name,')))
        log.error('%s is not a valid hdd_name' % hdd_name)

    # hdd root
    hdd_root = request.POST.get('HDDRoot', '')
    if path.exists(hdd_root):
        hdd_root_db = HDDRoot.get_solo()
        hdd_root_db.path = hdd_root
        hdd_root_db.save()
        log.info('hdd_root = %s saved to db' % hdd_root)
    else:
        error = True
        err_msg = ' '.join(((err_msg, 'HDD Root,')))
        log.error('%s is not a valid path' % hdd_root)

    # movie folder
    movie_folder = request.POST.get('MovieFolder', '')
    log.info('POST: movie_folder = %s' % movie_folder)
    if path.exists(movie_folder):
        movie_folder_db = MovieFolder.get_solo()
        movie_folder_db.relpath = movie_folder
        movie_folder_db.save()
        log.info('movie_folder = %s saved to db' % movie_folder)
    else:
        error = True
        err_msg = ' '.join((err_msg, 'Movie Folder,'))
        log.error('%s is not a valid path' % movie_folder)

    # tmdb key
    # TODO: check tmdb key is valid
    tmdb_key = request.POST.get('TMDB_KEY', '')
    log.info('POST: tmdb_key = %s' % tmdb_key)
    if len(tmdb_key) >= 5:
        tmdb_db = TMDbKey.get_solo()
        tmdb_db.key = tmdb_key
        tmdb_db.save()
        log.info('tmdb_key = %s saved to db' % tmdb_key)
    else:
        error = True
        err_msg = ' '.join(((err_msg, 'TMDb Key,')))
        log.error('%s is not a valid tmdb_key' % tmdb_key)

    # opensub
    # TODO: check opensub key is valid
    opensub_id = request.POST.get('OpenSubID', '')
    opensub_key = request.POST.get('OpenSubKey', '')
    log.info('opensub id:%s key:%s' % (opensub_id, opensub_key))
    if opensub_id and opensub_key:
        if len(opensub_id) >= 5 and len(opensub_key) >= 5:
            opensub_db = OpenSubKey.get_solo()
            opensub_db.uid = opensub_id
            opensub_db.key = opensub_key
            opensub_db.save()
            log.info('opensub id:%s key:%s saved to db' % (
                opensub_id, opensub_key
            ))
        else:
            error = True
            err_msg = ' '.join((err_msg, 'OpenSubtitles ID and Key,'))
            log.info('opensub id:%s key:%s are not valid' % (
                opensub_id, opensub_key
            ))

    if error is False:
        log.info('setup complete, redirected to welcome page')
        return render(
            request,
            'hdd_indexer/help.html',
            {
                'welcome': True,
            }
        )

    log.error('setup input has errors, redirect to setup page')
    return render(
        request,
        'hdd_indexer/setup.html',
        {
            'RegistrationKey': RegistrationKey,
            'hdd_name': hdd_name,
            'hdd_root': hdd_root,
            'movie_folder': movie_folder,
            'opensub_id': opensub_id,
            'opensub_key': opensub_key,
            'tmdb_key': tmdb_key,
            'error': error,
            'err_msg': err_msg,
        }
    )
Beispiel #3
0
def opensub(relpath):
    """OpenSubtitle identification of movie

    Uses the OpenSubtitles API to identify movie

    Args:
        relpath(str): relative path of movie file

    Returns:
        imdb_id(int): on success, returns idetified imdb id
        None: on failure

    Raises:
        None
    """
    if 'sub' not in opensub.__dict__:
            sub = opensub_initiate()
            if sub:
                opensub.sub = sub
                token = sub.login(
                    OpenSubKey.get_solo().uid,
                    OpenSubKey.get_solo().key
                )
                opensub.token = token
            opensub.lock = Lock()

    try:
        # login to opensub using API
        sub = opensub.sub
        token = opensub.token
        if not token:
            # return sub
            print 'null token'
            log.error('path: %s open sub null token' % relpath)
            return
        # check that the file is accessible
        if not path.exists(path.join(
            HDDRoot.get_solo().path,
            MovieFolder.get_solo().relpath,
            relpath,
        )):
            print "ERROR: " + relpath
            log.error('path: %s does not exist' % relpath)
            return
        f = File(path.join(
            HDDRoot.get_solo().path,
            MovieFolder.get_solo().relpath,
            relpath,
        ))
        if f is None:
            log.error('path: %s open sub file error' % relpath)
            return
        hash = f.get_hash()
        size = f.size
        with opensub.lock:
            data = sub.search_subtitles([{
                'sublanguageid': 'all',
                'moviehash': hash,
                'moviebytesize': size,
            }])
        if type(data) is list:
            if data[0].get('IDMovieImdb', None):
                return data[0]['IDMovieImdb']
        else:
            log.warning('%s opensub failed to identify movie' % relpath)
    except ProtocolError as e:
        # most likely network error or API server error
        print "E: " + str(e)
    except AssertionError:
        print 'Failed to authenticate opensubtitles login.'
    except ProtocolError as e:
        """
        TODO: gaierror:
            [Errno 8] nodename nor servname provided, or not known
        """
        if e.errcode == 503:
            # ProtocolError - 503 Service Unavailable
            print 'Check network connection and try again.'
        log.error('path: %s open sub error occured' % relpath)
        log.error(traceback.format_exc())
    except Exception:
        log.error('path: %s open sub error occured' % relpath)
        log.error(traceback.format_exc())