Skip to content

Example source code

Dag Wieers edited this page Feb 14, 2020 · 6 revisions

Sending a JSONRPC signal to the Up Next add-on

The following example code can help implement Up Next integration without requiring AddonSignals.

Typically to send the message to the Up Next add-on, you would do:

upnext_signal(sender='plugin.video.foobar', data=next_info)

kodiutils.py

import xbmc

def upnext_signal(sender, next_info):
    """Send a signal to Kodi using JSON RPC"""
    from base64 import b64encode
    from json import dumps
    from kodiutils import notify, to_unicode
    data = [to_unicode(b64encode(dumps(next_info).encode()))]
    notify(sender=sender + '.SIGNAL', message='upnext_data', data=data)

def notify(sender, message, data):
    """Send a notification to Kodi using JSON RPC"""
    result = jsonrpc(method='JSONRPC.NotifyAll', params=dict(
        sender=sender,
        message=message,
        data=data,
    ))
    if result.get('result') != 'OK':
        xbmc.log('Failed to send notification: ' + result.get('error').get('message'), 4)
        return False
    return True

def jsonrpc(**kwargs):
    """Perform JSONRPC calls"""
    from json import dumps, loads
    if kwargs.get('id') is None:
        kwargs.update(id=0)
    if kwargs.get('jsonrpc') is None:
        kwargs.update(jsonrpc='2.0')
    return loads(xbmc.executeJSONRPC(dumps(kwargs)))

def to_unicode(text, encoding='utf-8', errors='strict'):
    """Force text to unicode"""
    if isinstance(text, bytes):
        return text.decode(encoding, errors=errors)
    return text