示例#1
0
def root(plugin, content_type="video"):
    """
    :param Route plugin: The plugin parent object.
    :param str content_type: The type of content been listed e.g. video, music. This is passed in from kodi and
                             we have no use for it as of yet.
    """
    yield Listitem.recent(recent_videos)
    yield Listitem.from_dict(top_videos, plugin.localize(TOP_VIDEOS))
    yield Listitem.from_dict(watching_now, plugin.localize(WATCHING_NOW))
    yield Listitem.search(video_list)

    # Fetch HTML Source
    url = url_constructor("/mobile/category.html")
    resp = urlquick.get(url, headers={"Cookie": "COOKIE_DEVICE=mobile"})
    root_elem = resp.parse(u"ul", attrs={"id": "category_listing"})
    for elem in root_elem.iterfind("li"):
        a_tag = elem.find("a")
        item = Listitem()

        # Set label with video count added
        item.label = "%s (%s)" % (a_tag.text, elem.find("span").text)
        item.set_callback(video_list, cat=a_tag.get("href"))
        yield item

    # Add the video items here so that show at the end of the listing
    yield Listitem.from_dict(play_video, plugin.localize(VIDEO_OF_THE_DAY), params={"url": "index.html"})
    yield Listitem.from_dict(party_play, plugin.localize(PARTY_MODE), params={"url": "randomizer.php"})
示例#2
0
def root(plugin):
    yield Listitem.from_dict(
        **{
            "label": "Featured",
            "art": {
                "thumb": IMG_CATCHUP_SHOWS + "cms/TKSS_Carousal1.jpg",
                "icon": IMG_CATCHUP_SHOWS + "cms/TKSS_Carousal1.jpg",
                "fanart": IMG_CATCHUP_SHOWS + "cms/TKSS_Carousal1.jpg",
            },
            "callback": Route.ref("/resources/lib/main:show_featured")
        })
    for e in ["Genres", "Languages"]:
        yield Listitem.from_dict(
            **{
                "label": e,
                "art": {
                    "thumb": CONFIG[e][0].get("tvImg"),
                    "icon": CONFIG[e][0].get("tvImg"),
                    "fanart": CONFIG[e][0].get("promoImg"),
                },
                "callback": Route.ref("/resources/lib/main:show_listby"),
                "params": {
                    "by": e
                }
            })
示例#3
0
def root(plugin, content_type="video"):
    """
    :param Route plugin: The plugin parent object.
    :param str content_type: The type of content been listed e.g. video, music. This is passed in from kodi and
                             we have no use for it as of yet.
    """
    yield Listitem.recent(video_list, url="newvideos.html")
    yield Listitem.from_dict(top_videos, bold(plugin.localize(TOP_VIDEOS)))
    yield Listitem.from_dict(watching_now, bold(plugin.localize(WATCHING_NOW)))
    yield Listitem.search(search_videos)

    # Fetch HTML Source
    url = url_constructor("/browse.html")
    resp = urlquick.get(url)
    root_elem = resp.parse("div", attrs={"id": "primary"})
    for elem in root_elem.iterfind("ul/li"):
        img = elem.find(".//img")
        item = Listitem()

        # The image tag contains both the image url and title
        item.label = img.get("alt")
        item.art["thumb"] = img.get("src")

        url = elem.find("div/a").get("href")
        item.set_callback(video_list, url=url)
        yield item

    # Add the video items here so that show at the end of the listing
    bold_text = bold(plugin.localize(VIDEO_OF_THE_DAY))
    yield Listitem.from_dict(play_video,
                             bold_text,
                             params={"url": "/index.html"})
    yield Listitem.from_dict(party_play,
                             plugin.localize(PARTY_MODE),
                             params={"url": "/randomizer.php"})
示例#4
0
文件: addon.py 项目: camster1/RTOTV
def root(plugin, content_type):
    """
    :param Route plugin: The plugin parent object.
    :param str content_type: The type of content been listed e.g. video, music. This is passed in from kodi and
                             we have no use for it as of yet.
    """
    yield Listitem.recent(recent_videos)
    yield Listitem.from_dict(plugin.localize(TOP_VIDEOS), top_videos)
    yield Listitem.from_dict(plugin.localize(WATCHING_NOW), watching_now)
    yield Listitem.search(video_list)

    # Fetch HTML Source
    url = url_constructor("/mobile/category.html")
    html = plugin.request.get(url, headers={"Cookie": "COOKIE_DEVICE=mobile"})
    root_elem = html.parse(u"ul", attrs={"id": "category_listing"})
    for elem in root_elem.iterfind("li"):
        a_tag = elem.find("a")
        item = Listitem()

        # Set label with video count added
        item.label = "%s (%s)" % (a_tag.text, elem.find("span").text)
        item.set_callback(video_list, cat=a_tag.get("href"))
        yield item

    # Add the video items here so that show at the end of the listing
    yield Listitem.from_dict(plugin.localize(VIDEO_OF_THE_DAY), play_video, params={"url": "index.html"})
    yield Listitem.from_dict(plugin.localize(PARTY_MODE), party_play, params={"url": "randomizer.php"})
示例#5
0
def root(plugin, content_type="video"):
    """
    :param Route plugin: The plugin parent object.
    :param str content_type: The type of content been listed e.g. video, music. This is passed in from kodi and
                             we have no use for it as of yet.
    """
    yield Listitem.recent(video_list, url="newvideos.html")
    yield Listitem.from_dict(top_videos, bold(plugin.localize(TOP_VIDEOS)))
    yield Listitem.from_dict(watching_now, bold(plugin.localize(WATCHING_NOW)))
    yield Listitem.search(search_videos)

    # Fetch HTML Source
    url = url_constructor("/browse.html")
    resp = urlquick.get(url)
    root_elem = resp.parse("div", attrs={"id": "primary"})
    for elem in root_elem.iterfind("ul/li"):
        img = elem.find(".//img")
        item = Listitem()

        # The image tag contains both the image url and title
        item.label = img.get("alt")
        item.art["thumb"] = img.get("src")

        url = elem.find("div/a").get("href")
        item.set_callback(video_list, url=url)
        yield item

    # Add the video items here so that show at the end of the listing
    bold_text = bold(plugin.localize(VIDEO_OF_THE_DAY))
    yield Listitem.from_dict(play_video, bold_text, params={"url": "/index.html"})
    yield Listitem.from_dict(party_play, plugin.localize(PARTY_MODE), params={"url": "/randomizer.php"})
