#!/bin/bash
#
# Bash script for playing Live streams of Olympic Games.
#
# Thanks to: Martin Beránek (mousehouse) - providing URL extraction method
#            hikikomori82 - compatible sed with older version
#            Jakub Lucký - various code enhancements (dumpstream)
#            Marián Kyral - Generate token, store it in ~/.zoh.token
#
#  Copyright (c) 2010 Radek Novacek
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

# Replace with your favorite player
COMMAND="smplayer -playlist"
TOKEN_FILE=~/.zoh.token

help() {
    echo "Missing argument. Use one of following: CT4OH, CT2OH, CTHD, ZOH1, ZOH2, ZOH3, ZOH4, ZOH5, ZOH6"
    echo "Usage: zoh.sh VIDEO [dump [outfile]]"
    exit 1
}

getToken() {
  TOKEN=$(echo $(curl http://zoh.ct24.cz/live.asp 2>/dev/null |grep -i token |grep  -i token |sed  's/^.*token=\([^,]*\).*$/\1/'))
  echo "TOKEN=\"$TOKEN\"" > "$TOKEN_FILE"
  echo $TOKEN
}

getPlaylist() {
TEMP=`mktemp`
TOKEN="$1"
ID="$2"

if [ "$ID" = "CTHD" ]
then
  QUALITY=WHD
else
  QUALITY=WH
fi

EXPIRE=`date +%FT%T.%N%:z --date="4 hours"`

cat << EOF > $TEMP
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <GetPlaylistUrl xmlns="http://ivysilani.visual.cz/services">
            <request>
                <Format>$QUALITY</Format>
                <ClientAddress>$TOKEN</ClientAddress>
                <Expiration>$EXPIRE</Expiration>
                <Playlist>
                    <PlaylistItem>
                        <Type>Live</Type>
                        <Identifier>$ID</Identifier>
                    </PlaylistItem>
                </Playlist>
            </request>
        </GetPlaylistUrl>
   </soap:Body>
</soap:Envelope>
EOF


echo $(curl -H "Content-Type: text/xml; charset=utf-8" \
     -H "SOAPAction: \"http://ivysilani.visual.cz/services/GetPlaylistUrl\"" \
     -d "@$TEMP" http://ctdir.visual.cz/ivysilani/services/streaming/slp.asmx | \
     sed 's/</\n</g' | grep GetPlaylistUrlResult | sed 's/>/\n/' | grep http)

rm $TEMP

}

loadToken() {
  if [ -f "$TOKEN_FILE" ]
  then
    . "$TOKEN_FILE"
  else
    TOKEN=$(getToken)
  fi
  echo $TOKEN
}

playChanel() {
  TOKEN=$(loadToken)
  echo "====================================================="
  echo "Using token $TOKEN"
  echo

  PLAYLIST=$(getPlaylist "$TOKEN" "$ID" )

  echo "===================================================================================="
  echo "Playlist: $PLAYLIST"
  echo "===================================================================================="
  echo

  if [ -z "$PLAYLIST" ]
  then
    echo "Error: Playlist url is incorrect"
    return 1
  else
    $COMMAND "$PLAYLIST"
  fi

}

if [ $# -lt 1 ];
then
  help
else
  if [ $(echo "$1" |egrep -c "CT4OH|CT2OH|ZOH1|ZOH2|ZOH3|ZOH4|ZOH5|ZOH6|CTHD") -gt 0 ]
  then
    ID=$1;
  else
    help
  fi
fi

if [ $# -gt 1 ]
then
  if [  "$2" = "dump" -a  -n "$3"  ];
  then
      COMMAND="mplayer -dumpfile $3 -dumpstream -playlist "
  elif [ "$2" == "dump" ];
  then
      COMMAND="mplayer -dumpstream -playlist "
  fi
fi

playChanel
if [ $? -gt 0 ]
then
  echo "Generating new token..."
  TOKEN=$(getToken)
  playChanel
  if [ $? -gt 0 ]
  then
    echo "Sorry, cannot fetch playlist"
  fi
fi

