<%pre>

#include <setup.h>
#include <tools.h>
#include <users.h>
#include <recman.h>
#include <livefeatures.h>

using namespace vdrlive;

</%pre>
<%args>
  std::string channelid;
  std::string recid;
</%args>
<%session scope="global">
  bool logged_in(false);
</%session>
<%include>page_init.eh</%include>
<%cpp>
  if (!logged_in && LiveSetup().UseAuth()) {
    cToSvConcat targetUrl = "/login.html?redirect=";
    targetUrl.appendUrlEscaped(request.getQuery());
    return reply.redirect(targetUrl.data());
  }
  if (!cUser::CurrentUserHasRightTo(UR_STARTREPLAY))
    throw HtmlError( tr("Sorry, no permission. Please contact your administrator!") );

  std::string videourl;
  std::string server = request.getHost();
  server = server.substr(0, server.rfind(':'));
  reply.setContentType("audio/x-mpegurl");

  if (recid.empty()) {
// live stream
    tChannelID channel = tChannelID::FromString(channelid.c_str());
    LOCK_CHANNELS_READ;
    const cChannel* Channel = Channels->GetByChannelID(channel);
    if (!Channel) {
      throw HtmlError( tr("Couldn't find channel or no channels available. Maybe you mistyped your request?") );
    }
    videourl = concat("#EXTM3U\n#EXTINF:-1,", Channel->Name(), "\nhttp://", server, ":", cToSvInt(LiveSetup().GetStreamdevPort()), "/", LiveSetup().GetStreamdevType(), "/", channelid);
  } else {
// stream recording
    LOCK_RECORDINGS_READ;
    const cRecording* recording = RecordingsManager::GetByHash(recid, Recordings);
    cToSvConcat rfid;
    if (LiveFeatures<features::streamdev_server>().Loaded()) {
      if (recording) {
        struct stat st;
        if (stat(recording->FileName(), &st) == 0)
          rfid.appendFormatted("%lu:%llu.rec", (unsigned long) st.st_dev, (unsigned long long) st.st_ino);
      }
    }

    if (rfid.empty())
      videourl = concat("#EXTM3U\n#EXTINF:-1,", recording?recording->Name():"recording not found", "\nhttp://", server, ":", cToSvInt(LiveSetup().GetServerPort()), "/recstream.html?recid=", recid);
    else
      videourl = concat("#EXTM3U\n#EXTINF:-1,", recording?recording->Name():"recording not found", "\nhttp://", server, ":", cToSvInt(LiveSetup().GetStreamdevPort()), "/", LiveSetup().GetStreamdevType(), "/", rfid, ".ts");
  }
</%cpp>
<& playlist.m3u videourl=(videourl) &>
<%include>page_exit.eh</%include>

<%def m3u>
<%args>
  std::string videourl;
</%args>
<$ videourl $>
</%def>
