Add-on:Kodi Callbacks

From Official Kodi Wiki
Revision as of 02:55, 4 February 2018 by Addonbot (talk | contribs) (Addon-Bot repo category update)
Jump to navigation Jump to search

Kodi Callbacks
icon.png

See this add-on on the kodi.tv showcase

Author: KenV99
Website: link
Type: Services
Repo:

License: GPL v3.0
Source: Source code
Summary: Callbacks for Kodi
Home icon grey.png   ▶ Add-ons ▶ Kodi Callbacks
Attention talk.png Need help with this add-on? See here.

Provides user definable actions for specific events within Kodi. Credit to Yesudeep Mangalapilly (gorakhargosh on github) and contributors for watchdog and pathtools modules.

Installing

This add-on is installed from the Add-on browser located in Kodi as follows:

  1. Settings
  2. Add-ons
  3. Install from repository
  4. Services
  5. Kodi Callbacks
  6. Install



Features

  • Runs as a service when Kodi starts
  • Runs user configured tasks when events occur in Kodi (jump to list of events)
  • Currently can create tasks for:
  1. Running an external script with or without the shell
  2. Running an external python script either directly or via dynamic import
  3. Running a Kodi builtin
  4. Sending an http string (response)
  5. Sending a Json-RPC notification
  • Utilizes a simple substitution language so that runtime arguments can be mixed with static user-defined elements to send to the external file as arguments
  • 31 different Kodi events are supported
  • Tasks can be tested directly from the Settings page with direct user feedback for troubleshooting
  • New tasks can be created and shared with others by subclassing an abstract base class and then placing the file in the userdata/addon_data/script.service.kodi.callbacks/lib/tasks folder
    • It is better to put user tasks here than in the addon's tasks folder since that folder may be rewritten during updates
  • Credit to Yesudeep Mangalapilly (gorakhargosh on github) and contributors for watchdog and pathtools modules.

Installation

Overview

The script is not currently available via the official repo but has been submitted as of 27-02-2016.
The addon is now available through the official repo (isengard forward) as of 22-04-2016!!!
It has one dependency - the requests module. This should automatically be installed by Kodi.
If desired, it can also be downloaded manually copied to the Kodi Add-Ons folder, overwriting the previous version.
Or after download you can load it via the settings addon 'install from zip' action.
The most recent version of the script can be downloaded here: https://github.com/KenV99/service.kodi.callbacks/archive/master.zip

PLEASE NOTE: If you are updating from an installation from before 2-27-2016 (version 0.9.7.6 or earlier), you will be required to reset the settings to default and re-input them. I apologize, this could not be avoided.

Details

To manually install the script, first unzip the script to a convenient, temporary location and then copy the entire directory named ‘service.kodi.callbacks-master’ with its structure intact to the Kodi addons directory. In windows, this is typically located on your system drive at 'Users/Username/AppData/Roaming/Kodi/addons/'. If you have a previous installation, consider backing it up to a safe place before installing.

Remove the '-master' from the end of the folder name!!!

If you are replacing xbmc.callbacks2 which will no longer be developed, the settings from there are not compatible. Copy your settings over to the new addon and then disable or delete xbmc.callbacks2

Configuration

Overview

In Kodi go to System > Add-Ons > Enabled Add-Ons > Services > Kodi Callbacks > Configure

In general:

  1. Configure your task.
  2. On the next page, associate your task with one or more events.
  3. Click OK to save.
  4. Re-enter settings by clicking configure.
  5. Test your setup via the settings page.
  6. Re-test by triggering your event if possible.

Details

There are four pages of settings - Tasks, Events, General and Update

Settings - Tasks

Kodi-callbacks-settings1-1.PNG

You can configure up to 10 tasks.

For each task, select a type - builtin, http, python, script or json-rpc-notify.

For all you can configure:

  1. The maximum number of this task that can be running simultaneously
  2. The maximum number of times this task can be run for a given Kodi session
  3. A refractory period after a task is run where it won't be re-run

