コード例 #1
0
ファイル: systemtools.py プロジェクト: stick141/modules4all
def Sleep_If_Window_Active(window_type=10147):
    """
This will allow you to pause code while a specific window is open.

CODE: Sleep_If_Window_Active(window_type)

AVAILABLE PARAMS:

    window_type  -  This is the window xml name you want to check for, if it's
    active then the code will sleep until it becomes inactive. By default this
    is set to the custom text box (10147). You can find a list of window ID's
    here: http://kodi.wiki/view/Window_IDs

EXAMPLE CODE:
koding.Text_Box('EXAMPLE TEXT','This is just an example, normally a text box would not pause code and the next command would automatically run immediately over the top of this.')
koding.Sleep_If_Window_Active(10147) # This is the window id for the text box
dialog.ok('WINDOW CLOSED','The window has now been closed so this dialog code has now been initiated')
~"""
    from __init__ import dolog
    windowactive = False
    counter      = 0

    if window_type == 'yesnodialog' or window_type == 10100:
        count = 30
    else:
        count = 10
    
    okwindow = False

# Do not get stuck in an infinite loop. Check x amount of times and if condition isn't met after x amount it quits
    while not okwindow and counter < count:
        xbmc.sleep(100)
        dolog('### %s not active - sleeping (%s)' % (window_type, counter))
        okwindow = xbmc.getCondVisibility('Window.IsActive(%s)' % window_type)
        counter += 1

# Window is active
    while okwindow:
        okwindow = xbmc.getCondVisibility('Window.IsActive(%s)' % window_type)
        xbmc.sleep(250)

    return okwindow
コード例 #2
0
ファイル: systemtools.py プロジェクト: smoke61/modules4all
def Sleep_If_Window_Active(window_type=10147):
    """
This will allow you to pause code while a specific window is open.

CODE: Sleep_If_Window_Active(window_type)

AVAILABLE PARAMS:

    window_type  -  This is the window xml name you want to check for, if it's
    active then the code will sleep until it becomes inactive. By default this
    is set to the custom text box (10147). You can find a list of window ID's
    here: http://kodi.wiki/view/Window_IDs

EXAMPLE CODE:
koding.Text_Box('EXAMPLE TEXT','This is just an example, normally a text box would not pause code and the next command would automatically run immediately over the top of this.')
koding.Sleep_If_Window_Active(10147) # This is the window id for the text box
dialog.ok('WINDOW CLOSED','The window has now been closed so this dialog code has now been initiated')
~"""
    from __init__ import dolog
    windowactive = False
    counter = 0

    if window_type == 'yesnodialog' or window_type == 10100:
        count = 30
    else:
        count = 10

    okwindow = False

    # Do not get stuck in an infinite loop. Check x amount of times and if condition isn't met after x amount it quits
    while not okwindow and counter < count:
        xbmc.sleep(100)
        dolog('### %s not active - sleeping (%s)' % (window_type, counter))
        okwindow = xbmc.getCondVisibility('Window.IsActive(%s)' % window_type)
        counter += 1

# Window is active
    while okwindow:
        okwindow = xbmc.getCondVisibility('Window.IsActive(%s)' % window_type)
        xbmc.sleep(250)

    return okwindow
コード例 #3
0
ファイル: directory.py プロジェクト: stick141/modules4all
def Populate_List(url, start_point=r'<li+.<a href="', end_point=r'</a+.</li>', separator = r">", skip=['..','.','Parent Directory']):
    """
If you have a basic index web page or a webpage with a common
format for displaying links (on all pages) then you can use this
to populate an add-on. It's capable of cleverly working out what
needs to be sent through as a directory and what's a playable item.

CODE: Populate_List(url, [start_point, end_point, separator, skip]):

AVAILABLE PARAMS:

    (*) url  -  The start page of where to pull the first links from

    start_point  -  Send through the code tags you want to search for in the
    webpage. By default it's setup for a standard indexed site so the start_point
    is '<li+.<a href="'. The code will then grab every instance of start_point to end_point.

    end_point    -  Send through the code tags you want to search for in the
    webpage. By default it's setup for a standard indexed site so the end_point
    is '</a+.</li>'. The code will then grab every instance of start_point to end_point.

    separator  -  This is the point in the grabbed links (from above) where you want
    to split the string into a url and a display name. The default is ">".

    skip       -  By default this is set to ['..', '.', 'Parent Directory']. This is
    a list of links you don't want to appear in your add-on listing.

EXAMPLE CODE:
link ='http://totalrevolution.tv/videos/'
sp   ='<a href="'
ep   ='</a>'
sep  = '">'
koding.Populate_List(url=link, start_point=sp, end_point=ep, separator=sep)
~"""
    import re
    import urlparse
    from __init__       import dolog
    from filetools      import Find_In_Text
    from systemtools    import Cleanup_String
    from video          import Play_Video
    from web            import Open_URL, Get_Extension, Cleanup_URL

    badlist = []
    if '<~>' in url:
        params      = Grab_Params(extras=url,keys='url,start,end,separator,skip')
        url         = params['url']
        start_point = params['start']
        end_point   = params['end']
        separator   = params['separator']
        skip        = params['skip']
    raw_content = Open_URL(url).replace('\n','').replace('\r','').replace('\t','')
    raw_list    = Find_In_Text(content=raw_content,start=start_point,end=end_point,show_errors=False)
    if raw_list != None:
        for item in raw_list:
            cont = True
            try:
                dolog('ITEM: %s'%item)
                new_sep = re.search(separator, item).group()
                link, title = item.split(new_sep)
            except:
                dolog('^ BAD ITEM, adding to badlist')
                badlist.append(item)
                cont = False
                # break
            if cont:
                title       = Cleanup_String(title)
                if title not in skip:
    # Make sure the link we've grabbed isn't a full web address
                    if not '://' in link:
                        link        = urlparse.urljoin(url, link)
                    link        = Cleanup_URL(link)
                    extension   = Get_Extension(link)

                    if not link.endswith('/') and extension == '':
                        link = link+'/'
                    if extension == '' and not 'mms://' in link:
                        Add_Dir(name=title, url=link+'<~>%s<~>%s<~>%s<~>%s'%(start_point,end_point,separator,skip),mode='populate_list',folder=True)
                    else:
                        Add_Dir(name=title, url=link,mode='play_video',folder=False)
    else:
        Add_Dir(name='Link 1', url=params["url"],mode='play_video',folder=False)
    if len(badlist)>0:
        dialog.ok('ERROR IN REGEX','The separator used is not working, an example raw match from the web page has now been printed to the log.')
        for item in badlist:
            dolog('BADLIST ITEM: %s'%item)
コード例 #4
0
def Populate_List(url,
                  start_point=r'<li+.<a href="',
                  end_point=r'</a+.</li>',
                  separator=r">",
                  skip=['..', '.', 'Parent Directory']):
    """
If you have a basic index web page or a webpage with a common
format for displaying links (on all pages) then you can use this
to populate an add-on. It's capable of cleverly working out what
needs to be sent through as a directory and what's a playable item.

CODE: Populate_List(url, [start_point, end_point, separator, skip]):

AVAILABLE PARAMS:

    (*) url  -  The start page of where to pull the first links from

    start_point  -  Send through the code tags you want to search for in the
    webpage. By default it's setup for a standard indexed site so the start_point
    is '<li+.<a href="'. The code will then grab every instance of start_point to end_point.

    end_point    -  Send through the code tags you want to search for in the
    webpage. By default it's setup for a standard indexed site so the end_point
    is '</a+.</li>'. The code will then grab every instance of start_point to end_point.

    separator  -  This is the point in the grabbed links (from above) where you want
    to split the string into a url and a display name. The default is ">".

    skip       -  By default this is set to ['..', '.', 'Parent Directory']. This is
    a list of links you don't want to appear in your add-on listing.

EXAMPLE CODE:
link ='http://totalrevolution.tv/videos/'
sp   ='<a href="'
ep   ='</a>'
sep  = '">'
koding.Populate_List(url=link, start_point=sp, end_point=ep, separator=sep)
~"""
    import re
    import urlparse
    from __init__ import dolog
    from vartools import Find_In_Text, Cleanup_String
    from video import Play_Video
    from web import Open_URL, Get_Extension, Cleanup_URL

    badlist = []
    if '<~>' in url:
        params = Grab_Params(extras=url, keys='url,start,end,separator,skip')
        url = params['url']
        start_point = params['start']
        end_point = params['end']
        separator = params['separator']
        skip = params['skip']
    raw_content = Open_URL(url).replace('\n',
                                        '').replace('\r',
                                                    '').replace('\t', '')
    raw_list = Find_In_Text(content=raw_content,
                            start=start_point,
                            end=end_point,
                            show_errors=False)
    if raw_list != None:
        for item in raw_list:
            cont = True
            try:
                dolog('ITEM: %s' % item)
                new_sep = re.search(separator, item).group()
                link, title = item.split(new_sep)
            except:
                dolog('^ BAD ITEM, adding to badlist')
                badlist.append(item)
                cont = False
                # break
            if cont:
                title = Cleanup_String(title)
                if title not in skip:
                    # Make sure the link we've grabbed isn't a full web address
                    if not '://' in link:
                        link = urlparse.urljoin(url, link)
                    link = Cleanup_URL(link)
                    extension = Get_Extension(link)

                    if not link.endswith('/') and extension == '':
                        link = link + '/'
                    if extension == '' and not 'mms://' in link:
                        Add_Dir(name=title,
                                url=link + '<~>%s<~>%s<~>%s<~>%s' %
                                (start_point, end_point, separator, skip),
                                mode='populate_list',
                                folder=True)
                    else:
                        Add_Dir(name=title,
                                url=link,
                                mode='play_video',
                                folder=False)
    else:
        Add_Dir(name='Link 1',
                url=params["url"],
                mode='play_video',
                folder=False)
    if len(badlist) > 0:
        dialog.ok(
            'ERROR IN REGEX',
            'The separator used is not working, an example raw match from the web page has now been printed to the log.'
        )
        for item in badlist:
            dolog('BADLIST ITEM: %s' % item)
コード例 #5
0
def Add_Dir(name,
            url='',
            mode='',
            folder=False,
            icon='',
            fanart='',
            description='',
            info_labels={},
            set_art={},
            set_property={},
            content_type='',
            context_items=None,
            context_override=False,
            playable=False):
    """
This allows you to create a list item/folder inside your add-on.
Please take a look at your addon default.py comments for more information
(presuming you created one at http://totalrevolution.tv)

TOP TIP: If you want to send multiple variables through to a function just
send through as a dictionary encapsulated in quotation marks. In the function
you can then use the following code to access them:

params = eval(url)
^ That will then give you a dictionary where you can just pull each variable and value from.

CODE: Add_Dir(name, url, mode, [folder, icon, fanart, description, info_labels, content_type, context_items, context_override, playable])

AVAILABLE PARAMS:

    (*) name  -  This is the name you want to show for the list item

    url   -  If the route (mode) you're calling requires extra paramaters
    to be sent through then this is where you add them. If the function is
    only expecting one item then you can send through as a simple string.
    Unlike many other Add_Dir functions Python Koding does allow for multiple
    params to be sent through in the form of a dictionary so let's say your
    function is expecting the 2 params my_time & my_date. You would send this info
    through as a dictionary like this:
    url={'my_time':'10:00', 'my_date':'01.01.1970'}
    
    If you send through a url starting with plugin:// the item will open up into
    that plugin path so for example:
    url='plugin://plugin.video.youtube/play/?video_id=FTI16i7APhU'

    mode  -  The mode you want to open when this item is clicked, this is set
    in your master_modes dictionary (see template add-on linked above)

    folder       -  This is an optional boolean, by default it's set to False.
    True will open into a folder rather than an executable command

    icon         -  The path to the thumbnail you want to use for this list item

    fanart       -  The path to the fanart you want to use for this list item

    description  - A description of your list item, it's skin dependant but this
    usually appears below the thumbnail

    info_labels  - You can send through any number of info_labels via this option.
    For full details on the infolabels available please check the pydocs here:
    http://mirrors.kodi.tv/docs/python-docs/16.x-jarvis/xbmcgui.html#ListItem-setInfo

    When passing through infolabels you need to use a dictionary in this format:
    {"genre":"comedy", "title":"test video"}
    
    set_art  -  Using the same format as info_labels you can set your artwork via
    a dictionary here. Full details can be found here:
    http://mirrors.kodi.tv/docs/python-docs/16.x-jarvis/xbmcgui.html#ListItem-setArt

    set_property  -  Using the same format as info_labels you can set your artwork via
    a dictionary here. Full details can be found here:
    http://kodi.wiki/view/InfoLabels#ListItem

    content_type - By default this will set the content_type for kodi to a blank string
    which is what Kodi expects for generic category listings. There are plenty of different
    types though and when set Kodi will perform different actions (such as access the
    database looking for season/episode information for the list item).

    WARNING: Setting the wrong content type for your listing can cause the system to
    log thousands of error reports in your log, cause the system to lag and make
    thousands of unnecessary db calls - sometimes resulting in a crash. You can find
    details on the content_types available here: http://forum.kodi.tv/showthread.php?tid=299107

    context_items - Add context items to your directory. The params you need to send through
    need to be in a list format of [(label, action,),] look at the example code below for
    more details.

    context_override - By default your context items will be added to the global context
    menu items but you can override this by setting this to True and then only your
    context menu items will show.

    playable  -  By default this is set to False but if set to True kodi will just try
    and play this item natively with no extra fancy functions.

EXAMPLE:
my_context = [('Music','xbmc.executebuiltin("ActivateWindow(music)")'),('Programs','xbmc.executebuiltin("ActivateWindow(programs)")')]
# ^ This is our two basic context menu items (music and programs)

Add_Dir(name='TEST DIRECTORY', url='', mode='test_directory', folder=True, context_items=my_context, context_override=True)
# ^ This will add a folder AND a context menu item for when bring up the menu (when focused on this directory).
# ^^ The context_override is set to True which means it will override the default Kodi context menu items.

Add_Dir(name='TEST ITEM', url='', mode='test_item', folder=False, context_items=my_context, context_override=False)
# ^ This will add an item to the list AND a context menu item for when bring up the menu (when focused on this item).
# ^^ The context_override is set to False which means the new items will appear alongside the default Kodi context menu items.
~"""
    from __init__ import dolog
    from systemtools import Data_Type
    from vartools import Convert_Special

    module_id = 'script.module.python.koding.aio'
    this_module = xbmcaddon.Addon(id=module_id)

    addon_handle = int(sys.argv[1])
    # Check we're in an appropriate section for the content type set
    dolog(xbmc.getInfoLabel('Window.Property(xmlfile)'))
    song_only_modes = ['songs', 'artist', 'album', 'song', 'music']
    video_only_modes = [
        'sets', 'tvshows', 'seasons', 'actors', 'directors', 'unknown',
        'video', 'set', 'movie', 'tvshow', 'season', 'episode'
    ]
    if xbmc.getInfoLabel(
            'Window.Property(xmlfile)'
    ) == 'MyVideoNav.xml' and content_type in song_only_modes:
        content_type = ''
    if xbmc.getInfoLabel(
            'Window.Property(xmlfile)'
    ) == 'MyMusicNav.xml' and content_type in video_only_modes:
        content_type = ''

    if description == '':
        description = this_module.getLocalizedString(30837)

    if Data_Type(url) == 'dict':
        url = repr(url)

    if Data_Type(info_labels) != 'dict':
        dialog.ok(
            'WRONG INFO LABELS',
            'Please check documentation, these should be sent through as a dictionary.'
        )

    if Data_Type(set_art) != 'dict':
        dialog.ok(
            'WRONG SET_ART',
            'Please check documentation, these should be sent through as a dictionary.'
        )

    if Data_Type(set_property) != 'dict':
        dialog.ok(
            'WRONG SET_PROPERTY',
            'Please check documentation, these should be sent through as a dictionary.'
        )