示例#6
0
def root(plugin):
    """:type plugin: Route"""
    # Set context parameters based on default view setting
    if plugin.setting.get_int("defaultview") == 0:
        context_label = plugin.localize(LIST_AUDIO)
        context_type = "segment"
        item_type = "video"
    else:
        context_label = plugin.localize(LIST_VIDEO)
        context_type = "video"
        item_type = "segment"

    # Fetch HTML Source
    url = "https://www.sciencefriday.com/explore/"
    html = plugin.request.get(url)

    # Parse for the content
    root_elem = html.parse("form", attrs={"class": "searchandfilter"})
    sfid = root_elem.get("data-sf-form-id")

    # Add Youtube & Recent Content
    yield Listitem.youtube("UUDjGU4DP3b-eGxrsipCvoVQ")

    # Add Recent Videos link
    yield Listitem.from_dict(label=plugin.localize(RECENT_VIDEOS),
                             callback=content_lister,
                             params={
                                 "sfid": sfid,
                                 "ctype": "video"
                             })
    # Add Recent Audio link
    yield Listitem.from_dict(label=plugin.localize(RECENT_AUDIO),
                             callback=content_lister,
                             params={
                                 "sfid": sfid,
                                 "ctype": "segment"
                             })

    # List all topics
    for elem in root_elem.iterfind(".//option[@data-sf-cr]"):
        item = Listitem()
        item.label = elem.text

        # Add context item to link to the opposite content type. e.g. audio if video is default
        item.context.container(context_label,
                               content_lister,
                               topic=elem.attrib["value"],
                               sfid=sfid,
                               ctype=context_type)
        item.set_callback(content_lister,
                          topic=elem.attrib["value"],
                          ctype=item_type,
                          sfid=sfid)
        yield item
示例#7
0
def show_epg(plugin, day, channel_id):
    resp = urlquick.get(CATCHUP_SRC.format(day, channel_id), max_age=-1).json()
    epg = sorted(
        resp['epg'], key=lambda show: show['startEpoch'], reverse=True)
    livetext = '[COLOR red] [ LIVE ] [/COLOR]'
    for each in epg:
        current_epoch = int(time()*1000)
        if not each['stbCatchupAvailable'] or each['startEpoch'] > current_epoch:
            continue
        islive = each['startEpoch'] < current_epoch and each['endEpoch'] > current_epoch
        showtime = '   '+livetext if islive else datetime.fromtimestamp(
            int(each['startEpoch']*.001)).strftime('    [ %I:%M %p -') + datetime.fromtimestamp(int(each['endEpoch']*.001)).strftime(' %I:%M %p ]   %a')
        yield Listitem.from_dict(**{
            "label": each['showname'] + showtime,
            "art": {
                'thumb': IMG_CATCHUP_SHOWS+each['episodePoster'],
                'icon': IMG_CATCHUP_SHOWS+each['episodePoster'],
                'fanart': IMG_CATCHUP_SHOWS+each['episodePoster'],
            },
            "callback": play,
            "info": {
                'title': each['showname'] + showtime,
                'originaltitle': each['showname'],
                "tvshowtitle": each['showname'],
                'genre': each['showGenre'],
                'plot': each['description'],
                "episodeguide": each.get("episode_desc"),
                'episode': 0 if each['episode_num'] == -1 else each['episode_num'],
                'cast': each['starCast'].split(', '),
                'director': each['director'],
                'duration': each['duration']*60,
                'tag': each['keywords'],
                'mediatype': 'episode',
            },
            "params": {
                "channel_id": each.get("channel_id"),
                "showtime": None if islive else each.get("showtime", "").replace(":", ""),
                "srno": None if islive else datetime.fromtimestamp(int(each.get("startEpoch", 0)*.001)).strftime('%Y%m%d')
            }
        })
    if int(day) == 0:
        for i in range(-1, -7, -1):
            label = 'Yesterday' if i == - \
                1 else (date.today() + timedelta(days=i)).strftime('%A %d %B')
            yield Listitem.from_dict(**{
                "label": label,
                "callback": Route.ref("/resources/lib/main:show_epg"),
                "params": {
                    "day": i,
                    "channel_id": channel_id
                }
            })
示例#8
0
 def buildMenu(self):
     for name, id in ROOT_CONFIG:
         yield Listitem.from_dict(**{
             "label": name,
             "callback": self.callbackRefs.get("menu_list"),
             "params": {"url": url_constructor("/apis/2ccce09e59153fc9/v1/plus-home/getget/%s/0" % id)}
         })
示例#9
0
def show_category(plugin, category_id, by):
    resp = urlquick.get(CHANNELS_SRC).json()

    def fltr(x):
        fby = by.lower()[:-1]
        if fby == "genre":
            return x.get(fby) == category_id and Settings.get_boolean(
                x.get("language"))
        else:
            return x.get(fby) == category_id

    for each in filter(fltr, resp):
        art = {
            "thumb": IMG_CATCHUP + each.get("default_logo"),
            "icon": IMG_CATCHUP + each.get("default_logo"),
            "fanart": IMG_CATCHUP + each.get("default_logo")
        }
        if each.get("icon"):
            art["thumb"] = art["icon"] = IMG_PUBLIC + each.get("icon")
        if each.get("fanart"):
            art["fanart"] = IMG_PUBLIC + each.get("fanart")
        litm = Listitem.from_dict(
            **{
                "label": each.get("name"),
                "art": art,
                "callback": PLAY_URL + each.get("data")
            })
        if each.get("isCatchupAvailable"):
            litm.context.container(show_epg, "Catchup", 0, each.get("id"),
                                   PLAY_URL + each.get("data"))
        yield litm
