Plugin API

Warning

Please know that the API is not stable at this time. API changes, additions and removals are only documented in the release changelogs, so make sure to read them. Things should stabilize once HPX enters beta status.

Interface

The plugin interface module is named __hpx__. Import it in your plugin to access the methods and classes defined by the module:

import __hpx__ as hpx
logger = hpx.get_logger(__name__)

In addition to what is defined here, exceptions and enums defined by HPX are also available at the module-level and can be imported like so:

import __hpx__ as hpx
from __hpx__ import PluginError, PluginState
print(PluginState) # -> <enum 'PluginState'>
print(hpx.ImageSize) # -> <enum 'ImageSize'>
raise PluginError("", "")
raise hpx.PluginError("", "")

command

The object command is available on the module-level and provides access to the various different commands defined by HPX:

from __hpx__ import command
command.CheckUpdate()

See Commands for all the various commands available information.


constants

The object constants is available on the module-level and provides various useful constant values.:

from __hpx__ import constants
print(constants.version) # -> (0, 0, 0)
  • version: current HPX version

  • database_version: current HPX database version

  • webclient_version: current HPX webclient version

  • dev: developer mode enabled

  • debug: debug mode enabled

  • is_frozen: application has been made into an executable

  • is_osx: application is running on OS X

  • is_linux: application is running on Linux

  • is_win: application is running on Windows

  • is_posix: application is running on a posix-compliant OS (true for both OS X and Linux)

  • download_path: path to the downloads folder

  • tumbnail_path: path to the thumbnails folder

  • translation_path: path to the translations folder

  • current_dir: path to the plugin’s folder

current_dir : str =

database_version : tuple = (0, 9, 0)

debug : bool = False

dev : bool = False

download_path : str = downloads

is_frozen : bool = False

is_linux : bool = True

is_osx : bool = False

is_posix : bool = True

is_win : bool = False

thumbnail_path : str = static/thumbnails

translation_path : str = translations

version : tuple = (0, 13, 3)

webclient_version : tuple = (0, 13, 1)


addfilter(f=None, command=None, on=None)

Add a callable to a pipeline command

Parameters
  • f (Optional[Callable]) – a callable

  • command (Optional[str]) – name of pipeline command

  • on (Optional[str]) – on a specific action

attach(f=None, command=None, trigger=None)

Attach a handler to a command entry

Parameters
  • f (Optional[Callable]) – command handler

  • command (Optional[str]) – a fully qualified command name, required

  • trigger (Union[str, list, tuple, None]) – trigger only on a special keyword

get_logger(name=None)

Get the logging.Logger object for this plugin

Parameters

name (Optional[str]) – name of logger

get_plugin_config()

Get a dict-like object with configuration specific to this plugin

Returns

dict-like object

get_setting(namespace, key, default=<class 'happypanda.core.plugin_interface._NO_DEFAULT'>)

Get the value of any setting in the configuration. See Settings.

Parameters
  • namespace (str) – setting namespace

  • key (str) – setting key

  • default – default value if no key was found

Returns

value of setting or default value if default was set, else raise a KeyError

removefilter(f=None, command=None, on=None)

Remove a callable from a pipeline command

Parameters
  • f (Optional[Callable]) – a callable

  • command (Optional[str]) – name of pipeline command

  • on (Optional[str]) – on a specific action

Returns

a boolean indicating whether the filter was removed

save_plugin_config(obj)

Save configuration specific to this plugin

The configuration will appear in the plugin.config.<plugin shortname> namespace.

Parameters

obj (dict) – dict-like object

Returns

bool on if config was saved

subscribe(f=None, commandevent=None, trigger=None)

Subscribe a handler to a command event

Parameters
  • f (Optional[Callable]) – command event handler

  • commandevent (Optional[str]) – a fully qualified command event name, required

  • trigger (Union[str, list, tuple, None]) – trigger only on a special keyword

update_setting(namespace, key, value, user=True)

Update the value of any setting in the configuration. See Settings.

Parameters
  • namespace (str) – setting namespace

  • key (str) – setting key

  • value (Union[dict, list, int, float, tuple, str]) – value to set

  • user (bool) – the value should only apply to the current client user. Note that a user haven’t necessarily been assigned.

Special Commands

Besides the command entries and events listed here, HPX also provides some plugin meta events that are specific for each plugin. These events are emitted on plugin state changes. See PluginState for the different kinds of plugin states.

  • init – this event is emitted for a plugin after it has initialized and after all its dependencies has been initialized.

    It is therefore ideal to put the plugin’s own initialization on this event.

  • disable – this event is emitted when a plugin has been disabled, either manually by the user or because of some other cause.

    The plugin should listen to this event to terminate any on-going process it has running.

  • remove – this event is emitted just before a plugin is to be removed. HPX will handle the deletion of the plugin folder.

    The disable event will always be emitted before this event. The plugin should listen to this event to remove any produced items that would still be lingering even after its folder has been deleted.

  • before_update – this event is emitted just before a plugin is updated.

    The plugin should listen to this event to perform actions before it is updated.

  • after_update – this event is emitted just after a plugin has been updated.

    The plugin should listen to this event to perform actions after it has been updated.

  • config_update (dict) – this event is emitted with a dict of configuration that has been updated, usually from a client.

    The plugin should listen to this event to be notified when its configuration has been updated.

These are special entries each plugin can attach to.

  • message (dict) -> dict – this entry is called is called with a message, usually from a client. A dict is expected to be returned.

    The plugin should attach to this entry when wanting to exchange messages with a client or another plugin.

Summary

Meta

BackupApplication(*args, **kwargs)

Backup the application

CheckPluginUpdate(*args, **kwargs)

Check for new plugin release

CheckUpdate(*args, **kwargs)

Check for new release

ClientLogger(*args, **kwargs)

InitApplication(*args, **kwargs)

Initialize the appplication

Notification(*args, **kwargs)

Notify client

ReIndex(*args, **kwargs)

Trigger a reindex

RemoveCommandFilter(*args, **kwargs)

Remove a callable to a pipeline command

RestartApplication(*args, **kwargs)

Restart the appplication

RestoreApplication(*args, **kwargs)

Restore the application from a backup

ShutdownApplication(*args, **kwargs)

Shutdown the appplication

TrashSweeper(*args, **kwargs)

Sweeps trashed items

UpdateApplication(*args, **kwargs)

Check for new release and update the application

UpdatePlugin(*args, **kwargs)

Check for new release and update a plugin

I/O

CacheCleaner(*args, **kwargs)

Clean the provided folder

CoreFS([path, archive])

Encapsulates path on the filesystem

DeletePath(*args, **kwargs)

Delete path or database item files from filesystem

FSCreatedEvent([is_dir, src, name])

FSDeletedEvent([is_dir, src, name])

FSDirCreatedEvent([is_dir, src, name])

FSDirDeletedEvent([is_dir, src, name])

FSDirModifiedEvent([is_dir, src, name])

FSDirMovedEvent([is_dir, src, dest, name])

FSEvent([name, is_dir, src])

FSFileCreatedEvent([is_dir, src, name])

FSFileDeletedEvent([is_dir, src, name])

FSFileModifiedEvent([is_dir, src, name])

FSFileMovedEvent([is_dir, src, dest, name])

FSModifiedEvent([is_dir, src, name])

FSMovedEvent([is_dir, src, name, dest])

GalleryFS(path_or_dbitem[, ensure_in_session])

Encapsulates an gallery object on the filesystem :type path_or_dbitem: Union[Gallery, str, CoreFS, Path, PathItem] :param path_or_dbitem: path to a valid gallery archive/folder, a PathItem or a db.Gallery database item

GetImage(*args, **kwargs)

Generate an image from source image

ImageProperties([size, radius, output_dir, …])

ItemTextParser(name)

Extract several components from a gallery name (usually a filename)

PathItem(item, path, related)

PathMatch(*args, **kwargs)

WatchDir(*args, **kwargs)

Watch a directory for file system changes

Database

DeleteItem(*args, **kwargs)

Delete a database item

GetDatabaseModel(*args, **kwargs)

Get database model item by name

GetDatabaseSort(*args, **kwargs)

Returns a name or, a namedtuple(expr, joins) of a data sort expression and additional tables to join, for a given sort index

GetModelHash(*args, **kwargs)

GetModelImage(*args, **kwargs)

Fetch a database model item’s image

GetModelItems(*args, **kwargs)

Fetch model items from the database

GetSession(*args, **kwargs)

Get a database session

MostCommonTags(*args, **kwargs)

Get the most common tags for item

UpdateItem(*args, **kwargs)

Update database items

UpdateItemData(*args, **kwargs)

Update a database item’s attribute

Item

GetItemLog(*args, **kwargs)

Get logs for item

ItemWatcher(*args, **kwargs)

Watches a specified directory for supported items

LogItem(*args, **kwargs)

Log a message for item

LogItemCritical(*args, **kwargs)

A convenience wrapper around LogItem

LogItemDebug(*args, **kwargs)

A convenience wrapper around LogItem

LogItemError(*args, **kwargs)

A convenience wrapper around LogItem

LogItemInfo(*args, **kwargs)

A convenience wrapper around LogItem

LogItemWarning(*args, **kwargs)

A convenience wrapper around LogItem

MoveItem(*args, **kwargs)

Move database item files on filesystem

SetItemConfig(*args, **kwargs)

Set/update configuration for item

UpdateGalleryProgress(*args, **kwargs)

Update a GalleryProgress

db_item_key(item_id, model)

Gallery

OpenGallery(*args, **kwargs)

Open a gallery in an external viewer

ScanGallery(*args, **kwargs)

SimilarGallery(*args, **kwargs)

Get a list of similar galleries to given gallery

SyncWithSource(*args, **kwargs)

Synchronise the gallery source with the database, meaning if the source is a path on the filesystem, it will rescan the source for any possibly new items for given item.

Item Data

ArtistData([item, names, info, galleries, …])

ArtistNameData([item, name, artist_id, …])

ArtistUserDataData([item, user_id, …])

BaseData()

Base Data

CategoryData([item, galleries, name, id, …])

CircleData([item, artists, galleries, name, …])

CollectionData([item, info, pub_date, …])

CollectionUserDataData([item, user_id, …])

EventData([item, item_id, by_table, …])

FilterData([item, name, user, user_id, …])

GalleryData([item, last_read, pub_date, …])

GalleryProgressData([item, user_id, …])

GalleryUserDataData([item, user_id, …])

GroupingData([item, status_id, timestamp, …])

HashData([item, type, name, id, timestamp, …])

LanguageData([item, code, galleries, name, …])

MetaListData([item, name, id, timestamp, …])

MetaTagData([item, is_user_data, name, id, …])

NamespaceData([item, tags, name, id, …])

NamespaceTagData([item, tag_id, …])

NamespaceTagUserDataData([item, user_id, …])

NotSet()

Op(value)

Base operation

PageData([item, number, name, path, …])

PageUserDataData([item, user_id, parent_id, …])

ParodyData([item, names, galleries, id, …])

ParodyNameData([item, name, parody_id, …])

ProfileData([item, path, data, size, …])

Remove(value)

A remove operation

Set(value)

An append operation

StatusData([item, groupings, name, id, …])

TagData([item, namespaces, name, id, …])

TaggableData([item, tags, last_updated, id, …])

TitleData([item, name, language_id, …])

UrlData([item, name, id, timestamp, user, …])

UserData([item, name, role, address, …])

yData([item, name, id, timestamp, user, …])

artist_preferred_validate(self, attr, value)

base_id_validate(self, attr, value)

filter_search_validate(obj, attr, value)

gallery_preferred_validate(self, attr, value)

gallery_rating_validate(self, attr, value)

gallery_times_read_validate(self, attr, value)

get_data_class(db_cls)

hashtype_validate(self, attr, value)

metatags_validate(self, attr, value)

plugin_validate(self, attr, value)

tags_validate(self, attr, value)

trash_validate(self, attr, value)

user_right_add_validate(self, attr, value)

user_right_remove_validate(self, attr, value)

user_right_update_validate(self, attr, value)

userdata_validate(self, attr, value)

userrole_validate(self, attr, value)

Login

GetLoginSession(*args, **kwargs)

Get the login session if logged in, else None

GetLoginStatus(*args, **kwargs)

Check if user is logged in

GetLoginText(*args, **kwargs)

Get login status text

Login(*args, **kwargs)

LoginInfo([identifier, name, parser, sites, …])

Metadata

Metadata(*args, **kwargs)

Fetch metadata

MetadataData(metadataitem[, title, url, …])

MetadataInfo([identifier, name, parser, …])

MetadataItem(item[, url, options])

MetadataResult(data, status[, reason])

Search

Index(*args, **kwargs)

Index data

IndexData(touched[, action, index, indexes])

LegacyPartialModelFilter(*args, **kwargs)

Perform a partial search on database model with a single term

ModelFilter(*args, **kwargs)

Perform a full search on database model