# Set the default title, filename and plot if not sent through already via info_labels
    try:
        title = info_labels["Title"]
        if title == '':
            info_labels["Title"] = name
    except:
        info_labels["Title"] = name

    try:
        filename = info_labels["FileName"]
        # if filename == '':
        #     info_labels["FileName"] = name
    except:
        info_labels["FileName"] = name

    try:
        plot = info_labels["plot"]
        if plot == '':
            info_labels["plot"] = description
    except:
        info_labels["plot"] = description
# Set default thumbnail image used for listing (if not sent through via set_art)
    try:
        set_art["icon"]
    except:
        set_art["icon"] = icon

# Set default Fanart if not already sent through via set_property
    try:
        set_property["Fanart_Image"]
    except:
        set_property["Fanart_Image"] = fanart

# Set the main listitem properties
    liz = xbmcgui.ListItem(label=str(name),
                           iconImage=str(icon),
                           thumbnailImage=str(icon))

    # Set the infolabels
    liz.setInfo(type=content_type, infoLabels=info_labels)

    # Set the artwork
    liz.setArt(set_art)

    # Loop through the set_property list and set each item in there
    for item in set_property.items():
        liz.setProperty(item[0], item[1])

# Add a context item (if details for context items are sent through)
    if context_items:
        liz.addContextMenuItems(context_items, context_override)

    u = sys.argv[0]
    u += "?mode=" + str(mode)
    u += "&url=" + Convert_Special(url, string=True)
    u += "&name=" + urllib.quote_plus(name)
    u += "&iconimage=" + urllib.quote_plus(icon)
    u += "&fanart=" + urllib.quote_plus(fanart)
    u += "&description=" + urllib.quote_plus(description)

    if url.startswith('plugin://'):
        xbmcplugin.addDirectoryItem(handle=addon_handle,
                                    url=url,
                                    listitem=liz,
                                    isFolder=True)

    elif folder:
        xbmcplugin.addDirectoryItem(handle=addon_handle,
                                    url=u,
                                    listitem=liz,
                                    isFolder=True)

    elif playable:
        liz.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem(handle=addon_handle,
                                    url=url,
                                    listitem=liz,
                                    isFolder=False)

    else:
        xbmcplugin.addDirectoryItem(handle=addon_handle,
                                    url=u,
                                    listitem=liz,
                                    isFolder=False)
コード例 #6
0
def Toggle_Addons(addon='all',
                  enable=True,
                  safe_mode=True,
                  exclude_list=[],
                  new_only=True,
                  refresh=True):
    """
Send through either a list of add-on ids or one single add-on id.
The add-ons sent through will then be added to the addons*.db
and enabled or disabled (depending on state sent through).
WARNING: If safe_mode is set to False this directly edits the
addons*.db rather than using JSON-RPC. Although directly amending
the db is a lot quicker there is no guarantee it won't cause
severe problems in later versions of Kodi (this was created for v17).
DO NOT set safe_mode to False unless you 100% understand the consequences!
CODE:  Toggle_Addons([addon, enable, safe_mode, exclude_list, new_only, refresh])
AVAILABLE PARAMS:
    (*) addon  -  This can be a list of addon ids, one single id or
    'all' to enable/disable all. If enabling all you can still use
    the exclude_list for any you want excluded from this function.
    enable  -  By default this is set to True, if you want to disable
    the add-on(s) then set this to False.
    safe_mode  -  By default this is set to True which means the add-ons
    are enabled/disabled via JSON-RPC which is the method recommended by
    the XBMC foundation. Setting this to False will result in a much
    quicker function BUT there is no guarantee this will work on future
    versions of Kodi and it may even cause corruption in future versions.
    Setting to False is NOT recommended and you should ONLY use this if
    you 100% understand the risks that you could break multiple setups.
    exclude_list  -  Send through a list of any add-on id's you do not
    want to be included in this command.
    new_only  -  By default this is set to True so only newly extracted
    add-on folders will be enabled/disabled. This means that any existing
    add-ons which have deliberately been disabled by the end user are
    not affected.
    refresh  - By default this is set to True, it will refresh the
    current container and also force a local update on your add-ons db.
EXAMPLE CODE:
from systemtools import Refresh
xbmc.executebuiltin('ActivateWindow(Videos, addons://sources/video/)')
xbmc.sleep(2000)
dialog.ok('DISABLE YOUTUBE','We will now disable YouTube (if installed)')
koding.Toggle_Addons(addon='plugin.video.youtube', enable=False, safe_mode=True, exclude_list=[], new_only=False)
koding.Refresh('container')
xbmc.sleep(2000)
dialog.ok('ENABLE YOUTUBE','When you click OK we will enable YouTube (if installed)')
koding.Toggle_Addons(addon='plugin.video.youtube', enable=True, safe_mode=True, exclude_list=[], new_only=False)
koding.Refresh('container')
~"""
    from __init__ import dolog
    from filetools import DB_Path_Check, Get_Contents
    from database import DB_Query
    from systemtools import Data_Type, Last_Error, Refresh, Set_Setting, Timestamp

    kodi_ver = int(float(xbmc.getInfoLabel("System.BuildVersion")[:2]))
    addons_db = DB_Path_Check('addons')
    data_type = Data_Type(addon)
    state = int(bool(enable))
    enabled_list = []
    disabled_list = []
    if kodi_ver >= 17:
        on_system = DB_Query(addons_db,
                             'SELECT addonID, enabled from installed')
        # Create a list of enabled and disabled add-ons already on system
        enabled_list = Addon_List(enabled=True)
        disabled_list = Addon_List(enabled=False)

# If addon has been sent through as a string we add into a list
    if data_type == 'unicode':
        addon = addon.encode('utf8')
        data_type = Data_Type(addon)

    if data_type == 'str' and addon != 'all':
        addon = [addon, '']

# Grab all the add-on ids from addons folder
    if addon == 'all':
        addon = []
        ADDONS = xbmc.translatePath('special://home/addons')
        my_addons = Get_Contents(path=ADDONS,
                                 exclude_list=['packages', 'temp'])
        for item in my_addons:
            addon_id = Get_Addon_ID(item)
            addon.append(addon_id)

# Find out what is and isn't enabled in the addons*.db
    temp_list = []
    for addon_id in addon:
        if not addon_id in exclude_list and addon_id != '':
            dolog('CHECKING: %s' % addon_id)
            if addon_id in disabled_list and not new_only and enable:
                temp_list.append(addon_id)
            elif addon_id not in disabled_list and addon_id not in enabled_list:
                temp_list.append(addon_id)
            elif addon_id in enabled_list and not enable:
                temp_list.append(addon_id)
            elif addon_id in disabled_list and enable:
                temp_list.append(addon_id)
    addon = temp_list

    # If you want to bypass the JSON-RPC mode and directly modify the db (READ WARNING ABOVE!!!)
    if not safe_mode and kodi_ver >= 17:
        installedtime = Timestamp('date_time')
        insert_query = 'INSERT or IGNORE into installed (addonID , enabled, installDate) VALUES (?,?,?)'
        update_query = 'UPDATE installed SET enabled = ? WHERE addonID = ? '
        insert_values = [addon, state, installedtime]
        try:
            for item in addon:
                DB_Query(addons_db, insert_query, [item, state, installedtime])
                DB_Query(addons_db, update_query, [state, item])
        except:
            dolog(Last_Error())
        if refresh:
            Refresh()

# Using the safe_mode (JSON-RPC)
    else:
        final_enabled = []
        if state:
            my_value = 'true'
            log_value = 'ENABLED'
        else:
            my_value = 'false'
            log_value = 'DISABLED'

        for my_addon in addon:

            # If enabling the add-on then we also check for dependencies and enable them first
            if state:
                dolog('Checking dependencies for : %s' % my_addon)
                dependencies = Dependency_Check(addon_id=my_addon,
                                                recursive=True)

                # traverse through the dependencies in reverse order attempting to enable
                for item in reversed(dependencies):
                    if not item in exclude_list and not item in final_enabled and not item in enabled_list:
                        dolog('Attempting to enable: %s' % item)
                        addon_set = Set_Setting(setting_type='addon_enable',
                                                setting=item,
                                                value='true')

                        # If we've successfully enabled then we add to list so we can skip any other instances
                        if addon_set:
                            dolog('%s now %s' % (my_addon, log_value))
                            final_enabled.append(item)

# Now the dependencies are enabled we need to enable the actual main add-on
            if not my_addon in final_enabled:
                addon_set = Set_Setting(setting_type='addon_enable',
                                        setting=my_addon,
                                        value=my_value)
            try:
                if addon_set:
                    dolog('%s now %s' % (my_addon, log_value))
                    final_enabled.append(addon)
            except:
                pass
    if refresh:
        Refresh(['addons', 'container'])


# NEW CODE NOT WORKING
#     from __init__       import dolog
#     from filetools      import DB_Path_Check, Get_Contents
#     from database       import DB_Query
#     from systemtools    import Data_Type, Last_Error, Refresh, Set_Setting, Timestamp
#     from web            import Validate_Link

#     addons_db       = DB_Path_Check('addons')
#     data_type       = Data_Type(addon)
#     state           = int(bool(enable))
#     enabled_list    = []
#     disabled_list   = []
#     if kodi_ver >= 17:
#         on_system   = DB_Query(addons_db,'SELECT addonID, enabled from installed')
# # Create a list of enabled and disabled add-ons already on system
#         enabled_list  = Addon_List(enabled=True)
#         disabled_list = Addon_List(enabled=False)

# # If addon has been sent through as a string we add into a list
#     if data_type == 'unicode':
#         addon = addon.encode('utf8')
#         data_type = Data_Type(addon)

#     if data_type == 'str' and addon!= 'all':
#         addon = [addon,'']

# # Grab all the add-on ids from addons folder
#     if addon == 'all':
#         addon     = []
#         my_addons = Get_Contents(path=ADDONS, exclude_list=['packages','temp'])
#         for item in my_addons:
#             addon_id = Get_Addon_ID(item)
#             addon.append(addon_id)

# # Find out what is and isn't enabled in the addons*.db
#     temp_list = []
#     for addon_id in addon:
#         if not addon_id in exclude_list and addon_id != '':
#             dolog('CHECKING: %s'%addon_id)

# # Check ALL addons and not just newly extracted not yet in db
#             if addon_id in disabled_list and not new_only and enable:
#                 dolog('[1] Adding to temp list: %s'%addon_id)
#                 temp_list.append(addon_id)

# # Check addons not in our disabled list and also aren't in the enabled list
#             elif addon_id not in disabled_list and addon_id not in enabled_list:
#                 dolog('[2] Adding to temp list: %s'%addon_id)
#                 temp_list.append(addon_id)

# # Check addons that are already enabled, get ready to disable
#             elif addon_id in enabled_list and not enable:
#                 dolog('[3] Adding to temp list: %s'%addon_id)
#                 temp_list.append(addon_id)

# # Check addons which are disabled get ready to enable (same as first if function??)
#             elif addon_id in disabled_list and enable:
#                 dolog('[4] Adding to temp list: %s'%addon_id)
#                 temp_list.append(addon_id)
#     addon = temp_list