示例#10
0
def show_category(plugin, category_id, by):
    resp = urlquick.get(CHANNELS_SRC).json().get("result")

    def fltr(x):
        fby = by.lower()[:-1]
        if fby == "genre":
            return GENRE_MAP[x.get(
                "channelCategoryId")] == category_id and Settings.get_boolean(
                    LANG_MAP[x.get("channelLanguageId")])
        else:
            return LANG_MAP[x.get("channelLanguageId")] == category_id

    for each in filter(fltr, resp):
        litm = Listitem.from_dict(
            **{
                "label": each.get("channel_name"),
                "art": {
                    "thumb": IMG_CATCHUP + each.get("logoUrl"),
                    "icon": IMG_CATCHUP + each.get("logoUrl"),
                    "fanart": IMG_CATCHUP + each.get("logoUrl"),
                    "clearlogo": IMG_CATCHUP + each.get("logoUrl"),
                    "clearart": IMG_CATCHUP + each.get("logoUrl"),
                },
                "callback": play,
                "params": {
                    "channel_id": each.get("channel_id")
                }
            })
        if each.get("isCatchupAvailable"):
            litm.context.container(show_epg, "Catchup", 0,
                                   each.get("channel_id"))
        yield litm
示例#11
0
def root(plugin, content_type="video"):
    """
    :param Route plugin: The plugin parent object.
    :param str content_type: The type of content being listed e.g. video, music. This is passed in from kodi and
                             we have no use for it as of yet.
    """
    yield Listitem.recent(video_list, url="/newvideos.html")
    yield Listitem.from_dict(top_videos, bold(plugin.localize(TOP_VIDEOS)))
    yield Listitem.from_dict(video_list,
                             bold(plugin.localize(FEATURED)),
                             params={
                                 "url": "/index.html",
                                 "filter_mode": 2
                             })
    yield Listitem.search(search_videos)

    # List Categories
    resp = urlquick.get(url_constructor("/browse.html"))
    root_elem = resp.parse(
        "ul",
        attrs={"class": "pm-ul-browse-categories list-unstyled thumbnails"})
    for elem in root_elem.iterfind("li/div"):
        url_tag = elem.find("a")
        item = Listitem()

        item.label = url_tag.find("h3").text
        item.art["thumb"] = url_tag.find(".//img").get("src")
        url = url_tag.get("href")

        # Add Context menu item to sort by Views, Ratings and/or Title
        for sort in ("views", "rating", "title"):
            sort_url = url.replace("date.html", "{}.html".format(sort))
            item.context.container(video_list,
                                   "By {}".format(sort),
                                   url=sort_url)

        item.set_callback(video_list, url=url)
        yield item

    # Video of the day
    yield Listitem.from_dict(party_play,
                             plugin.localize(PARTY_MODE),
                             params={"url": "/index.html"})
示例#12
0
def show_listby(plugin, by):
    for each in CONFIG[by]:
        yield Listitem.from_dict(**{
            "label": each.get("name"),
            "art": {
                "thumb": each.get("tvImg"),
                "icon": each.get("tvImg"),
                "fanart": each.get("promoImg")
            },
            "callback": Route.ref("/resources/lib/main:show_category"),
            "params": {"category_id": each.get("name").replace(" ", ""), "by": by}
        })
示例#13
0
def root(plugin):
    headers = get_headers()
    if EMAIL and PASSWORD:
        profiles_data = urlquick.get(PROFILES_URL, headers=headers,
                                     max_age=0).json()
        pin = profiles_data['pinCode']
    else:
        pin = None
        avatar_k = urlquick.get(AVATAR_URL +
                                'kidsDefault').json()['avatars'][0]['url']
        id_k = ''.join(choice('0123456789abcdef-')
                       for n in range(36)).encode('utf-8')
        avatar_a = urlquick.get(AVATAR_URL +
                                'adultDefault').json()['avatars'][0]['url']
        id_a = ''.join(choice('0123456789abcdef-')
                       for n in range(36)).encode('utf-8')
        profiles_data = {
            'profiles': [{
                'type': 'ADULT',
                'default': True,
                'id': id_a,
                'name': plugin.localize(30302),
                "avatar": {
                    "url": formatimg(avatar_a, 'icon')
                }
            }, {
                'type': 'KID',
                'default': True,
                'name': plugin.localize(30301),
                'id': id_k,
                "avatar": {
                    "url": formatimg(avatar_k, 'icon')
                }
            }]
        }
    for profile in profiles_data['profiles']:
        profile_type = profile['type']
        if MODE_KIDS and profile_type != 'KID' and (not EMAIL or not PASSWORD):
            continue
        profile_id = profile['id']
        profile_name = profile['name'].title()
        is_master = profile['default']
        avatar = formatimg(profile['avatar']['url'], 'icon')
        yield Listitem.from_dict(sub_menu,
                                 bold(profile_name),
                                 art={"thumb": avatar},
                                 params={
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'pin': pin,
                                     'is_master': is_master
                                 })
示例#14
0
def root(plugin):
    """:type plugin: Route"""
    # Set context parameters based on default view setting
    if plugin.setting.get_int("defaultview") == 0:
        context_label = plugin.localize(LIST_AUDIO)
        context_type = "segment"
        item_type = "video"
    else:
        context_label = plugin.localize(LIST_VIDEO)
        context_type = "video"
        item_type = "segment"

    # Fetch HTML Source
    url = "https://www.sciencefriday.com/explore/"
    html = urlquick.get(url)

    # Parse for the content
    root_elem = html.parse("form", attrs={"class": "searchandfilter"})
    sfid = root_elem.get("data-sf-form-id")

    # Add Youtube & Recent Content
    yield Listitem.youtube("UCDjGU4DP3b-eGxrsipCvoVQ")

    # Add Recent Videos link
    yield Listitem.from_dict(content_lister, plugin.localize(RECENT_VIDEOS),
                             params={"sfid": sfid, "ctype": "video"})
    # Add Recent Audio link
    yield Listitem.from_dict(content_lister, plugin.localize(RECENT_AUDIO),
                             params={"sfid": sfid, "ctype": "segment"})

    # List all topics
    for elem in root_elem.iterfind(".//option[@data-sf-cr]"):
        item = Listitem()
        item.label = elem.text

        # Add context item to link to the opposite content type. e.g. audio if video is default
        item.context.container(content_lister, context_label, topic=elem.attrib["value"], sfid=sfid, ctype=context_type)
        item.set_callback(content_lister, topic=elem.attrib["value"], ctype=item_type, sfid=sfid)
        yield item
