StarVibe LiveDocumentation

Documentation / Add-ons for developers

Add-ons for developers

How your own developer adds features to this site without changing its code: a folder of your own PHP, JavaScript and CSS that the site loads, and the hook points where that code can join in. Updates never touch it.

The examples use YOURCODE. Signed in as an affiliate, you see your own campaign code here.

#Overview

The site's own code is locked: parts of it are encoded, and an update replaces the rest. Changes made inside those files would be lost or impossible. Instead, the site has hook points: places where it hands a value to your code, or tells your code that something happened. Your code lives in its own folder, the site loads it, and updates leave it alone.

PluginsYour own add-ons
Made byFluffCams (bought in your FluffCams account)You or your developer
Whereplugins/<id>/, installed from System > Pluginscustom/<name>/, copied onto the server
SignedYes: the site refuses any other zipNo: they are your own files on your own server
Switched onWhen installedOnly when an admin switches it on (System > Plugins, "Your own add-ons")

Both use the same hook points, listed in Hook points.

#Quick start

  1. On the server, make a folder in custom/ with a short name of lower-case letters, digits, - or _, for example custom/my-chat-extras/.
  2. Add addon.json with a name and a description, so the admin knows what it is.
  3. Add addon.php for server code and/or assets/room.js and assets/room.css for the live room (see Folder layout).
  4. Make sure the web server can read the files (owner or group www-data, for example chmod -R a+rX custom/my-chat-extras).
  5. In the admin panel open System > Plugins. The folder is listed under Your own add-ons, switched off. Press Switch on.
custom/my-chat-extras/addon.json
{
  "name": "My chat extras",
  "description": "A /dice command and a gold name for our moderators.",
  "version": "1.0"
}

#Folder layout

FileWhat it does
addon.jsonOptional. name, description and version shown to the admin.
addon.phpOptional. Runs on every request while the add-on is on. It registers your code at the hook points with \Msg\Plugins::on(). The variable $addon holds id and dir (its folder).
assets/site.css, assets/site.jsLoaded on every page that has the site header (home, categories, the live room, account pages).
assets/room.css, assets/room.jsLoaded in the live room that viewers watch.
assets/studio.css, assets/studio.jsLoaded in the Studio, the page models broadcast from.
assets/ (anything else)Pictures, fonts and more files. The web can reach assets/ and nothing else in your folder.
pages/<page>.phpYour own public page, at addon.php?a=<name>&p=<page>. See Your own pages.
admin/<page>.phpYour own admin page, at admin/addon.php?a=<name>&view=<page> (main admins only). A button for it appears under the add-on on System > Plugins.
sql/<name>__001_what.sqlYour own database tables. They are made when the add-on is switched on, and by every update. Every file must start with the add-on's name and two underscores; a later change is a new file (<name>__002_...), never an edit of an old one.
addon.json "jobs"Scheduled work: [{"key": "cleanup", "script": "cli/cleanup.php", "every": 60, "label": "Clean up"}] runs cli/cleanup.php every 60 minutes with the site's own jobs. It shows on System > Scheduled jobs.

Scripts are loaded with defer, after the site's own scripts. Each file address carries its date, so a changed file is fetched again by browsers.

#Hook points

A filter hands your function a value and uses what you return (return the value unchanged when you have nothing to do). An event only tells you something happened. Register both with \Msg\Plugins::on('name', function (...) { ... }) in addon.php.