For different types, there may be additional parameters to configure:

  • For scripts:
    1. Whether the script requires the shell to run. In the majority of cases this is NOT needed. The addon will use bash on *nix or sh on Android for any .sh files.
    2. Also, whether the program should wait for the task to complete (useful to wait during testing if the outside script prints to stdout which will be displayed).
    3. Under some circumstances such as launching a daemon-like program, it may be desired NOT to wait for completion.
    4. NOTE: The script file line is displayed twice: the first opens a file picker dialog. The second will allow you to edit the line or you can enter text directly. This allows you to use standard naming short cuts (i.e ~/.) or otherwise edit the way the command is sent to the interpreter instead of being committed to only picking a file.
  • For python:
    1. Execute the python file directly OR
    2. Import the file as a module and call whatever is designated within as 'run' - arguments will be passed as run(args)
  • A note on Unicode filenames and directories:
    1. Please note that using scripts or python files with names with unicode characters beyond the ASCII character set for the above two task types is NOT uniformly supported on all platforms.
    2. To ensure that your files work, avoid using filenames or placing the files in directories with names that are outside the ASCII character set.
  • For http:
    1. Put only the url with port here. Further specification will be done on the events page when invoking this task.
    2. Optionally a username and password can be provided for Basic Auth only.
    3. Choose which http request type is desired (most commonly GET or POST).
    4. For POST or PUT, choose what Content-Type you want in the header.
    5. Other CGI query type data (i.e ?var1=x&var2=y) will be done on the events page.
  • For builtins:
    1. See the wiki for a list of functions: List_of_built-in_functions
    2. Arguments can be passed via userags when configuring the event
  • For json notifications:
    1. You can configure the 'sender' string to be used during the notification broadcast
    2. Note that all available data is sent in the 'data' submessage', so userargs is not utilized for this task

Note the task number as that is how it will be referred to on the next settings page.



Settings - Events

Kodi-callbacks-settings2-1.PNG

You can configure up to 10 events and have each use a different task or reuse the same task.

Click on 'Choose'. Your choice will appear on the following line after choosing. This was needed to make this work with other languages.

For each event, select an event type. There are currently 31 different events.

For some events, additional information is required:

  1. For JSON notification events, the sender, method and data are required. This uses the python xbmc.Monitor.OnNotification function. Note that this does not receive ALL notifications. This is a json notification receiver event. It is completely separate from the json-rpc-notify TASK which sends notifications.
  2. For Window Open and Close events, the window id is needed (see: Kodi Window Ids).
  3. For on Idle events, the idle time in seconds (note that idle is when there is no user interaction and no media is playing).
  4. For on Resume after Idle events, the idle time in seconds. This event will fire only after there is user activity after the defined idle time.
    1. All of the timers for on Idle and on Resume After Idle events are completely independent of one another and multiple definitions of idle time is supported.
    2. For example setting an on Idle event to dim your lights after 600 seconds and turn them off after 1200 seconds.
    3. Using on Resume After Idle, one could also set an event to turn them back on with user activity after 601 seconds, if desired.
  5. For detecting when a portion of a string is written to the log onLogSimple and and onLogRegex require 'matchIf' strings.
    1. A simple match detects a case-sensitive substring in an individual log line, while a regex match matches whatever you configure it to on a line.
    2. Log strings can also be rejected if a different portion matches 'rejectIf'.
  6. For File System Change events, the folder to be monitored, the file or folder patterns to monitor (ie. *.txt, *.*), the patterns to reject, whether to monitor folder changes and whether or not to monitor subfolders (recursive)
    1. For multiple patterns, separate them with a comma without spaces (i.e. "*.mkv,*.mp4,*.mov")
    2. Similar to Script Tasks, there are two lines on the settings page for the folder. The first is a standard folder picker and the second is a free text field. This allows one to edit or type the folder directly. The free text line will allow translation of Kodi's special directories (i.e. special://) as well as OS specific substitutions such as '~/.' or %appdata%.
    3. In many cases monitoring folder changes is not desirable as it may create two events for each change (i.e. adding a file causes a fileAdded event AND a folderChange event).
    4. Note that on OSX, this publisher will use a low-performing, resource intensive polling routine. If this presents an issue and you are adept, install watchdog via 'pip' and then go to your site-packages directory and copy over _fsevents.so and _watchdog_fsevents.so to the resources/lib directory. Requires XCODE is installed as well.
  7. There is a separate File System Change at Startup event
    1. This takes a snapshot of any monitored folders during a normal Kodi shutdown and saves it in the addon_data folder.
    2. The snapshot is reloaded at startup and compared to a new snapshot to detect changes, using patterns as above.
    3. If any changes are detected, a single event is fired. The user can obtain the list of changes via argument substitution, if desired.