示例#15
0
def __get_categories():
    items = []
    html = urlquick.get(url_constructor('/show'))
    document = html.parse('select', attrs={'id': 'filter-category'})
    for option in document.iterfind('optgroup/option'):
        category_id = option.get('value')
        if category_id == '0':
            continue
        items.append(
            Listitem.from_dict(tvshow_category,
                               option.text,
                               params={'category_id': category_id}))
    return items
示例#16
0
def favourites(plugin, start=0, **kwargs):
    """Build 'favourites' menu of the addon ('favourites' menu callback function)

    Args:
        plugin (codequick.script.Script)
        start (int): Index of the menu starting item (multiple pages support)
        **kwargs: Arbitrary keyword arguments
    Returns:
        Iterator[codequick.listing.Listitem]: Kodi 'favourites' menu
    """

    # Get sorted items
    sorted_menu = []
    fav_dict = fav.get_fav_dict_from_json()
    menu = []
    for item_hash, item_dict in list(fav_dict['items'].items()):
        item = (item_dict['params']['order'], item_hash, item_dict)
        menu.append(item)

    # We sort the menu according to the item_order values
    sorted_menu = sorted(menu, key=lambda x: x[0])

    # Notify the user if there is no item in favourites
    if len(sorted_menu) == 0:
        Script.notify(Script.localize(30033), Script.localize(30806), display_time=7000)
        yield False

    # Add each item in the listing
    cnt = 0

    for index, (item_order, item_hash, item_dict) in enumerate(sorted_menu):
        if index < start:
            continue

        # If more thant 30 items add a new page
        if cnt == 30:
            yield Listitem().next_page(start=index)
            break

        cnt += 1

        item_dict['params']['from_fav'] = True
        item_dict['params']['item_hash'] = item_hash

        try:
            # Build item from dict
            item = Listitem.from_dict(**item_dict)

            # Generate a valid callback
            url = build_kodi_url(item_dict['callback'], item_dict['params'])
            item.set_callback(url, is_folder=item_dict['params']['is_folder'], is_playbale=item_dict['params']['is_playable'])
示例#17
0
def root(plugin):
    for e in ["Genres", "Languages"]:
        yield Listitem.from_dict(
            **{
                "label": e,
                "art": {
                    "thumb": CONFIG[e][0].get("tvImg"),
                    "icon": CONFIG[e][0].get("tvImg"),
                    "fanart": CONFIG[e][0].get("promoImg"),
                },
                "callback": show_listby,
                "params": {
                    "by": e
                }
            })
示例#18
0
def root(_):
    """
    Lists all categories and link's to 'Shows', 'MsMojo' and 'All videos'.
    site: http://www.watchmojo.com
    """
    # Add links to watchmojo youtube channels
    yield Listitem.youtube("UCaWd5_7JhbQBe4dknZhsHJg")  # WatchMojo
    yield Listitem.search(search_results)
    yield Listitem.youtube("UCMm0YNfHOCA-bvHmOBSx-ZA", label="WatchMojo UK")
    yield Listitem.youtube("UC9_eukrzdzY91jjDZm62FXQ", label="MojoTravels")
    yield Listitem.youtube("UC4HnC-AS714lT2TCTJ-A1zQ", label="MojoPlays")
    yield Listitem.youtube("UC88y_sxutS1mnoeBDroS74w", label="MojoTalks")
    yield Listitem.youtube("UC3rLoj87ctEHCcS7BuvIzkQ", label="MsMojo")
    yield Listitem.youtube("UCYJyrEdlwxUu7UwtFS6jA_Q", label="UnVeiled")

    source = urlquick.get(BASE_URL)
    root_elem = source.parse()

    # Find each category and fetch the image for the first video in the list
    for elem in root_elem.iterfind("./body/section/div[@class='line']"):
        # If we have a 'link' tag with class=more, then we are in the right section
        tag = elem.find("a[@class='more']")
        if tag is not None:
            url = tag.get("href")
            # Only list category entrys
            if url.startswith("/categories"):
                item = Listitem()

                item.label = elem.find("h2").text.strip().title()
                item.art["thumb"] = url_constructor(elem.find(".//img").get("src"))
                item.set_callback(video_list, url=url)
                yield item

    # Add link to exclusive watchmojo video
    yield Listitem.from_dict(video_list, "Exclusive", params={"url": "/exclusive/1"},
                             art={"thumb": "https://www.watchmojo.com/uploads/blipthumbs/Fi-M-Top10-Well-"
                                           "Regarded-Controversial-Films_R7D2Y7-720p30-C_480.jpg"})