# # If you want to bypass the JSON-RPC mode and directly modify the db (READ WARNING ABOVE!!!)
#     if not safe_mode and kodi_ver >= 17:
#         installedtime   = Timestamp('date_time')
#         insert_query    = 'INSERT or IGNORE into installed (addonID , enabled, installDate) VALUES (?,?,?)'
#         update_query    = 'UPDATE installed SET enabled = ? WHERE addonID = ? '
#         insert_values   = [addon, state, installedtime]
#         try:
#             for item in addon:
#                 DB_Query(addons_db, insert_query, [item, state, installedtime])
#                 DB_Query(addons_db, update_query, [state, item])
#         except:
#             dolog(Last_Error())
#         if refresh:
#             Refresh()

# # Using the safe_mode (JSON-RPC)
#     else:
#         Refresh('addons')
#         xbmc.sleep(1000)
#         final_enabled = []
#         if state:
#             my_value = 'true'
#             log_value = 'ENABLED'
#         else:
#             my_value = 'false'
#             log_value = 'DISABLED'

#         for my_addon in addon:

# # If enabling the add-on then we also check for dependencies and enable them first
#             if state:
#                 dolog('Checking dependencies for : %s'%my_addon)
#                 dependencies = Dependency_Check(addon_id=my_addon, recursive=True)
#                 dolog('Dependencies: %s'%dependencies)

# # traverse through the dependencies in reverse order attempting to enable
#                 for item in reversed(dependencies):
#                     if not item in exclude_list and not item in final_enabled and not item in enabled_list:
#                         dolog('Attempting to enable: %s'%item)
#                         addon_set = Set_Setting(setting_type='addon_enable', setting=item, value = 'true')

# # If we've successfully enabled then we add to list so we can skip any other instances
#                         if addon_set:
#                             dolog('%s now %s' % (my_addon, log_value))
#                             final_enabled.append(item)

# # Now the dependencies are enabled we need to enable the actual main add-on
#         bad_repo = []
#         for my_addon in addon:
#             if not my_addon in final_enabled:
#                 ok = True
#                 addon_set = True
#                 if 'repo' in my_addon:
#                     ok = Check_Repo(my_addon)
#                     if not ok:
#                         dolog('BAD REPO: %s IS NOT RESOLVING SO WE ARE NOT INSTALLING'%my_addon)
#                         addon_set = False
#                 if addon_set:
#                     addon_set = Set_Setting(setting_type='addon_enable', setting=my_addon, value = my_value)
#                 if addon_set:
#                     dolog('%s now %s' % (my_addon, log_value))
#                     final_enabled.append(addon)
#                 else:
#                     bad_repo.append(my_addon)
#         if len(bad_repo) > 0:
#             final_list = 'The following repostitories are not resolving so have not been installed: '
#             for item in bad_repo:
#                 final_list += item+','
#             final_list = final_list[:-1]
#             dialog.ok('[COLOR=gold]BAD REPOSITORIES FOUND[/COLOR]',final_list)
#     if refresh:
#         Refresh('container')
# ----------------------------------------------------------------
コード例 #7
0
ファイル: video.py プロジェクト: stick141/modules4all
def Play_Video(video,showbusy=True,content='video',ignore_dp=False,timeout=10, item=None):
    """
This will attempt to play a video and return True or False on
whether or not playback was successful. This function is similar
to Check_Playback but this actually tries a number of methods to
play the video whereas Check_Playback does not actually try to
play a video - it will just return True/False on whether or not
a video is currently playing.

CODE: Play_Video(video, [showbusy, content])

AVAILABLE PARAMS:

    (*) video  -  This is the path to the video, this can be a local
    path, online path or a channel number from the PVR.

    showbusy  -  By default this is set to True which means while the
    function is attempting to playback the video the user will see the
    busy dialog. Set to False if you prefer this not to appear but do
    bare in mind a user may navigate to another section and try playing
    something else if they think this isn't doing anything.

    content  -  By default this is set to 'video', however if you're
    passing through audio you may want to set this to 'music' so the
    system can correctly set the tags for artist, song etc.

    ignore_dp  -  By default this is set to True but if set to False
    this will ignore the DialogProgress window. If you use a DP while
    waiting for the stream to start then you'll want to set this True.
    Please bare in mind the reason this check is in place and enabled
    by default is because some streams do bring up a DialogProgress
    when initiated (such as f4m proxy links) and disabling this check
    in those circumstances can cause false positives.

    timeout  -  This is the amount of time you want to allow for playback
    to start before sending back a response of False. Please note if
    ignore_dp is set to True then it will also add a potential 10s extra
    to this amount if a DialogProgress window is open. The default setting
    for this is 10s.

EXAMPLE CODE:
isplaying = koding.Play_Video('http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')
if isplaying:
    dialog.ok('PLAYBACK SUCCESSFUL','Congratulations, playback was successful')
    xbmc.Player().stop()
else:
    dialog.ok('PLAYBACK FAILED','Sorry, playback failed :(')
~"""

    dolog('### ORIGINAL VIDEO: %s'%video)
    import urlresolver
    try:    import simplejson as json
    except: import json

    if not item:
        meta = {}
        for i in ['title', 'originaltitle', 'tvshowtitle', 'year', 'season', 'episode', 'genre', 'rating', 'votes',
                  'director', 'writer', 'plot', 'tagline']:
            try:
                meta[i] = xbmc.getInfoLabel('listitem.%s' % i)
            except:
                pass
        meta = dict((k, v) for k, v in meta.iteritems() if not v == '')
        if 'title' not in meta:
            meta['title'] = xbmc.getInfoLabel('listitem.label')
        icon = xbmc.getInfoLabel('listitem.icon')
        item = xbmcgui.ListItem(path=video, iconImage =icon, thumbnailImage=icon)
        if content == "music":
            try:
                meta['artist'] = xbmc.getInfoLabel('listitem.artist')
                item.setInfo(type='Music', infoLabels={'title': meta['title'], 'artist': meta['artist']})
            except:
                item.setInfo(type='Video', infoLabels=meta)
        else:
            item.setInfo(type='Video', infoLabels=meta)

    else:
        item.setInfo(type='Video', infoLabels=meta)

    playback = False
    if showbusy:
        Show_Busy()


# if a plugin path is sent we try activate window
    if video.startswith('plugin://'):
        try:
            dolog('Attempting to play via xbmc.Player().play() method')
            xbmc.Player().play(video)
            # dolog('Attempting to play via XBMC.ActivateWindow(10025, ...) method')
            # xbmc.executebuiltin('XBMC.ActivateWindow(10025,%s)' % video)
            playback = Check_Playback(ignore_dp,timeout)
            is_in_progress = True
            progress_count = 0
            while is_in_progress:
                xbmc.sleep(1000)
                progress_count += 1
                dolog('Progress check is active, sleeping %s'%progress_count)
                is_in_progress = os.path.exists(check_started)

        except:
            dolog(Last_Error())

# If an XBMC action has been sent through we do an executebuiltin command
    elif video.startswith('ActivateWindow') or video.startswith('RunAddon') or video.startswith('RunScript') or video.startswith('PlayMedia'):
        try:
            dolog('Attempting to play via xbmc.executebuiltin method')
            xbmc.executebuiltin('%s'%video)
            playback = Check_Playback(ignore_dp,timeout)
            is_in_progress = True
            progress_count = 0
            while is_in_progress:
                xbmc.sleep(1000)
                progress_count += 1
                dolog('Progress check is active, sleeping %s'%progress_count)
                is_in_progress = os.path.exists(check_started)

        except:
            dolog(Last_Error())

    elif ',' in video:
# Standard xbmc.player method (a comma in url seems to throw urlresolver off)
        try:
            dolog('Attempting to play via xbmc.Player.play() method')
            xbmc.Player().play('%s'%video, item)
            playback = Check_Playback(ignore_dp,timeout)
            is_in_progress = True
            progress_count = 0
            while is_in_progress:
                xbmc.sleep(1000)
                progress_count += 1
                dolog('Progress check is active, sleeping %s'%progress_count)
                is_in_progress = os.path.exists(check_started)

# Attempt to resolve via urlresolver
        except:
            try:
                dolog('Attempting to resolve via urlresolver module')
                dolog('video = %s'%video)
                hmf = urlresolver.HostedMediaFile(url=video, include_disabled=False, include_universal=True)
                if hmf.valid_url() == True:
                    video = hmf.resolve()
                    dolog('### VALID URL, RESOLVED: %s'%video)
                xbmc.Player().play('%s' % video, item)
                playback = Check_Playback(ignore_dp,timeout)
                is_in_progress = True
                progress_count = 0
                while is_in_progress:
                    xbmc.sleep(1000)
                    progress_count += 1
                    dolog('Progress check is active, sleeping %s'%progress_count)
                    is_in_progress = os.path.exists(check_started)

            except:
                dolog(Last_Error())

# Play from a db entry - untested
    elif video.isdigit():
        dolog('### Video is digit, presuming it\'s a db item')
        command = ('{"jsonrpc": "2.0", "id":"1", "method": "Player.Open","params":{"item":{"channelid":%s}}}' % url)
        xbmc.executeJSONRPC(command)
        playback = Check_Playback(ignore_dp,timeout)
        is_in_progress = True
        progress_count = 0
        while is_in_progress:
            xbmc.sleep(1000)
            progress_count += 1
            dolog('Progress check is active, sleeping %s'%progress_count)
            is_in_progress = os.path.exists(check_started)
            
    else:
# Attempt to resolve via urlresolver
        try:
            dolog('Attempting to resolve via urlresolver module')
            dolog('video = %s'%video)
            hmf = urlresolver.HostedMediaFile(url=video, include_disabled=False, include_universal=True)
            if hmf.valid_url() == True:
                video = hmf.resolve()
                dolog('### VALID URL, RESOLVED: %s'%video)
            xbmc.Player().play('%s' % video, item)
            playback = Check_Playback(ignore_dp,timeout)
            is_in_progress = True
            progress_count = 0
            while is_in_progress:
                xbmc.sleep(1000)
                progress_count += 1
                dolog('Progress check is active, sleeping %s'%progress_count)
                is_in_progress = os.path.exists(check_started)

# Standard xbmc.player method
        except:
            try:
                dolog('Attempting to play via xbmc.Player.play() method')
                xbmc.Player().play('%s' % video, item)
                playback = Check_Playback(ignore_dp,timeout)
                is_in_progress = True
                progress_count = 0
                while is_in_progress:
                    xbmc.sleep(1000)
                    progress_count += 1
                    dolog('Progress check is active, sleeping %s'%progress_count)
                    is_in_progress = os.path.exists(check_started)

            except:
                dolog(Last_Error())

    dolog('Playback status: %s' % playback)
    Show_Busy(False)
    return playback
コード例 #8
0
def Check_Repo(repo,show_busy=True,timeout=10):
    """
This will check the status of repo and return True if the repo is online or False
if it contains paths that are no longer accessible online.

IMPORTANT: If you're running an old version of Kodi which uses the old Python 2.6
(OSX and Android lower than Kodi 17 or a linux install with old Python installed on system)
you will get a return of False on https links regardless of their real status. This is due
to the fact Python 2.6 cannot access secure links. Any still using standard http links
will return the correct results.

CODE:  Check_Repo(repo, [show_busy, timeout])

AVAILABLE PARAMS:

    (*) repo  -  This is the name of the folder the repository resides in.
    You can either use the full path or just the folder name which in 99.99%
    of cases is the add-on id. If only using the folder name DOUBLE check first as
    there are a handful which have used a different folder name to the actual add-on id!

    show_busy - By default this is set to True and a busy dialog will show during the check

    timeout - By default this is set to 10 (seconds) - this is the maximum each request
    to the repo url will take before timing out and returning False.

EXAMPLE CODE:
repo_status = Check_Repo('repository.xxxecho',show_busy=False,timeout=10)
if repo_status:
    dialog.ok('REPO STATUS','The repository modules4all is: [COLOR=lime]ONLINE[/COLOR]')
else:
    dialog.ok('REPO STATUS','The repository modules4all is: [COLOR=red]OFFLINE[/COLOR]')
~"""
    import re

    from __init__  import dolog
    from filetools import Text_File
    from guitools  import Show_Busy
    from web       import Validate_Link
    dolog('### CHECKING %s'%repo)
    status = True
    if show_busy:
        Show_Busy()
    if repo.startswith('special://'):
        repo_path = xbmc.translatePath(repo)
    elif not ADDONS in repo and not XBMC_PATH in repo:
        repo_path = os.path.join(ADDONS,repo)
    else:
        repo_path = repo
    repo_path = os.path.join(repo_path,'addon.xml')
    dolog(repo_path)
    if os.path.exists(repo_path):
        content  = Text_File(repo_path,'r')
        md5_urls = re.findall(r'<checksum>(.+?)</checksum>', content, re.DOTALL)
        for item in md5_urls:
            link_status = Validate_Link(item,timeout)
            dolog(item)
            dolog('STATUS: %s'%link_status)
            if link_status < 200 or link_status >= 400:
                status = False
                break
        if show_busy:
            Show_Busy(False)
        return status
    else:
        if show_busy:
            Show_Busy(False)
        return False
