yysaki
3/17/2013 - 7:22 AM

rec_radiko.sh

#!/bin/sh
# original: http://laiso.hatenablog.com/entry/2012/05/24/205547

echo "[echo] record $*"

cd `dirname $0`

playerurl=http://radiko.jp/player/swf/player_3.0.0.01.swf
playerfile=./player.swf
keyfile=./authkey.jpg
suffix=`date '+%Y%m%d'`


if [ $# -eq 1 ]; then
  channel=$1
  name=./$1.flv
elif [ $# -eq 2 ]; then
  channel=$1
  name=$2
elif [ $# -eq 3 ]; then
  channel=$1
  name=$2
  stop=$3
else
  echo "[DEBUG] usage : $0 channel_name [outputfile]"
  exit 1
fi

#
# get player
#
if [ ! -f $playerfile ]; then
  wget -q -O $playerfile $playerurl

  if [ $? -ne 0 ]; then
    echo "failed get player"
    exit 1
  fi
fi

#
# get keydata (need swftool)
#
if [ ! -f $keyfile ]; then
  swfextract -b 14 $playerfile -o $keyfile

  if [ ! -f $keyfile ]; then
    echo "[ERROR] failed get keydata"
    exit 1
  fi
fi

if [ -f auth1_fms ]; then
  rm -f auth1_fms
fi

#
# access auth1_fms
#
wget -q \
  --header="pragma: no-cache" \
  --header="X-Radiko-App: pc_1" \
  --header="X-Radiko-App-Version: 2.0.1" \
  --header="X-Radiko-User: test-stream" \
  --header="X-Radiko-Device: pc" \
  --post-data='\r\n' \
  --no-check-certificate \
  --save-headers \
  https://radiko.jp/v2/api/auth1_fms

if [ $? -ne 0 ]; then
  echo "[ERROR] failed auth1 process"
  exit 1
fi

#
# get partial key
#
authtoken=`perl -ne 'print $1 if(/x-radiko-authtoken: ([\w-]+)/i)' auth1_fms`
offset=`perl -ne 'print $1 if(/x-radiko-keyoffset: (\d+)/i)' auth1_fms`
length=`perl -ne 'print $1 if(/x-radiko-keylength: (\d+)/i)' auth1_fms`

partialkey=`dd if=$keyfile bs=1 skip=${offset} count=${length} 2> /dev/null | base64`

echo "[DEBUG] authtoken: ${authtoken} \noffset: ${offset} length: ${length} \npartialkey: $partialkey"

rm -f auth1_fms

if [ -f auth2_fms ]; then
  rm -f auth2_fms
fi

#
# access auth2_fms
#
wget -q \
  --header="pragma: no-cache" \
  --header="X-Radiko-App: pc_1" \
  --header="X-Radiko-App-Version: 2.0.1" \
  --header="X-Radiko-User: test-stream" \
  --header="X-Radiko-Device: pc" \
  --header="X-Radiko-Authtoken: ${authtoken}" \
  --header="X-Radiko-Partialkey: ${partialkey}" \
  --post-data='\r\n' \
  --no-check-certificate \
  https://radiko.jp/v2/api/auth2_fms

if [ $? -ne 0 -o ! -f auth2_fms ]; then
  echo "[ERROR] failed auth2 process"
  exit 1
fi

echo "[DEBUG] authentication success"

areaid=`perl -ne 'print $1 if(/^([^,]+),/i)' auth2_fms`
echo "[DEBUG] areaid: $areaid"

rm -f auth2_fms

#
# rtmpdump
#
time=`ruby -e 'puts Time.now.strftime("%Y%m%d%H%M%S") + (Time.now.usec/1000).round.to_s'`
flv="${time}.flv"
rtmpdump -v \
         -B $stop \
         -r "rtmpe://w-radiko.smartstream.ne.jp" \
         --playpath "simul-stream.stream" \
         --app "${channel}/_definst_" \
         -W $playerurl \
         -C S:"" -C S:"" -C S:"" -C S:$authtoken \
         --live \
         --flv $flv

dst="${time}.mp3"
ffmpeg -i $flv -ab 128 -ar 48000 $dst
if [ -f $dst ]; then
  rm $flv
fi

ruby siwake.rb $dst "${name}"