示例#19
0
def content_lister(plugin, sfid, ctype, topic=None, page_count=1):
    """
    :type plugin: Route
    :type sfid: unicode
    :type ctype: unicode
    :type topic: unicode
    :type page_count: int
    """
    # Add link to Alternitve Listing
    if page_count == 1 and topic:
        params = {"_updatelisting_": True, "sfid": sfid, "topic": topic,
                  "ctype": u"segment" if ctype == u"video" else u"video"}
        label = plugin.localize(LIST_AUDIO) if ctype == u"video" else plugin.localize(LIST_VIDEO)
        item_dict = {"label": label, "callback": content_lister, "params": params}
        yield Listitem.from_dict(**item_dict)

    # Create content url
    if topic:
        url = "https://www.sciencefriday.com/wp-admin/admin-ajax.php?action=get_results&paged=%(next)s&" \
              "sfid=%(sfid)s&post_types=%(ctype)s&_sft_topic=%(topic)s" % \
              {"sfid": sfid, "ctype": ctype, "topic": topic, "next": page_count}
    else:
        url = "https://www.sciencefriday.com/wp-admin/admin-ajax.php?action=get_results&paged=%(next)s&" \
              "sfid=%(sfid)s&post_types=%(ctype)s" % \
              {"sfid": sfid, "ctype": ctype, "next": page_count}

    # Fetch & parse HTML Source
    ishd = bool(plugin.setting.get_int("video_quality", addon_id="script.module.youtube.dl"))
    root_elem = urlquick.get(url).parse()

    # Fetch next page
    next_url = root_elem.find(".//a[@rel='next']")
    if next_url is not None:  # pragma: no branch
        yield Listitem.next_page(sfid=sfid, ctype=ctype, page_count=page_count+1)

    # Parse the elements
    for element in root_elem.iterfind(".//article"):
        tag_a = element.find(".//a[@rel='bookmark']")
        item = Listitem()
        item.label = tag_a.text
        item.stream.hd(ishd)

        # Fetch plot & duration
        tag_p = element.findall(".//p")
        if tag_p and tag_p[0].get("class") == "run-time":
            item.info["duration"] = tag_p[0].text
            item.info["plot"] = tag_p[1].text
        elif tag_p:  # pragma: no branch
            item.info["plot"] = tag_p[0].text

        # Fetch image if exists
        img = element.find(".//img[@data-src]")
        if img is not None:
            item.art["thumb"] = img.get("data-src")

        # Fetch audio/video url
        tag_audio = element.find(".//a[@data-audio]")
        if tag_audio is not None:
            audio_url = tag_audio.get("data-audio")
            item.set_callback(audio_url)
        else:
            item.set_callback(play_video, url=tag_a.get("href"))

        yield item
示例#20
0
文件: main.py 项目: akuala/repo.kuala
def favourites(plugin, start=0, **kwargs):
    """Build 'favourites' menu of the addon ('favourites' menu callback function)

    Args:
        plugin (codequick.script.Script)
        start (int): Index of the menu starting item (multiple pages support)
        **kwargs: Arbitrary keyword arguments
    Returns:
        Iterator[codequick.listing.Listitem]: Kodi 'favourites' menu
    """

    # Get sorted items
    sorted_menu = []
    fav_dict = fav.get_fav_dict_from_json()
    menu = []
    for item_hash, item_dict in list(fav_dict.items()):
        item = (item_dict['params']['order'], item_hash, item_dict)
        menu.append(item)

    # We sort the menu according to the item_order values
    sorted_menu = sorted(menu, key=lambda x: x[0])

    # Notify the user if there is not item in favourites
    if len(sorted_menu) == 0:
        Script.notify(Script.localize(30033), Script.localize(30806), display_time=7000)
        yield False

    # Add each item in the listing
    cnt = 0

    for index, (item_order, item_hash, item_dict) in enumerate(sorted_menu):
        if index < start:
            continue

        # If more thant 30 items add a new page
        if cnt == 30:
            yield Listitem().next_page(start=index)
            break

        cnt += 1
        # Listitem.from_dict fails with subtitles
        # See https://github.com/willforde/script.module.codequick/issues/30
        if 'subtitles' in item_dict:
            item_dict.pop('subtitles')

        # Listitem.from_dict only works if context is a list
        if 'context' in item_dict and not isinstance(item_dict['context'], list):
            item_dict.pop('context')

        # Remove original move and hide contexts:
        if 'context' in item_dict:
            new_context = []
            for context in item_dict['context']:
                if 'move_item' not in context[1] and 'hide' not in context[1]:
                    new_context.append(context)
            item_dict['context'] = new_context

        item_dict['params']['from_fav'] = True
        item_dict['params']['item_hash'] = item_hash

        item = Listitem.from_dict(**item_dict)
        url = build_kodi_url(item_dict['callback'], item_dict['params'])

        item.set_callback(url)

        item.is_folder = item_dict['params']['is_folder']
        item.is_playbale = item_dict['params']['is_playable']

        # Rename
        item.context.script(fav.rename_favourite_item,
                            plugin.localize(LABELS['Rename']),
                            item_hash=item_hash)

        # Remove
        item.context.script(fav.remove_favourite_item,
                            plugin.localize(LABELS['Remove']),
                            item_hash=item_hash)

        # Move up
        if item_dict['params']['order'] > 0:
            item.context.script(fav.move_favourite_item,
                                plugin.localize(LABELS['Move up']),
                                direction='up',
                                item_hash=item_hash)

        # Move down
        if item_dict['params']['order'] < len(fav_dict) - 1:
            item.context.script(fav.move_favourite_item,
                                plugin.localize(LABELS['Move down']),
                                direction='down',
                                item_hash=item_hash)

        yield item
示例#21
0
def show_page(plugin, show_id):
    html = urlquick.get(url_constructor('/show/{}'.format(show_id)))
    document = html.parse('div', attrs={'class': 'container main-container'})
    title = document.find('.//div[@id="h-show-title"]')
    if title is not None:
        all_seasons_item = Listitem()
        all_seasons_item.art['thumb'] = __get_poster_url(show_id)

        title = bold(title.text)
        title_original = document.find(
            './/div[@class="app-show-header-title-original"]').text
        all_seasons_item.label = __replace_html_codes('&emsp;'.join(
            [title, 'Все сезоны']))
        years = ''.join(
            document.find('.//div[@class="app-show-header-years"]').itertext())
        genres = filter(
            None,
            map(__clear_tvshow_tags,
                document.findall('.//ul[@class="app-show-tags"]/li/a')))
        country = document.find(
            './/ul[@class="app-show-tags"]/li/a[@class="app-show-tags-flag"]')
        country = country.text if country is not None else 'un'
        description = __replace_html_codes(
            document.find('.//p[@class="app-show-description"]').text)

        seasons = []
        for season_block in document.iterfind(
                './/section[@class="app-show-seasons-section-light hidden"]'):
            season = {'title': '', 'episodes': []}
            season['title'] = season_block.find('.//h3').text

            for link in season_block.iterfind('.//div/ul/li/a'):
                episode_id = link.get('id')[31:]
                season['episodes'].append(episode_id)
            seasons.append(season)
            # Script.log(season_number, lvl=Script.ERROR)
            # Script.log(episode_number, lvl=Script.ERROR)

        plot = [__format_join('[CR]', [title, title_original]), description]
        all_seasons_item.info['plot'] = '[CR][CR]'.join(plot)

        episodes_ids = []
        seasons_items = []
        for season in seasons:
            item = Listitem()
            episodes_count = len(season['episodes'])
            item.label = __replace_html_codes('&emsp;'.join(
                [bold(season['title']), '({})'.format(episodes_count)]))
            item.art['thumb'] = __get_poster_url(show_id)
            plot = [
                title, season['title'], 'Эпизодов: {}'.format(episodes_count)
            ]
            item.info['plot'] = '[CR][CR]'.join(plot)
            item.set_callback(tvshow_episodes,
                              episodes_ids=season['episodes'],
                              show_id=show_id)
            episodes_ids.extend(season['episodes'])
            seasons_items.append(item)

        all_seasons_item.set_callback(tvshow_episodes,
                                      episodes_ids=episodes_ids,
                                      show_id=show_id)
        yield all_seasons_item

        mix_playlist = episodes_ids[:]
        random.shuffle(mix_playlist)
        yield Listitem.from_dict(
            play_episodes_mix,
            'Микс',
            art={'thumb': __get_poster_url(show_id)},
            info={'plot': 'Воспроизвести в случайном порядке'},
            params={'episodes_ids': mix_playlist})

        for item in seasons_items:
            yield item