コード例 #9
0
def Open_URL(
        url='',
        post_type='get',
        payload={},
        headers={
            'User-Agent':
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
        },
        cookies=True,
        auth=None,
        timeout=None,
        cookiejar=None,
        proxies={}):
    """
If you need to pull the contents of a webpage it's very simple to do so by using this function.
This uses the Python Requests module, for more detailed info on how the params work
please look at the following link: http://docs.python-requests.org/en/master/user/advanced/

IMPORTANT: This function will attempt to convert a url with a query string into the
correct params for a post or get command but I highly recommend sending through your
query string as a dictionary using the payload params. It's much cleaner and is a
safer way of doing things, if you send through your url with a query string attached
then I take no responsibility if it doesn't work!

CODE:   Open_URL(url,[post_type,payload,headers,cookies,auth,timeout,cookiejar])

AVAILABLE PARAMS:

    url  -  This is the main url you want to send through. Send it through
    as a query string format even if it's a post.

    post_type  -  By default this is set to 'get' but this can be set to 'post',
    if set to post the query string will be split up into a post format automatically.
    
    payload - By default this is not used but if you just want a standard
    basic Open_URL function you can add a dictionary of params here. If you
    don't enter anything in here the function will just split up your url
    accordingly. Make sure you read the important information at the top
    of this tutorial text.

    headers -  Optionally send through headers in form of a dictionary.

    cookies  -  If set to true your request will send through and store cookies.

    auth  -  User/pass details

    timeout  -  Optionally set a timeout for the request.

    cookiejar  -  An name for the location to store cookies. By default it's
    set to addon_data/<addon_id>/cookies/cookiejar but if you have multiple
    websites you access then you may want to use a separate filename for each site.

    proxies - Use a proxy for accessing the link, see requests documentation for full
    information but essentially you would send through a dictionary like this:
    proxies = {"http":"http://10.10.1.10:3128","htts":"https://10.10.1.10:3128"}

EXAMPLE CODE:
dialog.ok('OPEN FORUM PAGE','We will attempt to open the noobsandnerds forum page and return the contents. You will now be asked for your forum credentials.')
myurl = 'http://noobsandnerds.com/support/index.php'
username = koding.Keyboard('ENTER USERNAME')
password = koding.Keyboard('ENTER PASSWORD')
params = {"username":username,"password":password}
xbmc.log(repr(params),2)
url_contents = koding.Open_URL(url=myurl, payload=params, post_type='get')
koding.Text_Box('CONTENTS OF WEB PAGE',url_contents)
~"""
    import os
    import pickle
    import requests
    import sys
    import xbmc
    import xbmcaddon

    from __init__ import converthex, dolog, ADDON_ID, KODI_VER
    from addons import Addon_Info
    from filetools import Text_File

    Addon_Version = Addon_Info(id='version')
    Addon_Profile = Addon_Info(id='profile')
    Cookie_Folder = os.path.join(Addon_Profile, 'cookies')
    xbmc.log(Cookie_Folder, 2)
    if not xbmcvfs.exists(Cookie_Folder):
        xbmcvfs.mkdirs(Cookie_Folder)

    if cookiejar == None:
        Cookie_Jar = os.path.join(Cookie_Folder, 'cookiejar')
    else:
        Cookie_Jar = os.path.join(Cookie_Folder, cookiejar)

    my_cookies = None
    if cookies:
        if xbmcvfs.exists(Cookie_Jar):
            try:
                openfile = xbmcvfs.File(Cookie_Jar)
                f = openfile.read()
                openfile.close()
                my_cookies = pickle.load(f)
            except:
                my_cookies = None

# If the payload is empty we split the params
    if len(payload) == 0:

        if '?' in url:
            url, args = url.split('?')
            args = args.split('&')
            for item in args:
                var, data = item.split('=')
                payload[var] = data

    dolog('PAYLOAD: %s' % payload)

    try:
        if Python_Version() < 2.7 and url.startswith('https'):
            url = url.replace('https', 'http')

        if post_type == 'post':
            r = requests.post(url,
                              payload,
                              headers=headers,
                              cookies=my_cookies,
                              auth=auth,
                              timeout=timeout,
                              proxies=proxies)
        else:
            r = requests.get(url,
                             payload,
                             headers=headers,
                             cookies=my_cookies,
                             auth=auth,
                             timeout=timeout,
                             proxies=proxies)
    except:
        dolog('Failed to pull content for %s' % url)
        return False
    dolog('### CODE: %s   |   REASON: %s' % (r.status_code, r.reason))
    if r.status_code >= 200 and r.status_code < 400:
        content = r.text.encode('utf-8')
        dolog('content: %s' % content)
        if cookies:
            openfile = xbmcvfs.File(Cookie_Jar, 'wb')
            pickle.dump(r.cookies, openfile)
            openfile.close()
        return content
    else:
        dolog('Failed to pull content for %s' % url)
        return False
コード例 #10
0
ファイル: video.py プロジェクト: smoke61/modules4all
def Check_Playback(ignore_dp=False, timeout=10):
    """
This function will return true or false based on video playback. Simply start a stream
(whether via an add-on, direct link to URL or local storage doesn't matter), the code will
then work out if playback is successful. This uses a number of checks and should take into
account all potential glitches which can occur during playback. The return should happen
within a second or two of playback being successful (or not).

CODE: Check_Playback()

AVAILABLE PARAMS:

    ignore_dp  -  By default this is set to True but if set to False
    this will ignore the DialogProgress window. If you use a DP while
    waiting for the stream to start then you'll want to set this True.
    Please bare in mind the reason this check is in place and enabled
    by default is because some streams do bring up a DialogProgress
    when initiated (such as f4m proxy links) and disabling this check
    in those circumstances can cause false positives.

    timeout  -  This is the amount of time you want to allow for playback
    to start before sending back a response of False. Please note if
    ignore_dp is set to True then it will also add a potential 10s extra
    to this amount if a DialogProgress window is open. The default setting
    for this is 10s.

EXAMPLE CODE:
xbmc.Player().play('http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')
isplaying = koding.Check_Playback()
if isplaying:
    dialog.ok('PLAYBACK SUCCESSFUL','Congratulations, playback was successful')
    xbmc.Player().stop()
else:
    dialog.ok('PLAYBACK FAILED','Sorry, playback failed :(')
~"""
    if not ignore_dp:
        isdialog = True
        counter = 1

        # Check if the progress window is active and wait for playback
        while isdialog and counter < 60:
            if xbmc.getCondVisibility('Window.IsActive(progressdialog)'):
                try:
                    if dp.iscanceled():
                        dp.close()
                        break
                except:
                    pass
            dolog('### Current Window: %s' %
                  xbmc.getInfoLabel('System.CurrentWindow'))
            dolog('### Current XML: %s' %
                  xbmc.getInfoLabel('Window.Property(xmlfile)'))
            dolog('### Progress Dialog active, sleeping for %s seconds' %
                  counter)
            xbmc.sleep(1000)
            if xbmc.getCondVisibility('Window.IsActive(progressdialog)') or (
                    xbmc.getInfoLabel('Window.Property(xmlfile)')
                    == 'DialogProgress.xml'):
                isdialog = True
            else:
                isdialog = False
            counter += 1
            dolog('counter: %s' % counter)

            # Given the DialogProgress 10 seconds to finish and it's still up - time to close it
            if counter >= 10:
                try:
                    dolog('attempting to send click to close dp')
                    xbmc.executebuiltin('SendClick()')
                    if dp.iscanceled():
                        dp.close()
                    try:
                        dp.close()
                    except:
                        pass
                except:
                    dolog('### FAILED TO CLOSE DP')
    try:
        dp.close()
    except:
        pass

    isplaying = xbmc.Player().isPlaying()
    counter = 1
    if xbmc.Player().isPlayingAudio():
        return True
# If xbmc player is not yet active give it some time to initialise
    while not isplaying and counter < timeout:
        xbmc.sleep(1000)
        isplaying = xbmc.Player().isPlaying()
        dolog('### XBMC Player not yet active, sleeping for %s seconds' %
              counter)
        counter += 1

    success = 0
    counter = 0

    # If it's playing give it time to physically start streaming then attempt to pull some info
    if isplaying:
        xbmc.sleep(1000)
        while not success and counter < 5:
            try:
                if xbmc.Player().isPlayingVideo():
                    infotag = xbmc.Player().getVideoInfoTag()
                vidtime = xbmc.Player().getTime()
                if vidtime > 0:
                    success = 1

# If playback doesn't start automatically (buffering) we force it to play
                else:
                    dolog(
                        '### Playback active but time at zero, trying to unpause'
                    )
                    xbmc.executebuiltin('PlayerControl(Play)')
                    xbmc.sleep(2000)
                    vidtime = xbmc.Player().getTime()
                    if vidtime > 0:
                        success = 1

# If no infotag or time could be pulled then we assume playback failed, try and stop the xbmc.player
            except:
                counter += 1
                xbmc.sleep(1000)

# Check if the busy dialog is still active from previous locked up playback attempt
    isbusy = xbmc.getCondVisibility('Window.IsActive(busydialog)')
    counter = 1
    while isbusy:
        dolog('### Busy dialog active, sleeping for %ss' % counter)
        xbmc.sleep(1000)
        isbusy = xbmc.getCondVisibility('Window.IsActive(busydialog)')
        counter += 1
        if counter >= 5:
            xbmc.executebuiltin('Dialog.Close(busydialog)')

    if not success:
        xbmc.executebuiltin('PlayerControl(Stop)')
        dolog('### Failed playback, stopped stream')
        return False
    else:
        return True
コード例 #11
0
def Open_URL(
        url='',
        post_type='get',
        payload={},
        headers={
            'User-Agent':
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
        },
        cookies=True,
        auth=None,
        timeout=None,
        cookiejar=None):
    """
If you need to pull the contents of a webpage it's very simple to do so by using this function.

IMPORTANT: This function is designed to convert a query string into a post.
If you want to send through a post which contains ampersands or question
marks you MUST send the params through as a dictionary. By default this function
presumes the url only contains one question mark and it splits at that point and
will then split the params at every instance of an ampersand.

CODE:   koding.Open_URL(url,[post_type,payload,headers,cookies,auth,timeout,cookiejar])

AVAILABLE PARAMS:

    url  -  This is the main url you want to send through. Send it through
    as a query string format even if it's a post.

    post_type  -  By default this is set to 'get' but this can be set to 'post',
    if set to post the query string will be split up into a post format automatically.
    
    payload - By default this is not used but if you just want a standard
    basic Open_URL function you can add a dictionary of params here. If you
    don't enter anything in here the function will just split up your url
    accordingly. Make sure you read the important information at the top
    of this tutorial text.

    headers -  Optionally send through headers in form of a dictionary.

    cookies  -  If set to true your request will send through and store cookies.

    auth  -  User/pass details

    timeout  -  Optionally set a timeout for the request.

    cookiejar  -  An name for the location to store cookies. By default it's
    set to addon_data/<addon_id>/cookies/cookiejar but if you have multiple
    websites you access then you may want to use a separate filename for each site.

EXAMPLE CODE:
url_contents = koding.Open_URL('http://testpage.com?query1=value1&query2=value2', post_type='get')
koding.Text_Box('CONTENTS OF WEB PAGE',url_contents)
~"""
    import os
    import pickle
    import requests
    import sys
    import xbmc
    import xbmcaddon

    from __init__ import converthex, dolog, Encryption, ADDON_ID, LOGIN, FORUM, USERNAME, PASSWORD, KODI_VER
    from addons import Addon_Info
    from filetools import Text_File
    dolog('POST TYPE: %s' % post_type)
    dolog('url: %s' % url)
    Addon_Version = Addon_Info(id='version')
    Addon_Profile = xbmc.translatePath(Addon_Info(id='profile'))
    Cookie_Folder = os.path.join(Addon_Profile, 'cookies')
    if not os.path.exists(Cookie_Folder):
        os.makedirs(Cookie_Folder)

    if cookiejar == None:
        Cookie_Jar = os.path.join(Cookie_Folder, 'cookiejar')
    else:
        Cookie_Jar = os.path.join(Cookie_Folder, cookiejar)

    my_cookies = None
    if cookies:
        if os.path.exists(Cookie_Jar):
            try:
                with open(Cookie_Jar, 'rb') as f:
                    my_cookies = pickle.load(f)
            except:
                my_cookies = None

# If the payload is empty we split the params
    if len(payload) == 0:
        dolog('###### QUERY STRING CONVERSION MODE')

        # If the url sent through is not http then we presume it's hitting the NaN page
        if not url.startswith(converthex('68747470')):
            NaN_URL = True
            args = url
            post_type = 'post'
            url = converthex(
                '687474703a2f2f6e6f6f6273616e646e657264732e636f6d2f43505f53747566662f6c6f67696e5f74657374696e672e7068703f753d257326703d257326663d257326613d257326763d2573266b3d257326653d2573'
            ) % (USERNAME, PASSWORD, FORUM, ADDON_ID, Addon_Version, KODI_VER,
                 args)
        else:
            NaN_URL = False
        if '?' in url:
            url, args = url.split('?')
            args = args.split('&')
            for item in args:
                var, data = item.split('=')
                if NaN_URL:
                    payload[var] = Encryption('e', data)
                else:
                    payload[var] = data

    dolog('PAYLOAD: %s' % payload)

    try:
        if post_type == 'post':
            r = requests.post(url,
                              payload,
                              headers=headers,
                              cookies=my_cookies,
                              auth=auth,
                              timeout=timeout)
        else:
            r = requests.get(url,
                             payload,
                             headers=headers,
                             cookies=my_cookies,
                             auth=auth,
                             timeout=timeout)
    except:
        dolog('Failed to pull content for %s' % url)
        return False
    dolog('### CODE: %s   |   REASON: %s' % (r.status_code, r.reason))
    if r.status_code >= 200 and r.status_code < 400:
        content = r.text.encode('utf-8')
        dolog('content: %s' % content)
        if cookies:
            with open(Cookie_Jar, 'wb') as f:
                pickle.dump(r.cookies, f)
        return content
    else:
        dolog('Failed to pull content for %s' % url)
        return False
