Exemplo n.º 1
0
def register_user_old(product_name, user_name, priority=None, session=None):
    '''
    Create and register the user_name to the product_name
    '''
    try:
        #check that the product exists - must be created by the admin
        product_name = product_name.upper()
        prod = session.query(Product).filter(Product.id==product_name).one()
        
        user_products = session.query(UserProduct).join(User).filter(User.id==user_name).all()
        if len(user_products):
            #check if the user is already subscribed to this product
            if product_name in [p.product.id for p in user_products]:
                return com.error(com.WARN_ALREADY_REGISTERED)
            #the user exists but is not registered to this category
            user = user_products[0].user
        else:
            #the user does not exist - create it
            user = User(id=user_name, password="")
        up = UserProduct(user=user, product=prod, priority=priority)
        user.user_products.append(up)
        session.add(user)
        session.commit()
        return com.success()
    except NoResultFound:
        return com.error(com.ERR_INVALID_PRODUCT)
Exemplo n.º 2
0
def register_user_old(product_name, user_name, priority=None, session=None):
    '''
    Create and register the user_name to the product_name
    '''
    try:
        #check that the product exists - must be created by the admin
        product_name = product_name.upper()
        prod = session.query(Product).filter(Product.id == product_name).one()

        user_products = session.query(UserProduct).join(User).filter(
            User.id == user_name).all()
        if len(user_products):
            #check if the user is already subscribed to this product
            if product_name in [p.product.id for p in user_products]:
                return com.error(com.WARN_ALREADY_REGISTERED)
            #the user exists but is not registered to this category
            user = user_products[0].user
        else:
            #the user does not exist - create it
            user = User(id=user_name, password="")
        up = UserProduct(user=user, product=prod, priority=priority)
        user.user_products.append(up)
        session.add(user)
        session.commit()
        return com.success()
    except NoResultFound:
        return com.error(com.ERR_INVALID_PRODUCT)
Exemplo n.º 3
0
def _get_playlist_videos_html(playlist):
    result = []
    url = "https://www.youtube.com/playlist?list=%s" % playlist
    try:
        response = requests.get(url)
        if response is not None and response.status_code == 200:
            formatter = BeautifulSoup(response.text, "html.parser")
            listing = formatter.find_all(attrs={"class": "pl-video"})
            for item in listing:
                video = dict()
                try:
                    data = item.find(attrs={
                        "class": "yt-thumb-clip"
                    }).find("img")
                    if data.get("data-thumb") is not None:
                        video["thumb"] = data["data-thumb"]
                    else:
                        video["thumb"] = data["src"]
                    data = item.find(attrs={
                        "class": "pl-video-title"
                    }).find("a")
                    video["id"] = _getvid(data["href"])[0]
                    video["url"] = 'https://www.youtube.com%s' % data["href"]
                    video["title"] = data.text.strip()
                    result.append(video)
                except BaseException as ex:
                    commons.warn("Error extracting video from playlist: %s" %
                                 str(ex))
    except ConnectionError as err:
        commons.error("Error connecting to playlist video list: %s" % str(err))
    return result