示例#22
0
def show_featured(plugin, id=None):
    resp = urlquick.get(FEATURED_SRC,
                        headers={
                            "usergroup": "tvYR7NSNn7rymo3F",
                            "os": "android",
                            "devicetype": "phone",
                            "versionCode": "226"
                        },
                        max_age=-1).json()
    for each in resp.get("featuredNewData", []):
        if id:
            if int(each.get("id", 0)) == int(id):
                data = each.get("data", [])
                for child in data:
                    info_dict = {
                        "art": {
                            "thumb":
                            IMG_CATCHUP_SHOWS + child.get("episodePoster", ""),
                            "icon":
                            IMG_CATCHUP_SHOWS + child.get("episodePoster", ""),
                            "fanart":
                            IMG_CATCHUP_SHOWS + child.get("episodePoster", ""),
                            "clearart":
                            IMG_CATCHUP + child.get("logoUrl", ""),
                            "clearlogo":
                            IMG_CATCHUP + child.get("logoUrl", ""),
                        },
                        "info": {
                            'originaltitle':
                            child.get("showname"),
                            "tvshowtitle":
                            child.get("showname"),
                            "genre":
                            child.get("showGenre"),
                            "plot":
                            child.get("description"),
                            "episodeguide":
                            child.get("episode_desc"),
                            "episode":
                            0 if child.get("episode_num") == -1 else
                            child.get("episode_num"),
                            "cast":
                            child.get("starCast", "").split(', '),
                            "director":
                            child.get("director"),
                            "duration":
                            child.get("duration") * 60,
                            "tag":
                            child.get("keywords"),
                            "mediatype":
                            "movie" if child.get("channel_category_name")
                            == "Movies" else "episode",
                        }
                    }
                    if child.get("showStatus") == "Now":
                        info_dict[
                            "label"] = info_dict["info"]["title"] = child.get(
                                "showname",
                                "") + " [COLOR red] [ LIVE ] [/COLOR]"
                        info_dict["callback"] = play
                        info_dict["params"] = {
                            "channel_id": child.get("channel_id")
                        }
                        yield Listitem.from_dict(**info_dict)
                    elif child.get("showStatus") == "future":
                        timetext = datetime.fromtimestamp(
                            int(child.get("startEpoch", 0) * .001)).strftime(
                                '    [ %I:%M %p -') + datetime.fromtimestamp(
                                    int(child.get("endEpoch", 0) *
                                        .001)).strftime(' %I:%M %p ]   %a')
                        info_dict["label"] = info_dict["info"][
                            "title"] = child.get("showname", "") + (
                                " [COLOR green]%s[/COLOR]" % timetext)
                        info_dict["callback"] = ""
                        yield Listitem.from_dict(**info_dict)
                    elif child.get("showStatus") == "catchup":
                        timetext = datetime.fromtimestamp(
                            int(child.get("startEpoch", 0) * .001)).strftime(
                                '    [ %I:%M %p -') + datetime.fromtimestamp(
                                    int(child.get("endEpoch", 0) *
                                        .001)).strftime(' %I:%M %p ]   %a')
                        info_dict["label"] = info_dict["info"][
                            "title"] = child.get("showname", "") + (
                                " [COLOR yellow]%s[/COLOR]" % timetext)
                        info_dict["callback"] = play
                        info_dict["params"] = {
                            "channel_id":
                            child.get("channel_id"),
                            "showtime":
                            child.get("showtime", "").replace(":", ""),
                            "srno":
                            datetime.fromtimestamp(
                                int(child.get("startEpoch", 0) *
                                    .001)).strftime('%Y%m%d')
                        }
                        yield Listitem.from_dict(**info_dict)
        else:
            yield Listitem.from_dict(
                **{
                    "label": each.get("name"),
                    "art": {
                        "thumb":
                        IMG_CATCHUP_SHOWS +
                        each.get("data", [{}])[0].get("episodePoster"),
                        "icon":
                        IMG_CATCHUP_SHOWS +
                        each.get("data", [{}])[0].get("episodePoster"),
                        "fanart":
                        IMG_CATCHUP_SHOWS +
                        each.get("data", [{}])[0].get("episodePoster"),
                    },
                    "callback": Route.ref("/resources/lib/main:show_featured"),
                    "params": {
                        "id": each.get("id")
                    }
                })
示例#23
0
def root(plugin, content_type="video"):
    yield Listitem.search(search)
    yield Listitem.from_dict(last_added, bold('Последние поступления'))
    categories = __get_categories()
    for category in categories:
        yield category