コード例 #12
0
ファイル: addons.py プロジェクト: varunrai/scrapers
def Toggle_Addons(addon='all', enable=True, safe_mode=True, exclude_list=[], new_only=True, refresh=True, update_status=0):
    """
Send through either a list of add-on ids or one single add-on id.
The add-ons sent through will then be added to the addons*.db
and enabled or disabled (depending on state sent through).

WARNING: If safe_mode is set to False this directly edits the
addons*.db rather than using JSON-RPC. Although directly amending
the db is a lot quicker there is no guarantee it won't cause
severe problems in later versions of Kodi (this was created for v17).
DO NOT set safe_mode to False unless you 100% understand the consequences!

CODE:  Toggle_Addons([addon, enable, safe_mode, exclude_list, new_only, refresh])

AVAILABLE PARAMS:
    (*) addon  -  This can be a list of addon ids, one single id or
    'all' to enable/disable all. If enabling all you can still use
    the exclude_list for any you want excluded from this function.
    enable  -  By default this is set to True, if you want to disable
    the add-on(s) then set this to False.
    
    safe_mode  -  By default this is set to True which means the add-ons
    are enabled/disabled via JSON-RPC which is the method recommended by
    the XBMC foundation. Setting this to False will result in a much
    quicker function BUT there is no guarantee this will work on future
    versions of Kodi and it may even cause corruption in future versions.
    Setting to False is NOT recommended and you should ONLY use this if
    you 100% understand the risks that you could break multiple setups.
    
    exclude_list  -  Send through a list of any add-on id's you do not
    want to be included in this command.
    
    new_only  -  By default this is set to True so only newly extracted
    add-on folders will be enabled/disabled. This means that any existing
    add-ons which have deliberately been disabled by the end user are
    not affected.
    
    refresh  - By default this is set to True, it will refresh the
    current container and also force a local update on your add-ons db.

    update_status  - When running this function it needs to disable the
    auto-update of add-ons by Kodi otherwise it risks crashing. This
    update_status paramater is the state you want Kodi to revert back to
    once the toggle of add-ons has completed. By default this is set to 0
    which is auto-update. You can also choose 1 (notify of updates) or 2
    (disable auto updates).

EXAMPLE CODE:
from systemtools import Refresh
xbmc.executebuiltin('ActivateWindow(Videos, addons://sources/video/)')
xbmc.sleep(2000)
dialog.ok('DISABLE YOUTUBE','We will now disable YouTube (if installed)')
koding.Toggle_Addons(addon='plugin.video.youtube', enable=False, safe_mode=True, exclude_list=[], new_only=False)
koding.Refresh('container')
xbmc.sleep(2000)
dialog.ok('ENABLE YOUTUBE','When you click OK we will enable YouTube (if installed)')
koding.Toggle_Addons(addon='plugin.video.youtube', enable=True, safe_mode=True, exclude_list=[], new_only=False)
koding.Refresh('container')
~"""
    from __init__       import dolog
    from filetools      import DB_Path_Check, Get_Contents
    from database       import DB_Query
    from systemtools    import Last_Error, Refresh, Set_Setting, Sleep_If_Function_Active, Timestamp
    from vartools       import Data_Type

    Set_Setting('general.addonupdates', 'kodi_setting', '2')
    dolog('disabled auto updates for add-ons')
    kodi_ver        = int(float(xbmc.getInfoLabel("System.BuildVersion")[:2]))
    addons_db       = DB_Path_Check('addons')
    data_type       = Data_Type(addon)
    state           = int(bool(enable))
    enabled_list    = []
    disabled_list   = []
    if kodi_ver >= 17:
        on_system   = DB_Query(addons_db,'SELECT addonID, enabled from installed')
# Create a list of enabled and disabled add-ons already on system
        enabled_list  = Addon_List(enabled=True)
        disabled_list = Addon_List(enabled=False)

# If addon has been sent through as a string we add into a list
    if data_type == 'unicode':
        addon = addon.encode('utf8')
        data_type = Data_Type(addon)

    if data_type == 'str' and addon!= 'all':
        addon = [addon]

# Grab all the add-on ids from addons folder
    if addon == 'all':
        addon     = []
        ADDONS    = xbmc.translatePath('special://home/addons')
        my_addons = Get_Contents(path=ADDONS, exclude_list=['packages','temp'])
        for item in my_addons:
            addon_id = Get_Addon_ID(item)
            addon.append(addon_id)

# Find out what is and isn't enabled in the addons*.db
    temp_list = []
    for addon_id in addon:
        if not addon_id in exclude_list and addon_id != '':
            if addon_id in disabled_list and not new_only and enable:
                temp_list.append(addon_id)
            elif addon_id not in disabled_list and addon_id not in enabled_list:
                temp_list.append(addon_id)
            elif addon_id in enabled_list and not enable:
                temp_list.append(addon_id)
            elif addon_id in disabled_list and enable:
                temp_list.append(addon_id)
    addon = temp_list

# If you want to bypass the JSON-RPC mode and directly modify the db (READ WARNING ABOVE!!!)
    if not safe_mode and kodi_ver >= 17:
        installedtime   = Timestamp('date_time')
        insert_query    = 'INSERT or IGNORE into installed (addonID , enabled, installDate) VALUES (?,?,?)'
        update_query    = 'UPDATE installed SET enabled = ? WHERE addonID = ? '
        insert_values   = [addon, state, installedtime]
        try:
            for item in addon:
                DB_Query(addons_db, insert_query, [item, state, installedtime])
                DB_Query(addons_db, update_query, [state, item])
        except:
            dolog(Last_Error())
        if refresh:
            Refresh()

# Using the safe_mode (JSON-RPC)
    else:
        mydeps        = []
        final_enabled = []
        if state:
            my_value      = 'true'
            log_value     = 'ENABLED'
            final_addons  = []
        else:
            my_value      = 'false'
            log_value     = 'DISABLED'
            final_addons  = addon

        for my_addon in addon:

        # If enabling the add-on then we also check for dependencies and enable them first
            if state:
                dependencies = Dependency_Check(addon_id=my_addon, recursive=True)
                mydeps.append(dependencies)

    # if enable selected we traverse through the dependencies enabling addons with lowest amount of deps to highest
        if state:
            mydeps = sorted(mydeps, key=len)
            for dep in mydeps:
                counter = 0
                for item in dep:
                    enable_dep = True
                    if counter == 0:
                        final_addons.append(item)
                        enable_dep = False
                    elif item in final_enabled:
                        enable_dep = False
                    else:
                        enable_dep = True
                    if enable_dep:
                        if not item in exclude_list and not item in final_enabled and not item in enabled_list:
                            if Set_Setting(setting_type='addon_enable', setting=item, value = 'true'):
                                final_enabled.append(item)
                    counter += 1

    # Now the dependencies are enabled we need to enable the actual main add-ons
        for my_addon in final_addons:
            if not my_addon in final_enabled:
                if Set_Setting(setting_type='addon_enable', setting=my_addon, value = my_value):
                    final_enabled.append(addon)
    if refresh:
        Refresh(['addons','container'])
    Set_Setting('general.addonupdates', 'kodi_setting', '%s'%update_status)
#----------------------------------------------------------------
コード例 #13
0
ファイル: addons.py プロジェクト: varunrai/scrapers
def Check_Repo(repo,show_busy=True,timeout=10):
    """
This will check the status of repo and return True if the repo is online or False
if it contains paths that are no longer accessible online.

IMPORTANT: If you're running an old version of Kodi which uses the old Python 2.6
(OSX and Android lower than Kodi 17 or a linux install with old Python installed on system)
you will get a return of False on https links regardless of their real status. This is due
to the fact Python 2.6 cannot access secure links. Any still using standard http links
will return the correct results.

CODE:  Check_Repo(repo, [show_busy, timeout])

AVAILABLE PARAMS:

    (*) repo  -  This is the name of the folder the repository resides in.
    You can either use the full path or just the folder name which in 99.99%
    of cases is the add-on id. If only using the folder name DOUBLE check first as
    there are a handful which have used a different folder name to the actual add-on id!

    show_busy - By default this is set to True and a busy dialog will show during the check

    timeout - By default this is set to 10 (seconds) - this is the maximum each request
    to the repo url will take before timing out and returning False.

EXAMPLE CODE:
repo_status = Check_Repo('special://xbmc',show_busy=False,timeout=10)
if repo_status:
    dialog.ok('REPO STATUS','The repository modules4all is: [COLOR=lime]ONLINE[/COLOR]')
else:
    dialog.ok('REPO STATUS','The repository modules4all is: [COLOR=red]OFFLINE[/COLOR]')
~"""
    import re

    from __init__  import dolog
    from filetools import Text_File
    from guitools  import Show_Busy
    from web       import Validate_Link
    xbmc.log('### CHECKING %s'%repo,2)
    status = True
    if show_busy:
        Show_Busy()
    if not ADDONS in repo and not XBMC_PATH in repo:
        repo_path = os.path.join(ADDONS,repo)
    else:
        repo_path = repo
    repo_path = Physical_Path(repo_path)
    xbmc.log(repo_path,2)
    repo_path = os.path.join(repo_path,'addon.xml')
    xbmc.log(repo_path,2)
    if os.path.exists(repo_path):
        content  = Text_File(repo_path,'r')
        md5_urls = re.findall(r'<checksum>(.+?)</checksum>', content, re.DOTALL)
        for item in md5_urls:
            link_status = Validate_Link(item,timeout)
            dolog(item)
            dolog('STATUS: %s'%link_status)
            if link_status < 200 or link_status >= 400:
                status = False
                break
        if show_busy:
            Show_Busy(False)
        return status
    else:
        if show_busy:
            Show_Busy(False)
        return False
コード例 #14
0
ファイル: video.py プロジェクト: stick141/modules4all
def Check_Playback(ignore_dp=False,timeout=10):
    """
This function will return true or false based on video playback. Simply start a stream
(whether via an add-on, direct link to URL or local storage doesn't matter), the code will
then work out if playback is successful. This uses a number of checks and should take into
account all potential glitches which can occur during playback. The return should happen
within a second or two of playback being successful (or not).

CODE: Check_Playback()

AVAILABLE PARAMS:
    
    ignore_dp  -  By default this is set to True but if set to False
    this will ignore the DialogProgress window. If you use a DP while
    waiting for the stream to start then you'll want to set this True.
    Please bare in mind the reason this check is in place and enabled
    by default is because some streams do bring up a DialogProgress
    when initiated (such as f4m proxy links) and disabling this check
    in those circumstances can cause false positives.

    timeout  -  This is the amount of time you want to allow for playback
    to start before sending back a response of False. Please note if
    ignore_dp is set to True then it will also add a potential 10s extra
    to this amount if a DialogProgress window is open. The default setting
    for this is 10s.

EXAMPLE CODE:
xbmc.Player().play('http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')
isplaying = koding.Check_Playback()
if isplaying:
    dialog.ok('PLAYBACK SUCCESSFUL','Congratulations, playback was successful')
    xbmc.Player().stop()
else:
    dialog.ok('PLAYBACK FAILED','Sorry, playback failed :(')
~"""
    if not os.path.exists(check_started):
        os.makedirs(check_started)
    
    if not ignore_dp:
        isdialog = True
        counter = 1

# Check if the progress window is active and wait for playback
        while isdialog:
            dolog('### Current Window: %s' % xbmc.getInfoLabel('System.CurrentWindow'))
            dolog('### Current XML: %s' % xbmc.getInfoLabel('Window.Property(xmlfile)'))
            dolog('### Progress Dialog active, sleeping for %s seconds' % counter)
            xbmc.sleep(1000)
            if xbmc.getCondVisibility('Window.IsActive(progressdialog)') or (xbmc.getInfoLabel('Window.Property(xmlfile)') == 'DialogProgress.xml'):
                isdialog = True
            else:
                isdialog = False
            counter += 1
            dolog('counter: %s' % counter)

# Given the DialogProgress 10 seconds to finish and it's still up - time to close it
            if counter == 10:
                try:
                    dolog('attempting to send click to close dp')
                    xbmc.executebuiltin('SendClick()')
                    if dp.iscanceled():
                        dp.close()
                except:
                    dolog('### FAILED TO CLOSE DP')

    isplaying = xbmc.Player().isPlaying()
    counter   = 1
    if xbmc.Player().isPlayingAudio():
        return True
# If xbmc player is not yet active give it some time to initialise
    while not isplaying and counter < timeout:
        xbmc.sleep(1000)
        isplaying = xbmc.Player().isPlaying()
        dolog('### XBMC Player not yet active, sleeping for %s seconds' % counter)
        counter += 1

    success = 0
    counter = 0

# If it's playing give it time to physically start streaming then attempt to pull some info
    if isplaying:
        xbmc.sleep(1000)
        while not success and counter < 10:
            try:
                if xbmc.Player().isPlayingVideo():
                    infotag = xbmc.Player().getVideoInfoTag()
                vidtime = xbmc.Player().getTime()
                if vidtime > 0:
                    success = 1