NameKindYour function getsUse it to
chat.commandfilternull, the command word, the rest of the line, the contextAnswer a chat command such as /dice
chat.messagefilterthe text (after the site's own checks), the contextChange a message, or refuse it
chat.extrafilter[], the message (id, user, role, text), the contextAttach values your script uses to draw the message
chat.senteventthe message as it was sent, the contextLog, count, or react to messages
room.allowfiltertrue, [room, user, type, role]Keep a viewer out of a room by your own rules (return a reason)
room.joinedevent[room, user, type, role, public]Someone entered a room (user is empty for a guest)
model.live, model.offlineevent[room]A model went live / went offline
tip.paidevent[room, user, amount, label, menu]React to a tip (the tokens are already moved)
show.started, show.endedevent[room, user, kind, price, show] / [room, user, kind, reason, show]A private or spy show began / ended (money settled)
ticket.bought, fanclub.joined, wheel.spun, media.boughteventroom, user and what was boughtReact to a purchase in a room
page.assetsfilter['css' => [], 'js' => []], the page (site, room, studio)Load more of your own files
site.name, site.titlefilterthe textChange the site name shown in titles and emails
site.origin, site.homefilterthe site's address / the logo's linkServe the site under another address
site.logofilternull, the page's way back to the site root, bar or bgShow another logo (['src' => ..., 'style' => ''])
site.coloursfilterthe nine coloursGive some visitors another look
browse.visiblefilter[sql, params] of the models anybody may seeNarrow the model lists (you may only ADD conditions)
referral.campaignfilter0Credit a sign-up without a link cookie to an affiliate campaign
affiliate.tabsfilterthe affiliate area's sectionsAdd a section to the affiliate area
mail.logo, pwa.configfilterthe email logo / the app's name and coloursBrand emails and the phone app
site.hostsfilter[]Extra addresses that need their own https certificate (servers made with the FluffCams set-up script)

The context of a chat hook is room (the model's name), user (the writer's public name), type (member, model, staff or studio), role in this room (member, mod, owner, staff, studio) and show (true inside a paid show). It never holds an account number: the site keeps those away from add-ons and browsers on purpose.

#Room and money events

The room tells add-ons what happens in it, AFTER the site has finished its own work (tokens moved, earnings written). Your code cannot change those amounts, so a mistake in an add-on can never lose anybody's money; it can do anything else: thank people, keep your own scores, call another service, send a message.

<?php
// custom/big-tippers/addon.php: keep our own top-tipper board
\Msg\Plugins::on('tip.paid', function (array $t) {
    \Msg\Db::exec(
        'INSERT INTO big_tippers__board (room, user, total) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE total = total + VALUES(total)',
        [$t['room'], $t['user'], $t['amount']]
    );
});

\Msg\Plugins::on('room.allow', function ($ok, array $who) {
    return $who['type'] === 'guest' && $who['room'] === 'MembersOnlyRoom' ? 'Please sign in to watch this room.' : $ok;
});

\Msg\Db is the site's database helper: Db::exec($sql, $params), Db::all(...), Db::one(...), Db::val(...), always with ? placeholders for values.

#Your own pages

A file pages/<page>.php is a public page at addon.php?a=<name>&p=<page>. It gets $addon (id, dir, url) and $me (the signed-in person, or null). To look like the rest of the site, open and close it with the site's own frame:

<?php
// custom/big-tippers/pages/board.php  ->  addon.php?a=big-tippers&p=board
use Live\{Chrome, Page};

Page::head('Top tippers', 'lv-page', [], '', 'live/');
echo '<link rel="stylesheet" href="custom/big-tippers/assets/board.css">';
Chrome::render('', '');
$rows = \Msg\Db::all('SELECT user, SUM(total) AS t FROM big_tippers__board GROUP BY user ORDER BY t DESC LIMIT 20');
echo '<main class="bt-board"><h1>Top tippers</h1><ol>';
foreach ($rows as $r) {
    echo '<li>' . htmlspecialchars($r['user']) . ' <b>' . (int) $r['t'] . '</b></li>';
}
echo '</ol></main>';
Page::footer($me, '');

An admin page admin/<page>.php works the same way inside the admin panel: handle your form first (check \Msg\AdminAuth::requirePost() on a POST), then draw between include $adminDir . '/_header-admin.php' and include $adminDir . '/_footer-admin.php'.

#Chat: server side

#A chat command

When somebody writes a line that starts with / followed by a word, the site asks chat.command. Return ['notice' => '...'] to answer only the writer (nothing is stored or shown to others), ['text' => '...'] to send that text instead, or the value you were given when the command is not yours.

<?php
// custom/my-chat-extras/addon.php
\Msg\Plugins::on('chat.command', function ($v, string $cmd, string $args, array $ctx) {
    if ($cmd === 'dice') {
        return ['text' => $ctx['user'] . ' rolled a ' . random_int(1, 6)];
    }
    if ($cmd === 'help') {
        return ['notice' => 'Commands: /dice'];
    }
    return $v; // not ours: the next add-on (or the plain message) goes on
});

#Changing or refusing a message

chat.message runs after the site's own checks (word filter, rate limits, bans). Return the text, a changed text, or ['refuse' => 'Your reason'] (or false) to stop it. The writer sees your reason. Text you return is cleaned and limited to 300 characters like typed text.

<?php
\Msg\Plugins::on('chat.message', function ($text, array $ctx) {
    if ($ctx['type'] === 'member' && preg_match('/\bcasino\b/i', $text)) {
        return ['refuse' => 'No advertising in this room.'];
    }
    return $text;
});

#Values for your own drawing

chat.extra lets you attach up to 10 short values to a message (names of lower-case letters, digits and _; text up to 200 characters, numbers, true or false). They arrive in the browser as message.x, live and when the history is loaded, so your script can draw them the same way after a refresh.

<?php
\Msg\Plugins::on('chat.extra', function (array $x, array $msg, array $ctx) {
    if ($msg['role'] === 'mod') {
        $x['glow'] = 'gold';
    }
    return $x;
});

#Chat: in the browser

The chat (in the live room and the Studio) sends events on document that your room.js / studio.js can listen to:

EventdetailUse it to
fc:chat-messagerow (the element on the page), message (id, u name, r role, text, ts, x your values), mine, modelDecorate a message once it is on the page
fc:chat-sendtext, model. Cancelable.Change detail.text before it is sent, or preventDefault() to stop it
fc:chat-sentmessage, modelReact after your own message was accepted
// custom/my-chat-extras/assets/room.js
document.addEventListener('fc:chat-message', function (e) {
  var m = e.detail.message;
  if (m.x && m.x.glow === 'gold') {
    e.detail.row.classList.add('my-glow');
  }
});

document.addEventListener('fc:chat-send', function (e) {
  e.detail.text = e.detail.text.replace(/:\)/g, '\uD83D\uDE42'); // turn :) into an emoji
});