Exemplo n.º 4
0
def _get_search_html(query):
    result = []
    try:
        query = str(query).strip().replace(' ', '+')
        response = requests.get(
            "https://www.youtube.com/results?search_query=%s" % query)
        if response is not None and response.status_code == 200:
            formatter = BeautifulSoup(response.text, "html.parser")
            listing = formatter.find_all(attrs={"class": "yt-lockup"})
            for item in listing:
                video = dict()
                try:
                    data = item.find(attrs={
                        "class": "video-thumb"
                    }).find("img")
                    if data.get("data-thumb") is not None:
                        video["thumb"] = data["data-thumb"]
                    else:
                        video["thumb"] = data["src"]
                    data = item.find(attrs={
                        "class": "yt-lockup-title"
                    }).find("a")
                    video["title"] = data.text.strip()
                    video["url"] = 'https://www.youtube.com%s' % data["href"]
                    if data["href"].startswith(
                            "/watch") and data["href"].find("list=") < 0:
                        tmpobj = _getvid(data["href"])
                        video["type"] = tmpobj[1]
                        video["id"] = tmpobj[0]
                    elif data["href"].startswith(
                            "/user") or data["href"].startswith("/channel"):
                        tmpobj = _getcid(data["href"])
                        video["type"] = tmpobj[1]
                        video["id"] = tmpobj[0]
                    elif data["href"].startswith(
                            "/playlist") or data["href"].find("list=") >= 0:
                        tmpobj = _getpid(data["href"])
                        video["type"] = tmpobj[1]
                        video["id"] = tmpobj[0]
                    data = item.find(attrs={"class": "video-time"})
                    if data:
                        video["time"] = data.text
                    if video.get(
                            'type') is not None and video['type'] == "user":
                        data = formatter.find(
                            attrs={"class": "yt-uix-subscription-button"})
                        video['id'] = data["data-channel-external-id"]
                        video["type"] = "channel"
                    result.append(video)
                except BaseException as ex:
                    commons.warn(
                        "Error extracting video from search list: %s" %
                        str(ex))
    except ConnectionError as err:
        commons.error("Error connecting to search video list: %s" % str(err))
    return result
Exemplo n.º 5
0
 def tor_print(self):
     log.debug("print view")
     lang = self.request.matchdict.get("lang")
     dates = self.facade.get_dates(datetime.now())
     if lang:
         if lang in ["pl", "en"]:
             log.info("Processing view for {0}".format(lang))
         else:
             return commons.error(self.request, "Not supported option")
     else:
         return commons.error(self.request, "No enough data to process request")
     return dict(lang = lang, start = dates["start"], end = dates["end"], prev_year = dates["prev_year"])
Exemplo n.º 6
0
 def __init__(self):
     self.userdata = xbmc.translatePath('special://userdata/keymaps')
     self.userkeymapfile = os.path.join(self.userdata, 'gen.xml')
     self.userkeymap = []
     self.syskeymapfile = xbmc.translatePath(
         'special://xbmc/system/keymaps/keyboard.xml')
     self.syskeymap = []
     try:
         if not os.path.exists(self.userdata):
             os.makedirs(self.userdata)
         else:
             # make sure there are no user defined keymaps
             for name in os.listdir(self.userdata):
                 if name.endswith('.xml') and name != os.path.basename(
                         self.userkeymapfile):
                     src = os.path.join(self.userdata, name)
                     for i in xrange(100):
                         dst = os.path.join(self.userdata,
                                            "%s.bak.%d" % (name, i))
                         if os.path.exists(dst):
                             continue
                         shutil.move(src, dst)
                         # successfully renamed
                         break
     except Exception as ex:
         KeyEditor.rpc('GUI.ShowNotification',
                       title="Keymap Editor",
                       message=commons.translate(30011),
                       image='error')
         commons.debug("Failed to remove old keymap file: %s" % str(ex))
     # load system keymap
     if os.path.exists(self.syskeymapfile):
         try:
             self.syskeymap = self.getKeymap(self.syskeymapfile)
         except Exception as ex:
             KeyEditor.rpc('GUI.ShowNotification',
                           title="Keymap Editor",
                           message=commons.translate(30012),
                           image='error')
             commons.error("Failed to load system keymap file: %s" %
                           str(ex))
     # load user keymap
     if os.path.exists(self.userkeymapfile):
         try:
             self.userkeymap = self.getKeymap(self.userkeymapfile)
         except Exception as ex:
             KeyEditor.rpc('GUI.ShowNotification',
                           title="Keymap Editor",
                           message=commons.translate(30013),
                           image='error')
             commons.error("Failed to load user keymap file: %s" % str(ex))
Exemplo n.º 7
0
 def tor_generate(self):
     log.debug("generate pdf")
     lang = self.request.matchdict.get("lang")
     site = dict()
     if lang:
         if lang in ["pl", "en"]:
             log.info("Processing view for {0}".format(lang))
             now = datetime.now()
             site = self.facade.generate(now.year, now.month)
         else:
             return commons.error(self.request, "Not supported option")
     else:
         return commons.error(self.request, "No enough data to process request")
     return dict(site = site)
Exemplo n.º 8
0
def _get_trending_html(locale='US'):
    """
	Get the list of most popular (trending) videos using HTML website content
	:param context: modshell provider context
	:return: list of video dictionary objects providing many properties for identification and also for playing
	"""
    result = []
    try:
        response = requests.get("https://www.youtube.com/feed/trending?gl=%s" %
                                locale)
        if response is not None and response.status_code == 200:
            formatter = BeautifulSoup(response.text, "html.parser")
            listing = formatter.find_all(
                attrs={"class": "expanded-shelf-content-item"})
            for item in listing:
                video = dict()
                try:
                    data = item.find(attrs={
                        "class": ["yt-thumb", "video-thumb"]
                    }).find(attrs={
                        "class": "yt-thumb-simple"
                    }).find("img")
                    if data.get("data-thumb") is not None:
                        video["thumb"] = data["data-thumb"]
                    else:
                        video["thumb"] = data["src"]
                    data = item.find(attrs={
                        "class": "yt-lockup-title"
                    }).find("a")
                    video["id"] = _getvid(data["href"])[0]
                    video["url"] = 'https://www.youtube.com%s' % data["href"]
                    video["title"] = data.text
                    data = data.select("span.accessible-description")
                    if len(data) != 0:
                        video["time"] = data[0].text
                    else:
                        video["time"] = ""
                    data = item.find(attrs={"class": "yt-lockup-meta-info"})
                    if data and len(data.contents) > 1:
                        video["date"] = data.contents[0].string
                        video["views"] = data.contents[1].string.split(" ")[0]
                    result.append(video)
                except BaseException as ex:
                    commons.warn(
                        "Error extracting video from trending list: %s" %
                        str(ex))
    except ConnectionError as err:
        commons.error("Error connecting to trending video list: %s" % str(err))
    return result
Exemplo n.º 9
0
def create_product(product_name, session=None):
    product_name = product_name.upper()
    products = session.query(Product).filter(Product.id==product_name).all()
    if len(products):
        return com.error(com.WARN_EXISTING_CATEGORY)
    else:
        p = Product(id = product_name)
        session.add(p)
        session.commit()
    return com.success()
Exemplo n.º 10
0
def create_product(product_name, session=None):
    product_name = product_name.upper()
    products = session.query(Product).filter(Product.id == product_name).all()
    if len(products):
        return com.error(com.WARN_EXISTING_CATEGORY)
    else:
        p = Product(id=product_name)
        session.add(p)
        session.commit()
    return com.success()
Exemplo n.º 11
0
def register_user(product_name, user_name, priority=None, session=None):
    '''
    Create and register the user_name to the product_name
    '''
    try:
        #check that the product exists - must be created by the admin
        product_name = product_name.upper()
        prod = session.query(Product).filter(Product.id==product_name).one()
        users = prod.users
        if user_name in [u.id for u in users]:
            return com.error(com.WARN_ALREADY_REGISTERED)
        users = session.query(User).filter(User.id==user_name).all()
        if len(users):
            user = users[0]
        else:
            user = User(id=user_name, password="")
        user.products.append(prod)
        session.add(user)
        session.commit()
        return com.success()
    except NoResultFound:
        return com.error(com.ERR_INVALID_PRODUCT)
Exemplo n.º 12
0
def register_user(product_name, user_name, priority=None, session=None):
    '''
    Create and register the user_name to the product_name
    '''
    try:
        #check that the product exists - must be created by the admin
        product_name = product_name.upper()
        prod = session.query(Product).filter(Product.id == product_name).one()
        users = prod.users
        if user_name in [u.id for u in users]:
            return com.error(com.WARN_ALREADY_REGISTERED)
        users = session.query(User).filter(User.id == user_name).all()
        if len(users):
            user = users[0]
        else:
            user = User(id=user_name, password="")
        user.products.append(prod)
        session.add(user)
        session.commit()
        return com.success()
    except NoResultFound:
        return com.error(com.ERR_INVALID_PRODUCT)
Exemplo n.º 13
0
def _get_datalist_api(base):
    result = []
    try:
        pageno = 0
        token = ""
        while token is not None and pageno <= 20:
            if token is not None and token != "":
                url = "%s&pageToken=%s" % (base, token)
            else:
                url = base
            response = requests.get(url)
            if response is not None and response.status_code == 200:
                data = json.loads(response.text)
                if data.get('nextPageToken') is not None:
                    token = data['nextPageToken']
                    pageno += 1
                else:
                    token = None
                if data.get('items') is not None:
                    for item in data['items']:
                        video = dict()
                        try:
                            if item['kind'] == "youtube#video":
                                video["id"] = item['id']
                                video["type"] = "video"
                                video[
                                    "url"] = 'https://www.youtube.com/watch?v=%s' % video[
                                        "id"]
                            elif item['kind'] == "youtube#searchResult":
                                if item['id']['kind'] == 'youtube#video':
                                    video["id"] = item['id']['videoId']
                                    video["type"] = "video"
                                    video[
                                        "url"] = 'https://www.youtube.com/watch?v=%s' % video[
                                            "id"]
                                elif item['id']['kind'] == 'youtube#channel':
                                    video["id"] = item['id']['channelId']
                                    video["type"] = "channel"
                                    video[
                                        "url"] = 'https://www.youtube.com/channel/%s' % video[
                                            "id"]
                                elif item['id']['kind'] == 'youtube#playlist':
                                    video["id"] = item['id']['playlistId']
                                    video["type"] = "playlist"
                                    video[
                                        "url"] = 'https://www.youtube.com/playlist?list=%s' % video[
                                            "id"]
                            elif item['kind'] == "youtube#channel":
                                video["id"] = item['id']
                                video["type"] = "channel"
                                video[
                                    "url"] = 'https://www.youtube.com/channel/%s' % video[
                                        "id"]
                            snippet = item["snippet"]
                            video["title"] = snippet['title']
                            if item['kind'] == "youtube#playlistItem" and snippet.get(
                                    'resourceId') is not None:
                                if snippet['resourceId'][
                                        'kind'] == 'youtube#video':
                                    video["id"] = snippet['resourceId'][
                                        'videoId']
                                    video["type"] = "video"
                                    video[
                                        "url"] = 'https://www.youtube.com/watch?v=%s' % video[
                                            "id"]
                            if snippet.get('thumbnails') is not None:
                                thumbnails = snippet['thumbnails']
                                if thumbnails.get('standard') is not None:
                                    video["thumb"] = thumbnails['standard'][
                                        'url']
                                elif thumbnails.get('high') is not None:
                                    video["thumb"] = thumbnails['high']['url']
                                elif thumbnails.get('medium') is not None:
                                    video["thumb"] = thumbnails['medium'][
                                        'url']
                                elif thumbnails.get('default') is not None:
                                    video["thumb"] = thumbnails['default'][
                                        'url']
                            if snippet.get('publishedAt') is not None:
                                video["date"] = snippet['publishedAt']
                            result.append(video)
                        except BaseException as ex:
                            commons.warn(
                                "Error extracting video from API list: %s" %
                                str(ex))
            else:
                token = None
    except ConnectionError as err:
        commons.error("Error connecting to API video list: %s" % str(err))
    return result
Exemplo n.º 14
0
 def error(self, text):
     commons.error(text)