# If playback doesn't start automatically (buffering) we force it to play
                else:
                    dolog('### Playback active but time at zero, trying to unpause')
                    xbmc.executebuiltin('PlayerControl(Play)')
                    xbmc.sleep(2000)
                    vidtime = xbmc.Player().getTime()
                    if vidtime > 0:
                        success = 1

# If no infotag or time could be pulled then we assume playback failed, try and stop the xbmc.player
            except:
                counter += 1
                xbmc.sleep(1000)

# Check if the busy dialog is still active from previous locked up playback attempt
    isbusy  = xbmc.getCondVisibility('Window.IsActive(busydialog)')
    counter   = 1
    while isbusy:
        dolog('### Busy dialog active, sleeping for %ss' % counter)
        xbmc.sleep(1000)
        isbusy  = xbmc.getCondVisibility('Window.IsActive(busydialog)')
        counter += 1
        if counter == 5:
            xbmc.executebuiltin('Dialog.Close(busydialog)')

    if not success:
        xbmc.executebuiltin('PlayerControl(Stop)')
        dolog('### Failed playback, stopped stream')
        shutil.rmtree(check_started)
        return False

    else:
        shutil.rmtree(check_started)
        return True
コード例 #15
0
ファイル: directory.py プロジェクト: stick141/modules4all
def Add_Dir(name, url='', mode='', folder=False, icon='', fanart='', description='', info_labels={}, set_art={}, set_property={}, content_type='', context_items=None, context_override=False, playable=False):
    """
This allows you to create a list item/folder inside your add-on.
Please take a look at your addon default.py comments for more information
(presuming you created one at http://totalrevolution.tv)

TOP TIP: If you want to send multiple variables through to a function just
send through as a dictionary encapsulated in quotation marks. In the function
you can then use the following code to access them:

params = eval(url)
^ That will then give you a dictionary where you can just pull each variable and value from.

CODE: Add_Dir(name, url, mode, [folder, icon, fanart, description, info_labels, content_type, context_items, context_override, playable])

AVAILABLE PARAMS:

    (*) name  -  This is the name you want to show for the list item

    url   -  This is a temporary global variable (string), when you click on
    another list item it will change to whatever you have that set to. If you
    send through a url starting with plugin:// the item will open up into
    that plugin path.

    mode  -  The mode you want to open when this item is clicked, this is set
    in your master_modes dictionary (see template add-on linked above)

    folder       -  This is an optional boolean, by default it's set to False.
    True will open into a folder rather than an executable command

    icon         -  The path to the thumbnail you want to use for this list item

    fanart       -  The path to the fanart you want to use for this list item

    description  - A description of your list item, it's skin dependant but this
    usually appears below the thumbnail

    info_labels  - You can send through any number of info_labels via this option.
    For full details on the infolabels available please check the pydocs here:
    http://mirrors.kodi.tv/docs/python-docs/16.x-jarvis/xbmcgui.html#ListItem-setInfo

    When passing through infolabels you need to use a dictionary in this format:
    {"genre":"comedy", "title":"test video"}
    
    set_art  -  Using the same format as info_labels you can set your artwork via
    a dictionary here. Full details can be found here:
    http://mirrors.kodi.tv/docs/python-docs/16.x-jarvis/xbmcgui.html#ListItem-setArt

    set_property  -  Using the same format as info_labels you can set your artwork via
    a dictionary here. Full details can be found here:
    http://kodi.wiki/view/InfoLabels#ListItem

    content_type - By default this will set the content_type for kodi to a blank string
    which is what Kodi expects for generic category listings. There are plenty of different
    types though and when set Kodi will perform different actions (such as access the
    database looking for season/episode information for the list item).

    WARNING: Setting the wrong content type for your listing can cause the system to
    log thousands of error reports in your log, cause the system to lag and make
    thousands of unnecessary db calls - sometimes resulting in a crash. You can find
    details on the content_types available here: http://forum.kodi.tv/showthread.php?tid=299107

    context_items - Add context items to your directory. The params you need to send through
    need to be in a list format of [(label, action,),] look at the example code below for
    more details.

    context_override - By default your context items will be added to the global context
    menu items but you can override this by setting this to True and then only your
    context menu items will show.

    playable  -  By default this is set to False but if set to True kodi will just try
    and play this item natively with no extra fancy functions.

EXAMPLE:
my_context = [('Music','xbmc.executebuiltin("ActivateWindow(music)")'),('Programs','xbmc.executebuiltin("ActivateWindow(programs)")')]
# ^ This is our two basic context menu items (music and programs)

Add_Dir(name='TEST DIRECTORY', url='', mode='test_directory', folder=True, context_items=my_context, context_override=True)
# ^ This will add a folder AND a context menu item for when bring up the menu (when focused on this directory).
# ^^ The context_override is set to True which means it will override the default Kodi context menu items.

Add_Dir(name='TEST ITEM', url='', mode='test_item', folder=False, context_items=my_context, context_override=False)
# ^ This will add an item to the list AND a context menu item for when bring up the menu (when focused on this item).
# ^^ The context_override is set to False which means the new items will appear alongside the default Kodi context menu items.
~"""
    


    from __init__       import dolog
    from systemtools    import Data_Type

    module_id   =  'script.module.python.koding.aio'
    this_module =  xbmcaddon.Addon(id=module_id)

    addon_handle = int(sys.argv[1])
# Check we're in an appropriate section for the content type set
    dolog(xbmc.getInfoLabel('Window.Property(xmlfile)'))
    song_only_modes  = ['songs','artist','album','song','music']
    video_only_modes = ['sets','tvshows','seasons','actors','directors','unknown','video','set','movie','tvshow','season','episode']
    if xbmc.getInfoLabel('Window.Property(xmlfile)') == 'MyVideoNav.xml' and content_type in song_only_modes:
        content_type = ''
    if xbmc.getInfoLabel('Window.Property(xmlfile)') == 'MyMusicNav.xml' and content_type in video_only_modes:
        content_type = ''

    if description == '':
        description = this_module.getLocalizedString(30837)

    if Data_Type(info_labels) != 'dict':
        dialog.ok('WRONG INFO LABELS', 'Please check documentation, these should be sent through as a dictionary.')

    if Data_Type(set_art) != 'dict':
        dialog.ok('WRONG SET_ART', 'Please check documentation, these should be sent through as a dictionary.')

    if Data_Type(set_property) != 'dict':
        dialog.ok('WRONG SET_PROPERTY', 'Please check documentation, these should be sent through as a dictionary.')
     
# Set the default title, filename and plot if not sent through already via info_labels
    try:
        title = info_labels["Title"]
        if title == '':
            info_labels["Title"] = name
    except:
        info_labels["Title"] = name

    try:
        filename = info_labels["FileName"]
        # if filename == '':
        #     info_labels["FileName"] = name
    except:
        info_labels["FileName"] = name

    try:
        plot = info_labels["plot"]
        if plot == '':
            info_labels["plot"] = description
    except:
        info_labels["plot"] = description
# Set default thumbnail image used for listing (if not sent through via set_art)
    try:
        set_art["icon"]
    except:
        set_art["icon"] = icon

# Set default Fanart if not already sent through via set_property
    try:
        set_property["Fanart_Image"]
    except:
        set_property["Fanart_Image"] = fanart

# Set the main listitem properties
    liz = xbmcgui.ListItem(label=str(name), iconImage=str(icon), thumbnailImage=str(icon))

# Set the infolabels
    liz.setInfo(type=content_type, infoLabels=info_labels)

# Set the artwork
    liz.setArt(set_art)

# Loop through the set_property list and set each item in there
    for item in set_property.items():
        liz.setProperty(item[0], item[1])

# Add a context item (if details for context items are sent through)
    if context_items:
        liz.addContextMenuItems(context_items, context_override)

    u   = sys.argv[0]
    u += "?mode="           +str(mode)
    u += "&url="            +urllib.quote_plus(url)
    u += "&name="           +urllib.quote_plus(name)
    u += "&iconimage="      +urllib.quote_plus(icon)
    u += "&fanart="         +urllib.quote_plus(fanart)
    u += "&description="    +urllib.quote_plus(description)
    
    if url.startswith('plugin://'):
        xbmcplugin.addDirectoryItem(handle=addon_handle,url=url,listitem=liz,isFolder=True) 

    elif folder:
        xbmcplugin.addDirectoryItem(handle=addon_handle,url=u,listitem=liz,isFolder=True)

    elif playable:
        liz.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem(handle=addon_handle,url=url,listitem=liz,isFolder=False) 

    else:
        xbmcplugin.addDirectoryItem(handle=addon_handle,url=u,listitem=liz,isFolder=False) 
コード例 #16
0
ファイル: web.py プロジェクト: stick141/modules4all
def Open_URL(url='',post_type='get',payload={},headers={'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'},cookies=True,auth=None,timeout=None,cookiejar=None):
    """
If you need to pull the contents of a webpage it's very simple to do so by using this function.

IMPORTANT: This function is designed to convert a query string into a post.
If you want to send through a post which contains ampersands or question
marks you MUST send the params through as a dictionary. By default this function
presumes the url only contains one question mark and it splits at that point and
will then split the params at every instance of an ampersand.

CODE:   koding.Open_URL(url,[post_type,payload,headers,cookies,auth,timeout,cookiejar])

AVAILABLE PARAMS:

    url  -  This is the main url you want to send through. Send it through
    as a query string format even if it's a post.

    post_type  -  By default this is set to 'get' but this can be set to 'post',
    if set to post the query string will be split up into a post format automatically.
    
    payload - By default this is not used but if you just want a standard
    basic Open_URL function you can add a dictionary of params here. If you
    don't enter anything in here the function will just split up your url
    accordingly. Make sure you read the important information at the top
    of this tutorial text.

    headers -  Optionally send through headers in form of a dictionary.

    cookies  -  If set to true your request will send through and store cookies.

    auth  -  User/pass details

    timeout  -  Optionally set a timeout for the request.

    cookiejar  -  An name for the location to store cookies. By default it's
    set to addon_data/<addon_id>/cookies/cookiejar but if you have multiple
    websites you access then you may want to use a separate filename for each site.

EXAMPLE CODE:
url_contents = koding.Open_URL('http://testpage.com?query1=value1&query2=value2', post_type='get')
koding.Text_Box('CONTENTS OF WEB PAGE',url_contents)
~"""
    import os
    import pickle
    import requests
    import sys
    import xbmc
    import xbmcaddon

    from __init__   import converthex, dolog, Encryption, ADDON_ID, LOGIN, FORUM, USERNAME, PASSWORD, KODI_VER
    from addons     import Addon_Info
    from filetools  import Text_File
    dolog('POST TYPE: %s'%post_type)
    dolog('url: %s'%url)
    Addon_Version = Addon_Info(id='version')
    Addon_Profile = xbmc.translatePath(Addon_Info(id='profile'))
    Cookie_Folder = os.path.join(Addon_Profile,'cookies')
    if not os.path.exists(Cookie_Folder):
        os.makedirs(Cookie_Folder)

    if cookiejar == None:
        Cookie_Jar = os.path.join(Cookie_Folder,'cookiejar')
    else:
        Cookie_Jar = os.path.join(Cookie_Folder,cookiejar)
    
    my_cookies = None
    if cookies:
        if os.path.exists(Cookie_Jar):
            try:
                with open(Cookie_Jar, 'rb') as f:
                    my_cookies = pickle.load(f)
            except:
                my_cookies = None

# If the payload is empty we split the params
    if len(payload) == 0:
        dolog('###### QUERY STRING CONVERSION MODE')

# If the url sent through is not http then we presume it's hitting the NaN page
        if not url.startswith(converthex('68747470')):
            NaN_URL = True
            args = url
            post_type = 'post'
            url = converthex('687474703a2f2f6e6f6f6273616e646e657264732e636f6d2f43505f53747566662f6c6f67696e5f74657374696e672e7068703f753d257326703d257326663d257326613d257326763d2573266b3d257326653d2573') % (USERNAME, PASSWORD, FORUM, ADDON_ID, Addon_Version, KODI_VER, args)
        else:
            NaN_URL = False
        if '?' in url:
            url, args = url.split('?')
            args = args.split('&')
            for item in args:
                var, data = item.split('=')
                if NaN_URL:
                    payload[var] = Encryption('e', data)
                else:
                    payload[var] = data

    dolog('PAYLOAD: %s'%payload)

    try:
        if post_type == 'post':
            r = requests.post(url, payload, headers=headers, cookies=my_cookies, auth=auth, timeout=timeout)
        else:
            r = requests.get(url, payload, headers=headers, cookies=my_cookies, auth=auth, timeout=timeout)
    except:
        dolog('Failed to pull content for %s'%url)
        return False
    dolog('### CODE: %s   |   REASON: %s' % (r.status_code, r.reason))
    if r.status_code >= 200 and r.status_code < 400:
        content = r.text.encode('utf-8')
        dolog('content: %s'%content)
        if cookies:
            with open(Cookie_Jar, 'wb') as f:
                pickle.dump(r.cookies, f)
        return content
    else:
        dolog('Failed to pull content for %s'%url)
        return False
