#!/bin/bash
# Uses UPnP/DLNA to list contents.
# Depends on: curl, php, pygmentize, html-beautify (from js-beautify)
#
# Usage: ./upnp-dir.sh [ObjectID]
# ObjectID '0' is the root, folders can be listed with '0$4'.
#
# Copyright (C) 2014 Peter Wu
# https://lekensteyn.nl/zxv10-h220n/

controlurl=http://192.168.2.254:52869/web/cds_control
type=urn:schemas-upnp-org:service:ContentDirectory:1
action=Browse

# Folders: 0$4
objectid=${1:-0}

# Takes a SOAP enveloppe from stdin.
process() {
    curl -s -d @- \
        "$controlurl" \
        -H 'Content-Type: text/xml' \
        -H "SOAPAction: \"$type#$action\""
}
# Decode the entities in <Result>, beautify it and colorize it
post_process() {
    local colorcmd
    colorcmd='pygmentize -f 256 -l xml /dev/stdin'
    [ -t 1 ] || colorcmd=cat

    php -r 'echo html_entity_decode(file_get_contents("php://stdin"));' |
    html-beautify /dev/stdin |
    $colorcmd
}

process <<XML | post_process
<?xml version="1.0" ?>
<s:Envelope
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
    s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <s:Body>
        <u:$action xmlns:u="$type">
             <ObjectID>$objectid</ObjectID>
             <BrowseFlag>BrowseDirectChildren</BrowseFlag>
             <Filter>*</Filter>
             <StartingIndex>0</StartingIndex>
             <RequestedCount>100</RequestedCount>
             <SortCriteria/>
        </u:$action>
    </s:Body>
</s:Envelope>
XML

# vim: set sw=4 et ts=4:
