def __createSession__(self):
        # Try to load a cached token
        try:
            session_token_store = Store("app://tokens/session/{username}".format(username=self.username))
            session_tokens = session_token_store.retrieve()
            self.session_token = None
            if len(session_tokens):
                for cached_token in session_tokens:
                    cached_token_expiration_time = datetime.fromtimestamp(jwt.decode(cached_token, verify=False)['exp'])

                    token_validity_time_remaining = cached_token_expiration_time - datetime.now()

                    if token_validity_time_remaining.total_seconds() <= 60 * 60 * 24:
                        self.session_token = None
                    else:
                        self.session_token = cached_token
            else:
                self.session_token = None
        except:
            self.session_token = None

        if self.session_token is None:
            self.__requestSessionToken()
        else:
            pass
    def __createAuthorization__(self):
        if self.session_token is not None:
            # Try to load a cached social token
            try:
                social_token_store = Store("app://tokens/social/{username}".format(username=self.username))
                social_tokens = social_token_store.retrieve()
                if len(social_tokens):
                    for cached_token in social_tokens:
                        cached_token_expiration_time = datetime.fromtimestamp(jwt.decode(cached_token, verify=False)['exp'])

                        token_validity_time_remaining = cached_token_expiration_time - datetime.now()

                        if token_validity_time_remaining.total_seconds() <= 60 * 60 * 24:
                            self.__requestSocialToken()
                        else:
                            self.session.headers["Authorization"] = "JWT " + cached_token
                else:
                    self.__requestSocialToken()

            except:
                self.__requestSocialToken()
    def __requestSocialToken(self):
        dict = {"identity_provider_url": __ACCOUNT_IDENTITY_PROVIDER_URL__, "access_token": self.session_token}

        token_request = self.session.post(__ACCOUNT_SOCIAL_AUTHENTICATE__, data=json.dumps(dict))
        if token_request.ok:
            self.session.headers["Authorization"] = "JWT " + token_request.json()["token"]

            # Save the token
            try:
                session_token_store = Store("app://tokens/social/{username}".format(username=self.username))
                session_token_store.clear()
                session_token_store.append(token_request.json()["token"])
            except:
                pass
    def __requestSessionToken(self):
        login_dict = {"Login": self.username, "Password": self.password}
        r = self.session.post(__ACCOUNT_CREATE_SESSION__, headers=self.auth_headers, data=json.dumps(login_dict))

        if r.ok and 'Fault' not in r.json():
            if r.json()["data"]["subscriptionStatus"] != "active":
                raise ValueError('Subscription is not active.')

            self.session_token = r.json()["data"]["subscriptionToken"]

            # Save the token
            try:
                session_token_store = Store("app://tokens/session/{username}".format(username=self.username))
                session_token_store.clear()
                session_token_store.append(self.session_token)
            except:
                pass
        else:
            raise ValueError('Account Authentication failed.')
Exemplo n.º 5
0
from cache import Cache, Store, conditional_headers

from . import kodiutils as ku

LOC_URI = "https://www.loc.gov/"
LOS_MEDIA_TEMPLATE = "https://media.loc.gov/services/v1/media?id={}"
LOC_SEARCH_TEMPLATE = "{}film-and-videos/{{}}" \
                      "?fa=online-format:video&fo=json&q={{}}&dates={{}}&c={{}}&sp={{}}".format(LOC_URI)
LOC_STATIC_IMAGE = "/static/images/original-format/film-video.png"
LOC_DEFAULT_IMAGE_URI = "{}{}".format(LOC_URI, LOC_STATIC_IMAGE.lstrip("/"))

SEARCH_SAVED = ku.get_setting_as_bool("search_saved")
SEARCH_MAX_RESULTS = ku.get_setting("search_max_results")
SEARCH_TIMEOUT = 60

searches = Store("app://saved-searches")
recents = Store("app://recently-viewed")
logger = logging.getLogger(__name__)


def extract_year(text):
    # type: (str) -> int
    """Attempts to extract the first four digits in sequence from a string, defaults to 0"""
    data = re.search(r"\d{4}", text)
    return int(data.group()) if data else 0


def get_art(data):
    # type: (dict) -> dict
    """Gets the art-work for the given result data"""
    image = data.get("resources", [{}])[0].get("image")