ParseSearch(*args, **kwargs)

Parse a search query.

ParseTerm(*args, **kwargs)

Parse a single term

SearchToESearch(*args, **kwargs)

Convert a list of ns:tag from ParseSearch to an ESearch query.

Term(namespace, tag, operator, exclusion)

used to encapsulate a single term, e.g: pages::>5 where pages is the namespace, > is the operator and 5 is the tag

UpdateFilters(*args, **kwargs)

Update filters

get_search_options()

nest_query(inner_query, path[, nested, index])

Network

Method(value)

An enumeration.

MultiGETRequest(*args, **kwargs)

A convenience wrapper around MultiRequest for GET requests

MultiPOSTRequest(*args, **kwargs)

A convenience wrapper around MultiRequest for POST requests

MultiRequest(*args, **kwargs)

Make multiple HTTP requests

RequestProperties([method, name, session, …])

Response(*args, **kwargs)

A request response.

SingleGETRequest(*args, **kwargs)

A convenience wrapper around SingleRequest for GET requests

SinglePOSTRequest(*args, **kwargs)

A convenience wrapper around SingleRequest for POST requests

SingleRequest(*args, **kwargs)

Make a HTTP request

Download

DownloadInfo([identifier, name, parser, …])

DownloadItem(url[, options, name, type, …])

DownloadRequest(downloaditem, url[, type, …])

DownloadResource(*args, **kwargs)

DownloadResult(downloaditem, requests, status)

GetDownloadInfo(*args, **kwargs)

Commands

.Meta

Error

happypanda.core.commands.meta_cmd

.I/O

class ImageProperties(size=ImageSize(width=200, height=276), radius=0, output_dir=None, output_path=None, name=None, create_symlink=True, crop=False)

create an artificial symlink til the source image instead of copying it (only useful if image size isn’t modified)

crop: bool

crop the image when scaling to keep aspect ratio

name: str

name of image file when saved to output_dir, else a random name will be generated

output_dir: str

folder to save the image to

output_path: str

path to save the image to, this and output_dir are mutually exclusive

radius: int

corner radius

size: happypanda.common.utils.ImageSize

size of image, a utils.ImageSize object

Error

happypanda.core.commands.io_cmd

.Database

GetDatabaseSort.SortTuple = NamedTuple

Error

happypanda.core.commands.database_cmd

.Item

Error

happypanda.core.commands.item_cmd

Error

happypanda.core.commands.gallery_cmd

.Item Data

.Login

Error

happypanda.core.commands.login_cmd

.Metadata

Error

happypanda.core.commands.metadata_cmd

Error

happypanda.core.commands.search_cmd

.Network

class Method(value)

An enumeration.

DELETE = 'delete'

DELETE

GET = 'get'

GET

HEAD = 'head'

HEAD

OPTIONS = 'options'

OPTIONS

POST = 'post'

POST

PUT = 'put'

PUT

class RequestProperties(method=None, name='', session=None, timeout=None, proxy=None, headers=None, files=None, data=None, json=None, params=None, auth=None, cookies=None, stream=False, stream_callback=None, progress=False)
auth

auth

cookies

cookies

data

data

files

files

headers

headers

json

json

method: happypanda.core.commands.network_cmd.Method

a Method object

params

params

progress

progress

proxy

proxy

session: bool

set to True for new session, None for default session, False for no session, or to a custom session

stream

stream

stream_callback

stream_callback

timeout: int

request timeout

GetDefaultSession()

Retrieve the default session

Available entries:

Available events:

MultiGETRequest(*args, **kwargs)

A convenience wrapper around MultiRequest for GET requests

Available entries:

Available events:

MultiPOSTRequest(*args, **kwargs)

A convenience wrapper around MultiRequest for POST requests

Available entries:

Available events:

MultiRequest(*args, **kwargs)

Make multiple HTTP requests

Available entries:

Available events:

Response(_url, _request_method, _request_kwargs, _props, _session)

A request response. Not meant to be instanced publicly.

Available entries:

Available events:

SingleGETRequest(*args, **kwargs)

A convenience wrapper around SingleRequest for GET requests

Available entries:

Available events:

SinglePOSTRequest(*args, **kwargs)

A convenience wrapper around SingleRequest for POST requests

Available entries:

Available events:

SingleRequest(*args, **kwargs)

Make a HTTP request

Available entries:

Available events:

.Download

Error

happypanda.core.commands.download_cmd