Explanation
This script will add a very simplistic maximum viewer count to a stream. This will block viewers if the viewer limit was reached 5 seconds ago. This does have the potential for some viewers to get through if they're within that 5 second limit.
It also logs every connection to an accesslog, to disable this comment every line containing ACCESSLOG
.
Usage
This script is meant to be used with the USER_NEW trigger.
Dependencies:
- cat
- date
- echo
- jq
Script
#!/bin/sh
#Limit goes here. Change it to whatever you want.
LIMIT=30
#Accesslog will keep track of everyone attempting a view
ACCESSLOG=/media/accesslog.log
#Collect the trigger payload
DATA=`cat`
NOW=`date`
#Debugging
#echo "$DATA" >> $ACCESSLOG
#Stream name attempted from 1st line
STREAM=`echo "$DATA" | sed -n 1p`
#Requester logged from 5th line
REQ=`echo "$DATA" | sed -n 5p`
APISTREAM=`echo -n "$STREAM" | jq -sRr @uri`
#IP address requester logged from 2nd line
IP=`echo -n "$DATA" | sed -n 2p`
#Grab viewers since 1 second ago for the attempted stream name through local apiv2
VIEWERS=`wget -O - 'http://localhost:4242/api2?command={"active_streams":{"fields":["viewers"],"streams":["'$APISTREAM'"]},{"time":-1}}' -q | jq '.active_streams.data["'$STREAM'"][0]'`
#Check if current viewers are greater or equal to the limit and reject/accept
if test $VIEWERS -ge $LIMIT
then
echo false
echo "$NOW - REJECT FOR $STREAM: Viewers: $VIEWERS limit: $LIMIT Requester: $REQ APISTREAM: $APISTREAM IP: $IP" >> $ACCESSLOG
else
echo true
echo "$NOW - ACCEPT FOR $STREAM: Viewers: $VIEWERS limit: $LIMIT Requester: $REQ APISTREAM: $APISTREAM IP: $IP" >> $ACCESSLOG
fi