Argument variable substitution
  • A variable substituted argument string can then optionally be provided to pass additional information to your task.
  • The variables that can be passed are dependent on the event and are shown on the settings page.
  • Only the variables shown will be searched for and substituted.
  • To ensure that literal percent signs are passed correctly, use '%%'.
  • Because of the way arguments are passed to script files and python files, they are usually split where spaces or commas occur.
  • If you need to ensure that a space is not split, for a space use %_ (percent underscore) and for a comma, use %__ (percent underscore underscore).
  • Spaces can also cause problems when they appear in the substituted variables.
  • -Depending on how your file processes arguments, consider placing double-quotes around variables that may contains spaces such as titles, filenames and loglines.
  • When the task that is being run is an http task using either POST or PUT, anything following double question-mark "??" will be treated as payload.
    1. The ?? will not appear as part of the transmitted url string.
    2. What you put following the ?? should depend on the Content-Type selected for the task on the Tasks settings page.

Note: If you wish to use the On Shutdown event to run a script after Kodi exits, one would use a task script which does not wait and pass out the pid (%pi) to the script. The script can then be configured to wait until the pid is no longer running and then execute the desired code. See below for example code using this technique.

Testing

A fully configured event can be tested from the Event Settings Page.

First click OK to cause any changes made to be written to the user settings file.

Then re-enter Settings and navigate back to the event to be tested and click "Test command'.

First some simple validation tests will be run and if they fail, this will be reported back to the user on the screen.

Then an attempt will be made to run the task with simulated runtime arguments (i.e. the filename, title, etc will be simulated).

NOTE: The test will, in most circumstances, wait for the task to 'return'. So if the task launches a program, no further information will be provided until that program ends.

Exceptions or any returned text will then be displayed.

List of events

Events are monitored by different publishers. The events are published as topics. Tasks then subscribe to specific topics. For performance reasons, true decoupling was not achieved in this Publish/Subscribe pattern, in that only subscribed window open and close events and log matching events are published. Publishers are only started if there is a subscription to one of the topics it publishes.

Event listing
Player Publisher Monitor Publisher Loop Publisher Log Publisher Main Thread Watchdog Schedule
onPlayBackStarted onCleanStarted onStereoModeChange onLogSimple onStartup onFileSystemChange onDailyAlarm
onPlayBackEnded onCleanFinished onProfileChange onLogRegex onShutdown onFileSystemChangeAtStartup onIntervalAlarm
onPlayBackPaused onDPMSActivated onWindowOpen
onPlayBackResumed onDMPSDeactivated onWindowClose
onPlayBackSeek onNotification onIdle
onPlayBackSeekChapter onScanStarted onResumeAfterIdle
onPlayBackSpeedChanged onScanFinished
onQueueNextItem onScreensaverActivated
onScreensaverDeactivated



Settings - General

Kodi-callbacks-settings3-1.PNG

The addon can optionally show a brief notification each time a task is run.

Polling frequencies can be configured. If you have a low powered system and performance suffers causing video stuttering, consider increasing the times.

The Loop Frequency is for events such as onIdle, onWindow open or close, profile changes and stereomode changes.

The Log frequency is for the log checker.

The Task frequency is for the main task dispatcher.


An option is provided to elevate all routine messages to the normal log, instead of the debug log.

A request has been made by the Kodi developers that addons avoid writing to the normal log and will be the default in Krypton and beyond.

This setting allows you to selectively elevate messages to the normal (non-debug) log for troubleshooting and then turn it back off once fixed.

This avoids having the user turn on the full debug mode with its OSD.

You can click to regenerate the addon's settings.xml file. This is only needed if you have created your own custom task and placed it in the userdata/addon_data/script.service.kodi.callbacks/lib/usertasks folder. This will read in whatever settings you need so that they appear on the settings pages.

You can force the addon to log all of it's settings to kodi.log. PLEASE do this if you are uploading a log to ask for help troubleshooting.

If you have the Kodi log uploader addon installed, then you will see a clickable link to send your log directly from this page.


Last, you can run a test to ensure that tasks are working properly on your system. The results will be found in the log. You may see the debug OSD come on briefly and the system mute toggle on and off. The results may be separated in the log so look through carefully. This has been tested to work on Windows, OSX, Linux Mint and Android. There may be an issue detecting a successful builtin test on Jarvis. This will be corrected soon. On Android, python imports cannot be correctly tested, but the method works and has been tested directly.


Settings - Update

Kodi-callbacks-settings4-1.PNG

Before any update via this page, the current installation is backed up to the addon_data folder for this addon under the sub-directory backup.

The last five backups are kept.

  1. FOR THE NONREPO BRANCH ONLY (this is the version that is not in the official Kodi repository and must be downloaded and installed manually - may be better if you want to participate in development):
    1. Downloading and installing from Github directly in the addon is not allowed in the official repository, this the need for a separate branch.
    2. These additional functions are useful to developers especially for multiplatform testing. If you want to develop your own task, consider downloading and installing the nonrepo branch.
    3. Developers will need to manually edit a couple of lines to point to their own clone on Github. Ask on the forum if you need help with this.
    4. The typical install from zip from Kodi will overwrite your directory including anything that you have added including git and development gui settings if they are in the addon directory.
    5. These routines will prevent this from happening during the development/testing cycle and are easier to use on keyboardless systems for testing.
    6. The first line shows the branch name for the current installation. This corresponds to the available branch names on GitHub. If you install directly via the addon settings page or copy over, this may be inaccurate.
    7. Repository branch name for downloads from GitHub. When the addon runs it retrieves this info directly from GitHub. This activity triggers a warning in the log because it utilizes urlib3 via the requests module. Don't worry about the warning.
    8. You can choose to have the addon download from GitHub when updates are available and install them. An update is triggered when the version number is bumped in addon.xml. Don't worry, not every commit will be downloaded.
    9. You can allow the install to take place silently.
    10. You can manually trigger a check on GitHub and then optionally install the most recent even if the version is the same.
  2. You can also update from a manually downloaded zip file. This renames the folder name, removing the branch name so that you don't need to do it manually.
  3. You can also reinstall from one of the automatic backups.
  • Note: These routines have some advantages over installing from the main addons page built into Kodi. They automatically rename the directory. They will leave any files that you have added into the directory. Only newer files will be copied over via a timestamping mechanism in most circumstances.
  • Note: I have occasionally encountered an error while downloading from GitHub. If you see an error notification, please just try again. This has always worked for me as long as I have an internet connection.

Create your own custom task

Why would you want to do this?

If you have some code that does something useful and would like to make it available to others.

Specifically if your code is written in python and others would need to provide information via a settings page to configure it properly.

First steps