A message row is .lv-row (its data-role is the writer's role), the name inside it .lv-u, the text .lv-text. Use the site's colours through the --msg-* CSS variables (for example --msg-accent, --msg-text, --msg-gold), so your add-on follows whatever look the admin picks.

#Room: buttons and panels

Your room.js can add a button and a panel to the live room through window.LiveExt (it is ready before your script runs; a script that runs earlier can wait for the lv:ext-ready event on document). On a computer and in the classic phone layout the button sits on the model bar; in the full-screen phone layout it is one of the icons behind the "more" button. The panel opens like the fan club's: at the right on a computer, up from the bottom on a phone, over the whole screen in the full-screen phone layout.

WhatGives
LiveExt.button({id, label, icon, go})Adds the button. id: lower-case letters, digits and dashes. icon: a name of the room's icon set (for example bag, gift, star, heart, info). go: your function, called on a tap.
LiveExt.panel(title){el, body, title, open(), close(), isOpen, onClose}: fill body with your own elements, then call open().
LiveExt.model, .me, .viewer, .type, .csrfThe room's model, the viewer's name, member or guest, the account type, and the token a POST to the site needs (header X-CSRF-Token).
LiveExt.join()Opens the sign-up window (for a guest who taps something that needs an account).
// custom/my-extras/assets/room.js
(function () {
  function start() {
    var panel = LiveExt.panel('Hello');
    panel.body.textContent = 'Hello from my add-on in ' + LiveExt.model + '\'s room.';
    LiveExt.button({ id: 'my-hello', label: 'Hello', icon: 'star', go: function () { panel.open(); } });
  }
  if (window.LiveExt) { start(); } else { document.addEventListener('lv:ext-ready', start); }
})();

Selling something for tokens: take them with \Msg\Ledger::charge($memberId, $modelId, $tokens, 'plugin', '<your short name>', $yourId, $uniqueKey, $note) (one unique key per purchase, so a doubled tap pays once) and pay the model with \Msg\Earnings::recordPlugin('<your name>', $yourId, $memberName, $modelName, $tokens): the model's usual share, a studio's split and every payout screen work as for a tip. \Msg\Ledger::refund(...) gives tokens back and \Msg\Earnings::reversePlugin(...) takes a payment back. Tell people through \Acct\Notices::add($type, $id, 'shop', $title, $body, $link) (the bell and, if they allow it, a phone alert).

#Good practice

  • Keep hook functions fast. Chat hooks run on every message; site hooks run on every page.
  • Store your own data in your own tables with names that start with your add-on's name. Never change the site's own tables.
  • Never show account numbers in a page, a script or a URL. Use the public names the hooks give you.
  • Escape everything you print (htmlspecialchars in PHP, textContent in JavaScript).
  • Updates never touch custom/, but a hook may gain new values over time: read what you need and ignore the rest.
  • To stop an add-on at once, switch it off on System > Plugins, or remove its folder.

Back to the top