示例#24
0
def content_lister(plugin, sfid, ctype, topic=None, page_count=1):
    """
    :type plugin: Route
    :type sfid: unicode
    :type ctype: unicode
    :type topic: unicode
    :type page_count: int
    """
    # Add link to Alternitve Listing
    if page_count == 1 and topic:
        params = {
            "sfid": sfid,
            "ctype": u"segment" if ctype == u"video" else u"video",
            "topic": topic
        }
        label = plugin.localize(
            LIST_AUDIO) if ctype == u"video" else plugin.localize(LIST_VIDEO)
        item_dict = {
            "label": label,
            "callback": content_lister,
            "params": params
        }
        yield Listitem.from_dict(**item_dict)

    # Create content url
    if topic:
        url = "https://www.sciencefriday.com/wp-admin/admin-ajax.php?action=get_results&paged=%(next)s&" \
              "sfid=%(sfid)s&post_types=%(ctype)s&_sft_topic=%(topic)s" % \
              {"sfid": sfid, "ctype": ctype, "topic": topic, "next": page_count}
    else:
        url = "https://www.sciencefriday.com/wp-admin/admin-ajax.php?action=get_results&paged=%(next)s&" \
              "sfid=%(sfid)s&post_types=%(ctype)s" % \
              {"sfid": sfid, "ctype": ctype, "next": page_count}

    # Fetch & parse HTML Source
    ishd = bool(
        plugin.setting.get_int("video_quality",
                               addon_id="script.module.youtube.dl"))
    root_elem = plugin.request.get(url).parse()

    # Fetch next page
    next_url = root_elem.find(".//a[@rel='next']")
    if next_url is not None:
        yield Listitem.next_page(sfid=sfid,
                                 ctype=ctype,
                                 page_count=page_count + 1)

    # Parse the elements
    for element in root_elem.iterfind(".//article"):
        tag_a = element.find(".//a[@rel='bookmark']")
        item = Listitem()
        item.label = tag_a.text
        item.stream.hd(ishd)

        # Fetch plot & duration
        tag_p = element.findall(".//p")
        if tag_p and tag_p[0].get("class") == "run-time":
            item.info["duration"] = tag_p[0].text
            item.info["plot"] = tag_p[1].text
        elif tag_p:
            item.info["plot"] = tag_p[0].text

        # Fetch image if exists
        img = element.find(".//img[@data-src]")
        if img is not None:
            item.art["thumb"] = img.get("data-src")

        # Fetch audio/video url
        tag_audio = element.find(".//a[@data-audio]")
        if tag_audio is not None:
            audio_url = tag_audio.get("data-audio")
            item.set_callback(audio_url)
        else:
            item.set_callback(play_video, url=tag_a.get("href"))

        yield item
示例#25
0
def root(plugin, content_type="segment"):

    HomeItems = {
        "label": "Home",
        "info": {
            "plot": "Watch Telugu Movies From AHA.video"
        },
        "art": {
            "thumb":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png",
            "fanart":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png"
        },
        "callback": list_home_content
    }

    MoviesItem = {
        "label": "Curated Movies",
        "info": {
            "plot": "Watch Telugu Movies From AHA.video"
        },
        "art": {
            "thumb":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png",
            "fanart":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png"
        },
        "callback": list_curated_movies
    }

    ShowsItem = {
        "label": "Curated Shows",
        "info": {
            "plot": "Watch Telugu Shows From AHA.video"
        },
        "art": {
            "thumb":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png",
            "fanart":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png"
        },
        "callback": list_curated_shows
    }

    AllMoviesItem = {
        "label": "All Movies",
        "info": {
            "plot": "Watch Telugu Movies From AHA.video"
        },
        "art": {
            "thumb":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png",
            "fanart":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png"
        },
        "callback": list_all_movies
    }

    AllShowsItem = {
        "label": "All Shows",
        "info": {
            "plot": "Watch AHA Original & Shows"
        },
        "art": {
            "thumb":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png",
            "fanart":
            "https://appcmsprod.viewlift.com/38c1e2aa-64c1-41c3-8b5e-674247d490c8/images/aha_logo.png"
        },
        "callback": list_all_shows
    }

    yield Listitem.from_dict(**HomeItems)
    yield Listitem.from_dict(**MoviesItem)
    yield Listitem.from_dict(**ShowsItem)
    yield Listitem.from_dict(**AllMoviesItem)
    yield Listitem.from_dict(**AllShowsItem)
    yield Listitem.search(search_content)
示例#26
0
 def buildSettings(self):
     return Listitem.from_dict(Route.ref("/resources/lib/main:settings"), "Settings")
示例#27
0
def show_epg(plugin, day, channel_id, live_url=""):
    resp = urlquick.get(CATCHUP_SRC.format(day, channel_id)).json()
    epg = sorted(resp['epg'],
                 key=lambda show: show['startEpoch'],
                 reverse=True)
    livetext = '[COLOR red][B][ LIVE ][/B][/COLOR]'
    items = []
    for each in epg:
        current_epoch = int(time() * 1000)
        if not each[
                'stbCatchupAvailable'] or each['startEpoch'] > current_epoch:
            continue
        islive = each['startEpoch'] < current_epoch and each[
            'endEpoch'] > current_epoch
        showtime = '   ' + livetext if islive else datetime.fromtimestamp(
            int(each['startEpoch'] *
                .001)).strftime('    [ %I:%M %p -') + datetime.fromtimestamp(
                    int(each['endEpoch'] * .001)).strftime(' %I:%M %p ]   %a')
        timestr = datetime.fromtimestamp(int(each.get("startEpoch", 0) *
                                             .001)).strftime('%d_%m_%y_%H_%M')
        yield Listitem.from_dict(
            **{
                "label": each['showname'] + showtime,
                "art": {
                    'thumb': IMG_CATCHUP_SHOWS + each['episodePoster'],
                    'icon': IMG_CATCHUP_SHOWS + each['episodePoster'],
                    'fanart': IMG_CATCHUP_SHOWS + each['episodePoster'],
                },
                "callback": live_url if islive else play,
                "info": {
                    'title':
                    each['showname'] + showtime,
                    'originaltitle':
                    each['showname'],
                    "tvshowtitle":
                    each['showname'],
                    'genre':
                    each['showGenre'],
                    'plot':
                    each['description'],
                    "episodeguide":
                    each.get("episode_desc"),
                    'episode':
                    0 if each['episode_num'] == -1 else each['episode_num'],
                    'cast':
                    each['starCast'].split(', '),
                    'director':
                    each['director'],
                    'duration':
                    each['duration'] * 60,
                    'tag':
                    each['keywords'],
                    'mediatype':
                    'episode',
                },
                "params": {
                    "dt": {
                        "proto":
                        "hls",
                        "pUrl":
                        CATCHUP_PLAY.format(
                            resp['logoUrl'][:-4], timestr,
                            urlencode(
                                ChannelRequestHandler.getTokenParams(6000))),
                        "lUrl":
                        "{TOKEN}|{HEADERS}|R{SSM}|",
                        "hdrs":
                        "User-Agent=Jiotv"
                    }
                }
            })
    if int(day) == 0:
        for i in range(-1, -7, -1):
            label = 'Yesterday' if i == - \
                1 else (date.today() + timedelta(days=i)).strftime('%A %d %B')
            yield Listitem.from_dict(
                **{
                    "label": label,
                    "callback": show_epg,
                    "params": {
                        "day": i,
                        "channel_id": channel_id
                    }
                })