コード例 #17
0
ファイル: video.py プロジェクト: smoke61/modules4all
def M3U_Selector(url, post_type='get', header='Stream Selection'):
    """
Send through an m3u/m3u8 playlist and have the contents displayed via a dialog select.
The return will be a dictionary of 'name' and 'url'. You can send through either
a locally stored filepath or an online URL.

This function will try it's best to pull out the relevant playlist details even if the
web page isn't a correctly formatted m3u playlist (e.g. an m3u playlist embedded into
a blog page).

CODE: M3U_Selector(url, [post_type, header])

AVAILABLE PARAMS:
    (*) url  -  The location of your m3u file, this can be local or online

    post_type  -  If you need to use POST rather than a standard query string
    in your url set this to 'post', by default it's set to 'get'.

    header  -  This is the header you want to appear at the top of your dialog
    selection window, by default it's set to "Stream Selection"

EXAMPLE CODE:
# This example uses YouTube plugin paths but any playable paths will work
vid = koding.M3U_Selector(url='http://totalrevolution.tv/videos/playlists/youtube.m3u')

# Make sure there is a valid link returned
if vid:
    playback = koding.Play_Video(video=vid['url'], showbusy=False)
    if playback:
        dialog.ok('SUCCESS!','Congratulations the playback was successful!')
        xbmc.Player().stop()
    else:
        dialog.ok('OOPS!','Looks like something went wrong there, the playback failed. Check the links are still valid.')
~"""
    from web import Open_URL
    from vartools import Cleanup_String, Find_In_Text
    from filetools import Text_File
    success = False
    if url.startswith('http'):
        content = Open_URL(url=url, post_type=post_type, timeout=10)
    else:
        try:
            url = xbmc.translatePath(url)
        except:
            pass
        content = Text_File(url, 'r')
    if content:
        newcontent = content.splitlines()
        name_array = []
        url_array = []
        name = ''
        for line in newcontent:
            line = line.strip()
            # Grab the name of the stream
            if line.startswith('#EXT'):
                name = line.split(',')
                name.pop(0)
                name = ''.join(name)
        # Grab the url(s) of the stream
            if name != '' and line != '' and not line.startswith('#EXT'):
                name_array.append(Cleanup_String(name))
                line = line.replace('<br>',
                                    '').replace('<br />',
                                                '').replace('<br/>', '')
                line = line.replace('</p>',
                                    '').replace('</div>',
                                                '').replace('</class>', '')
                dolog('line: %s' % line)
                if 'm3u' in line or 'm3u8' in line:
                    line = 'LIST~' + line
                if 'src="' in line:
                    line = Find_In_Text(content=line, start='src="',
                                        end='"')[0]
                url_array.append(line)
                name = ''
                line = ''
        # If there is only one entry with no names/comments just return as unknown with the link
            if not '#EXT' in content:
                return {'name': 'Unknown', 'url': line}

    # If there's a list we show a dialog select of the available links
        if len(name_array) > 0:
            choice = xbmcgui.Dialog().select(header, name_array)
            if choice >= 0:

                # If the selection is a final url and not a list of multiple links
                if not url_array[choice].startswith('LIST~'):
                    success = True
                    return {
                        'name': name_array[choice],
                        'url': url_array[choice]
                    }

            # List of multiple links detected, give option of which link to play
                else:
                    clean_link = url_array[choice].replace('LIST~', '')
                    content = Open_URL(url=clean_link, timeout=10)
                    if content:
                        newcontent = content.splitlines()
                        name_array = []
                        url_array = []
                        name = ''
                        counter = 1
                        for line in newcontent:
                            # Show name as link 1,2,3,4 etc.
                            if line.startswith('#EXT'):
                                name = 'LINK ' + str(counter)
                        # Grab the link(s) to the video
                            if name != '' and line != '' and not line.startswith(
                                    '#EXT'):
                                name_array.append(name)
                                line = line.replace('<br>', '').replace(
                                    '<br />', '').replace('<br/>', '')
                                line = line.replace('</p>', '').replace(
                                    '</div>', '').replace('</class>', '')
                                url_array.append(line)
                                name = ''
                                line = ''
                                counter += 1
                        # If there is only one entry with no names/comments just return as unknown with the link
                            if not '#EXT' in content:
                                return {'name': 'Unknown', 'url': line}

                    # Give option of which link to play in case of multiple links available
                        if len(name_array) > 0:
                            choice = xbmcgui.Dialog().select(
                                header, name_array)
                            if choice >= 0:
                                success = True
                                return {
                                    'name': name_array[choice],
                                    'url': url_array[choice]
                                }
    if not success:
        xbmcgui.Dialog().ok(
            'NO LINKS FOUND',
            'Sorry no valid links could be found for this stream.')
        return False
コード例 #18
0
ファイル: video.py プロジェクト: smoke61/modules4all
def Play_Video(video,
               showbusy=True,
               content='video',
               ignore_dp=False,
               timeout=10,
               item=None,
               player=xbmc.Player()):
    """
This will attempt to play a video and return True or False on
whether or not playback was successful. This function is similar
to Check_Playback but this actually tries a number of methods to
play the video whereas Check_Playback does not actually try to
play a video - it will just return True/False on whether or not
a video is currently playing.

If you have m3u or m3u8 playlist links please use the M3U_Selector
function to get the final resolved url.

CODE: Play_Video(video, [showbusy, content, ignore_dp, timeout, item])

AVAILABLE PARAMS:

    (*) video  -  This is the path to the video, this can be a local
    path, online path or a channel number from the PVR.

    showbusy  -  By default this is set to True which means while the
    function is attempting to playback the video the user will see the
    busy dialog. Set to False if you prefer this not to appear but do
    bare in mind a user may navigate to another section and try playing
    something else if they think this isn't doing anything.

    content  -  By default this is set to 'video', however if you're
    passing through audio you may want to set this to 'music' so the
    system can correctly set the tags for artist, song etc.

    ignore_dp  -  By default this is set to True but if set to False
    this will ignore the DialogProgress window. If you use a DP while
    waiting for the stream to start then you'll want to set this True.
    Please bare in mind the reason this check is in place and enabled
    by default is because some streams do bring up a DialogProgress
    when initiated (such as f4m proxy links) and disabling this check
    in those circumstances can cause false positives.

    timeout  -  This is the amount of time you want to allow for playback
    to start before sending back a response of False. Please note if
    ignore_dp is set to True then it will also add a potential 10s extra
    to this amount if a DialogProgress window is open. The default setting
    for this is 10s.

    item  -  By default this is set to None and in this case the metadata
    will be auto-populated from the previous Add_Dir so you'll just get the
    basics like title, thumb and description. If you want to send through your
    own metadata in the form of a dictionary you can do so and it will override
    the auto-generation. If anything else sent through no metadata will be set,
    you would use this option if you've already set metadata in a previous function.


EXAMPLE CODE:
isplaying = koding.Play_Video('http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')
if isplaying:
    dialog.ok('PLAYBACK SUCCESSFUL','Congratulations, playback was successful')
    xbmc.Player().stop()
else:
    dialog.ok('PLAYBACK FAILED','Sorry, playback failed :(')
~"""

    dolog('### ORIGINAL VIDEO: %s' % video)
    import urlresolver
    try:
        import simplejson as json
    except:
        import json

    if not item:
        meta = {}
        for i in [
                'title', 'originaltitle', 'tvshowtitle', 'year', 'season',
                'episode', 'genre', 'rating', 'votes', 'director', 'writer',
                'plot', 'tagline'
        ]:
            try:
                meta[i] = xbmc.getInfoLabel('listitem.%s' % i)
            except:
                pass
        meta = dict((k, v) for k, v in meta.iteritems() if not v == '')
        if 'title' not in meta:
            meta['title'] = xbmc.getInfoLabel('listitem.label')
        icon = xbmc.getInfoLabel('listitem.icon')
        item = xbmcgui.ListItem(path=video,
                                iconImage=icon,
                                thumbnailImage=icon)
        if content == "music":
            try:
                meta['artist'] = xbmc.getInfoLabel('listitem.artist')
                item.setInfo(type='Music',
                             infoLabels={
                                 'title': meta['title'],
                                 'artist': meta['artist']
                             })
            except:
                item.setInfo(type='Video', infoLabels=meta)
        else:
            item.setInfo(type='Video', infoLabels=meta)

    elif type(item).__name__ == 'dict':
        item.setInfo(type='Video', infoLabels=meta)

    else:
        pass

    playback = False
    if showbusy:
        Show_Busy()

# if a plugin path is sent we try activate window
    if video.startswith('plugin://'):
        try:
            dolog('Attempting to play via xbmc.Player().play() method')
            player.play(video)
            playback = Check_Playback(ignore_dp, timeout)
        except:
            dolog(Last_Error())

# If an XBMC action has been sent through we do an executebuiltin command
    elif video.startswith('ActivateWindow') or video.startswith(
            'RunAddon') or video.startswith('RunScript') or video.startswith(
                'PlayMedia'):
        try:
            dolog('Attempting to play via xbmc.executebuiltin method')
            xbmc.executebuiltin('%s' % video)
            playback = Check_Playback(ignore_dp, timeout)
        except:
            dolog(Last_Error())

    elif ',' in video:
        # Standard xbmc.player method (a comma in url seems to throw urlresolver off)
        try:
            dolog('Attempting to play via xbmc.Player.play() method')
            player.play('%s' % video, item)
            playback = Check_Playback(ignore_dp, timeout)

# Attempt to resolve via urlresolver
        except:
            try:
                dolog('Attempting to resolve via urlresolver module')
                dolog('video = %s' % video)
                hmf = urlresolver.HostedMediaFile(url=video,
                                                  include_disabled=False,
                                                  include_universal=True)
                if hmf.valid_url() == True:
                    video = hmf.resolve()
                    dolog('### VALID URL, RESOLVED: %s' % video)
                player.play('%s' % video, item)
                playback = Check_Playback(ignore_dp, timeout)
            except:
                dolog(Last_Error())

# Play from a db entry - untested
    elif video.isdigit():
        dolog('### Video is digit, presuming it\'s a db item')
        command = (
            '{"jsonrpc": "2.0", "id":"1", "method": "Player.Open","params":{"item":{"channelid":%s}}}'
            % url)
        xbmc.executeJSONRPC(command)
        playback = Check_Playback(ignore_dp, timeout)

    else:
        # Attempt to resolve via urlresolver
        try:
            dolog('Attempting to resolve via urlresolver module')
            dolog('video = %s' % video)
            hmf = urlresolver.HostedMediaFile(url=video,
                                              include_disabled=False,
                                              include_universal=True)
            if hmf.valid_url() == True:
                video = hmf.resolve()
                dolog('### VALID URL, RESOLVED: %s' % video)
            player.play('%s' % video, item)
            playback = Check_Playback(ignore_dp, timeout)

# Standard xbmc.player method
        except:
            try:
                dolog('Attempting to play via xbmc.Player.play() method')
                player.play('%s' % video, item)
                playback = Check_Playback(ignore_dp, timeout)
            except:
                dolog(Last_Error())

    dolog('Playback status: %s' % playback)
    Show_Busy(False)
    counter = 1
    dialogprogress = xbmc.getCondVisibility('Window.IsActive(progressdialog)')
    if not ignore_dp:
        while dialogprogress:
            dp.create('Playback Good', 'Closing dialog...')
            dolog('Attempting to close dp #%s' % counter)
            dp.close()
            xbmc.sleep(1000)
            counter += 1
            dialogprogress = xbmc.getCondVisibility(
                'Window.IsActive(progressdialog)')

    return playback
コード例 #19
0
def Open_URL(url='',
             post_type='get',
             headers=None,
             cookies=True,
             auth=None,
             timeout=None,
             cookiejar=None):
    """
If you need to pull the contents of a webpage it's very simple to do so by using this function.

CODE:   koding.Open_URL(url,[post_type,headers,cookies,auth,timeout,cookiejar])

AVAILABLE PARAMS:

    url  -  This is the main url you want to send through. Send it through
    as a query string format even if it's a post.

    post_type  -  By default this is set to 'get' but this can be set to 'post',
    if set to post the query string will be split up into a post format automatically.
    
    headers -  Optionally send through headers in form of a dictionary.

    cookies  -  If set to true your request will send through and store cookies.

    auth  -  User/pass details

    timeout  -  Optionally set a timeout for the request.

    cookiejar  -  An name for the location to store cookies. By default it's
    set to addon_data/<addon_id>/cookies/cookiejar but if you have multiple
    websites you access then you may want to use a separate filename for each site.

EXAMPLE CODE:
url_contents = koding.Open_URL('http://testpage.com?query1=value1&query2=value2', post_type='get')
koding.Text_Box('CONTENTS OF WEB PAGE',url_contents)
~"""
    import os
    import pickle
    import requests
    import sys
    import xbmc
    import xbmcaddon

    from __init__ import converthex, dolog, Encryption, ADDON_ID, LOGIN, FORUM, USERNAME, PASSWORD, KODI_VER
    from addons import Addon_Info
    from filetools import Text_File

    Addon_Version = Addon_Info(id='version')
    Addon_Profile = xbmc.translatePath(Addon_Info(id='profile'))
    Cookie_Folder = os.path.join(Addon_Profile, 'cookies')
    if not os.path.exists(Cookie_Folder):
        os.makedirs(Cookie_Folder)

    if cookiejar == None:
        Cookie_Jar = os.path.join(Cookie_Folder, 'cookiejar')
    else:
        Cookie_Jar = os.path.join(Cookie_Folder, cookiejar)

    my_cookies = None
    if cookies:
        if os.path.exists(Cookie_Jar):
            try:
                with open(Cookie_Jar, 'rb') as f:
                    my_cookies = pickle.load(f)
            except:
                my_cookies = None

    payload = {}

    # If the url sent through is not http then we presume it's hitting the NaN page
    if not url.startswith(converthex('68747470')):
        NaN_URL = True
        args = url
        post_type = 'post'
        url = converthex(
            '687474703a2f2f6e6f6f6273616e646e657264732e636f6d2f43505f53747566662f6c6f67696e5f74657374696e672e7068703f753d257326703d257326663d257326613d257326763d2573266b3d257326653d2573'
        ) % (USERNAME, PASSWORD, FORUM, ADDON_ID, Addon_Version, KODI_VER,
             args)
    else:
        NaN_URL = False
    if '?' in url:
        url, args = url.split('?')
        args = args.split('&')
        for item in args:
            var, data = item.split('=')
            if NaN_URL:
                payload[var] = Encryption('e', data)
            else:
                payload[var] = data
    try:
        if post_type == 'post':
            r = requests.post(url,
                              payload,
                              headers=headers,
                              cookies=my_cookies,
                              auth=auth,
                              timeout=timeout)
        else:
            r = requests.get(url,
                             payload,
                             headers=headers,
                             cookies=my_cookies,
                             auth=auth,
                             timeout=timeout)
    except:
        return 'This url could not be opened: %s' % url
    dolog('### CODE: %s   |   REASON: %s' % (r.status_code, r.reason))
    if r.status_code >= 200 and r.status_code < 400:
        content = r.text.encode('utf-8')
        dolog('content: %s' % content)
        if cookies:
            with open(Cookie_Jar, 'wb') as f:
                pickle.dump(r.cookies, f)
        return content
    else:
        return 'This url could not be opened: %s' % url
コード例 #20
0
def Toggle_Addons(addon='all', enable=True, safe_mode=True, exclude_list=[], new_only=True, refresh=True, update_status=0):
    """
Send through either a list of add-on ids or one single add-on id.
The add-ons sent through will then be added to the addons*.db
and enabled or disabled (depending on state sent through).

WARNING: If safe_mode is set to False this directly edits the
addons*.db rather than using JSON-RPC. Although directly amending
the db is a lot quicker there is no guarantee it won't cause
severe problems in later versions of Kodi (this was created for v17).
DO NOT set safe_mode to False unless you 100% understand the consequences!

CODE:  Toggle_Addons([addon, enable, safe_mode, exclude_list, new_only, refresh])

AVAILABLE PARAMS:
    (*) addon  -  This can be a list of addon ids, one single id or
    'all' to enable/disable all. If enabling all you can still use
    the exclude_list for any you want excluded from this function.
    enable  -  By default this is set to True, if you want to disable
    the add-on(s) then set this to False.
    
    safe_mode  -  By default this is set to True which means the add-ons
    are enabled/disabled via JSON-RPC which is the method recommended by
    the XBMC foundation. Setting this to False will result in a much
    quicker function BUT there is no guarantee this will work on future
    versions of Kodi and it may even cause corruption in future versions.
    Setting to False is NOT recommended and you should ONLY use this if
    you 100% understand the risks that you could break multiple setups.
    
    exclude_list  -  Send through a list of any add-on id's you do not
    want to be included in this command.
    
    new_only  -  By default this is set to True so only newly extracted
    add-on folders will be enabled/disabled. This means that any existing
    add-ons which have deliberately been disabled by the end user are
    not affected.
    
    refresh  - By default this is set to True, it will refresh the
    current container and also force a local update on your add-ons db.

    update_status  - When running this function it needs to disable the
    auto-update of add-ons by Kodi otherwise it risks crashing. This
    update_status paramater is the state you want Kodi to revert back to
    once the toggle of add-ons has completed. By default this is set to 0
    which is auto-update. You can also choose 1 (notify of updates) or 2
    (disable auto updates).

EXAMPLE CODE:
from systemtools import Refresh
xbmc.executebuiltin('ActivateWindow(Videos, addons://sources/video/)')
xbmc.sleep(2000)
dialog.ok('DISABLE YOUTUBE','We will now disable YouTube (if installed)')
koding.Toggle_Addons(addon='plugin.video.youtube', enable=False, safe_mode=True, exclude_list=[], new_only=False)
koding.Refresh('container')
xbmc.sleep(2000)
dialog.ok('ENABLE YOUTUBE','When you click OK we will enable YouTube (if installed)')
koding.Toggle_Addons(addon='plugin.video.youtube', enable=True, safe_mode=True, exclude_list=[], new_only=False)
koding.Refresh('container')
~"""
    from __init__       import dolog
    from filetools      import DB_Path_Check, Get_Contents
    from database       import DB_Query
    from systemtools    import Data_Type, Last_Error, Refresh, Set_Setting, Sleep_If_Function_Active, Timestamp

    Set_Setting('general.addonupdates', 'kodi_setting', '2')
    dolog('disabled auto updates for add-ons')
    kodi_ver        = int(float(xbmc.getInfoLabel("System.BuildVersion")[:2]))
    addons_db       = DB_Path_Check('addons')
    data_type       = Data_Type(addon)
    state           = int(bool(enable))
    enabled_list    = []
    disabled_list   = []
    if kodi_ver >= 17:
        on_system   = DB_Query(addons_db,'SELECT addonID, enabled from installed')
# Create a list of enabled and disabled add-ons already on system
        enabled_list  = Addon_List(enabled=True)
        disabled_list = Addon_List(enabled=False)

# If addon has been sent through as a string we add into a list
    if data_type == 'unicode':
        addon = addon.encode('utf8')
        data_type = Data_Type(addon)

    if data_type == 'str' and addon!= 'all':
        addon = [addon]

# Grab all the add-on ids from addons folder
    if addon == 'all':
        addon     = []
        ADDONS    = xbmc.translatePath('special://home/addons')
        my_addons = Get_Contents(path=ADDONS, exclude_list=['packages','temp'])
        for item in my_addons:
            addon_id = Get_Addon_ID(item)
            addon.append(addon_id)

# Find out what is and isn't enabled in the addons*.db
    temp_list = []
    for addon_id in addon:
        if not addon_id in exclude_list and addon_id != '':
            dolog('CHECKING: %s'%addon_id)
            if addon_id in disabled_list and not new_only and enable:
                temp_list.append(addon_id)
            elif addon_id not in disabled_list and addon_id not in enabled_list:
                temp_list.append(addon_id)
            elif addon_id in enabled_list and not enable:
                temp_list.append(addon_id)
            elif addon_id in disabled_list and enable:
                temp_list.append(addon_id)
    addon = temp_list

# If you want to bypass the JSON-RPC mode and directly modify the db (READ WARNING ABOVE!!!)
    if not safe_mode and kodi_ver >= 17:
        installedtime   = Timestamp('date_time')
        insert_query    = 'INSERT or IGNORE into installed (addonID , enabled, installDate) VALUES (?,?,?)'
        update_query    = 'UPDATE installed SET enabled = ? WHERE addonID = ? '
        insert_values   = [addon, state, installedtime]
        try:
            for item in addon:
                DB_Query(addons_db, insert_query, [item, state, installedtime])
                DB_Query(addons_db, update_query, [state, item])
        except:
            dolog(Last_Error())
        if refresh:
            Refresh()

# Using the safe_mode (JSON-RPC)
    else:
        mydeps        = []
        final_enabled = []
        if state:
            my_value      = 'true'
            log_value     = 'ENABLED'
            final_addons  = []
        else:
            my_value      = 'false'
            log_value     = 'DISABLED'
            final_addons  = addon

        for my_addon in addon:

        # If enabling the add-on then we also check for dependencies and enable them first
            if state:
                dolog('Checking dependencies for : %s'%my_addon)
                dependencies = Dependency_Check(addon_id=my_addon, recursive=True)
                mydeps.append(dependencies)

    # if enable selected we traverse through the dependencies enabling addons with lowest amount of deps to highest
        if state:
            mydeps = sorted(mydeps, key=len)
            for dep in mydeps:
                counter = 0
                for item in dep:
                    enable_dep = True
                    if counter == 0:
                        final_addons.append(item)
                        enable_dep = False
                    elif item in final_enabled:
                        enable_dep = False
                    else:
                        enable_dep = True
                    if enable_dep:
                        if not item in exclude_list and not item in final_enabled and not item in enabled_list:
                            dolog('Attempting to enable: %s'%item)
                            if Set_Setting(setting_type='addon_enable', setting=item, value = 'true'):
                                dolog('%s now %s' % (item, log_value))
                                final_enabled.append(item)
                    counter += 1

    # Now the dependencies are enabled we need to enable the actual main add-ons
        for my_addon in final_addons:
            if not my_addon in final_enabled:
                dolog('Attempting to enable: %s'%my_addon)
                if Set_Setting(setting_type='addon_enable', setting=my_addon, value = my_value):
                    dolog('%s now %s' % (my_addon, log_value))
                    final_enabled.append(addon)
            else:
                dolog('Already enabled, skipping: %s'%my_addon)
    if refresh:
        Refresh(['addons','container'])
    Set_Setting('general.addonupdates', 'kodi_setting', '%s'%update_status)
#----------------------------------------------------------------
コード例 #21
0
ファイル: web.py プロジェクト: varunrai/scrapers
def Open_URL(url='',post_type='get',payload={},headers={'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'},cookies=True,auth=None,timeout=None,cookiejar=None,proxies={}):
    """
If you need to pull the contents of a webpage it's very simple to do so by using this function.
This uses the Python Requests module, for more detailed info on how the params work
please look at the following link: http://docs.python-requests.org/en/master/user/advanced/

IMPORTANT: This function will attempt to convert a url with a query string into the
correct params for a post or get command but I highly recommend sending through your
query string as a dictionary using the payload params. It's much cleaner and is a
safer way of doing things, if you send through your url with a query string attached
then I take no responsibility if it doesn't work!

CODE:   Open_URL(url,[post_type,payload,headers,cookies,auth,timeout,cookiejar])

AVAILABLE PARAMS:

    url  -  This is the main url you want to send through. Send it through
    as a query string format even if it's a post.

    post_type  -  By default this is set to 'get' but this can be set to 'post',
    if set to post the query string will be split up into a post format automatically.
    
    payload - By default this is not used but if you just want a standard
    basic Open_URL function you can add a dictionary of params here. If you
    don't enter anything in here the function will just split up your url
    accordingly. Make sure you read the important information at the top
    of this tutorial text.

    headers -  Optionally send through headers in form of a dictionary.

    cookies  -  If set to true your request will send through and store cookies.

    auth  -  User/pass details

    timeout  -  Optionally set a timeout for the request.

    cookiejar  -  An name for the location to store cookies. By default it's
    set to addon_data/<addon_id>/cookies/cookiejar but if you have multiple
    websites you access then you may want to use a separate filename for each site.

    proxies - Use a proxy for accessing the link, see requests documentation for full
    information but essentially you would send through a dictionary like this:
    proxies = {"http":"http://10.10.1.10:3128","htts":"https://10.10.1.10:3128"}

EXAMPLE CODE:
dialog.ok('OPEN FORUM PAGE','We will attempt to open the noobsandnerds forum page and return the contents. You will now be asked for your forum credentials.')
myurl = 'http://noobsandnerds.com/support/index.php'
username = koding.Keyboard('ENTER USERNAME')
password = koding.Keyboard('ENTER PASSWORD')
params = {"username":username,"password":password}
xbmc.log(repr(params),2)
url_contents = koding.Open_URL(url=myurl, payload=params, post_type='get')
koding.Text_Box('CONTENTS OF WEB PAGE',url_contents)
~"""
    import os
    import pickle
    import requests
    import sys
    import xbmc
    import xbmcaddon

    from __init__   import converthex, dolog, ADDON_ID, KODI_VER
    from addons     import Addon_Info
    from filetools  import Text_File

    Addon_Version = Addon_Info(id='version')
    Addon_Profile = Addon_Info(id='profile')
    Cookie_Folder = os.path.join(Addon_Profile,'cookies')
    xbmc.log(Cookie_Folder,2)
    if not xbmcvfs.exists(Cookie_Folder):
        xbmcvfs.mkdirs(Cookie_Folder)

    if cookiejar == None:
        Cookie_Jar = os.path.join(Cookie_Folder,'cookiejar')
    else:
        Cookie_Jar = os.path.join(Cookie_Folder,cookiejar)
    
    my_cookies = None
    if cookies:
        if xbmcvfs.exists(Cookie_Jar):
            try:
                openfile = xbmcvfs.File(Cookie_Jar)
                f = openfile.read()
                openfile.close()
                my_cookies = pickle.load(f)
            except:
                my_cookies = None

# If the payload is empty we split the params
    if len(payload) == 0:

        if '?' in url:
            url, args = url.split('?')
            args = args.split('&')
            for item in args:
                var, data = item.split('=')
                payload[var] = data

    dolog('PAYLOAD: %s'%payload)

    try:
        if Python_Version() < 2.7 and url.startswith('https'):
            url = url.replace('https','http')

        if post_type == 'post':
            r = requests.post(url, payload, headers=headers, cookies=my_cookies, auth=auth, timeout=timeout, proxies=proxies)
        else:
            r = requests.get(url, payload, headers=headers, cookies=my_cookies, auth=auth, timeout=timeout, proxies=proxies)
    except:
        dolog('Failed to pull content for %s'%url)
        return False
    dolog('### CODE: %s   |   REASON: %s' % (r.status_code, r.reason))
    if r.status_code >= 200 and r.status_code < 400:
        content = r.text.encode('utf-8')
        dolog('content: %s'%content)
        if cookies:
            openfile = xbmcvfs.File(Cookie_Jar,'wb')
            pickle.dump(r.cookies, openfile)
            openfile.close()
        return content
    else:
        dolog('Failed to pull content for %s'%url)
        return False