Take a look at the current tasks in the resources/lib/tasks folder and the resources/lib/taskExample file which is better documented (had to be placed here to avoid it's auto-discovery).

Each imports a few standard needed things and then defines a class that subclasses resources.lib.taskABC.AbstractTask.

This abstract base class provides needed functionality to work with the rest of the code.

Note that this is itself a subclass of threading.Thread.

You would put your own task code in an appropriately named .py file and place it in the following directory: userdata/addon_data/script.service.kodi.callbacks/lib/tasks

Class definition

At the class level, you need to define a 'tasktype'. Make it unique so that it doesn't conflict but descriptive.

Also at the class level, designate any variables that users would need to provide.

Each requires an 'id' that you will use to refer to it later in your code.

Then information in settings is used to format the way it should look on the settings page.

Refer to the Kodi wiki for the different 'types' of settings.

Class methods

Then define your __init__ and call the super.

Next you need to create a staticmethod for validate(). The user input info will be passed in as a dict with the 'id' above as the key. Return True if the input is valid, False if it's not.

Lastly, define run(). This is the code that will be run when the event occurs.

The reformatted variable substituted user args can be accessed via self.runtimeargs. This is provided as a list. Rejoin as necessary or overload self.processUserargs.

The original task variables are a dict keyed for 'id' as above (self.taskKwargs).

Try not to raise exceptions in your code. Assemble return information or errors in a 'msg' string and set err=True if an error occurred.

The last thing the run code block should do is call self.threadReturn(err, msg).

Once your custom task is placed in the proper folder, the settings.xml file for the addon needs to be regenerated via the third settings page (see above).

Post questions on the forum. Better to put them in public and not message me directly so that others can read and learn and so I don't answer the same question privately over and over.

Notes

The log checking events consume the most resources and regex checks utilize more than simple checks.

The watchdog file system watcher may also consume a lot of resources, depending on the system.

The loop checking items consume the next most (onStereoModeChange, onProfileChange, onWindow Open or Close and onIdle/afterIdle).

Each publisher is only started if there is a task configured that utilizes an event that it generates.

Example scripts:

  • To have a script execute after Kodi exits on windows while passing pid as an argument:
@echo off
:loop
tasklist | find " %1 " >nul
if not errorlevel 1 (
    timeout /t 2 >nul
    goto :loop
)
REM Put the code you want to run here
  • To have a script execute after Kodi exits in other OS's while passing pid as an argument:
#!/usr/bin/env bash
while kill -0 $1 > /dev/null 2>&1
do
    sleep 0.2
done
# insert your code here
  • To have a script run as sudo while passing the full path to script as a parameter:
#!/usr/bin/env bash
bash "$*"

FAQs

I need to a respond to an event that isn't listed as an event. Can you make it so that I can?

Most likely, no. Pretty much everything that can be detected is already there.

A number of users have requested to launch a task when another addon/plugin launches. The only way to do that is for you to hack into their plugin and insert code to write something to the log which you then can detect via the log checker. There is an undocumented function using xbmcvfs that can list running addons, however, his doesn't work for plugins, only script and service addons. Plugins run in a 'detached' state and often each page click causes the plugin script to run again so detecting each run is often not exactly what one may desire.

If all else fails, try looking in the log to see if something specific is written there when whatever it is that you are trying to detect occurs and then use the onLogSimple or onLogRegex events to detect your event.

I am having an issues, how can I get help?

The best place to get script help is in the KODI forum thread here: http://forum.kodi.tv/showthread.php?tid=256170

If things broke after a new update, please try rebuilding your settings first:

  1. Note down your settings
  2. On the settings page click 'Default' and then click 'OK'
  3. Rebuid your settings
  4. Click OK
  5. Restart Kodi

If you believe that things are not working as expected after trying the above,

  1. From the 'General' Settings page:
    1. Turn on 'Show debugging info in normal log'
    2. Click OK
    3. Recreate your problem
    4. Go back to Settings and on the General page, click to write your settings into the log.
    5. Exit Kodi
  2. Find your log file: Wiki: Log File Location
  3. UPLOAD AN ENTIRE COPY OF 'kodi.log' TO: XBMCLogs or pastebin
  4. INCLUDE A LINK TO THE LOG IN YOUR POST ON THE FORUM

Please do not turn on Kodi's debug mode before uploading a log unless asked to do so. This typically just generates more noise in the log, making it harder to pinpoint the problem.

I do not have a magic crystal ball. The program does not report back to me directly with your issue. No log link usually means no help can be provided.

The forum moderators frown upon posting your log directly in the forum.

If you are going to edit python for Kodi, PyCharm is the way to go!!! You can apply for a free license to open source projects.

Icon PyCharm.png