'Authenticates a session with IMDB, and grabs any IDs needed for getting/modifying list.'

def authenticate(self):

    cached_credentials = False
    with Session() as session:
        user = session.query(IMDBListUser).filter((IMDBListUser.user_name == self.config.get(u'login'))).one_or_none()
        if (user and user.cookies and user.user_id):
            log.debug(u'login    credentials    found    in    cache,    testing')
            self.cookies = user.cookies
            self.user_id = user.user_id
            r = self._session.head(u'http://www.imdb.com/profile', allow_redirects=False, cookies=self.cookies)
            if ((not r.headers.get(u'location')) or (u'login' in r.headers[u'location'])):
                log.debug(u'cache    credentials    expired')
            else:
                cached_credentials = True
        if (not cached_credentials):
            log.debug(u'user    credentials    not    found    in    cache    or    outdated,    fetching    from    IMDB')
            url_credentials = u'https://www.imdb.com/ap/signin?openid.return_to=https%3A%2F%2Fwww.imdb.com%2Fap-signin-handler&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=imdb_mobile_us&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0'
            try:
                r = self._session.get(url_credentials)
            except RequestException as e:
                raise PluginError(e.args[0])
            soup = get_soup(r.content)
            inputs = soup.select(u'form#ap_signin_form    input')
            data = dict(((i[u'name'], i.get(u'value')) for i in inputs if i.get(u'name')))
            data[u'email'] = self.config[u'login']
            data[u'password'] = self.config[u'password']
            action = soup.find(u'form', id=u'ap_signin_form').get(u'action')
            log.debug(u'email=%s,    password=%s', data[u'email'], data[u'password'])
            self._session.headers.update({u'Referer': url_credentials})
            d = self._session.post(action, data=data)
            self._session.headers.update({u'Referer': u'http://www.imdb.com/'})
            r = self._session.head(u'http://www.imdb.com/profile', allow_redirects=False)
            if ((not r.headers.get(u'location')) or (u'login' in r.headers[u'location'])):
                raise plugin.PluginError(u'Login    to    IMDB    failed.    Check    your    credentials.')
            self.user_id = re.search(u'ur\\d+(?!\\d)', r.headers[u'location']).group()
            self.cookies = dict(d.cookies)
        if user:
            for list in user.lists:
                if (self.config[u'list'] == list.list_name):
                    log.debug(u'found    list    ID    %s    matching    list    name    %s    in    cache', list.list_id, list.list_name)
                    self.list_id = list.list_id
        if (not self.list_id):
            log.debug(u'could    not    find    list    ID    in    cache,    fetching    from    IMDB')
            if (self.config[u'list'] == u'watchlist'):
                data = {u'consts[]': u'tt0133093', u'tracking_tag': u'watchlistRibbon'}
                wl_data = self._session.post(u'http://www.imdb.com/list/_ajax/watchlist_has', data=data, cookies=self.cookies).json()
                try:
                    self.list_id = wl_data[u'list_id']
                except KeyError:
                    raise PluginError(u'No    list    ID    could    be    received.    Please    initialize    list    by    manually    adding    an    item    to    it    and    try    again')
            elif ((self.config[u'list'] in IMMUTABLE_LISTS) or self.config[u'list'].startswith(u'ls')):
                self.list_id = self.config[u'list']
            else:
                data = {u'tconst': u'tt0133093'}
                list_data = self._session.post(u'http://www.imdb.com/list/_ajax/wlb_dropdown', data=data, cookies=self.cookies).json()
                for li in list_data[u'items']:
                    if (li[u'wlb_text'] == self.config[u'list']):
                        self.list_id = li[u'data_list_id']
                        break
                else:
                    raise plugin.PluginError((u'Could    not    find    list    %s' % self.config[u'list']))
        user = IMDBListUser(self.config[u'login'], self.user_id, self.cookies)
        list = IMDBListList(self.list_id, self.config[u'list'], self.user_id)
        user.lists.append(list)
        session.merge(user)
    self._authenticated = True