示例#28
0
def favourites(plugin, start=0, **kwargs):
    """
    Callback function called when the user enter in the
    favourites folder
    """

    # Get sorted items
    sorted_menu = []
    with storage.PersistentDict("favourites.pickle") as db:
        menu = []
        for item_hash, item_dict in db.items():
            item = (item_dict['params']['order'], item_hash, item_dict)

            menu.append(item)

        # We sort the menu according to the item_order values
        sorted_menu = sorted(menu, key=lambda x: x[0])

    # Notify the user if there is not item in favourites
    if len(sorted_menu) == 0:
        Script.notify(Script.localize(30033),
                      Script.localize(30806),
                      display_time=7000)
        yield False

    # Add each item in the listing
    cnt = 0
    for index, (item_order, item_hash, item_dict) in enumerate(sorted_menu):
        if index < start:
            continue

        # If more thant 30 items add a new page
        if cnt == 30:
            yield Listitem().next_page(start=index)
            break

        cnt += 1
        # Listitem.from_dict fails with this
        item_dict.pop('subtitles')
        item_dict.pop('context')

        item_dict['params']['from_fav'] = True
        item_dict['params']['item_hash'] = item_hash

        item = Listitem.from_dict(**item_dict)
        url = cqu.build_kodi_url(item_dict['callback'], item_dict['params'])

        item.set_callback(url)

        item.is_folder = item_dict['params']['is_folder']
        item.is_playbale = item_dict['params']['is_playable']

        # Hack for the rename feature
        item.label = item_dict['label']

        # Rename
        item.context.script(fav.rename_favourite_item,
                            plugin.localize(LABELS['Rename']),
                            item_hash=item_hash)

        # Remove
        item.context.script(fav.remove_favourite_item,
                            plugin.localize(LABELS['Remove']),
                            item_hash=item_hash)

        # Move up
        if item_dict['params']['order'] > 0:
            item.context.script(fav.move_favourite_item,
                                plugin.localize(LABELS['Move up']),
                                direction='up',
                                item_hash=item_hash)

        # Move down
        if item_dict['params']['order'] < len(db) - 1:
            item.context.script(fav.move_favourite_item,
                                plugin.localize(LABELS['Move down']),
                                direction='down',
                                item_hash=item_hash)

        yield item
示例#29
0
def sub_menu(plugin, profile_id, profile_type, is_master, pin):
    if profile_type == 'KID':
        plugin.log('Creating Kids Menu', lvl=plugin.WARNING)
        # get kids user id

        yield Listitem.from_dict(LIVE_TV,
                                 bold(plugin.localize(30101)),
                                 params={
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'is_master': is_master
                                 })
        yield Listitem.from_dict(BROWSE_TVSHOWS,
                                 bold(plugin.localize(30102)),
                                 params={
                                     "genreId": "",
                                     "productSubType": "SERIES",
                                     "page": 0,
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'is_master': is_master
                                 })
        yield Listitem.from_dict(BROWSE_TVSHOWS,
                                 bold(plugin.localize(30103)),
                                 params={
                                     "genreId": "",
                                     "productSubType": "PROGRAM",
                                     "page": 0,
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'is_master': is_master
                                 })
        yield Listitem.from_dict(BROWSE_MOVIES,
                                 bold(plugin.localize(30104)),
                                 params={
                                     'genreId': '',
                                     'page': 0,
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'is_master': is_master
                                 })
        yield Listitem.search(SEARCH_CONTENT,
                              profile_id=profile_id,
                              profile_type=profile_type,
                              is_master=is_master)
    else:
        if MODE_KIDS:
            user_input = keyboard("Enter your PIN Code", "", True)
            if user_input != pin:
                plugin.notify(plugin.localize(30202),
                              plugin.localize(30201),
                              display_time=5000,
                              sound=True)
                yield False
                return
        plugin.log('Creating Main Menu', lvl=plugin.WARNING)
        yield Listitem.from_dict(LIVE_TV,
                                 bold(plugin.localize(30101)),
                                 params={
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'is_master': is_master
                                 })
        yield Listitem.from_dict(CATEGORIES,
                                 bold(plugin.localize(30102)),
                                 params={
                                     "productSubType": "SERIES",
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'is_master': is_master
                                 })
        yield Listitem.from_dict(CATEGORIES,
                                 bold(plugin.localize(30103)),
                                 params={
                                     "productSubType": "PROGRAM",
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'is_master': is_master
                                 })
        yield Listitem.from_dict(CATEGORIES_M,
                                 bold(plugin.localize(30104)),
                                 params={
                                     'profile_id': profile_id,
                                     'profile_type': profile_type,
                                     'is_master': is_master
                                 })
        if EMAIL and PASSWORD:
            yield Listitem.from_dict(MY_LIST,
                                     bold(plugin.localize(30105)),
                                     params={
                                         'profile_id': profile_id,
                                         'profile_type': profile_type,
                                         'is_master': is_master
                                     })
        yield Listitem.search(SEARCH_CONTENT,
                              profile_id=profile_id,
                              profile_type=profile_type,
                              is_master=is_master)