Exemple #1
0
void CXRandR::LoadCustomModeLinesToAllOutputs(void)
{
/*
	歌方:
		1、
		
	卦指:
		1、
		
	傍苧:
		1、
*/
	Query();
	TiXmlDocument xmlDoc;

	if (!xmlDoc.LoadFile("special://xbmc/userdata/ModeLines.xml"))
	{
		return;
	}

	TiXmlElement *pRootElement = xmlDoc.RootElement();
	if (strcasecmp(pRootElement->Value(), "modelines") != 0)
	{
		// TODO ERROR
		return;
	}

	char cmd[255];
	CStdString name;
	CStdString strModeLine;

	for (TiXmlElement* modeline = pRootElement->FirstChildElement("modeline"); modeline; modeline = modeline->NextSiblingElement("modeline"))
	{
		name = modeline->Attribute("label");
		name.TrimLeft(" \n\t\r");
		name.TrimRight(" \n\t\r");
		strModeLine = modeline->FirstChild()->Value();
		strModeLine.TrimLeft(" \n\t\r");
		strModeLine.TrimRight(" \n\t\r");
		if (getenv("XBMC_BIN_HOME"))
		{
			snprintf(cmd, sizeof(cmd), "%s/xbmc-xrandr --newmode \"%s\" %s > /dev/null 2>&1", getenv("XBMC_BIN_HOME"), name.c_str(), strModeLine.c_str());
			if (system(cmd) != 0)
				CLog::Log(LOGERROR, "Unable to create modeline \"%s\"", name.c_str());
		}

		for (unsigned int i = 0; i < m_outputs.size(); i++)
		{
			if (getenv("XBMC_BIN_HOME"))
			{
				snprintf(cmd, sizeof(cmd), "%s/xbmc-xrandr --addmode %s \"%s\"  > /dev/null 2>&1", getenv("XBMC_BIN_HOME"),m_outputs[i].name.c_str(), name.c_str());
				if (system(cmd) != 0)
					CLog::Log(LOGERROR, "Unable to add modeline \"%s\"", name.c_str());
			}
		}
	}
}
Exemple #2
0
bool ParseIPFilter(CStdString in, std::list<CStdString>* output /*=0*/)
{
	bool valid = true;

	in.Replace(_T("\n"), _T(" "));
	in.Replace(_T("\r"), _T(" "));
	in.Replace(_T("\t"), _T(" "));
	while (in.Replace(_T("  "), _T(" ")));
	in.TrimLeft(_T(" "));
	in.TrimRight(_T(" "));
	in += _T(" ");

	int pos;
	while ((pos = in.Find(_T(" "))) != -1)
	{
		CStdString ip = in.Left(pos);
		if (ip == _T(""))
			break;
		in = in.Mid(pos + 1);

		if (ip == _T("*") || IsValidAddressFilter(ip))
		{
			if (output)
				output->push_back(ip);
		}
		else
			valid = false;
	}

	return valid;
}
Exemple #3
0
void PathHelper::RemoveFromPath(CStdString sPath)
{
	CStdString sFullPath = GetProcessPath();

	sFullPath.ToLower();
	sPath.ToLower();

	if ( sPath.Right(1) == _T("\\") )
	{
		sPath = sPath.Left(sPath.length() - 1);
	}

	int nStart = (x64_int_cast)sFullPath.find(sPath);

	while (nStart >= 0)  // there may be multiple copies
	{
		int nEnd = nStart + (x64_int_cast)sPath.length() + 1;

		sFullPath = sFullPath.Left(nStart) + sFullPath.Right(sFullPath.length() - nEnd );

		sFullPath.TrimRight();
		sFullPath.TrimLeft();

		if (sFullPath.Left(1) == _T(";"))
			sFullPath = sFullPath.Mid(1);

		sFullPath.Replace(_T(";;"),_T(";"));

		nStart = (x64_int_cast)sFullPath.find(sPath);
	}

	SetProcessPath(sFullPath);
}
Exemple #4
0
////////////////////////////////////////////////////////////////////////////////////
// Function: ExtractTimeFromIndex()
// Extracts the time information from the index string index, returning it as a value in
// milliseconds.
// Assumed format is:
// MM:SS:FF where MM is minutes, SS seconds, and FF frames (75 frames in a second)
////////////////////////////////////////////////////////////////////////////////////
int CCueDocument::ExtractTimeFromIndex(const CStdString &index)
{
  // Get rid of the index number and any whitespace
  CStdString numberTime = index.Mid(5);
  numberTime.TrimLeft();
  while (!numberTime.IsEmpty())
  {
    if (!isdigit(numberTime[0]))
      break;
    numberTime.erase(0, 1);
  }
  numberTime.TrimLeft();
  // split the resulting string
  CStdStringArray time;
  StringUtils::SplitString(numberTime, ":", time);
  if (time.size() != 3)
    return -1;

  int mins = atoi(time[0].c_str());
  int secs = atoi(time[1].c_str());
  int frames = atoi(time[2].c_str());

  return (mins*60 + secs)*75 + frames;
}
bool CGUIDialogPluginSettings::TranslateSingleString(const CStdString &strCondition, vector<CStdString> &condVec)
{
  CStdString strTest = strCondition;
  strTest.ToLower();
  strTest.TrimLeft(" ");
  strTest.TrimRight(" ");

  int pos1 = strTest.Find("(");
  int pos2 = strTest.Find(",");
  int pos3 = strTest.Find(")");
  if (pos1 >= 0 && pos2 > pos1 && pos3 > pos2)
  {
    condVec.push_back(strTest.Left(pos1));
    condVec.push_back(strTest.Mid(pos1 + 1, pos2 - pos1 - 1));
    condVec.push_back(strTest.Mid(pos2 + 1, pos3 - pos2 - 1));
    return true;
  }
  return false;
}
Exemple #6
0
void URIUtils::CreateArchivePath(CStdString& strUrlPath,
                                 const CStdString& strType,
                                 const CStdString& strArchivePath,
                                 const CStdString& strFilePathInArchive,
                                 const CStdString& strPwd)
{
  CStdString strBuffer;

  strUrlPath = strType+"://";

  if( !strPwd.IsEmpty() )
  {
    strBuffer = strPwd;
    CURL::Encode(strBuffer);
    strUrlPath += strBuffer;
    strUrlPath += "@";
  }

  strBuffer = strArchivePath;
  CURL::Encode(strBuffer);

  strUrlPath += strBuffer;

  strBuffer = strFilePathInArchive;
  strBuffer.Replace('\\', '/');
  strBuffer.TrimLeft('/');

  strUrlPath += "/";
  strUrlPath += strBuffer;

#if 0 // options are not used
  strBuffer = strCachePath;
  CURL::Encode(strBuffer);

  strUrlPath += "?cache=";
  strUrlPath += strBuffer;

  strBuffer.Format("%i", wOptions);
  strUrlPath += "&flags=";
  strUrlPath += strBuffer;
#endif
}
IMusicInfoTagLoader* CMusicInfoTagLoaderFactory::CreateLoader(const CStdString& strFileName)
{
  // dont try to read the tags for streams & shoutcast
  CFileItem item(strFileName, false);
  if (item.IsInternetStream())
    return NULL;

  if (item.IsMusicDb())
    return new CMusicInfoTagLoaderDatabase();

  CStdString strExtension;
  URIUtils::GetExtension( strFileName, strExtension);
  strExtension.ToLower();
  strExtension.TrimLeft('.');

  if (strExtension.IsEmpty())
    return NULL;

  if (strExtension == "aac" ||
      strExtension == "ape" || strExtension == "mac" ||
      strExtension == "mp3" || 
      strExtension == "wma" || 
      strExtension == "flac" || 
      strExtension == "m4a" || strExtension == "mp4" ||
      strExtension == "mpc" || strExtension == "mpp" || strExtension == "mp+" ||
      strExtension == "ogg" || strExtension == "oga" || strExtension == "oggstream" ||
#ifdef HAS_MOD_PLAYER
      ModPlayer::IsSupportedFormat(strExtension) ||
      strExtension == "mod" || strExtension == "nsf" || strExtension == "nsfstream" ||
      strExtension == "s3m" || strExtension == "it" || strExtension == "xm" ||
#endif
      strExtension == "wv")
  {
    CTagLoaderTagLib *pTagLoader = new CTagLoaderTagLib();
    return (IMusicInfoTagLoader*)pTagLoader;
  }
#ifdef HAS_DVD_DRIVE
  else if (strExtension == "cdda")
  {
    CMusicInfoTagLoaderCDDA *pTagLoader = new CMusicInfoTagLoaderCDDA();
    return (IMusicInfoTagLoader*)pTagLoader;
  }
#endif
  else if (strExtension == "shn")
  {
    CMusicInfoTagLoaderSHN *pTagLoader = new CMusicInfoTagLoaderSHN();
    return (IMusicInfoTagLoader*)pTagLoader;
  }
  else if (strExtension == "wav")
  {
    CMusicInfoTagLoaderWAV *pTagLoader = new CMusicInfoTagLoaderWAV();
    return (IMusicInfoTagLoader*)pTagLoader;
  }
  else if (strExtension == "spc")
  {
    CMusicInfoTagLoaderSPC *pTagLoader = new CMusicInfoTagLoaderSPC();
    return (IMusicInfoTagLoader*)pTagLoader;
  }
  else if (strExtension == "ym")
  {
    CMusicInfoTagLoaderYM *pTagLoader = new CMusicInfoTagLoaderYM();
    return (IMusicInfoTagLoader*)pTagLoader;
  }
#ifdef HAS_ASAP_CODEC
  else if (ASAPCodec::IsSupportedFormat(strExtension) || strExtension == "asapstream")
  {
    CMusicInfoTagLoaderASAP *pTagLoader = new CMusicInfoTagLoaderASAP();
    return (IMusicInfoTagLoader*)pTagLoader;
  }
#endif
  else if ( TimidityCodec::IsSupportedFormat( strExtension ) )
  {
    CMusicInfoTagLoaderMidi * pTagLoader = new CMusicInfoTagLoaderMidi();
    return (IMusicInfoTagLoader*)pTagLoader;
  }

  return NULL;
}
Exemple #8
0
void COptions::SetOption(int nOptionID, LPCTSTR value, bool save /*=true*/)
{
	CStdString str = value;
	Init();

	switch (nOptionID)
	{
	case OPTION_SERVERPORT:
	case OPTION_TLSPORTS:
		{
			std::set<int> portSet;

			str.TrimLeft(_T(" ,"));

			int pos = str.FindOneOf(_T(" ,"));
			while (pos != -1)
			{
				int port = _ttoi(str.Left(pos));
				if (port >= 1 && port <= 65535)
					portSet.insert(port);
				str = str.Mid(pos + 1);
				str.TrimLeft(_T(" ,"));
				pos = str.FindOneOf(_T(" ,"));
			}
			if (str != _T(""))
			{
				int port = _ttoi(str);
				if (port >= 1 && port <= 65535)
					portSet.insert(port);
			}

			str = _T("");
			for (std::set<int>::const_iterator iter = portSet.begin(); iter != portSet.end(); iter++)
			{
				CStdString tmp;
				tmp.Format(_T("%d "), *iter);
				str += tmp;
			}
			str.TrimRight(' ');
		}
		break;
	case OPTION_WELCOMEMESSAGE:
		{
			std::vector<CStdString> msgLines;
			int oldpos = 0;
			str.Replace(_T("\r\n"), _T("\n"));
			int pos = str.Find(_T("\n"));
			CStdString line;
			while (pos != -1)
			{
				if (pos)
				{
					line = str.Mid(oldpos, pos - oldpos);
					line = line.Left(CONST_WELCOMEMESSAGE_LINESIZE);
					line.TrimRight(_T(" "));
					if (msgLines.size() || line != _T(""))
						msgLines.push_back(line);
				}
				oldpos = pos + 1;
				pos = str.Find(_T("\n"), oldpos);
			}
			line = str.Mid(oldpos);
			if (line != _T(""))
			{
				line = line.Left(CONST_WELCOMEMESSAGE_LINESIZE);
				msgLines.push_back(line);
			}
			str = _T("");
			for (unsigned int i = 0; i < msgLines.size(); i++)
				str += msgLines[i] + _T("\r\n");
			str.TrimRight(_T("\r\n"));
			if (str == _T(""))
			{
				str = _T("%v");
				str += _T("\r\nwritten by Tim Kosse ([email protected])");
				str += _T("\r\nPlease visit https://filezilla-project.org/");
			}
		}
		break;
	case OPTION_ADMINIPBINDINGS:
		{
			CStdString sub;
			std::list<CStdString> ipBindList;
			for (unsigned int i = 0; i<_tcslen(value); i++)
			{
				TCHAR cur = value[i];
				if ((cur < '0' || cur > '9') && cur != '.' && cur != ':')
				{
					if (sub == _T("") && cur == '*')
					{
						ipBindList.clear();
						ipBindList.push_back(_T("*"));
						break;
					}

					if (sub != _T(""))
					{
						if (IsIpAddress(sub))
							ipBindList.push_back(sub);
						sub = _T("");
					}
				}
				else
					sub += cur;
			}
			if (sub != _T(""))
			{
				if (IsIpAddress(sub))
					ipBindList.push_back(sub);
			}
			str = _T("");
			for (std::list<CStdString>::iterator iter = ipBindList.begin(); iter!=ipBindList.end(); iter++)
				if (!IsLocalhost(*iter))
					str += *iter + _T(" ");

			str.TrimRight(_T(" "));
		}
		break;
	case OPTION_ADMINPASS:
		if (str != _T("") && str.GetLength() < 6)
			return;
		break;
	case OPTION_MODEZ_DISALLOWED_IPS:
	case OPTION_IPFILTER_ALLOWED:
	case OPTION_IPFILTER_DISALLOWED:
	case OPTION_ADMINIPADDRESSES:
		{
			str.Replace('\r', ' ');
			str.Replace('\n', ' ');
			str.Replace('\r', ' ');
			while (str.Replace(_T("  "), _T(" ")));
			str += _T(" ");

			CStdString ips;

			int pos = str.Find(' ');
			while (pos != -1)
			{
				CStdString sub = str.Left(pos);
				str = str.Mid(pos + 1);
				str.TrimLeft(' ');

				if (sub == _T("*"))
					ips += _T(" ") + sub;
				else
				{
					if (IsValidAddressFilter(sub))
						ips += " " + sub;
					pos = str.Find(' ');
				}
			}
			ips.TrimLeft(' ');

			str = ips;
		}
		break;
	case OPTION_IPBINDINGS:
		{
			std::list<CStdString> ipBindList;

			str += _T(" ");
			while (!str.empty()) {
				int pos  = str.Find(' ');
				if (pos < 0) {
					break;
				}
				CStdString sub = str.Left(pos);
				str = str.Mid(pos + 1);

				if (sub == _T("*")) {
					ipBindList.clear();
					ipBindList.push_back(_T("*"));
					break;
				}
				else if (IsIpAddress(sub, true)) {
					ipBindList.push_back(sub);
				}
			}

			if (ipBindList.empty())
				ipBindList.push_back(_T("*"));

			str.clear();
			for (auto const& ip : ipBindList) {
				str += ip + _T(" ");
			}

			str.TrimRight(_T(" "));
		}
		break;
	case OPTION_CUSTOMPASVIPSERVER:
		if (str.Find(_T("filezilla.sourceforge.net")) != -1)
			str = _T("http://ip.filezilla-project.org/ip.php");
		break;
	}

	{
		simple_lock lock(m_mutex);
		m_sOptionsCache[nOptionID-1].bCached = TRUE;
		m_sOptionsCache[nOptionID-1].nType = 0;
		m_sOptionsCache[nOptionID-1].str = str;
		m_OptionsCache[nOptionID-1]=m_sOptionsCache[nOptionID-1];
	}

	if (!save)
		return;

	USES_CONVERSION;
	CStdString xmlFileName = GetExecutableDirectory() + _T("FileZilla Server.xml");
	char* bufferA = T2A(xmlFileName);
	if (!bufferA)
		return;

	TiXmlDocument document;
	if (!document.LoadFile(bufferA))
		return;

	TiXmlElement* pRoot = document.FirstChildElement("FileZillaServer");
	if (!pRoot)
		return;

	TiXmlElement* pSettings = pRoot->FirstChildElement("Settings");
	if (!pSettings)
		pSettings = pRoot->LinkEndChild(new TiXmlElement("Settings"))->ToElement();

	TiXmlElement* pItem;
	for (pItem = pSettings->FirstChildElement("Item"); pItem; pItem = pItem->NextSiblingElement("Item"))
	{
		const char* pName = pItem->Attribute("name");
		if (!pName)
			continue;
		CStdString name(pName);
		if (name != m_Options[nOptionID-1].name)
			continue;

		break;
	}

	if (!pItem)
		pItem = pSettings->LinkEndChild(new TiXmlElement("Item"))->ToElement();
	pItem->Clear();
	pItem->SetAttribute("name", ConvToNetwork(m_Options[nOptionID - 1].name).c_str());
	pItem->SetAttribute("type", "string");
	pItem->LinkEndChild(new TiXmlText(ConvToNetwork(value).c_str()));

	document.SaveFile(bufferA);
}
Exemple #9
0
//-------------------------------------------------------------------------------------------------------------------
void Xcddb::parseData(const char *buffer)
{
  //writeLog("parseData Start");

  char *line;
  const char trenner[3] = {'\n', '\r', '\0'};
  line = strtok((char*)buffer, trenner);
  int line_cnt = 0;
  while ((line = strtok(0, trenner)))
  {
    if (line[0] != '#')
    {
      if (0 == strncmp(line, "DTITLE", 6))
      {
        // DTITLE=Modern Talking / Album: Victory (The 11th Album)
        unsigned int len = (unsigned int)strlen(line) - 6;
        bool found = false;
        unsigned int i = 5;
        for (;i < len;i++)
        {
          if ((i + 2) <= len && line[i] == ' ' && line[i + 1] == '/' && line[i + 2] == ' ')
          {
            // Jep found
            found = true;
            break;
          }
        }
        if (found)
        {
          CStdString strLine = (char*)(line + 7);
          CStdString strDisk_artist = strLine.Left(i - 7);
          CStdString strDisk_title = (char*)(line + i + 3);

          // You never know if you really get UTF-8 strings from cddb
          if (!g_charsetConverter.isValidUtf8(strDisk_artist))
            g_charsetConverter.stringCharsetToUtf8(strDisk_artist, m_strDisk_artist);
          else
            m_strDisk_artist=strDisk_artist;

          // You never know if you really get UTF-8 strings from cddb
          if (!g_charsetConverter.isValidUtf8(strDisk_title))
            g_charsetConverter.stringCharsetToUtf8(strDisk_title, m_strDisk_title);
          else
            m_strDisk_title=strDisk_title;
        }
        else
        {
          CStdString strDisk_title = (char*)(line + 7);
          // You never know if you really get UTF-8 strings from cddb
          if (!g_charsetConverter.isValidUtf8(strDisk_title))
            g_charsetConverter.stringCharsetToUtf8(strDisk_title, m_strDisk_title);
          else
            m_strDisk_title=strDisk_title;
        }
      }
      else if (0 == strncmp(line, "DYEAR", 5))
      {
        CStdString strYear = (char*)(line + 5);
        strYear.TrimLeft("= ");
        // You never know if you really get UTF-8 strings from cddb
        if (!g_charsetConverter.isValidUtf8(strYear))
          g_charsetConverter.stringCharsetToUtf8(strYear, m_strYear);
        else
          m_strYear=strYear;
      }
      else if (0 == strncmp(line, "DGENRE", 6))
      {
        CStdString strGenre = (char*)(line + 6);
        strGenre.TrimLeft("= ");

        // You never know if you really get UTF-8 strings from cddb
        if (!g_charsetConverter.isValidUtf8(strGenre))
          g_charsetConverter.stringCharsetToUtf8(strGenre, m_strGenre);
        else
          m_strGenre=strGenre;
      }
      else if (0 == strncmp(line, "TTITLE", 6))
      {
        addTitle(line);
      }
      else if (0 == strncmp(line, "EXTD", 4))
      {
        CStdString strExtd((char*)(line + 4));

        if (m_strYear.IsEmpty())
        {
          // Extract Year from extended info
          // as a fallback
          int iPos = strExtd.Find("YEAR:");
          if (iPos > -1)
          {
            CStdString strYear;
            strYear = strExtd.Mid(iPos + 6, 4);

            // You never know if you really get UTF-8 strings from cddb
            if (!g_charsetConverter.isValidUtf8(strYear))
              g_charsetConverter.stringCharsetToUtf8(strYear, m_strYear);
            else
              m_strYear=strYear;
          }
        }

        if (m_strGenre.IsEmpty())
        {
          // Extract ID3 Genre
          // as a fallback
          int iPos = strExtd.Find("ID3G:");
          if (iPos > -1)
          {
            CStdString strGenre;
            strGenre = strExtd.Mid(iPos + 5, 4);
            strGenre.TrimLeft(' ');
            if (StringUtils::IsNaturalNumber(strGenre))
            {
              CID3Tag tag;
              m_strGenre=tag.ParseMP3Genre(strGenre);
            }
          }
        }
      }
      else if (0 == strncmp(line, "EXTT", 4))
      {
        addExtended(line);
      }
    }
    line_cnt++;
  }
  //writeLog("parseData Ende");
}
Exemple #10
0
////////////////////////////////////////////////////////////////////////////////////
// Function: Parse()
// Opens the .cue file for reading, and constructs the track database information
////////////////////////////////////////////////////////////////////////////////////
bool CCueDocument::Parse(const CStdString &strFile)
{
  if (!m_file.Open(strFile))
    return false;

  CStdString strLine;
  m_iTotalTracks = -1;
  CStdString strCurrentFile = "";
  bool bCurrentFileChanged = false;
  int time;

  // Run through the .CUE file and extract the tracks...
  while (true)
  {
    if (!ReadNextLine(strLine))
      break;
    if (StringUtils::StartsWith(strLine,"INDEX 01"))
    {
      if (bCurrentFileChanged)
      {
        OutputDebugString("Track split over multiple files, unsupported ('" + strFile + "')\n");
        return false;
      }

      // find the end of the number section
      time = ExtractTimeFromIndex(strLine);
      if (time == -1)
      { // Error!
        OutputDebugString("Mangled Time in INDEX 0x tag in CUE file!\n");
        return false;
      }
      if (m_iTotalTracks > 0)  // Set the end time of the last track
        m_Track[m_iTotalTracks - 1].iEndTime = time;

      if (m_iTotalTracks >= 0)
        m_Track[m_iTotalTracks].iStartTime = time; // start time of the next track
    }
    else if (StringUtils::StartsWith(strLine,"TITLE"))
    {
      if (m_iTotalTracks == -1) // No tracks yet
        ExtractQuoteInfo(strLine, m_strAlbum);
      else if (!ExtractQuoteInfo(strLine, m_Track[m_iTotalTracks].strTitle))
      {
        // lets manage tracks titles without quotes
        CStdString titleNoQuote = strLine.Mid(5);
        titleNoQuote.TrimLeft();
        if (!titleNoQuote.IsEmpty())
        {
          g_charsetConverter.unknownToUTF8(titleNoQuote);
          m_Track[m_iTotalTracks].strTitle = titleNoQuote;
        }
      }
    }
    else if (StringUtils::StartsWith(strLine,"PERFORMER"))
    {
      if (m_iTotalTracks == -1) // No tracks yet
        ExtractQuoteInfo(strLine, m_strArtist);
      else // New Artist for this track
        ExtractQuoteInfo(strLine, m_Track[m_iTotalTracks].strArtist);
    }
    else if (StringUtils::StartsWith(strLine,"TRACK"))
    {
      int iTrackNumber = ExtractNumericInfo(strLine.Mid(5));

      m_iTotalTracks++;

      CCueTrack track;
      m_Track.push_back(track);
      m_Track[m_iTotalTracks].strFile = strCurrentFile;

      if (iTrackNumber > 0)
        m_Track[m_iTotalTracks].iTrackNumber = iTrackNumber;
      else
        m_Track[m_iTotalTracks].iTrackNumber = m_iTotalTracks + 1;

      bCurrentFileChanged = false;
    }
    else if (StringUtils::StartsWith(strLine,"REM DISCNUMBER"))
    {
      int iDiscNumber = ExtractNumericInfo(strLine.Mid(14));
      if (iDiscNumber > 0)
        m_iDiscNumber = iDiscNumber;
    }
    else if (StringUtils::StartsWith(strLine,"FILE"))
    {
      // already a file name? then the time computation will be changed
      if(strCurrentFile.size() > 0)
        bCurrentFileChanged = true;

      ExtractQuoteInfo(strLine, strCurrentFile);

      // Resolve absolute paths (if needed).
      if (strCurrentFile.length() > 0)
        ResolvePath(strCurrentFile, strFile);
    }
    else if (StringUtils::StartsWith(strLine,"REM DATE"))
    {
      int iYear = ExtractNumericInfo(strLine.Mid(8));
      if (iYear > 0)
        m_iYear = iYear;
    }
    else if (StringUtils::StartsWith(strLine,"REM GENRE"))
    {
      if (!ExtractQuoteInfo(strLine, m_strGenre))
      {
        CStdString genreNoQuote = strLine.Mid(9);
        genreNoQuote.TrimLeft();
        if (!genreNoQuote.IsEmpty())
        {
          g_charsetConverter.unknownToUTF8(genreNoQuote);
          m_strGenre = genreNoQuote;
        }
      }
    }
    else if (StringUtils::StartsWith(strLine,"REM REPLAYGAIN_ALBUM_GAIN"))
      m_replayGainAlbumGain = (float)atof(strLine.Mid(26));
    else if (StringUtils::StartsWith(strLine,"REM REPLAYGAIN_ALBUM_PEAK"))
      m_replayGainAlbumPeak = (float)atof(strLine.Mid(26));
    else if (StringUtils::StartsWith(strLine,"REM REPLAYGAIN_TRACK_GAIN") && m_iTotalTracks >= 0)
      m_Track[m_iTotalTracks].replayGainTrackGain = (float)atof(strLine.Mid(26));
    else if (StringUtils::StartsWith(strLine,"REM REPLAYGAIN_TRACK_PEAK") && m_iTotalTracks >= 0)
      m_Track[m_iTotalTracks].replayGainTrackPeak = (float)atof(strLine.Mid(26));
  }

  // reset track counter to 0, and fill in the last tracks end time
  m_iTrack = 0;
  if (m_iTotalTracks >= 0)
    m_Track[m_iTotalTracks].iEndTime = 0;
  else
    OutputDebugString("No INDEX 01 tags in CUE file!\n");
  m_file.Close();
  if (m_iTotalTracks >= 0)
  {
    m_iTotalTracks++;
  }
  return (m_iTotalTracks > 0);
}
Exemple #11
0
CLinuxTimezone::CLinuxTimezone() : m_IsDST(0)
{
   char* line = NULL;
   size_t linelen = 0;
   int nameonfourthfield = 0;
   CStdString s;
   vector<CStdString> tokens;

   // Load timezones
   FILE* fp = fopen("/usr/share/zoneinfo/zone.tab", "r");
   if (fp)
   {
      CStdString countryCode;
      CStdString timezoneName;

      while (getdelim(&line, &linelen, '\n', fp) > 0)
      {
         tokens.clear();
         s = line;
         s.TrimLeft(" \t").TrimRight(" \n");

         if (s.length() == 0)
            continue;

         if (s[0] == '#')
            continue;

         CUtil::Tokenize(s, tokens, " \t");
         if (tokens.size() < 3)
            continue;

         countryCode = tokens[0];
         timezoneName = tokens[2];

         if (m_timezonesByCountryCode.count(countryCode) == 0)
         {
            vector<CStdString> timezones;
            timezones.push_back(timezoneName);
            m_timezonesByCountryCode[countryCode] = timezones;
         }
         else
         {
            vector<CStdString>& timezones = m_timezonesByCountryCode[countryCode];
            timezones.push_back(timezoneName);
         }

         m_countriesByTimezoneName[timezoneName] = countryCode;
      }
      fclose(fp);
   }

   if (line)
   {
     free(line);
     line = NULL;
     linelen = 0;
   }

   // Load countries
   fp = fopen("/usr/share/zoneinfo/iso3166.tab", "r");
   if (!fp)
   {
      fp = fopen("/usr/share/misc/iso3166", "r");
      nameonfourthfield = 1;
   }
   if (fp)
   {
      CStdString countryCode;
      CStdString countryName;

      while (getdelim(&line, &linelen, '\n', fp) > 0)
      {
         s = line;
         s.TrimLeft(" \t").TrimRight(" \n");

         if (s.length() == 0)
            continue;

         if (s[0] == '#')
            continue;

         // Search for the first non space from the 2nd character and on
         int i = 2;
         while (s[i] == ' ' || s[i] == '\t') i++;

         if (nameonfourthfield)
         {
            // skip three letter
            while (s[i] != ' ' && s[i] != '\t') i++;
            while (s[i] == ' ' || s[i] == '\t') i++;
            // skip number
            while (s[i] != ' ' && s[i] != '\t') i++;
            while (s[i] == ' ' || s[i] == '\t') i++;
         }

         countryCode = s.Left(2);
         countryName = s.Mid(i);

         m_counties.push_back(countryName);
         m_countryByCode[countryCode] = countryName;
         m_countryByName[countryName] = countryCode;
      }
      sort(m_counties.begin(), m_counties.end(), sortstringbyname());
      fclose(fp);
   }
   free(line);
}
bool PVRIptvData::LoadPlayList(void) 
{
	if (m_strM3uUrl.IsEmpty())
	{
		XBMC->Log(LOG_NOTICE, "Playlist file path is not configured. Channels not loaded.");
		return false;
	}

	CStdString strPlaylistContent;
	if (!GetCachedFileContents(M3U_FILE_NAME, m_strM3uUrl, strPlaylistContent))
	{
		XBMC->Log(LOG_ERROR, "Unable to load playlist file '%s':  file is missing or empty.", m_strM3uUrl.c_str());
		return false;
	}

	std::stringstream stream(strPlaylistContent);

	/* load channels */
	bool bFirst = true;

	int iUniqueChannelId = 0;
	int iUniqueGroupId = 0;
	int iCurrentGroupId = 0;
	int iChannelNum = 0;
	int iEPGTimeShift = 0;

	PVRIptvChannel tmpChannel;
	tmpChannel.strTvgId = "";
	tmpChannel.strChannelName = "";
	tmpChannel.strTvgName = "";
	tmpChannel.strTvgLogo = "";
	tmpChannel.iTvgShift = 0;

	char szLine[1024];
	while(stream.getline(szLine, 1024)) 
	{
	
		CStdString strLine = "";
		strLine.append(szLine);
		strLine.TrimRight(" \t\r\n");
		strLine.TrimLeft(" \t");

		if (strLine.IsEmpty())
		{
			continue;
		}

		if (bFirst) 
		{
			bFirst = false;
			if (strLine.Left(3) == "\xEF\xBB\xBF")
			{
				strLine.Delete(0, 3);
			}
			if (strLine.Left((int)strlen(M3U_START_MARKER)) == M3U_START_MARKER) 
			{
				double fTvgShift = atof(ReadMarkerValue(strLine, TVG_INFO_SHIFT_MARKER));
				iEPGTimeShift = (int) (fTvgShift * 3600.0);
				continue;
			}
			else
			{
				break;
			}
		}

		if (strLine.Left((int)strlen(M3U_INFO_MARKER)) == M3U_INFO_MARKER) 
		{
			bool        bRadio       = false;
			double      fTvgShift    = 0;
			CStdString	strChnlName  = "";
			CStdString	strTvgId     = "";
			CStdString	strTvgName   = "";
			CStdString	strTvgLogo   = "";
			CStdString	strGroupName = "";
			CStdString	strRadio     = "";

			// parse line
			int iColon = (int)strLine.Find(':');
			int iComma = (int)strLine.ReverseFind(',');
			if (iColon >= 0 && iComma >= 0 && iComma > iColon) 
			{
				// parse name
				iComma++;
				strChnlName = strLine.Right((int)strLine.size() - iComma).Trim();
				tmpChannel.strChannelName = XBMC->UnknownToUTF8(strChnlName);

				// parse info
				CStdString strInfoLine = strLine.Mid(++iColon, --iComma - iColon);

				strTvgId = ReadMarkerValue(strInfoLine, TVG_INFO_ID_MARKER);
				strTvgName = ReadMarkerValue(strInfoLine, TVG_INFO_NAME_MARKER);
				strTvgLogo = ReadMarkerValue(strInfoLine, TVG_INFO_LOGO_MARKER);
				strGroupName = ReadMarkerValue(strInfoLine, GROUP_NAME_MARKER);
				strRadio = ReadMarkerValue(strInfoLine, RADIO_MARKER);
				fTvgShift = atof(ReadMarkerValue(strInfoLine, TVG_INFO_SHIFT_MARKER));

				if (strTvgId.IsEmpty())
				{
					char buff[255];
					sprintf(buff, "%d", atoi(strInfoLine));
					strTvgId.append(buff);
				}
				if (strTvgLogo.IsEmpty())
				{
					strTvgLogo = strChnlName;
				}

				bRadio = !strRadio.CompareNoCase("true");
				tmpChannel.strTvgId   = strTvgId;
				tmpChannel.strTvgName = XBMC->UnknownToUTF8(strTvgName);
				tmpChannel.strTvgLogo = XBMC->UnknownToUTF8(strTvgLogo);
				tmpChannel.iTvgShift  = (int)(fTvgShift * 3600.0);
				tmpChannel.bRadio     = bRadio;

				if (tmpChannel.iTvgShift == 0 && iEPGTimeShift != 0)
				{
					tmpChannel.iTvgShift = iEPGTimeShift;
				}

				if (!strGroupName.IsEmpty())
				{
					strGroupName = XBMC->UnknownToUTF8(strGroupName);

					PVRIptvChannelGroup * pGroup;
					if ((pGroup = FindGroup(strGroupName)) == NULL)
					{
						PVRIptvChannelGroup group;
						group.strGroupName = strGroupName;
						group.iGroupId = ++iUniqueGroupId;
						group.bRadio = bRadio;

						m_groups.push_back(group);
						iCurrentGroupId = iUniqueGroupId;
					}
					else
					{
						iCurrentGroupId = pGroup->iGroupId;
					}
				}
			}
		} 
		else if (strLine[0] != '#')
		{
			PVRIptvChannel channel;
			channel.iUniqueId         = ++iUniqueChannelId;
			channel.iChannelNumber    = ++iChannelNum;
			channel.strTvgId          = tmpChannel.strTvgId;
			channel.strChannelName    = tmpChannel.strChannelName;
			channel.strTvgName        = tmpChannel.strTvgName;
			channel.strTvgLogo        = tmpChannel.strTvgLogo;
			channel.iTvgShift         = tmpChannel.iTvgShift;
			channel.bRadio            = tmpChannel.bRadio;
			channel.strStreamURL      = strLine;
			channel.iEncryptionSystem = 0;

			if (iCurrentGroupId > 0) 
			{
				channel.bRadio = m_groups.at(iCurrentGroupId - 1).bRadio;
				m_groups.at(iCurrentGroupId - 1).members.push_back(channel.iChannelNumber);
			}

			m_channels.push_back(channel);

			tmpChannel.strTvgId = "";
			tmpChannel.strChannelName = "";
			tmpChannel.strTvgName = "";
			tmpChannel.strTvgLogo = "";
			tmpChannel.iTvgShift = 0;
			tmpChannel.bRadio = false;
		}
	}
  
	stream.clear();

	if (m_channels.size() == 0)
	{
		XBMC->Log(LOG_ERROR, "Unable to load channels from file '%s':  file is corrupted.", m_strM3uUrl.c_str());
		return false;
	}

	ApplyChannelsLogos();

	XBMC->Log(LOG_NOTICE, "Loaded %d channels.", m_channels.size());
	return true;
}
Exemple #13
0
CStdString CID3Tag::ParseMP3Genre(const CStdString& str) const
{
  m_dll.Load();

  CStdString strTemp = str;
  set<CStdString> setGenres;

  while (!strTemp.IsEmpty())
  {
    // remove any leading spaces
    strTemp.TrimLeft();

    if (strTemp.IsEmpty())
      break;

    // start off looking for (something)
    if (strTemp[0] == '(')
    {
      strTemp.erase(0, 1);
      if (strTemp.empty())
        break;

      // now look for ((something))
      if (strTemp[0] == '(')
      {
        // remove ((something))
        int i = strTemp.find_first_of(')');
        strTemp.erase(0, i + 2);
      }
    }

    // no parens, so we have a start of a string
    // push chars into temp string until valid terminator found
    // valid terminators are ) or , or ;
    else
    {
      CStdString t;
      size_t i = strTemp.find_first_of("),;");
      if (i != std::string::npos)
      {
        t = strTemp.Left(i);
        strTemp.erase(0, i + 1);
      } else {
        t = strTemp;
        strTemp.clear();
      }
      
      // remove any leading or trailing white space
      // from temp string
      t.Trim();
      if (!t.length()) continue;

      // if the temp string is natural number try to convert it to a genre string
      if (StringUtils::IsNaturalNumber(t))
      {
        id3_ucs4_t* ucs4=m_dll.id3_latin1_ucs4duplicate((id3_latin1_t*)t.c_str());
        const id3_ucs4_t* genre=m_dll.id3_genre_name(ucs4);
        m_dll.id3_ucs4_free(ucs4);
        t=ToStringCharset(genre, ID3_FIELD_TEXTENCODING_ISO_8859_1);
      }

      // convert RX to Remix as per ID3 V2.3 spec
      else if ((t == "RX") || (t == "Rx") || (t == "rX") || (t == "rx"))
      {
        t = "Remix";
      }

      // convert CR to Cover as per ID3 V2.3 spec
      else if ((t == "CR") || (t == "Cr") || (t == "cR") || (t == "cr"))
      {
        t = "Cover";
      }

      // insert genre name in set
      setGenres.insert(t);
    }

  }

  // return a " / " seperated string
  CStdString strGenre;
  set<CStdString>::iterator it;
  for (it = setGenres.begin(); it != setGenres.end(); it++)
  {
    CStdString strTemp = *it;
    if (!strGenre.IsEmpty())
      strGenre += g_advancedSettings.m_musicItemSeparator;
    strGenre += strTemp;
  }
  return strGenre;
}
Exemple #14
0
bool CPlayListPLS::Load(const CStdString &strFile)
{
  //read it from the file
  CStdString strFileName(strFile);
  m_strPlayListName = URIUtils::GetFileName(strFileName);

  Clear();

  bool bShoutCast = false;
  if( strFileName.Left(8).Equals("shout://") )
  {
    strFileName.Delete(0, 8);
    strFileName.Insert(0, "http://");
    m_strBasePath = "";
    bShoutCast = true;
  }
  else
    URIUtils::GetParentPath(strFileName, m_strBasePath);

  CFile file;
  if (!file.Open(strFileName) )
  {
    file.Close();
    return false;
  }

  if (file.GetLength() > 1024*1024)
  {
    CLog::Log(LOGWARNING, "%s - File is larger than 1 MB, most likely not a playlist",__FUNCTION__);
    return false;
  }

  char szLine[4096];
  CStdString strLine;

  // run through looking for the [playlist] marker.
  // if we find another http stream, then load it.
  while (1)
  {
    if ( !file.ReadString(szLine, sizeof(szLine) ) )
    {
      file.Close();
      return size() > 0;
    }
    strLine = szLine;
    strLine.TrimLeft(" \t");
    strLine.TrimRight(" \n\r");
    if(strLine.Equals(START_PLAYLIST_MARKER))
      break;

    // if there is something else before playlist marker, this isn't a pls file
    if(!strLine.IsEmpty())
      return false;
  }

  bool bFailed = false;
  while (file.ReadString(szLine, sizeof(szLine) ) )
  {
    strLine = szLine;
    StringUtils::RemoveCRLF(strLine);
    int iPosEqual = strLine.Find("=");
    if (iPosEqual > 0)
    {
      CStdString strLeft = strLine.Left(iPosEqual);
      iPosEqual++;
      CStdString strValue = strLine.Right(strLine.size() - iPosEqual);
      strLeft.ToLower();
      while (strLeft[0] == ' ' || strLeft[0] == '\t')
        strLeft.erase(0,1);

      if (strLeft == "numberofentries")
      {
        m_vecItems.reserve(atoi(strValue.c_str()));
      }
      else if (strLeft.Left(4) == "file")
      {
        vector <int>::size_type idx = atoi(strLeft.c_str() + 4);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }

        // Skip self - do not load playlist recursively
        if (URIUtils::GetFileName(strValue).Equals(URIUtils::GetFileName(strFileName)))
          continue;

        if (m_vecItems[idx - 1]->GetLabel().empty())
          m_vecItems[idx - 1]->SetLabel(URIUtils::GetFileName(strValue));
        CFileItem item(strValue, false);
        if (bShoutCast && !item.IsAudio())
          strValue.Replace("http:", "shout:");

        strValue = URIUtils::SubstitutePath(strValue);
        CUtil::GetQualifiedFilename(m_strBasePath, strValue);
        g_charsetConverter.unknownToUTF8(strValue);
        m_vecItems[idx - 1]->SetPath(strValue);
      }
      else if (strLeft.Left(5) == "title")
      {
        vector <int>::size_type idx = atoi(strLeft.c_str() + 5);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }
        g_charsetConverter.unknownToUTF8(strValue);
        m_vecItems[idx - 1]->SetLabel(strValue);
      }
      else if (strLeft.Left(6) == "length")
      {
        vector <int>::size_type idx = atoi(strLeft.c_str() + 6);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }
        m_vecItems[idx - 1]->GetMusicInfoTag()->SetDuration(atol(strValue.c_str()));
      }
      else if (strLeft == "playlistname")
      {
        m_strPlayListName = strValue;
        g_charsetConverter.unknownToUTF8(m_strPlayListName);
      }
    }
  }
  file.Close();

  if (bFailed)
  {
    CLog::Log(LOGERROR, "File %s is not a valid PLS playlist. Location of first file,title or length is not permitted (eg. File0 should be File1)", URIUtils::GetFileName(strFileName).c_str());
    return false;
  }

  // check for missing entries
  ivecItems p = m_vecItems.begin();
  while ( p != m_vecItems.end())
  {
    if ((*p)->GetPath().empty())
    {
      p = m_vecItems.erase(p);
    }
    else
    {
      ++p;
    }
  }

  return true;
}
Exemple #15
0
void CNetworkInterfaceLinux::SetSettings(NetworkAssignment& assignment, CStdString& ipAddress, CStdString& networkMask, CStdString& defaultGateway, CStdString& essId, CStdString& key, EncMode& encryptionMode)
{
#ifndef __APPLE__
   FILE* fr = fopen("/etc/network/interfaces", "r");
   if (!fr)
   {
      // TODO
      return;
   }

   FILE* fw = fopen("/tmp/interfaces.temp", "w");
   if (!fw)
   {
      // TODO
      return;
   }

   char* line = NULL;
   size_t linel = 0;
   CStdString s;
   bool foundInterface = false;
   bool dataWritten = false;

   while (getdelim(&line, &linel, '\n', fr) > 0)
   {
      vector<CStdString> tokens;

      s = line;
      s.TrimLeft(" \t").TrimRight(" \n");

      // skip comments
      if (!foundInterface && (s.length() == 0 || s.GetAt(0) == '#'))
      {
        fprintf(fw, "%s", line);
        continue;
      }

      // look for "iface <interface name> inet"
      CUtil::Tokenize(s, tokens, " ");
      if (tokens.size() == 2 &&
          tokens[0].Equals("auto") &&
          tokens[1].Equals(GetName()))
      {
         continue;
      }
      else if (!foundInterface &&
          tokens.size() == 4 &&
          tokens[0].Equals("iface") &&
          tokens[1].Equals(GetName()) &&
          tokens[2].Equals("inet"))
      {
         foundInterface = true;
         WriteSettings(fw, assignment, ipAddress, networkMask, defaultGateway, essId, key, encryptionMode);
         dataWritten = true;
      }
      else if (foundInterface &&
               tokens.size() == 4 &&
               tokens[0].Equals("iface"))
      {
        foundInterface = false;
        fprintf(fw, "%s", line);
      }
      else if (!foundInterface)
      {
        fprintf(fw, "%s", line);
      }
   }

   if (line)
     free(line);

   if (!dataWritten && assignment != NETWORK_DISABLED)
   {
      fprintf(fw, "\n");
      WriteSettings(fw, assignment, ipAddress, networkMask, defaultGateway, essId, key, encryptionMode);
   }

   fclose(fr);
   fclose(fw);

   // Rename the file
   // NEUROS: Since on the Link we have sudo setup with no password, this will always work
   system("sudo cp /tmp/interfaces.temp /etc/network/interfaces");

   CLog::Log(LOGINFO, "Stopping interface %s", GetName().c_str());
   std::string cmd = "sudo /sbin/ifdown " + GetName();
   system(cmd.c_str());

   if (assignment != NETWORK_DISABLED)
   {
      CLog::Log(LOGINFO, "Starting interface %s", GetName().c_str());
      cmd = "sudo /sbin/ifup " + GetName();
      system(cmd.c_str());
   }
#endif
}
Exemple #16
0
void CNetworkInterfaceLinux::GetSettings(NetworkAssignment& assignment, CStdString& ipAddress, CStdString& networkMask, CStdString& defaultGateway, CStdString& essId, CStdString& key, EncMode& encryptionMode)
{
    ipAddress = "0.0.0.0";
    networkMask = "0.0.0.0";
    defaultGateway = "0.0.0.0";
    essId = "";
    key = "";
    encryptionMode = ENC_NONE;
    assignment = NETWORK_DISABLED;

#if defined(TARGET_LINUX)
    FILE* fp = fopen("/etc/network/interfaces", "r");
    if (!fp)
    {
        // TODO
        return;
    }

    char* line = NULL;
    size_t linel = 0;
    CStdString s;
    bool foundInterface = false;

    while (getdelim(&line, &linel, '\n', fp) > 0)
    {
        vector<CStdString> tokens;

        s = line;
        s.TrimLeft(" \t").TrimRight(" \n");

        // skip comments
        if (s.length() == 0 || s.GetAt(0) == '#')
            continue;

        // look for "iface <interface name> inet"
        CUtil::Tokenize(s, tokens, " ");
        if (!foundInterface &&
                tokens.size() >=3 &&
                tokens[0].Equals("iface") &&
                tokens[1].Equals(GetName()) &&
                tokens[2].Equals("inet"))
        {
            if (tokens[3].Equals("dhcp"))
            {
                assignment = NETWORK_DHCP;
                foundInterface = true;
            }
            if (tokens[3].Equals("static"))
            {
                assignment = NETWORK_STATIC;
                foundInterface = true;
            }
        }

        if (foundInterface && tokens.size() == 2)
        {
            if (tokens[0].Equals("address")) ipAddress = tokens[1];
            else if (tokens[0].Equals("netmask")) networkMask = tokens[1];
            else if (tokens[0].Equals("gateway")) defaultGateway = tokens[1];
            else if (tokens[0].Equals("wireless-essid")) essId = tokens[1];
            else if (tokens[0].Equals("wireless-key"))
            {
                key = tokens[1];
                if (key.length() > 2 && key[0] == 's' && key[1] == ':')
                    key.erase(0, 2);
                encryptionMode = ENC_WEP;
            }
            else if (tokens[0].Equals("wpa-ssid")) essId = tokens[1];
            else if (tokens[0].Equals("wpa-proto") && tokens[1].Equals("WPA")) encryptionMode = ENC_WPA;
            else if (tokens[0].Equals("wpa-proto") && tokens[1].Equals("WPA2")) encryptionMode = ENC_WPA2;
            else if (tokens[0].Equals("wpa-psk")) key = tokens[1];
            else if (tokens[0].Equals("auto") || tokens[0].Equals("iface") || tokens[0].Equals("mapping")) break;
        }
    }
    free(line);

    // Fallback in case wpa-proto is not set
    if (key != "" && encryptionMode == ENC_NONE)
        encryptionMode = ENC_WPA;

    fclose(fp);
#endif
}
bool CShoutcastDirectory::ParseStations(TiXmlElement *root, CFileItemList &items, CURL &url)
{
  TiXmlElement *element = NULL;
  CStdString path;

  items.m_idepth = 2; /* station list */

  element = root->FirstChildElement("tunein");
  if(element == NULL) 
  {
    CLog::Log(LOGWARNING, "%s - No tunein base found", __FUNCTION__);
    return false;
  }
  
  path = element->Attribute("base");
  path.TrimLeft("/");

  url.SetFileName(path);

  element = root->FirstChildElement("station");

  if(element == NULL)
  {
    CLog::Log(LOGWARNING, "%s - No stations found", __FUNCTION__);
    return false;
  }
  int stations = 0;
  while(element != NULL && stations < 1000)
  {
    CStdString name = element->Attribute("name");
    CStdString id = element->Attribute("id");
    CStdString bitrate = element->Attribute("br");
    CStdString genre = element->Attribute("genre");
    CStdString listeners = element->Attribute("lc");
    CStdString content = element->Attribute("mt");

    CStdString label = name;

    url.SetOptions("?id=" + id);
    url.GetURL(path);
    //printf("%s: %s\n", name.c_str(), path.c_str());

    CFileItem* pItem = new CFileItem;
    pItem->m_bIsFolder = false;
    
    /* we highjack the music tag for this stuff, they will be used by */
    /* viewstates to sort and display proper information */
    pItem->GetMusicInfoTag()->SetArtist(listeners);
    pItem->GetMusicInfoTag()->SetAlbum(bitrate);
    pItem->GetMusicInfoTag()->SetGenre(genre);

    /* this is what will be sorted upon */
    pItem->GetVideoInfoTag()->m_fRating = (float)atoi(listeners.c_str());
    pItem->m_dwSize = atoi(bitrate.c_str());


    pItem->SetLabel(label);

    /* content type is known before hand, should save later lookup */
    /* wonder if we could combine the contentype of the playlist and of the real stream */
    pItem->SetContentType("audio/x-scpls");

    pItem->m_strPath = path;
    
    items.Add(pItem);

    stations++;
    element = element->NextSiblingElement("station");
  }

  return true;
}
Exemple #18
0
CStdString CPlayListM3U::GetBestBandwidthStream(const CStdString &strFileName, size_t bandwidth)
{
  // we may be passed a playlist that does not contain playlists of different
  // bitrates (eg: this playlist is really the HLS video). So, default the
  // return to the filename so it can be played
  char szLine[4096];
  CStdString strLine;
  CStdString strPlaylist = strFileName;
  size_t maxBandwidth = 0;

  // if we cannot get the last / we wont be able to determine the sub-playlists
  size_t baseEnd = strPlaylist.rfind('/');
  if (baseEnd == std::string::npos)
    return strPlaylist;

  // store the base path (the path without the filename)
  CStdString basePath = strPlaylist.substr(0, baseEnd + 1);

  // open the file, and if it fails, return
  CFile file;
  if (!file.Open(strFileName) )
  {
    file.Close();
    return strPlaylist;
  }

  // convert bandwidth specified in kbps to bps used by the m3u8
  bandwidth *= 1000;

  while (file.ReadString(szLine, 1024))
  {
    // read and trim a line
    strLine = szLine;
    strLine.TrimRight(" \t\r\n");
    strLine.TrimLeft(" \t");

    // skip the first line
    if (strLine == M3U_START_MARKER)
        continue;
    else if (strLine.Left(strlen(M3U_STREAM_MARKER)) == M3U_STREAM_MARKER)
    {
      // parse the line so we can pull out the bandwidth
      std::map< CStdString, CStdString > params = ParseStreamLine(strLine);
      std::map< CStdString, CStdString >::iterator it = params.find(M3U_BANDWIDTH_MARKER);

      if (it != params.end())
      {
        size_t streamBandwidth = atoi(it->second.c_str());
        if ((maxBandwidth < streamBandwidth) && (streamBandwidth <= bandwidth))
        {
          // read the next line
          if (!file.ReadString(szLine, 1024))
            continue;

          strLine = szLine;
          strLine.TrimRight(" \t\r\n");
          strLine.TrimLeft(" \t");

          // this line was empty
          if (strLine.empty())
            continue;

          // store the max bandwidth
          maxBandwidth = streamBandwidth;

          // if the path is absolute just use it
          if (CURL::IsFullPath(strLine))
            strPlaylist = strLine;
          else
            strPlaylist = basePath + strLine;
        }
      }
    }
  }

  CLog::Log(LOGINFO, "Auto-selecting %s based on configured bandwidth.", strPlaylist.c_str());

  return strPlaylist;
}
Exemple #19
0
bool CTagLoaderTagLib::Load(const string& strFileName, CMusicInfoTag& tag, EmbeddedArt *art /* = NULL */)
{  
  CStdString strExtension;
  URIUtils::GetExtension(strFileName, strExtension);
  strExtension.ToLower();
  strExtension.TrimLeft('.');

  if (strExtension.IsEmpty())
    return false;

  TagLibVFSStream*           stream = new TagLibVFSStream(strFileName, true);
  if (!stream)
  {
    CLog::Log(LOGERROR, "could not create TagLib VFS stream for: %s", strFileName.c_str());
    return false;
  }
  
  TagLib::File*              file = NULL;
  TagLib::APE::File*         apeFile = NULL;
  TagLib::ASF::File*         asfFile = NULL;
  TagLib::FLAC::File*        flacFile = NULL;
  TagLib::IT::File*          itFile = NULL;
  TagLib::Mod::File*         modFile = NULL;
  TagLib::MP4::File*         mp4File = NULL;
  TagLib::MPC::File*         mpcFile = NULL;
  TagLib::MPEG::File*        mpegFile = NULL;
  TagLib::Ogg::Vorbis::File* oggVorbisFile = NULL;
  TagLib::Ogg::FLAC::File*   oggFlacFile = NULL;
  TagLib::S3M::File*         s3mFile = NULL;
  TagLib::TrueAudio::File*   ttaFile = NULL;
  TagLib::WavPack::File*     wvFile = NULL;
  TagLib::XM::File*          xmFile = NULL;

  if (strExtension == "ape")
    file = apeFile = new APE::File(stream);
  else if (strExtension == "asf" || strExtension == "wmv" || strExtension == "wma")
    file = asfFile = new ASF::File(stream);
  else if (strExtension == "flac")
    file = flacFile = new FLAC::File(stream, ID3v2::FrameFactory::instance());
  else if (strExtension == "it")
    file = itFile = new IT::File(stream);
  else if (strExtension == "mod" || strExtension == "module" || strExtension == "nst" || strExtension == "wow")
    file = modFile = new Mod::File(stream);
  else if (strExtension == "mp4" || strExtension == "m4a" || 
           strExtension == "m4r" || strExtension == "m4b" || 
           strExtension == "m4p" || strExtension == "3g2")
    file = mp4File = new MP4::File(stream);
  else if (strExtension == "mpc")
    file = mpcFile = new MPC::File(stream);
  else if (strExtension == "mp3" || strExtension == "aac")
    file = mpegFile = new MPEG::File(stream, ID3v2::FrameFactory::instance());
  else if (strExtension == "s3m")
    file = s3mFile = new S3M::File(stream);
  else if (strExtension == "tta")
    file = ttaFile = new TrueAudio::File(stream, ID3v2::FrameFactory::instance());
  else if (strExtension == "wv")
    file = wvFile = new WavPack::File(stream);
  else if (strExtension == "xm")
    file = xmFile = new XM::File(stream);
  else if (strExtension == "ogg")
    file = oggVorbisFile = new Ogg::Vorbis::File(stream);
  else if (strExtension == "oga") // Leave this madness until last - oga container can have Vorbis or FLAC
  {
    file = oggFlacFile = new Ogg::FLAC::File(stream);
    if (!file || !file->isValid())
    {
      delete file;
      file = oggVorbisFile = new Ogg::Vorbis::File(stream);
    }
  }

  if (!file || !file->isOpen())
  {
    delete file;
    delete stream;
    CLog::Log(LOGDEBUG, "file could not be opened for tag reading");
    return false;
  }

  APE::Tag *ape = NULL;
  ASF::Tag *asf = NULL;
  MP4::Tag *mp4 = NULL;
  ID3v2::Tag *id3v2 = NULL;
  Ogg::XiphComment *xiph = NULL;
  Tag *generic = NULL;

  if (apeFile)
    ape = apeFile->APETag(false);
  else if (asfFile)
    asf = asfFile->tag();
  else if (flacFile)
  {
    xiph = flacFile->xiphComment(false);
    id3v2 = flacFile->ID3v2Tag(false);
  }
  else if (mp4File)
    mp4 = mp4File->tag();
  else if (mpegFile)
  {
    id3v2 = mpegFile->ID3v2Tag(false);
    ape = mpegFile->APETag(false);
  }
  else if (oggFlacFile)
    xiph = dynamic_cast<Ogg::XiphComment *>(oggFlacFile->tag());
  else if (oggVorbisFile)
    xiph = dynamic_cast<Ogg::XiphComment *>(oggVorbisFile->tag());
  else if (ttaFile)
    id3v2 = ttaFile->ID3v2Tag(false);
  else if (wvFile)
    ape = wvFile->APETag(false);
  else    // This is a catch all to get generic information for other files types (s3m, xm, it, mod, etc)
    generic = file->tag();

  if (file->audioProperties())
    tag.SetDuration(file->audioProperties()->length());

  if (ape && !g_advancedSettings.m_prioritiseAPEv2tags)
    ParseAPETag(ape, art, tag);

  if (asf)
    ParseASF(asf, art, tag);
  else if (id3v2)
    ParseID3v2Tag(id3v2, art, tag);
  else if (generic)
    ParseGenericTag(generic, art, tag);
  else if (mp4)
    ParseMP4Tag(mp4, art, tag);
  else if (xiph)
    ParseXiphComment(xiph, art, tag);

  // art for flac files is outside the tag
  if (flacFile)
    SetFlacArt(flacFile, art, tag);

  // Add APE tags over the top of ID3 tags if we want to prioritize them
  if (ape && g_advancedSettings.m_prioritiseAPEv2tags)
    ParseAPETag(ape, art, tag);

  if (!tag.GetTitle().IsEmpty() || !tag.GetArtist().empty() || !tag.GetAlbum().IsEmpty())
    tag.SetLoaded();
  tag.SetURL(strFileName);

  delete file;
  delete stream;
  
  return true;
}
Exemple #20
0
bool CPlayListM3U::Load(const CStdString& strFileName)
{
  char szLine[4096];
  CStdString strLine;
  CStdString strInfo = "";
  long lDuration = 0;

  Clear();

  m_strPlayListName = URIUtils::GetFileName(strFileName);
  URIUtils::GetParentPath(strFileName, m_strBasePath);

  CFile file;
  if (!file.Open(strFileName) )
  {
    file.Close();
    return false;
  }

  while (file.ReadString(szLine, 1024))
  {
    strLine = szLine;
    strLine.TrimRight(" \t\r\n");
    strLine.TrimLeft(" \t");

    if (strLine.Left( (int)strlen(M3U_INFO_MARKER) ) == M3U_INFO_MARKER)
    {
      // start of info
      int iColon = (int)strLine.find(":");
      int iComma = (int)strLine.find(",");
      if (iColon >= 0 && iComma >= 0 && iComma > iColon)
      {
        // Read the info and duration
        iColon++;
        CStdString strLength = strLine.Mid(iColon, iComma - iColon);
        lDuration = atoi(strLength.c_str());
        iComma++;
        strInfo = strLine.Right((int)strLine.size() - iComma);
        g_charsetConverter.unknownToUTF8(strInfo);
      }
    }
    else if (strLine != M3U_START_MARKER && strLine.Left(strlen(M3U_ARTIST_MARKER)) != M3U_ARTIST_MARKER && strLine.Left(strlen(M3U_ALBUM_MARKER)) != M3U_ALBUM_MARKER )
    {
      CStdString strFileName = strLine;

      if (strFileName.size() > 0 && strFileName[0] == '#')
        continue; // assume a comment or something else we don't support

      // Skip self - do not load playlist recursively
      if (URIUtils::GetFileName(strFileName).Equals(m_strPlayListName))
        continue;

      if (strFileName.length() > 0)
      {
        g_charsetConverter.unknownToUTF8(strFileName);

        // If no info was read from from the extended tag information, use the file name
        if (strInfo.length() == 0)
        {
          strInfo = URIUtils::GetFileName(strFileName);
        }

        // should substitition occur befor or after charset conversion??
        strFileName = URIUtils::SubstitutePath(strFileName);

        // Get the full path file name and add it to the the play list
        CUtil::GetQualifiedFilename(m_strBasePath, strFileName);
        CFileItemPtr newItem(new CFileItem(strInfo));
        newItem->SetPath(strFileName);
        if (lDuration && newItem->IsAudio())
          newItem->GetMusicInfoTag()->SetDuration(lDuration);
        Add(newItem);

        // Reset the values just in case there part of the file have the extended marker
        // and part don't
        strInfo = "";
        lDuration = 0;
      }
    }
  }

  file.Close();
  return true;
}
Exemple #21
0
void CNetworkInterfaceLinux::SetSettings(NetworkAssignment& assignment, CStdString& ipAddress, CStdString& networkMask, CStdString& defaultGateway, CStdString& essId, CStdString& key, EncMode& encryptionMode)
{
#if defined(TARGET_LINUX)
    FILE* fr = fopen("/etc/network/interfaces", "r");
    if (!fr)
    {
        // TODO
        return;
    }

    FILE* fw = fopen("/tmp/interfaces.temp", "w");
    if (!fw)
    {
        // TODO
        fclose(fr);
        return;
    }

    char* line = NULL;
    size_t linel = 0;
    CStdString s;
    bool foundInterface = false;
    bool dataWritten = false;

    while (getdelim(&line, &linel, '\n', fr) > 0)
    {
        vector<CStdString> tokens;

        s = line;
        s.TrimLeft(" \t").TrimRight(" \n");

        // skip comments
        if (!foundInterface && (s.length() == 0 || s.GetAt(0) == '#'))
        {
            fprintf(fw, "%s", line);
            continue;
        }

        // look for "iface <interface name> inet"
        CUtil::Tokenize(s, tokens, " ");
        if (tokens.size() == 2 &&
                tokens[0].Equals("auto") &&
                tokens[1].Equals(GetName()))
        {
            continue;
        }
        else if (!foundInterface &&
                 tokens.size() == 4 &&
                 tokens[0].Equals("iface") &&
                 tokens[1].Equals(GetName()) &&
                 tokens[2].Equals("inet"))
        {
            foundInterface = true;
            WriteSettings(fw, assignment, ipAddress, networkMask, defaultGateway, essId, key, encryptionMode);
            dataWritten = true;
        }
        else if (foundInterface &&
                 tokens.size() == 4 &&
                 tokens[0].Equals("iface"))
        {
            foundInterface = false;
            fprintf(fw, "%s", line);
        }
        else if (!foundInterface)
        {
            fprintf(fw, "%s", line);
        }
    }
    free(line);

    if (!dataWritten && assignment != NETWORK_DISABLED)
    {
        fprintf(fw, "\n");
        WriteSettings(fw, assignment, ipAddress, networkMask, defaultGateway, essId, key, encryptionMode);
    }

    fclose(fr);
    fclose(fw);

    // Rename the file
    if (rename("/tmp/interfaces.temp", "/etc/network/interfaces") < 0)
    {
        // TODO
        return;
    }

    std::string cmd = "/sbin/ifdown " + GetName();
    if (system(cmd.c_str()) != 0)
        CLog::Log(LOGERROR, "Unable to stop interface %s", GetName().c_str());
    else
        CLog::Log(LOGINFO, "Stopped interface %s", GetName().c_str());

    if (assignment != NETWORK_DISABLED)
    {
        cmd = "/sbin/ifup " + GetName();
        if (system(cmd.c_str()) != 0)
            CLog::Log(LOGERROR, "Unable to start interface %s", GetName().c_str());
        else
            CLog::Log(LOGINFO, "Started interface %s", GetName().c_str());
    }
#endif
}
Exemple #22
0
void CScraperParser::RemoveWhiteSpace(CStdString &string)
{
  string.TrimLeft(" \t\r\n");
  string.TrimRight(" \t\r\n");
}
Exemple #23
0
//-------------------------------------------------------------------------------------------------------------------
void Xcddb::parseData(const char *buffer)
{
  //writeLog("parseData Start");

  std::map<CStdString, CStdString> keywords;
  std::list<CStdString> keywordsOrder; // remember order of keywords as it appears in data received from CDDB

  // Collect all the keywords and put them in map. 
  // Multiple occurrences of the same keyword indicate that 
  // the data contained on those lines should be concatenated
  char *line;
  const char trenner[3] = {'\n', '\r', '\0'};
  line = strtok((char*)buffer, trenner); // skip first line
  while ((line = strtok(0, trenner)))
  {
    // Lines that begin with # are comments, should be ignored
    if (line[0] != '#')
    {
      char *s = strstr(line, "=");
      if (s != NULL)
      {
        CStdString strKeyword(line, s - line);
        strKeyword.TrimRight(" ");

        CStdString strValue(s+1);
        strValue.Replace("\\n", "\n"); 
        strValue.Replace("\\t", "\t"); 
        strValue.Replace("\\\\", "\\"); 
        g_charsetConverter.unknownToUTF8(strValue);

        std::map<CStdString, CStdString>::const_iterator it = keywords.find(strKeyword);
        if (it != keywords.end())
          strValue = it->second + strValue; // keyword occured before, concatenate
        else
          keywordsOrder.push_back(strKeyword);

        keywords[strKeyword] = strValue;
      }
    }
  }

  // parse keywords 
  for (std::list<CStdString>::const_iterator it = keywordsOrder.begin(); it != keywordsOrder.end(); ++it)
  {
    CStdString strKeyword = *it;
    CStdString strValue = keywords[strKeyword];

    if (strKeyword == "DTITLE")
    {
      // DTITLE may contain artist and disc title, separated with " / ",
      // for example: DTITLE=Modern Talking / Album: Victory (The 11th Album)
      bool found = false;
      for (int i = 0; i < strValue.GetLength() - 2; i++)
      {
        if (strValue[i] == ' ' && strValue[i + 1] == '/' && strValue[i + 2] == ' ')
        {
          m_strDisk_artist = TrimToUTF8(strValue.Left(i));
          m_strDisk_title = TrimToUTF8(strValue.Mid(i+3));
          found = true;
          break;
        }
      }

      if (!found)
        m_strDisk_title = TrimToUTF8(strValue);
    }
    else if (strKeyword == "DYEAR")
      m_strYear = TrimToUTF8(strValue);
    else if (strKeyword== "DGENRE")
      m_strGenre = TrimToUTF8(strValue);
    else if (strKeyword.Left(6) == "TTITLE")
      addTitle(strKeyword + "=" + strValue);
    else if (strKeyword == "EXTD")
    {
      CStdString strExtd(strValue);

      if (m_strYear.IsEmpty())
      {
        // Extract Year from extended info
        // as a fallback
        int iPos = strExtd.Find("YEAR:");
        if (iPos > -1) // You never know if you really get UTF-8 strings from cddb
          g_charsetConverter.unknownToUTF8(strExtd.Mid(iPos + 6, 4), m_strYear);
      }

      if (m_strGenre.IsEmpty())
      {
        // Extract ID3 Genre
        // as a fallback
        int iPos = strExtd.Find("ID3G:");
        if (iPos > -1)
        {
          CStdString strGenre = strExtd.Mid(iPos + 5, 4);
          strGenre.TrimLeft(' ');
          if (StringUtils::IsNaturalNumber(strGenre))
          {
            CID3Tag tag;
            m_strGenre=tag.ParseMP3Genre(strGenre);
          }
        }
      }
    }
    else if (strKeyword.Left(4) == "EXTT")
      addExtended(strKeyword + "=" + strValue);
  }

  //writeLog("parseData Ende");
}
CStdString DvSaveFormatConverter::NormaliseExtension(CStdString sExtension)
{
	sExtension.TrimLeft(L'.');
	sExtension.Normalize();
	return sExtension;
}