Beispiel #1
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
}
Beispiel #2
0
int CHDFile::Stat(const CURL& url, struct __stat64* buffer)
{
    CStdString strFile = GetLocal(url);

#ifdef _WIN32
    CStdStringW strWFile;
    /* _wstat64 can't handle long paths therefore we remove the \\?\ */
    strFile.Replace("\\\\?\\", "");
    // win32 can only stat root drives with a slash at the end
    if(strFile.length() == 2 && strFile[1] ==':')
        URIUtils::AddSlashAtEnd(strFile);
    /* _wstat64 calls FindFirstFileEx. According to MSDN, the path should not end in a trailing backslash.
      Remove it before calling _wstat64 */
    if (strFile.length() > 3 && URIUtils::HasSlashAtEnd(strFile))
        URIUtils::RemoveSlashAtEnd(strFile);
    g_charsetConverter.utf8ToW(strFile, strWFile, false);
    return _wstat64(strWFile.c_str(), buffer);
#else
    return _stat64(strFile.c_str(), buffer);
#endif
}
Beispiel #3
0
    String getRegion(const char* id)
    {
      TRACE;
      CStdString result;

      if (strcmpi(id, "datelong") == 0)
        {
          result = g_langInfo.GetDateFormat(true);
          result.Replace("DDDD", "%A");
          result.Replace("MMMM", "%B");
          result.Replace("D", "%d");
          result.Replace("YYYY", "%Y");
        }
      else if (strcmpi(id, "dateshort") == 0)
        {
          result = g_langInfo.GetDateFormat(false);
          result.Replace("MM", "%m");
          result.Replace("DD", "%d");
          result.Replace("YYYY", "%Y");
        }
      else if (strcmpi(id, "tempunit") == 0)
        result = g_langInfo.GetTempUnitString();
      else if (strcmpi(id, "speedunit") == 0)
        result = g_langInfo.GetSpeedUnitString();
      else if (strcmpi(id, "time") == 0)
        {
          result = g_langInfo.GetTimeFormat();
          result.Replace("H", "%H");
          result.Replace("h", "%I");
          result.Replace("mm", "%M");
          result.Replace("ss", "%S");
          result.Replace("xx", "%p");
        }
      else if (strcmpi(id, "meridiem") == 0)
        result.Format("%s/%s", g_langInfo.GetMeridiemSymbol(CLangInfo::MERIDIEM_SYMBOL_AM), g_langInfo.GetMeridiemSymbol(CLangInfo::MERIDIEM_SYMBOL_PM));

      return result;
    }
std::string ToThumbFileName(const char* strChannelName)
{
  CStdString strThumbName = strChannelName;

  strThumbName.Replace(":","_");
  strThumbName.Replace("/","_");
  strThumbName.Replace("\\","_");
  strThumbName.Replace(">","_");
  strThumbName.Replace("<","_");
  strThumbName.Replace("*","_");
  strThumbName.Replace("?","_");
  strThumbName.Replace("\"","_");
  strThumbName.Replace("|","_");

  return strThumbName;
}
Beispiel #5
0
CStdString CMediaManager::TranslateDevicePath(const CStdString& devicePath, bool bReturnAsDevice)
{
  CSingleLock waitLock(m_muAutoSource);
  CStdString strDevice = devicePath;
  // fallback for cdda://local/ and empty devicePath
#ifdef HAS_DVD_DRIVE
  if(devicePath.empty() || devicePath.Left(12).Compare("cdda://local")==0)
    strDevice = m_strFirstAvailDrive;
#endif

#ifdef TARGET_WINDOWS
  if(!m_bhasoptical)
    return "";

  if(bReturnAsDevice == false)
    strDevice.Replace("\\\\.\\","");
  else if(!strDevice.empty() && strDevice[1]==':')
    strDevice.Format("\\\\.\\%c:", strDevice[0]);

  URIUtils::RemoveSlashAtEnd(strDevice);
#endif
  return strDevice;
}
Beispiel #6
0
CStdString CMediaManager::TranslateDevicePath(const CStdString& devicePath, bool bReturnAsDevice)
{
  CSingleLock waitLock(m_muAutoSource);
  CStdString strDevice = devicePath;
  // fallback for cdda://local/ and empty devicePath
#ifdef HAS_DVD_DRIVE
  if(devicePath.empty() || devicePath.Left(12).Compare("cdda://local")==0)
    strDevice = MEDIA_DETECT::CLibcdio::GetInstance()->GetDeviceFileName();
#endif

#ifdef _WIN32
  if(!m_bhasoptical)
    return "";

  if(bReturnAsDevice == false)
    strDevice.Replace("\\\\.\\","");
  else if(!strDevice.empty() && strDevice[1]==':')
    strDevice.Format("\\\\.\\%c:", strDevice[0]);

  URIUtils::RemoveSlashAtEnd(strDevice);
#endif
  return strDevice;
}
Beispiel #7
0
void GG::chooseServer() {
	sDIALOG_choose sdc;
	CStdString servers = GETSTR(CFG_GG_SERVER);
	servers.Replace("\r" , "");
	if (servers.empty())
		ICMessage(IMI_ERROR , (int)"Nie masz wybranych ¿adnych serwerów!");
	servers+="\n";
	CStdString items = "";
	sdc.title = "Wybierz serwer GG";
	sdc.info = "Od wybranego serwera rozpocznie siê nastêpna próba ³¹czenia.";
	size_t start = 0;
	size_t end;
//	bool hubUsed = false;
	vector <int> pos;
	while (start < servers.size() && (end = servers.find('\n' , start)) != -1) {
		if (servers[start] != '!') {
			if (!items.empty()) items+="\n";
			if (servers[start]=='\n')
				items+="HUB";
			else items+=servers.substr(start , end - start);
			pos.push_back(start);
		}
		start = end + 1;
	}
	start = ("\n" + servers).find("\n" + lastServer + "\n");
	// Znajdujemy aktualny serwer...
	if (start != -1) {
		for (unsigned int i = 0; i<pos.size(); i++)
			if (pos[i] == start) {sdc.def = i+1;break;}
	}
	sdc.items = (char*)items.c_str();
	int r = ICMessage(IMI_DLGBUTTONS , (int)&sdc);
	if (!r) return;
	lastServer = servers.substr(pos[r-1] , servers.find('\n' , pos[r-1]) - pos[r-1]);

}
Beispiel #8
0
bool CGUIBaseContainer::OnClick(int actionID)
{
  int subItem = 0;
  if (actionID == ACTION_SELECT_ITEM || actionID == ACTION_MOUSE_LEFT_CLICK)
  {
    if (m_staticContent)
    { // "select" action
      int selected = GetSelectedItem();
      if (selected >= 0 && selected < (int)m_items.size())
      {
        CFileItemPtr item = boost::static_pointer_cast<CFileItem>(m_items[selected]);
        // multiple action strings are concat'd together, separated with " , "
        int controlID = GetID(); // save as these could go away as we send messages
        int parentID = GetParentID();
        vector<CStdString> actions;
        StringUtils::SplitString(item->m_strPath, " , ", actions);
        for (unsigned int i = 0; i < actions.size(); i++)
        {
          CStdString action = actions[i];
          action.Replace(",,", ",");
          CGUIMessage message(GUI_MSG_EXECUTE, controlID, parentID);
          message.SetStringParam(action);
          g_windowManager.SendMessage(message);
        }
      }
      return true;
    }
    // grab the currently focused subitem (if applicable)
    CGUIListItemLayout *focusedLayout = GetFocusedLayout();
    if (focusedLayout)
      subItem = focusedLayout->GetFocusedItem();
  }
  // Don't know what to do, so send to our parent window.
  CGUIMessage msg(GUI_MSG_CLICKED, GetID(), GetParentID(), actionID, subItem);
  return SendWindowMessage(msg);
}
PVRIptvEpgChannel * PVRIptvData::FindEpgForChannel(PVRIptvChannel &channel)
{
  vector<PVRIptvEpgChannel>::iterator it;
  for(it = m_epg.begin(); it < m_epg.end(); it++)
  {
    if (it->strId == channel.strTvgId)
    {
      return &*it;
    }
    CStdString strName = it->strName;
    strName.Replace(' ', '_');
    if (strName == channel.strTvgName
      || it->strName == channel.strTvgName)
    {
      return &*it;
    }
    if (it->strName == channel.strChannelName)
    {
      return &*it;
    }
  }

  return NULL;
}
Beispiel #10
0
void CExternalPlayer::Process()
{
  SetName("CExternalPlayer");

  CStdString mainFile = m_launchFilename;
  CStdString archiveContent = "";

  if (m_args.find("{0}") == std::string::npos)
  {
    // Unwind archive names
    CURL url(m_launchFilename);
    CStdString protocol = url.GetProtocol();
    if (protocol == "zip" || protocol == "rar"/* || protocol == "iso9660" ??*/)
    {
      mainFile = url.GetHostName();
      archiveContent = url.GetFileName();
    }
    if (protocol == "musicdb")
      mainFile = CFileMusicDatabase::TranslateUrl(url);
  }

  if (m_filenameReplacers.size() > 0) 
  {
    for (unsigned int i = 0; i < m_filenameReplacers.size(); i++)
    {
      std::vector<CStdString> vecSplit;
      StringUtils::SplitString(m_filenameReplacers[i], " , ", vecSplit);

      // something is wrong, go to next substitution
      if (vecSplit.size() != 4)
        continue;

      CStdString strMatch = vecSplit[0];
      strMatch.Replace(",,",",");
      bool bCaseless = vecSplit[3].Find('i') > -1;
      CRegExp regExp(bCaseless);

      if (!regExp.RegComp(strMatch.c_str()))
      { // invalid regexp - complain in logs
        CLog::Log(LOGERROR, "%s: Invalid RegExp:'%s'", __FUNCTION__, strMatch.c_str());
        continue;
      }

      if (regExp.RegFind(mainFile) > -1) 
      {
        CStdString strPat = vecSplit[1];
        strPat.Replace(",,",",");

        if (!regExp.RegComp(strPat.c_str()))
        { // invalid regexp - complain in logs
          CLog::Log(LOGERROR, "%s: Invalid RegExp:'%s'", __FUNCTION__, strPat.c_str());
          continue;
        }

        CStdString strRep = vecSplit[2];
        strRep.Replace(",,",",");
        bool bGlobal = vecSplit[3].Find('g') > -1;
        bool bStop = vecSplit[3].Find('s') > -1;
        int iStart = 0;
        while ((iStart = regExp.RegFind(mainFile, iStart)) > -1)
        {
          int iLength = regExp.GetFindLen();
          mainFile = mainFile.Left(iStart) + regExp.GetReplaceString(strRep.c_str()) + mainFile.Mid(iStart+iLength);
          if (!bGlobal)
            break;
        }
        CLog::Log(LOGINFO, "%s: File matched:'%s' (RE='%s',Rep='%s') new filename:'%s'.", __FUNCTION__, strMatch.c_str(), strPat.c_str(), strRep.c_str(), mainFile.c_str());
        if (bStop) break;
      }
    }
  }

  CLog::Log(LOGNOTICE, "%s: Player : %s", __FUNCTION__, m_filename.c_str());
  CLog::Log(LOGNOTICE, "%s: File   : %s", __FUNCTION__, mainFile.c_str());
  CLog::Log(LOGNOTICE, "%s: Content: %s", __FUNCTION__, archiveContent.c_str());
  CLog::Log(LOGNOTICE, "%s: Args   : %s", __FUNCTION__, m_args.c_str());
  CLog::Log(LOGNOTICE, "%s: Start", __FUNCTION__);

  // make sure we surround the arguments with quotes where necessary
  CStdString strFName;
  CStdString strFArgs;
#if defined(_WIN32)
  // W32 batch-file handline
  if (m_filename.Right(4) == ".bat" || m_filename.Right(4) == ".cmd")
  {
    // MSDN says you just need to do this, but cmd's handing of spaces and
    // quotes is soo broken it seems to work much better if you just omit
    // lpApplicationName and enclose the module in lpCommandLine in quotes
    //strFName = "cmd.exe";
    //strFArgs = "/c ";
  }
  else
#endif
    strFName = m_filename;

  strFArgs.append("\"");
  strFArgs.append(m_filename);
  strFArgs.append("\" ");
  strFArgs.append(m_args);

  int nReplaced = strFArgs.Replace("{0}", mainFile);

  if (!nReplaced)
    nReplaced = strFArgs.Replace("{1}", mainFile) + strFArgs.Replace("{2}", archiveContent);

  if (!nReplaced)
  {
    strFArgs.append(" \"");
    strFArgs.append(mainFile);
    strFArgs.append("\"");
  }

  int iActiveDevice = g_audioContext.GetActiveDevice();
  if (iActiveDevice != CAudioContext::NONE)
  {
    CLog::Log(LOGNOTICE, "%s: Releasing audio device %d", __FUNCTION__, iActiveDevice);
    g_audioContext.SetActiveDevice(CAudioContext::NONE);
  }

#if defined(_WIN32)
  if (m_warpcursor)
  {
    GetCursorPos(&m_ptCursorpos);
    int x = 0;
    int y = 0;
    switch (m_warpcursor)
    {
      case WARP_BOTTOM_RIGHT:
        x = GetSystemMetrics(SM_CXSCREEN);
      case WARP_BOTTOM_LEFT:
        y = GetSystemMetrics(SM_CYSCREEN);
        break;
      case WARP_TOP_RIGHT:
        x = GetSystemMetrics(SM_CXSCREEN);
        break;
      case WARP_CENTER:
        x = GetSystemMetrics(SM_CXSCREEN) / 2;
        y = GetSystemMetrics(SM_CYSCREEN) / 2;
        break;
    }
    CLog::Log(LOGNOTICE, "%s: Warping cursor to (%d,%d)", __FUNCTION__, x, y);
    SetCursorPos(x,y);
  }

  LONG currentStyle = GetWindowLong(g_hWnd, GWL_EXSTYLE);
#endif

  if (m_hidexbmc && !m_islauncher)
  {
    CLog::Log(LOGNOTICE, "%s: Hiding XBMC window", __FUNCTION__);
    g_Windowing.Hide();
  }
#if defined(_WIN32)
  else if (currentStyle & WS_EX_TOPMOST)
  {
    CLog::Log(LOGNOTICE, "%s: Lowering XBMC window", __FUNCTION__);
    SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOREDRAW);
  }

  CLog::Log(LOGDEBUG, "%s: Unlocking foreground window", __FUNCTION__);
  LockSetForegroundWindow(LSFW_UNLOCK);
#endif

  m_playbackStartTime = XbmcThreads::SystemClockMillis();
  BOOL ret = TRUE;
#if defined(_WIN32)
  ret = ExecuteAppW32(strFName.c_str(),strFArgs.c_str());
#elif defined(_LINUX)
  ret = ExecuteAppLinux(strFArgs.c_str());
#endif
  int64_t elapsedMillis = XbmcThreads::SystemClockMillis() - m_playbackStartTime;

  if (ret && (m_islauncher || elapsedMillis < LAUNCHER_PROCESS_TIME))
  {
    if (m_hidexbmc)
    {
      CLog::Log(LOGNOTICE, "%s: XBMC cannot stay hidden for a launcher process", __FUNCTION__);
      g_Windowing.Show(false);
    }

    {
      CSingleLock lock(g_graphicsContext);
      m_dialog = (CGUIDialogOK *)g_windowManager.GetWindow(WINDOW_DIALOG_OK);
      m_dialog->SetHeading(23100);
      m_dialog->SetLine(1, 23104);
      m_dialog->SetLine(2, 23105);
      m_dialog->SetLine(3, 23106);
    }

    if (!m_bAbortRequest) m_dialog->DoModal();
  }

  m_bIsPlaying = false;
  CLog::Log(LOGNOTICE, "%s: Stop", __FUNCTION__);

#if defined(_WIN32)
  g_Windowing.Restore();

  if (currentStyle & WS_EX_TOPMOST)
  {
    CLog::Log(LOGNOTICE, "%s: Showing XBMC window TOPMOST", __FUNCTION__);
    SetWindowPos(g_hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
    SetForegroundWindow(g_hWnd);
  }
  else
#endif
  {
    CLog::Log(LOGNOTICE, "%s: Showing XBMC window", __FUNCTION__);
    g_Windowing.Show();
  }

#if defined(_WIN32)
  if (m_warpcursor)
  {
    m_xPos = 0;
    m_yPos = 0;
    if (&m_ptCursorpos != 0)
    {
      m_xPos = (m_ptCursorpos.x);
      m_yPos = (m_ptCursorpos.y);
    }
    CLog::Log(LOGNOTICE, "%s: Restoring cursor to (%d,%d)", __FUNCTION__, m_xPos, m_yPos);
    SetCursorPos(m_xPos,m_yPos);
  }
#endif

  // We don't want to come back to an active screensaver
  g_application.ResetScreenSaver();
  g_application.WakeUpScreenSaverAndDPMS();

  if (iActiveDevice != CAudioContext::NONE)
  {
    CLog::Log(LOGNOTICE, "%s: Reclaiming audio device %d", __FUNCTION__, iActiveDevice);
    g_audioContext.SetActiveDevice(iActiveDevice);
  }

  if (!ret || (m_playOneStackItem && g_application.CurrentFileItem().IsStack()))
    m_callback.OnPlayBackStopped();
  else
    m_callback.OnPlayBackEnded();
}
Beispiel #11
0
bool CWIN32Util::XBMCShellExecute(const CStdString &strPath, bool bWaitForScriptExit)
{
  CStdString strCommand = strPath;
  CStdString strExe = strPath;
  CStdString strParams;
  CStdString strWorkingDir;

  strCommand.Trim();
  if (strCommand.IsEmpty())
  {
    return false;
  }
  int iIndex = -1;
  char split = ' ';
  if (strCommand[0] == '\"')
  {
    split = '\"';
  }
  iIndex = strCommand.Find(split, 1);
  if (iIndex != -1)
  {
    strExe = strCommand.substr(0, iIndex + 1);
    strParams = strCommand.substr(iIndex + 1);
  }

  strExe.Replace("\"","");

  strWorkingDir = strExe; 
  iIndex = strWorkingDir.ReverseFind('\\'); 
  if(iIndex != -1) 
  { 
    strWorkingDir[iIndex+1] = '\0'; 
  } 

  CStdStringW WstrExe, WstrParams, WstrWorkingDir;
  g_charsetConverter.utf8ToW(strExe, WstrExe);
  g_charsetConverter.utf8ToW(strParams, WstrParams);
  g_charsetConverter.utf8ToW(strWorkingDir, WstrWorkingDir);

  bool ret;
  SHELLEXECUTEINFOW ShExecInfo = {0};
  ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFOW);
  ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  ShExecInfo.hwnd = NULL;
  ShExecInfo.lpVerb = NULL;
  ShExecInfo.lpFile = WstrExe.c_str();
  ShExecInfo.lpParameters = WstrParams.c_str();
  ShExecInfo.lpDirectory = WstrWorkingDir.c_str();
  ShExecInfo.nShow = SW_SHOW;
  ShExecInfo.hInstApp = NULL;

  g_windowHelper.StopThread();

  LockSetForegroundWindow(LSFW_UNLOCK);
  ShowWindow(g_hWnd,SW_MINIMIZE);
  ret = ShellExecuteExW(&ShExecInfo) == TRUE;
  g_windowHelper.SetHANDLE(ShExecInfo.hProcess);

  // ShellExecute doesn't return the window of the started process
  // we need to gather it from somewhere to allow switch back to XBMC
  // when a program is minimized instead of stopped.
  //g_windowHelper.SetHWND(ShExecInfo.hwnd);
  g_windowHelper.Create();

  if(bWaitForScriptExit)
  {
    // Todo: Pause music and video playback
    WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
  }

  return ret;
}
Beispiel #12
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;
}
Beispiel #13
0
HANDLE FindFirstFile(LPCSTR szPath,LPWIN32_FIND_DATA lpFindData)
{
  if (lpFindData == NULL || szPath == NULL)
    return NULL;

  CStdString strPath(szPath);

  if (IsAliasShortcut(strPath))
    TranslateAliasShortcut(strPath);

  if (strPath.empty())
    return INVALID_HANDLE_VALUE;

  strPath.Replace("\\","/");

  // if the file name is a directory then we add a * to look for all files in this directory
#if defined(__APPLE__) || defined(__FreeBSD__)
  DIR *testDir = opendir(strPath.c_str());
#else
  DIR *testDir = opendir(szPath);
#endif
  if (testDir)
  {
    strPath += "/*";
    closedir(testDir);
  }

  int nFilePos = strPath.ReverseFind(XBMC_FILE_SEP);

  CStdString strDir = ".";
  CStdString strFiles = strPath;

  if (nFilePos > 0)
  {
    strDir = strPath.substr(0,nFilePos);
    strFiles = strPath.substr(nFilePos + 1);
  }

  if (strFiles == "*.*")
     strFiles = "*";

  strFiles = CStdString("^") + strFiles + "$";
  strFiles.Replace(".","\\.");
  strFiles.Replace("*",".*");
  strFiles.Replace("?",".");

  strFiles.MakeLower();  // Do we really want this case insensitive?
  CRegExp re(true);

  if (re.RegComp(strFiles.c_str()) == NULL)
    return(INVALID_HANDLE_VALUE);

  struct dirent **namelist = NULL;
  int n = scandir(strDir, &namelist, 0, alphasort);

  CXHandle *pHandle = new CXHandle(CXHandle::HND_FIND_FILE);
    pHandle->m_FindFileDir = strDir;

  while (n-- > 0)
  {
    CStdString strComp(namelist[n]->d_name);
    strComp.MakeLower();

    if (re.RegFind(strComp.c_str()) >= 0)
      pHandle->m_FindFileResults.push_back(namelist[n]->d_name);
    free(namelist[n]);
  }
  free(namelist);

  if (pHandle->m_FindFileResults.size() == 0)
  {
    delete pHandle;
    return INVALID_HANDLE_VALUE;
  }

  FindNextFile(pHandle, lpFindData);

  return pHandle;
}
void ADDON_ReadSettings(void)
{
  /* Read setting "host" from settings.xml */
  char buffer[1024];

  if (!XBMC)
    return;

  /* Connection settings */
  /***********************/
  if (XBMC->GetSetting("host", &buffer))
  {
    g_szHostname = buffer;
    uri::decode(g_szHostname);
  }
  else
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'host' setting, falling back to '127.0.0.1' as default");
    g_szHostname = DEFAULT_HOST;
  }

  /* Read setting "port" from settings.xml */
  if (!XBMC->GetSetting("port", &g_iPort))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'port' setting, falling back to '9596' as default");
    g_iPort = DEFAULT_PORT;
  }

  /* Read setting "timeout" from settings.xml */
  if (!XBMC->GetSetting("timeout", &g_iConnectTimeout))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'timeout' setting, falling back to %i seconds as default", DEFAULT_TIMEOUT);
    g_iConnectTimeout = DEFAULT_TIMEOUT;
  }

  /* MediaPortal settings */
  /***********************/

  /* Read setting "ftaonly" from settings.xml */
  if (!XBMC->GetSetting("ftaonly", &g_bOnlyFTA))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'ftaonly' setting, falling back to 'false' as default");
    g_bOnlyFTA = DEFAULT_FTA_ONLY;
  }

  /* Read setting "useradio" from settings.xml */
  if (!XBMC->GetSetting("useradio", &g_bRadioEnabled))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'useradio' setting, falling back to 'true' as default");
    g_bRadioEnabled = DEFAULT_RADIO;
  }

  if (!XBMC->GetSetting("tvgroup", &buffer))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'tvgroup' setting, falling back to '' as default");
  } else {
    g_szTVGroup = buffer;
    g_szTVGroup.Replace(";","|");
  }

  if (!XBMC->GetSetting("radiogroup", &buffer))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'radiogroup' setting, falling back to '' as default");
  } else {
    g_szRadioGroup = buffer;
    g_szRadioGroup.Replace(";","|");
  }

  if (!XBMC->GetSetting("streamingmethod", &g_eStreamingMethod))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'streamingmethod' setting, falling back to 'tsreader' as default");
    g_eStreamingMethod = TSReader;
  }

  /* Read setting "resolvertsphostname" from settings.xml */
  if (!XBMC->GetSetting("resolvertsphostname", &g_bResolveRTSPHostname))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'resolvertsphostname' setting, falling back to 'true' as default");
    g_bResolveRTSPHostname = DEFAULT_RESOLVE_RTSP_HOSTNAME;
  }

  /* Read setting "readgenre" from settings.xml */
  if (!XBMC->GetSetting("readgenre", &g_bReadGenre))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'readgenre' setting, falling back to 'true' as default");
    g_bReadGenre = DEFAULT_READ_GENRE;
  }

  /* Read setting "readgenre" from settings.xml */
  if (!XBMC->GetSetting("enableoldseriesdlg", &g_bEnableOldSeriesDlg))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'enableoldseriesdlg' setting, falling back to 'false' as default");
    g_bEnableOldSeriesDlg = false;
  }

  /* Read setting "sleeponrtspurl" from settings.xml */
  if (!XBMC->GetSetting("sleeponrtspurl", &g_iSleepOnRTSPurl))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'sleeponrtspurl' setting, falling back to %i seconds as default", DEFAULT_SLEEP_RTSP_URL);
    g_iSleepOnRTSPurl = DEFAULT_SLEEP_RTSP_URL;
  }


  /* TSReader settings */
  /*********************/
  /* Read setting "fastchannelswitch" from settings.xml */
  if (!XBMC->GetSetting("fastchannelswitch", &g_bFastChannelSwitch))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'fastchannelswitch' setting, falling back to 'false' as default");
    g_bFastChannelSwitch = false;
  }

  /* read setting "user" from settings.xml */
  if (!XBMC->GetSetting("smbusername", &buffer))
  {
    XBMC->Log(LOG_ERROR, "Couldn't get 'smbusername' setting, falling back to '%s' as default", DEFAULT_SMBUSERNAME);
    g_szSMBusername = DEFAULT_SMBUSERNAME;
  }
  else
    g_szSMBusername = buffer;

  /* read setting "pass" from settings.xml */
  if (!XBMC->GetSetting("smbpassword", &buffer))
  {
    XBMC->Log(LOG_ERROR, "Couldn't get 'smbpassword' setting, falling back to '%s' as default", DEFAULT_SMBPASSWORD);
    g_szSMBpassword = DEFAULT_SMBPASSWORD;
  }
  else
    g_szSMBpassword = buffer;

  /* Read setting "usertsp" from settings.xml */
  if (!XBMC->GetSetting("usertsp", &g_bUseRTSP))
  {
    /* If setting is unknown fallback to defaults */
    XBMC->Log(LOG_ERROR, "Couldn't get 'usertsp' setting, falling back to 'false' as default");
    g_bUseRTSP = false;
  }

  /* Log the current settings for debugging purposes */
  XBMC->Log(LOG_DEBUG, "settings: streamingmethod: %s, usertsp=%i", (( g_eStreamingMethod == TSReader) ? "TSReader" : "ffmpeg"), (int) g_bUseRTSP);
  XBMC->Log(LOG_DEBUG, "settings: host='%s', port=%i, timeout=%i", g_szHostname.c_str(), g_iPort, g_iConnectTimeout);
  XBMC->Log(LOG_DEBUG, "settings: ftaonly=%i, useradio=%i, tvgroup='%s', radiogroup='%s'", (int) g_bOnlyFTA, (int) g_bRadioEnabled, g_szTVGroup.c_str(), g_szRadioGroup.c_str());
  XBMC->Log(LOG_DEBUG, "settings: readgenre=%i, enableoldseriesdlg=%i, sleeponrtspurl=%i", (int)g_bReadGenre, (int)g_bEnableOldSeriesDlg, g_iSleepOnRTSPurl);
  XBMC->Log(LOG_DEBUG, "settings: resolvertsphostname=%i", (int) g_bResolveRTSPHostname);
  XBMC->Log(LOG_DEBUG, "settings: fastchannelswitch=%i", (int) g_bFastChannelSwitch);
  XBMC->Log(LOG_DEBUG, "settings: smb user='******', pass=%s", g_szSMBusername.c_str(), (g_szSMBpassword.length() > 0 ? "<set>" : "<empty>"));
}
Beispiel #15
0
CStdString CCDDARipper::GetAlbumDirName(const MUSIC_INFO::CMusicInfoTag& infoTag)
{
  CStdString strAlbumDir;

  // use audiocds.trackpathformat setting to format
  // directory name where CD tracks will be stored,
  // use only format part ending at the last '/'
  strAlbumDir = CSettings::Get().GetString("audiocds.trackpathformat");
  int pos = max(strAlbumDir.ReverseFind('/'), strAlbumDir.ReverseFind('\\'));
  if (pos < 0)
    return ""; // no directory
  
  strAlbumDir = strAlbumDir.Left(pos);

  // replace %A with album artist name
  if (strAlbumDir.Find("%A") != -1)
  {
    CStdString strAlbumArtist = StringUtils::Join(infoTag.GetAlbumArtist(), g_advancedSettings.m_musicItemSeparator);
    if (strAlbumArtist.IsEmpty())
      strAlbumArtist = StringUtils::Join(infoTag.GetArtist(), g_advancedSettings.m_musicItemSeparator);
    if (strAlbumArtist.IsEmpty())
      strAlbumArtist = "Unknown Artist";
    else
      strAlbumArtist.Replace('/', '_');
    strAlbumDir.Replace("%A", strAlbumArtist);
  }

  // replace %B with album title
  if (strAlbumDir.Find("%B") != -1)
  {
    CStdString strAlbum = infoTag.GetAlbum();
    if (strAlbum.IsEmpty()) 
      strAlbum.Format("Unknown Album %s", CDateTime::GetCurrentDateTime().GetAsLocalizedDateTime().c_str());
    else
      strAlbum.Replace('/', '_');
    strAlbumDir.Replace("%B", strAlbum);
  }

  // replace %G with genre
  if (strAlbumDir.Find("%G") != -1)
  {
    CStdString strGenre = StringUtils::Join(infoTag.GetGenre(), g_advancedSettings.m_musicItemSeparator);
    if (strGenre.IsEmpty())
      strGenre = "Unknown Genre";
    else
      strGenre.Replace('/', '_');
    strAlbumDir.Replace("%G", strGenre);
  }

  // replace %Y with year
  if (strAlbumDir.Find("%Y") != -1)
  {
    CStdString strYear = infoTag.GetYearString();
    if (strYear.IsEmpty())
      strYear = "Unknown Year";
    else
      strYear.Replace('/', '_');
    strAlbumDir.Replace("%Y", strYear);
  }

  return strAlbumDir;
}
void CGUIWindowFullScreen::RenderTTFSubtitles()
{
  if ((g_application.GetCurrentPlayer() == EPC_MPLAYER ||
#if defined(HAS_AMLPLAYER)
       g_application.GetCurrentPlayer() == EPC_AMLPLAYER ||
#endif
       g_application.GetCurrentPlayer() == EPC_DVDPLAYER) &&
      CUtil::IsUsingTTFSubtitles() && (g_application.m_pPlayer->GetSubtitleVisible()))
  {
    CSingleLock lock (m_fontLock);

    if(!m_subsLayout)
      return;

    CStdString subtitleText = "How now brown cow";
    if (g_application.m_pPlayer->GetCurrentSubtitle(subtitleText))
    {
      // Remove HTML-like tags from the subtitles until
      subtitleText.Replace("\\r", "");
      subtitleText.Replace("\r", "");
      subtitleText.Replace("\\n", "[CR]");
      subtitleText.Replace("\n", "[CR]");
      subtitleText.Replace("<br>", "[CR]");
      subtitleText.Replace("\\N", "[CR]");
      subtitleText.Replace("<i>", "[I]");
      subtitleText.Replace("</i>", "[/I]");
      subtitleText.Replace("<b>", "[B]");
      subtitleText.Replace("</b>", "[/B]");
      subtitleText.Replace("<u>", "");
      subtitleText.Replace("<p>", "");
      subtitleText.Replace("<P>", "");
      subtitleText.Replace("&nbsp;", "");
      subtitleText.Replace("</u>", "");
      subtitleText.Replace("</i", "[/I]"); // handle tags which aren't closed properly (happens).
      subtitleText.Replace("</b", "[/B]");
      subtitleText.Replace("</u", "");

      RESOLUTION res = g_graphicsContext.GetVideoResolution();
      g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetResInfo(), false);

      float maxWidth = (float) g_settings.m_ResInfo[res].Overscan.right - g_settings.m_ResInfo[res].Overscan.left;
      m_subsLayout->Update(subtitleText, maxWidth * 0.9f, false, true); // true to force LTR reading order (most Hebrew subs are this format)

      int subalign = g_guiSettings.GetInt("subtitles.align");
      float textWidth, textHeight;
      m_subsLayout->GetTextExtent(textWidth, textHeight);
      float x = maxWidth * 0.5f + g_settings.m_ResInfo[res].Overscan.left;
      float y = (float) g_settings.m_ResInfo[res].iSubtitles;

      if (subalign == SUBTITLE_ALIGN_MANUAL)
        y = (float) g_settings.m_ResInfo[res].iSubtitles - textHeight;
      else
      {
        CRect SrcRect, DestRect;
        g_application.m_pPlayer->GetVideoRect(SrcRect, DestRect);

        if ((subalign == SUBTITLE_ALIGN_TOP_INSIDE) || (subalign == SUBTITLE_ALIGN_TOP_OUTSIDE))
          y = DestRect.y1;
        else
          y = DestRect.y2;

        // use the manual distance to the screenbottom as an offset to the automatic location
        if ((subalign == SUBTITLE_ALIGN_BOTTOM_INSIDE) || (subalign == SUBTITLE_ALIGN_TOP_OUTSIDE))
          y -= textHeight + g_graphicsContext.GetHeight() - g_settings.m_ResInfo[res].iSubtitles;
        else
          y += g_graphicsContext.GetHeight() - g_settings.m_ResInfo[res].iSubtitles;

        y = std::max(y, (float) g_settings.m_ResInfo[res].Overscan.top);
        y = std::min(y, g_settings.m_ResInfo[res].Overscan.bottom - textHeight);
      }

      m_subsLayout->RenderOutline(x, y, 0, 0xFF000000, XBFONT_CENTER_X, maxWidth);

      // reset rendering resolution
      g_graphicsContext.SetRenderingResolution(m_coordsRes, m_needsScaling);
    }
  }
}
Beispiel #17
0
bool CPlexDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  CStdString strRoot = strPath;
  if (CUtil::HasSlashAtEnd(strRoot) && strRoot != "plex://")
    strRoot.Delete(strRoot.size() - 1);
  
  strRoot.Replace(" ", "%20");

  // Start the download thread running.
  printf("PlexDirectory::GetDirectory(%s)\n", strRoot.c_str());
  m_url = strRoot;
  CThread::Create(false, 0);

  // Now display progress, look for cancel.
  CGUIDialogProgress* dlgProgress = 0;
  
  int time = GetTickCount();
  
  while (m_downloadEvent.WaitMSec(100) == false)
  {
    // If enough time has passed, display the dialog.
    if (GetTickCount() - time > 1000 && m_allowPrompting == true)
    {
      dlgProgress = (CGUIDialogProgress*)m_gWindowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
      if (dlgProgress)
      {
        dlgProgress->ShowProgressBar(false);
        dlgProgress->SetHeading(40203);
        dlgProgress->SetLine(0, 40204);
        dlgProgress->SetLine(1, "");
        dlgProgress->SetLine(2, "");
        dlgProgress->StartModal();
      }
    }

    if (dlgProgress)
    {
      dlgProgress->Progress();
      if (dlgProgress->IsCanceled())
      {
        items.m_wasListingCancelled = true;
        m_http.Cancel();
        StopThread();
      }
    }
  }
  
  if (dlgProgress) 
    dlgProgress->Close();
  
  // Wait for the thread to exit.
  WaitForThreadExit(INFINITE);
  
  // See if we suceeded.
  if (m_bSuccess == false)
    return false;
  
  // See if we're supposed to parse the results or not.
  if (m_bParseResults == false)
    return true;
  
  // Parse returned xml.
  TiXmlDocument doc;
  doc.Parse(m_data.c_str());

  TiXmlElement* root = doc.RootElement();
  if (root == 0)
  {
    CLog::Log(LOGERROR, "%s - Unable to parse XML\n%s", __FUNCTION__, m_data.c_str());
    return false;
  }
  
  // Get the fanart.
  const char* fanart = root->Attribute("art");
  string strFanart;
  if (fanart && strlen(fanart) > 0)
    strFanart = ProcessUrl(strPath, fanart, false);

  // Walk the parsed tree.
  string strFileLabel = "%N - %T"; 
  string strDirLabel = "%B";
  string strSecondDirLabel = "%Y";
  
  Parse(m_url, root, items, strFileLabel, strDirLabel, strSecondDirLabel);
  
  // Set the window titles
  const char* title1 = root->Attribute("title1");
  const char* title2 = root->Attribute("title2");

  if (title1 && strlen(title1) > 0)
    items.SetFirstTitle(title1);
  if (title2 && strlen(title2) > 0)
    items.SetSecondTitle(title2);

  // Set fanart on items if they don't have their own.
  for (int i=0; i<items.Size(); i++)
  {
    CFileItemPtr pItem = items[i];
    
    if (strFanart.size() > 0 && pItem->GetQuickFanart().size() == 0)
      pItem->SetQuickFanart(strFanart);
      
    // Make sure sort label is lower case.
    string sortLabel = pItem->GetLabel();
    boost::to_lower(sortLabel);
    pItem->SetSortLabel(sortLabel);
  }
  
  // Set fanart on directory.
  if (strFanart.size() > 0)
    items.SetQuickFanart(strFanart);
    
  // Set the view mode.
  const char* viewmode = root->Attribute("viewmode");
  if (viewmode && strlen(viewmode) > 0)
  {
    CGUIViewState* viewState = CGUIViewState::GetViewState(0, items);
    viewState->SaveViewAsControl(atoi(viewmode));
  }
  
  // Override labels.
  const char* fileLabel = root->Attribute("filelabel");
  if (fileLabel && strlen(fileLabel) > 0)
    strFileLabel = fileLabel;

  const char* dirLabel = root->Attribute("dirlabel");
  if (dirLabel && strlen(dirLabel) > 0)
    strDirLabel = dirLabel;

  // Add the sort method.
  items.AddSortMethod(SORT_METHOD_NONE, 552, LABEL_MASKS(strFileLabel, "%D", strDirLabel, strSecondDirLabel));
  
  // Set the content label.
  const char* content = root->Attribute("content");
  if (content && strlen(content) > 0)
  {
    items.SetContent(content);
  }
  
  // Check for dialog message attributes
  CStdString strMessage = "";
  const char* header = root->Attribute("header");
  if (header && strlen(header) > 0)
  {
    const char* message = root->Attribute("message");
    if (message && strlen(message) > 0) 
      strMessage = message;
    
    items.m_displayMessage = true; 
    items.m_displayMessageTitle = header; 
    items.m_displayMessageContents = root->Attribute("message");
    
    // Don't cache these.
    m_dirCacheType = DIR_CACHE_NEVER;
  }
  
  // See if this directory replaces the parent.
  const char* replace = root->Attribute("replaceParent");
  if (replace && strcmp(replace, "1") == 0)
    items.SetReplaceListing(true);
  
  // See if we're saving this into the history or not.
  const char* noHistory = root->Attribute("noHistory");
    if (noHistory && strcmp(noHistory, "1") == 0)
      items.SetSaveInHistory(false);
  
  // See if we're not supposed to cache this directory.
  const char* noCache = root->Attribute("nocache");
  if (noCache && strcmp(noCache, "1") == 0)
    m_dirCacheType = DIR_CACHE_NEVER;
    
  return true;
}
Beispiel #18
0
bool CHDDirectory::GetNormalFolder(const CStdString& strPath1, CFileItemList &items)
{
  WIN32_FIND_DATA wfd;

  CStdString strPath=strPath1;
#ifndef _LINUX
  g_charsetConverter.utf8ToStringCharset(strPath);
#endif

  CFileItemList vecCacheItems;
  g_directoryCache.ClearDirectory(strPath1);

  CStdString strRoot = strPath;
  CURL url(strPath);

  memset(&wfd, 0, sizeof(wfd));
  if (!CUtil::HasSlashAtEnd(strPath) )
#ifndef _LINUX
    strRoot += "\\";
  strRoot.Replace("/", "\\");
#else
    strRoot += "/";
#endif
  if (CUtil::IsDVD(strRoot) && m_isoReader.IsScanned())
  {
    // Reset iso reader and remount or
    // we can't access the dvd-rom
    m_isoReader.Reset();

    CIoSupport::Dismount("Cdrom0");
    CIoSupport::RemapDriveLetter('D', "Cdrom0");
  }

  CStdString strSearchMask = strRoot;
#ifndef _LINUX
  strSearchMask += "*.*";
#else
  strSearchMask += "*";
#endif

  CAutoPtrFind hFind(FindFirstFile(strSearchMask.c_str(), &wfd));

  // On error, check if path exists at all, this will return true if empty folder.
  if (hFind.isValid() == false)
      return Exists(strPath1);

  do
  {
    if (wfd.cFileName[0] != 0)
    {
      CFileItemPtr pItem(BuildResolvedFileItem(strRoot, wfd));
      if (pItem)
      {
        // Always add to the cache.
        vecCacheItems.Add(pItem);

        // If it's allowed, add it to the list.
        if (IsAllowed(pItem.get(), wfd))
          items.Add(pItem);
      }
    }
  }
  while (FindNextFile((HANDLE)hFind, &wfd));

#ifdef _XBOX
  // if we use AutoPtrHandle, this auto-closes
  FindClose((HANDLE)hFind); //should be closed
#endif

  if (m_cacheDirectory)
    g_directoryCache.SetDirectory(strPath1, vecCacheItems);
  return true;
}
Beispiel #19
0
bool CHDDirectory::GetDirectory(const CStdString& strPath1, CFileItemList &items)
{
    WIN32_FIND_DATA wfd;

    CStdString strPath=strPath1;
#ifndef _LINUX
    g_charsetConverter.utf8ToStringCharset(strPath);
#endif

    CFileItemList vecCacheItems;
    g_directoryCache.ClearDirectory(strPath1);


    CStdString strRoot = strPath;
    CURL url(strPath);

    memset(&wfd, 0, sizeof(wfd));
    if (!CUtil::HasSlashAtEnd(strPath) )
#ifndef _LINUX
        strRoot += "\\";
    strRoot.Replace("/", "\\");
#else
        strRoot += "/";
#endif
    if (CUtil::IsDVD(strRoot) && m_isoReader.IsScanned())
    {
        // Reset iso reader and remount or
        // we can't access the dvd-rom
        m_isoReader.Reset();

        CIoSupport::Dismount("Cdrom0");
        CIoSupport::RemapDriveLetter('D', "Cdrom0");
    }

    CStdString strSearchMask = strRoot;
#ifndef _LINUX
    strSearchMask += "*.*";
#else
    strSearchMask += "*";
#endif

    FILETIME localTime;
    CAutoPtrFind hFind ( FindFirstFile(strSearchMask.c_str(), &wfd));

    // on error, check if path exists at all, this will return true if empty folder
    if (!hFind.isValid())
        return Exists(strPath1);

    if (hFind.isValid())
    {
        do
        {
            if (wfd.cFileName[0] != 0)
            {
#ifdef __APPLE__
                // Attempt to resolve aliases.
                FSRef   fsRef;
                Boolean isDir;
                Boolean isAlias;
                char    resolvedAliasPath[MAX_PATH];
                bool    useAlias = false;

                // Convert to FSRef.
                CStdString strFile = strRoot + wfd.cFileName;
                if (FSPathMakeRef((const UInt8* )strFile.c_str(), &fsRef, &isDir) == noErr)
                {
                    if (FSResolveAliasFileWithMountFlags(&fsRef, TRUE, &isDir, &isAlias, kResolveAliasFileNoUI) == noErr)
                    {
                        // If it was an alias, use the reference instead.
                        if (isAlias)
                        {
                            if (FSRefMakePath(&fsRef, (UInt8* )resolvedAliasPath, MAX_PATH) == noErr)
                                useAlias = true;
                        }
                    }
                }

                if (useAlias)
                {
                    // Add the alias.
                    CFileItem *pItem = new CFileItem(wfd.cFileName);
                    pItem->m_strPath = resolvedAliasPath;
                    pItem->m_bIsFolder = isDir ? true : false;

                    if (isDir == false)
                    {
                        // Get the size of the file.
                        struct stat64 statInfo;
                        stat64(resolvedAliasPath, &statInfo);
                        pItem->m_dwSize = statInfo.st_size;
                    }

                    FileTimeToLocalFileTime(&wfd.ftLastWriteTime, &localTime);
                    pItem->m_dateTime=localTime;

                    vecCacheItems.Add(pItem);
                    items.Add(new CFileItem(*pItem));
                }
                else
#endif
                    if ( (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
                    {
                        CStdString strDir = wfd.cFileName;
                        if (strDir != "." && strDir != "..")
                        {
                            CStdString strLabel=wfd.cFileName;
#ifndef _LINUX
                            g_charsetConverter.stringCharsetToUtf8(strLabel);
#endif

                            CFileItem *pItem = new CFileItem(strLabel);
                            pItem->m_strPath = strRoot;
                            pItem->m_strPath += wfd.cFileName;

#ifndef _LINUX
                            g_charsetConverter.stringCharsetToUtf8(pItem->m_strPath);
#endif
                            pItem->m_bIsFolder = true;
                            CUtil::AddSlashAtEnd(pItem->m_strPath);
                            FileTimeToLocalFileTime(&wfd.ftLastWriteTime, &localTime);
                            pItem->m_dateTime=localTime;

                            vecCacheItems.Add(pItem);
#ifdef _LINUX
                            /* Checks if the file is hidden. If it is then we don't really need to add it */
                            if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) || g_guiSettings.GetBool("filelists.showhidden"))
                                items.Add(new CFileItem(*pItem));
#else
                            items.Add(new CFileItem(*pItem));
#endif
                        }
                    }
                    else
                    {
                        CStdString strLabel=wfd.cFileName;
#ifndef _LINUX
                        g_charsetConverter.stringCharsetToUtf8(strLabel);
#endif
                        CFileItem *pItem = new CFileItem(strLabel);
                        pItem->m_strPath = strRoot;
                        pItem->m_strPath += wfd.cFileName;
#ifndef _LINUX
                        g_charsetConverter.stringCharsetToUtf8(pItem->m_strPath);
#endif
                        pItem->m_bIsFolder = false;
                        pItem->m_dwSize = CUtil::ToInt64(wfd.nFileSizeHigh, wfd.nFileSizeLow);
                        FileTimeToLocalFileTime(&wfd.ftLastWriteTime, &localTime);
                        pItem->m_dateTime=localTime;
#ifdef _LINUX
                        /* Checks if the file is hidden. If it is then we don't really need to add it */
                        if ((!(wfd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) || g_guiSettings.GetBool("filelists.showhidden")) && IsAllowed(wfd.cFileName))
#else
                        if ( IsAllowed( wfd.cFileName) )
#endif
                        {
                            vecCacheItems.Add(pItem);
                            items.Add(new CFileItem(*pItem));
                        }
                        else
                            vecCacheItems.Add(pItem);
                    }
            }
        }
        while (FindNextFile((HANDLE)hFind, &wfd));
#ifdef _XBOX
        // if we use AutoPtrHandle, this auto-closes
        FindClose((HANDLE)hFind); //should be closed
#endif
    }
    if (m_cacheDirectory)
        g_directoryCache.SetDirectory(strPath1, vecCacheItems);
    return true;
}
Beispiel #20
0
std::string CTsReader::TranslatePath(const char*  pszFileName)
{
#if defined (TARGET_WINDOWS)
  // Can we access the given file already?
  if ( OS::CFile::Exists(pszFileName) )
  {
    return pszFileName;
  }
#endif

  CStdString sFileName = pszFileName;

  // Card Id given? (only for Live TV / Radio). Check for an UNC path (e.g. \\tvserver\timeshift)
  if (m_cardId >= 0)
  {
    Card tscard;

    if ((m_cardSettings) && (m_cardSettings->GetCard(m_cardId, tscard)))
    {
      sFileName.Replace(tscard.TimeshiftFolder.c_str(), tscard.TimeshiftFolderUNC.c_str());
    }
  }
  else
  {
    // No Card Id given. This is a recording. Check for an UNC path (e.g. \\tvserver\recordings)
    size_t found = string::npos;

    if ((m_cardSettings) && (m_cardSettings->size() > 0))
    {
      for (CCards::iterator it = m_cardSettings->begin(); it < m_cardSettings->end(); it++)
      {
        // Determine whether the first part of the recording filename is shared with this card
        found = sFileName.find(it->RecordingFolder);
        if (found != string::npos)
        {
          // Remove the original base path and replace it with the given path
          sFileName.Replace(it->RecordingFolder.c_str(), it->RecordingFolderUNC.c_str());
          break;
        }
      }
    }
  }

#if defined(TARGET_LINUX) || defined(TARGET_OSX)
  CStdString CIFSName = sFileName;
  CIFSName.Replace("\\", "/");
  std::string SMBPrefix = "smb://";
  if (g_szSMBusername.length() > 0)
  {
    SMBPrefix += g_szSMBusername;
    if (g_szSMBpassword.length() > 0)
    {
      SMBPrefix += ":" + g_szSMBpassword;
    }
  }
  else
  {
    SMBPrefix += "Guest";
  }
  SMBPrefix += "@";
  CIFSName.Replace("//", SMBPrefix.c_str());
  sFileName = CIFSName;

  //size_t found = string::npos;

  //// Extract filename:
  //found = CIFSname.find_last_of("\\");

  //if (found != string::npos)
  //{
  //  CIFSname.erase(0, found + 1);
  //  CIFSname.insert(0, m_basePath.c_str());
  //  CIFSname.erase(0, 6); // Remove smb://
  //}
  //CIFSname.insert(0, SMBPrefix.c_str());

  //XBMC->Log(LOG_INFO, "CTsReader:TranslatePath %s -> %s", pszFileName, CIFSname.c_str());
  //return CIFSname;
#endif

  XBMC->Log(LOG_INFO, "CTsReader:TranslatePath %s -> %s", pszFileName, sFileName.c_str());

#if defined (TARGET_WINDOWS)
  // Can we access the given file already?
  if ( !OS::CFile::Exists(sFileName) )
  {
    XBMC->Log(LOG_ERROR, "%s: Cannot find/access file: %s", __FUNCTION__, sFileName.c_str());
  }
#endif

  return sFileName;
}
Beispiel #21
0
bool CLastFmManager::RequestRadioTracks()
{
  unsigned int start = XbmcThreads::SystemClockMillis();
  CStdString url;
  CStdString html;
  url.Format("http://" + m_RadioBaseUrl + m_RadioBasePath + "/xspf.php?sk=%s&discovery=0&desktop=", m_RadioSession);
  {
    CCurlFile http;
    if (!http.Get(url, html))
    {
      m_RadioSession.empty();
      CLog::Log(LOGERROR, "LastFmManager: Connect to Last.fm to request tracks failed.");
      return false;
    }
  }
  //CLog::Log(LOGDEBUG, "RequestRadioTracks: %s", html.c_str());

  //parse playlist
  CXBMCTinyXML xmlDoc;

  xmlDoc.Parse(html);
  if (xmlDoc.Error())
  {
    m_RadioSession.empty();
    CLog::Log(LOGERROR, "LastFmManager: Unable to parse tracklist Error: %s", xmlDoc.ErrorDesc());
    return false;
  }

  TiXmlElement* pRootElement = xmlDoc.RootElement();
  if (!pRootElement )
  {
    CLog::Log(LOGWARNING, "LastFmManager: No more tracks received");
    m_RadioSession.empty();
    return false;
  }

  TiXmlElement* pBodyElement = pRootElement->FirstChildElement("trackList");
  if (!pBodyElement )
  {
    CLog::Log(LOGWARNING, "LastFmManager: No more tracks received, no tracklist");
    m_RadioSession.empty();
    return false;
  }

  TiXmlElement* pTrackElement = pBodyElement->FirstChildElement("track");

  if (!pTrackElement)
  {
    CLog::Log(LOGWARNING, "LastFmManager: No more tracks received, empty tracklist");
    m_RadioSession.empty();
    return false;
  }
  while (pTrackElement)
  {
    CFileItemPtr newItem(new CFileItem);

    TiXmlElement* pElement = pTrackElement->FirstChildElement("location");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        CStdString url = child->Value();
        url.Replace("http:", "lastfm:");
        newItem->SetPath(url);
      }
    }
    pElement = pTrackElement->FirstChildElement("title");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        newItem->SetLabel(child->Value());
        newItem->GetMusicInfoTag()->SetTitle(child->Value());
      }
    }
    pElement = pTrackElement->FirstChildElement("creator");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        newItem->GetMusicInfoTag()->SetArtist(child->Value());
      }
    }
    pElement = pTrackElement->FirstChildElement("album");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        newItem->GetMusicInfoTag()->SetAlbum(child->Value());
      }
    }

    pElement = pTrackElement->FirstChildElement("duration");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        int iDuration = atoi(child->Value())/1000;
        newItem->GetMusicInfoTag()->SetDuration(iDuration);
      }
    }
    newItem->FillInDefaultIcon();
    pElement = pTrackElement->FirstChildElement("image");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        CStdString coverUrl = child->Value();
        if ((coverUrl != "") && (coverUrl.Find("noimage") == -1) && (coverUrl.Right(1) != "/"))
        {
          newItem->SetThumbnailImage(coverUrl);
        }
      }
    }
    //trackauth is needed for validating the track when scrobbling
    pElement = pTrackElement->FirstChildElement("lastfm:trackauth");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        CStdString trackAuth = child->Value();
        //abuse comment field for the track authcode
        newItem->GetMusicInfoTag()->SetComment(trackAuth);
      }
    }

    {
      CSingleLock lock(m_lockCache);
      m_RadioTrackQueue->Add(newItem);
    }
    pTrackElement = pTrackElement->NextSiblingElement();
  }
  //end parse
  CSingleLock lock(m_lockCache);
  int iNrCachedTracks = m_RadioTrackQueue->size();
  CLog::Log(LOGDEBUG, "%s: Done (time: %i ms)", __FUNCTION__, (int)(XbmcThreads::SystemClockMillis() - start));
  return iNrCachedTracks > 0;
}
Beispiel #22
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);
}
Beispiel #23
0
void CExternalPlayer::GetCustomRegexpReplacers(TiXmlElement *pRootElement,
                                               CStdStringArray& settings)
{
  int iAction = 0; // overwrite
  // for backward compatibility
  const char* szAppend = pRootElement->Attribute("append");
  if ((szAppend && stricmp(szAppend, "yes") == 0))
    iAction = 1;
  // action takes precedence if both attributes exist
  const char* szAction = pRootElement->Attribute("action");
  if (szAction)
  {
    iAction = 0; // overwrite
    if (stricmp(szAction, "append") == 0)
      iAction = 1; // append
    else if (stricmp(szAction, "prepend") == 0)
      iAction = 2; // prepend
  }
  if (iAction == 0)
    settings.clear();

  TiXmlElement* pReplacer = pRootElement->FirstChildElement("replacer");
  int i = 0;
  while (pReplacer)
  {
    if (pReplacer->FirstChild())
    {
      const char* szGlobal = pReplacer->Attribute("global");
      const char* szStop = pReplacer->Attribute("stop");
      bool bGlobal = szGlobal && stricmp(szGlobal, "true") == 0;
      bool bStop = szStop && stricmp(szStop, "true") == 0;

      CStdString strMatch;
      CStdString strPat;
      CStdString strRep;
      XMLUtils::GetString(pReplacer,"match",strMatch);
      XMLUtils::GetString(pReplacer,"pat",strPat);
      XMLUtils::GetString(pReplacer,"rep",strRep);

      if (!strPat.IsEmpty() && !strRep.IsEmpty())
      {
        CLog::Log(LOGDEBUG,"  Registering replacer:");
        CLog::Log(LOGDEBUG,"    Match:[%s] Pattern:[%s] Replacement:[%s]", strMatch.c_str(), strPat.c_str(), strRep.c_str());
        CLog::Log(LOGDEBUG,"    Global:[%s] Stop:[%s]", bGlobal?"true":"false", bStop?"true":"false");
        // keep literal commas since we use comma as a seperator
        strMatch.Replace(",",",,");
        strPat.Replace(",",",,");
        strRep.Replace(",",",,");

        CStdString strReplacer = strMatch + " , " + strPat + " , " + strRep + " , " + (bGlobal ? "g" : "") + (bStop ? "s" : "");
        if (iAction == 2)
          settings.insert(settings.begin() + i++, 1, strReplacer);
        else
          settings.push_back(strReplacer);
      }
      else
      {
        // error message about missing tag
        if (strPat.IsEmpty())
          CLog::Log(LOGERROR,"  Missing <Pat> tag");
        else
          CLog::Log(LOGERROR,"  Missing <Rep> tag");
      }
    }

    pReplacer = pReplacer->NextSiblingElement("replacer");
  }
}
Beispiel #24
0
bool CWINSMBDirectory::EnumerateFunc(LPNETRESOURCEW lpnr, CFileItemList &items)
{
  DWORD dwResult, dwResultEnum;
  HANDLE hEnum;
  DWORD cbBuffer = 16384;     // 16K is a good size
  LPNETRESOURCEW lpnrLocal;   // pointer to enumerated structures
  DWORD cEntries = -1;        // enumerate all possible entries
  //
  // Call the WNetOpenEnum function to begin the enumeration.
  //
  dwResult = WNetOpenEnumW( RESOURCE_GLOBALNET,  // all network resources
                            RESOURCETYPE_DISK,   // all disk resources
                            0,                   // enumerate all resources
                            lpnr,                // NULL first time the function is called
                            &hEnum);             // handle to the resource

  if (dwResult != NO_ERROR)
  {
    CLog::Log(LOGERROR,"WnetOpenEnum failed with error %d", dwResult);
    if(dwResult == ERROR_EXTENDED_ERROR)
    {
      DWORD dwWNetResult, dwLastError;
      CHAR szDescription[256];
      CHAR szProvider[256];
      dwWNetResult = WNetGetLastError(&dwLastError, // error code
                            (LPSTR) szDescription,  // buffer for error description
                            sizeof(szDescription),  // size of error buffer
                            (LPSTR) szProvider,     // buffer for provider name
                            sizeof(szProvider));    // size of name buffer
      if(dwWNetResult == NO_ERROR)
        CLog::Log(LOGERROR,"%s failed with code %ld; %s", szProvider, dwLastError, szDescription);
    }
    return false;
  }
  //
  // Call the GlobalAlloc function to allocate resources.
  //
  lpnrLocal = (LPNETRESOURCEW) GlobalAlloc(GPTR, cbBuffer);
  if (lpnrLocal == NULL)
  {
    CLog::Log(LOGERROR,"Can't allocate buffer %d", cbBuffer);
    return false;
  }

  do
  {
    //
    // Initialize the buffer.
    //
    ZeroMemory(lpnrLocal, cbBuffer);
    //
    // Call the WNetEnumResource function to continue
    //  the enumeration.
    //
    dwResultEnum = WNetEnumResourceW( hEnum,          // resource handle
                                      &cEntries,      // defined locally as -1
                                      lpnrLocal,      // LPNETRESOURCE
                                      &cbBuffer);     // buffer size
    //
    // If the call succeeds, loop through the structures.
    //
    if (dwResultEnum == NO_ERROR)
    {
      for (DWORD i = 0; i < cEntries; i++)
      {
        DWORD dwDisplayType = lpnrLocal[i].dwDisplayType;
        DWORD dwType = lpnrLocal[i].dwType;

        if((((dwDisplayType == RESOURCEDISPLAYTYPE_SERVER) && (m_bHost == false)) ||
           ((dwDisplayType == RESOURCEDISPLAYTYPE_SHARE) && m_bHost)) &&
           (dwType != RESOURCETYPE_PRINT))
        {
          CStdString strurl = "smb:";
          CStdStringW strRemoteNameW = lpnrLocal[i].lpRemoteName;
          CStdString  strName,strRemoteName;

          g_charsetConverter.wToUTF8(strRemoteNameW,strRemoteName);
          CLog::Log(LOGDEBUG,"Found Server/Share: %s", strRemoteName.c_str());

          strurl.append(strRemoteName);
          strurl.Replace("\\","/");
          CURL rooturl(strurl);
          rooturl.SetFileName("");

          if(!rooturl.GetShareName().empty())
            strName = rooturl.GetShareName();
          else
            strName = rooturl.GetHostName();

          strName.Replace("\\","");

          URIUtils::AddSlashAtEnd(strurl);
          CFileItemPtr pItem(new CFileItem(strName));
          pItem->SetPath(strurl);
          pItem->m_bIsFolder = true;
          items.Add(pItem);
        }

        // If the NETRESOURCE structure represents a container resource,
        //  call the EnumerateFunc function recursively.
        if (RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER))
          EnumerateFunc(&lpnrLocal[i], items);
      }
    }
    // Process errors.
    //
    else if (dwResultEnum != ERROR_NO_MORE_ITEMS)
    {
      CLog::Log(LOGERROR,"WNetEnumResource failed with error %d", dwResultEnum);
      break;
    }
  }
  //
  // End do.
  //
  while (dwResultEnum != ERROR_NO_MORE_ITEMS);
  //
  // Call the GlobalFree function to free the memory.
  //
  GlobalFree((HGLOBAL) lpnrLocal);
  //
  // Call WNetCloseEnum to end the enumeration.
  //
  dwResult = WNetCloseEnum(hEnum);

  if (dwResult != NO_ERROR)
  {
      //
      // Process errors.
      //
      CLog::Log(LOGERROR,"WNetCloseEnum failed with error %d", dwResult);
      return false;
  }

  return true;
}
Beispiel #25
0
CFileItem* CHDDirectory::BuildResolvedFileItem(const CStdString& strRoot, WIN32_FIND_DATA& wfd)
{
  CFileItem* pItem = 0;

#ifdef __APPLE__
  // Attempt to resolve aliases.
  FSRef   fsRef;
  Boolean isDir;
  Boolean isAlias;
  char    resolvedAliasPath[MAX_PATH];
  bool    useAlias = false;

  // Convert to FSRef.
  CStdString strPath = strRoot;
  CStdString strFile = strPath + wfd.cFileName;
  if (FSPathMakeRef((const UInt8* )strFile.c_str(), &fsRef, &isDir) == noErr)
  {
    if (FSResolveAliasFileWithMountFlags(&fsRef, TRUE, &isDir, &isAlias, kResolveAliasFileNoUI) == noErr)
    {
      // If it was an alias, use the reference instead.
      if (isAlias)
      {
        if (FSRefMakePath(&fsRef, (UInt8* )resolvedAliasPath, MAX_PATH) == noErr)
          useAlias = true;
      }
    }
    else
    {
      // Broken item.
      return 0;
    }
  }

  // Compute the *final* name/path of the file.
  if (useAlias)
  {
    strPath = resolvedAliasPath;
    strFile = CUtil::GetFileName(strPath);
    strPath = strPath.Left(strPath.length()-strFile.length());
  }
  else
  {
    strFile = wfd.cFileName;
  }

  // Check for smart folders.
  if (CUtil::IsSmartFolder(strFile))
  {
    // Use the original name, without extension.
    CStdString smartFolder = strFile;
    int iPos = smartFolder.ReverseFind(".");
    if (iPos > 0)
      smartFolder = smartFolder.Left(iPos);

    strFile.Replace(':', '/');
    pItem = new CFileItem(smartFolder);
    //pItem->m_strPath = "smartfolder:/" + strPath + strFile;
    pItem->m_strPath = strPath + strFile;
    pItem->m_bIsFolder = true;
  }
  else if (useAlias)
  {
    // Add the alias.
    strFile.Replace(':', '/');
    pItem = new CFileItem(strFile);
    pItem->m_strPath = resolvedAliasPath;
    pItem->m_bIsFolder = isDir ? true : false;

    if (isDir == false)
    {
      // Get the size of the file.
      struct stat64 statInfo;
      stat64(resolvedAliasPath, &statInfo);
      pItem->m_dwSize = statInfo.st_size;
    }
  }
  else
#endif
  {
    // Go the default route.
    pItem = BuildFileItem(strRoot, wfd);
  }

  // Save file time.
  FILETIME localTime;
  FileTimeToLocalFileTime(&wfd.ftLastWriteTime, &localTime);
  pItem->m_dateTime = localTime;

  return pItem;
}
Beispiel #26
0
bool CWINSMBDirectory::GetDirectory(const CStdString& strPath1, CFileItemList &items)
{
  WIN32_FIND_DATAW wfd;

  CStdString strPath=strPath1;

  CURL url(strPath);

  if(url.GetShareName().empty())
  {
    LPNETRESOURCEW lpnr = NULL;
    bool ret;
    if(!url.GetHostName().empty())
    {
      lpnr = (LPNETRESOURCEW) GlobalAlloc(GPTR, 16384);
      if(lpnr == NULL)
        return false;

      ConnectToShare(url);
      CStdString strHost = "\\\\" + url.GetHostName();
      CStdStringW strHostW;
      g_charsetConverter.utf8ToW(strHost,strHostW);
      lpnr->lpRemoteName = (LPWSTR)strHostW.c_str();
      m_bHost = true;
      ret = EnumerateFunc(lpnr, items);
      GlobalFree((HGLOBAL) lpnr);
      m_bHost = false;
    }
    else
      ret = EnumerateFunc(lpnr, items);

    return ret;
  }

  memset(&wfd, 0, sizeof(wfd));
  //rebuild the URL
  CStdString strUNCShare = "\\\\" + url.GetHostName() + "\\" + url.GetFileName();
  strUNCShare.Replace("/", "\\");
  if(!URIUtils::HasSlashAtEnd(strUNCShare))
    strUNCShare.append("\\");

  CStdStringW strSearchMask;
  g_charsetConverter.utf8ToW(strUNCShare, strSearchMask, false);
  strSearchMask += "*";

  FILETIME localTime;
  CAutoPtrFind hFind ( FindFirstFileW(strSearchMask.c_str(), &wfd));

  // on error, check if path exists at all, this will return true if empty folder
  if (!hFind.isValid())
  {
    DWORD ret = GetLastError();
    if(ret == ERROR_INVALID_PASSWORD || ret == ERROR_LOGON_FAILURE || ret == ERROR_ACCESS_DENIED || ret == ERROR_INVALID_HANDLE)
    {
      if(ConnectToShare(url) == false)
        return false;
      hFind.attach(FindFirstFileW(strSearchMask.c_str(), &wfd));
    }
    else
      return Exists(strPath1);
  }

  if (hFind.isValid())
  {
    do
    {
      if (wfd.cFileName[0] != 0)
      {
        CStdString strLabel;
        g_charsetConverter.wToUTF8(wfd.cFileName,strLabel);
        if ( (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
        {
          if (strLabel != "." && strLabel != "..")
          {
            CFileItemPtr pItem(new CFileItem(strLabel));
            CStdString path = URIUtils::AddFileToFolder(strPath, strLabel);
            URIUtils::AddSlashAtEnd(path);
            pItem->SetPath(path);
            pItem->m_bIsFolder = true;
            FileTimeToLocalFileTime(&wfd.ftLastWriteTime, &localTime);
            pItem->m_dateTime=localTime;

            if (wfd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
              pItem->SetProperty("file:hidden", true);

            items.Add(pItem);
          }
        }
        else
        {
          CFileItemPtr pItem(new CFileItem(strLabel));
          pItem->SetPath(URIUtils::AddFileToFolder(strPath, strLabel));
          pItem->m_bIsFolder = false;
          pItem->m_dwSize = CUtil::ToInt64(wfd.nFileSizeHigh, wfd.nFileSizeLow);
          FileTimeToLocalFileTime(&wfd.ftLastWriteTime, &localTime);
          pItem->m_dateTime=localTime;

          if (wfd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
            pItem->SetProperty("file:hidden", true);
          items.Add(pItem);
        }
      }
    }
    while (FindNextFileW((HANDLE)hFind, &wfd));
  }
  return true;
}
bool DVDPlayerCodec::Init(const CStdString &strFile, unsigned int filecache)
{
  m_decoded = NULL;;
  m_nDecodedLen = 0;

  CStdString strFileToOpen = strFile;

  CURL urlFile(strFile);
  if (urlFile.GetProtocol() == "shout" )
    strFileToOpen.Replace("shout://","http://");

  m_pInputStream = CDVDFactoryInputStream::CreateInputStream(NULL, strFileToOpen, m_strContentType);
  if (!m_pInputStream)
  {
    CLog::Log(LOGERROR, "%s: Error creating input stream for %s", __FUNCTION__, strFileToOpen.c_str());
    return false;
  }

  if (!m_pInputStream->Open(strFileToOpen.c_str(), m_strContentType))
  {
    CLog::Log(LOGERROR, "%s: Error opening file %s", __FUNCTION__, strFileToOpen.c_str());
    if (m_pInputStream)
      delete m_pInputStream;
    m_pInputStream = NULL;
    return false;
  }

  m_pDemuxer = NULL;

  try
  {
    m_pDemuxer = CDVDFactoryDemuxer::CreateDemuxer(m_pInputStream);
    if (!m_pDemuxer)
    {
      delete m_pInputStream;
      m_pInputStream = NULL;
      CLog::Log(LOGERROR, "%s: Error creating demuxer", __FUNCTION__);
      return false;
    }
  }
  catch(...)
  {
    CLog::Log(LOGERROR, "%s: Exception thrown when opeing demuxer", __FUNCTION__);
    if (m_pDemuxer)
    {
      delete m_pDemuxer;
      m_pDemuxer = NULL;
    }
    delete m_pInputStream;
    m_pInputStream = NULL;
    return false;
  }

  CDemuxStream* pStream = NULL;
  m_nAudioStream = -1;
  for (int i = 0; i < m_pDemuxer->GetNrOfStreams(); i++)
  {
    pStream = m_pDemuxer->GetStream(i);
    if (pStream && pStream->type == STREAM_AUDIO)
    {
      m_nAudioStream = i;
      break;
    }
  }

  if (m_nAudioStream == -1)
  {
    CLog::Log(LOGERROR, "%s: Could not find audio stream", __FUNCTION__);
    delete m_pDemuxer;
    m_pDemuxer = NULL;
    delete m_pInputStream;
    m_pInputStream = NULL;
    return false;
  }

  CDVDStreamInfo hint(*pStream, true);

  bool passthrough = AUDIO_IS_BITSTREAM(g_guiSettings.GetInt("audiooutput.mode"));
  m_pAudioCodec = CDVDFactoryCodec::CreateAudioCodec(hint, passthrough);
  if (!m_pAudioCodec)
  {
    CLog::Log(LOGERROR, "%s: Could not create audio codec", __FUNCTION__);
    delete m_pDemuxer;
    m_pDemuxer = NULL;
    delete m_pInputStream;
    m_pInputStream = NULL;
    return false;
  }

  // we have to decode initial data in order to get channels/samplerate
  // for sanity - we read no more than 10 packets
  int nErrors = 0;
  for (int nPacket=0; nPacket < 10 && (m_Channels == 0 || m_SampleRate == 0); nPacket++)
  {
    BYTE dummy[256];
    int nSize = 256;
    if (ReadPCM(dummy, nSize, &nSize) == READ_ERROR)
      ++nErrors;

    m_DataFormat    = m_pAudioCodec->GetDataFormat();
    m_BitsPerSample = CAEUtil::DataFormatToBits(m_DataFormat);
    m_SampleRate = m_pAudioCodec->GetSampleRate();
    m_EncodedSampleRate = m_pAudioCodec->GetEncodedSampleRate();
    m_Channels = m_pAudioCodec->GetChannels();
    m_ChannelInfo = m_pAudioCodec->GetChannelMap();

  }
  if (nErrors >= 10)
  {
    CLog::Log(LOGDEBUG, "%s: Could not decode data", __FUNCTION__);
    return false;
  }

  m_nDecodedLen = 0;

  if (m_Channels == 0) // no data - just guess and hope for the best
    m_Channels = 2;

  if (m_SampleRate == 0)
    m_SampleRate = 44100;

  m_TotalTime = m_pDemuxer->GetStreamLength();
  m_Bitrate = m_pAudioCodec->GetBitRate();
  m_pDemuxer->GetStreamCodecName(m_nAudioStream,m_CodecName);

  return true;
}
bool CDirectoryTuxBox::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  // so we know that we have enigma2
  static bool enigma2 = false;
  // Detect and delete slash at end
  CStdString strRoot = strPath;
  if (CUtil::HasSlashAtEnd(strRoot))
  strRoot.Delete(strRoot.size() - 1);

  //Get the request strings
  CStdString strBQRequest;
  CStdString strXMLRootString;
  CStdString strXMLChildString;
  if(!GetRootAndChildString(strRoot, strBQRequest, strXMLRootString, strXMLChildString))
    return false;

  //Set url Protocol
  CURL url(strRoot);
  CStdString strFilter;
  CStdString protocol = url.GetProtocol();
  CStdString strOptions = url.GetOptions();
  url.SetProtocol("http");
  bool bIsBouquet=false;

  int ipoint = strOptions.Find("?path=");
  if (ipoint >=0)
  {
    // send Zap!
    return g_tuxbox.ZapToUrl(url, strOptions, ipoint);
  }
  else
  {
    ipoint = strOptions.Find("&reference=");
    if (ipoint >=0 || enigma2)
    {
      //List reference
      strFilter = strOptions.Right((strOptions.size()-(ipoint+11)));
      bIsBouquet = false; //On Empty is Bouquet
      if (enigma2)
      {
        CStdString strPort;
        strPort.Format(":%i",url.GetPort());
        if (strRoot.Right(strPort.GetLength()) != strPort) // If not root dir, enable Channels
          strFilter = "e2"; // Disable Bouquets for Enigma2

        GetRootAndChildStringEnigma2(strBQRequest, strXMLRootString, strXMLChildString);
        url.SetOptions("");
        url.SetFileName(strBQRequest);
      }
    }
  }
  if(strFilter.IsEmpty())
  {
    url.SetOptions(strBQRequest);
    bIsBouquet = true;
  }
  //Open
  CFileCurl http;
  int iTryConnect = 0;
  int iWaitTimer = 20;
  bool result = false;

  while (iTryConnect < 4)
  {
    http.SetTimeout(iWaitTimer);
    if(http.Open(url))
    {
      //We are connected!
      iTryConnect = 4;

      // restore protocol
      url.SetProtocol(protocol);

      int size_read = 0;
      int size_total = (int)http.GetLength();
      int data_size = 0;
      CStdString data;
      data.reserve(size_total);

      // read response from server into string buffer
      char buffer[16384];
      while ((size_read = http.Read(buffer, sizeof(buffer)-1)) > 0)
      {
        buffer[size_read] = 0;
        data += buffer;
        data_size += size_read;
      }
      http.Close();

      // parse returned xml
      TiXmlDocument doc;
      data.Replace("></",">-</"); //FILL EMPTY ELEMENTS WITH "-"!
      doc.Parse(data.c_str());
      TiXmlElement *root = doc.RootElement();
      if(root == NULL)
      {
        CLog::Log(LOGERROR, "%s - Unable to parse xml", __FUNCTION__);
        CLog::Log(LOGERROR, "%s - Sample follows...\n%s", __FUNCTION__, data.c_str());
        return false;
      }
      if( strXMLRootString.Equals(root->Value()) && bIsBouquet)
      {
        data.Empty();
        if (enigma2)
          result = g_tuxbox.ParseBouquetsEnigma2(root, items, url, strFilter, strXMLChildString);
        else
          result = g_tuxbox.ParseBouquets(root, items, url, strFilter, strXMLChildString);
      }
      else if( strXMLRootString.Equals(root->Value()) && !strFilter.IsEmpty() )
      {
        data.Empty();
        if (enigma2)
          result = g_tuxbox.ParseChannelsEnigma2(root, items, url, strFilter, strXMLChildString);
        else
          result = g_tuxbox.ParseChannels(root, items, url, strFilter, strXMLChildString);
      }
      else
      {
        CLog::Log(LOGERROR, "%s - Invalid root xml element for TuxBox", __FUNCTION__);
        CLog::Log(LOGERROR, "%s - Sample follows...\n%s", __FUNCTION__, data.c_str());
        data.Empty();
        result = false;
      }
    }
    else
    {
      CLog::Log(LOGERROR, "%s - Unable to get XML structure! Try count:%i, Wait Timer:%is",__FUNCTION__, iTryConnect, iWaitTimer);
      iTryConnect++;
      if (iTryConnect == 2) //try enigma2 instead of enigma1, best entrypoint here i thought
      {	
        enigma2 = true;
        GetRootAndChildStringEnigma2(strBQRequest, strXMLRootString, strXMLChildString);
        url.SetOptions("");
        url.SetFileName(strBQRequest);
//        iTryConnect = 0;
        iWaitTimer = 20;
      }
      else
        iWaitTimer = iWaitTimer+10;
       
      result = false;
      http.Close(); // Close old connections
    }
  }

  return result;
}
Beispiel #29
0
bool CFileRar::OpenInArchive()
{
#ifdef HAS_FILESYSTEM_RAR
  int iHeaderSize;

  InitCRC();

  m_pCmd = new CommandData;
  if (!m_pCmd)
  {
    CleanUp();
    return false;
  }

  // Set the arguments for the extract command
  strcpy(m_pCmd->Command, "X");

  m_pCmd->AddArcName(const_cast<char*>(m_strRarPath.c_str()),NULL);

  strncpy(m_pCmd->ExtrPath, m_strCacheDir.c_str(), sizeof (m_pCmd->ExtrPath) - 2);
  m_pCmd->ExtrPath[sizeof (m_pCmd->ExtrPath) - 2] = 0;
  AddEndSlash(m_pCmd->ExtrPath);

  // Set password for encrypted archives
  if ((m_strPassword.size() > 0) &&
      (m_strPassword.size() < sizeof (m_pCmd->Password)))
  {
    strcpy(m_pCmd->Password, m_strPassword.c_str());
  }

  m_pCmd->ParseDone();

  // Open the archive
  m_pArc = new Archive(m_pCmd);
  if (!m_pArc)
  {
    CleanUp();
    return false;
  }
  if (!m_pArc->WOpen(m_strRarPath.c_str(),NULL))
  {
    CleanUp();
    return false;
  }
  if (!(m_pArc->IsOpened() && m_pArc->IsArchive(true)))
  {
    CleanUp();
    return false;
  }

  m_pExtract = new CmdExtract;
  if (!m_pExtract)
  {
    CleanUp();
    return false;
  }
  m_pExtract->GetDataIO().SetUnpackToMemory(m_szBuffer,0);
  m_pExtract->GetDataIO().SetCurrentCommand(*(m_pCmd->Command));
  struct FindData FD;
  if (FindFile::FastFind(m_strRarPath.c_str(),NULL,&FD))
    m_pExtract->GetDataIO().TotalArcSize+=FD.Size;
  m_pExtract->ExtractArchiveInit(m_pCmd,*m_pArc);

  while (true)
  {
    if ((iHeaderSize = m_pArc->ReadHeader()) <= 0)
    {
      CleanUp();
      return false;
    }

    if (m_pArc->GetHeaderType() == FILE_HEAD)
    {
      CStdString strFileName;

      if (m_pArc->NewLhd.FileNameW && wcslen(m_pArc->NewLhd.FileNameW) > 0)
      {
        g_charsetConverter.wToUTF8(m_pArc->NewLhd.FileNameW, strFileName);
      }
      else
      {
        g_charsetConverter.unknownToUTF8(m_pArc->NewLhd.FileName, strFileName);
      }

      /* replace back slashes into forward slashes */
      /* this could get us into troubles, file could two different files, one with / and one with \ */
      strFileName.Replace('\\', '/');

      if (strFileName == m_strPathInRar)
      {
        break;
      }
    }

    m_pArc->SeekToNext();
  }

  m_szBuffer = new byte[MAXWINMEMSIZE];
  m_szStartOfBuffer = m_szBuffer;
  m_pExtract->GetDataIO().SetUnpackToMemory(m_szBuffer,0);
  m_iDataInBuffer = -1;
  m_iFilePosition = 0;
  m_iBufferStart = 0;

  delete m_pExtractThread;
  m_pExtractThread = new CFileRarExtractThread();
  m_pExtractThread->Start(m_pArc,m_pCmd,m_pExtract,iHeaderSize);

  return true;
#else
  return false;
#endif
}
Beispiel #30
0
bool CNfsDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  CURI url(strPath);
  bool bResult = false;

  if(url.GetProtocol() != "nfs")
  {
     CLog::Log(LOGERROR, "CNfsDirectory::%s - invalid protocol [%s]", __func__, url.GetProtocol().c_str());
     return false;
  }

  CBrowserService* pBrowser = g_application.GetBrowserService();

  if( strPath == "nfs://" && pBrowser )
  {
    pBrowser->GetShare( CBrowserService::NFS_SHARE, items );
    return true;
  }

  // If we have the items in the cache, return them
  if (g_directoryCache.GetDirectory(strPath, items)) 
  {
    return true;
  }

  if(strPath == "nfs://all")
  {
     std::vector<NfsShare> shares;

     bool succedded = ScanNfsShares(shares);
     if(!succedded)
     {
       CLog::Log(LOGERROR, "CNfsDirectory::%s - failed to scan NFS shares", __func__);
       return false;
     }

     for(size_t i=0; i<shares.size(); i++)
     {
       CStdString hostName = shares[i].hostName.IsEmpty() ? shares[i].ipAddr : shares[i].hostName;
       CFileItemPtr pItem(new CFileItem(hostName));
       
       pItem->m_strTitle = hostName;
       pItem->m_bIsFolder = true;
       pItem->m_strPath.Format("nfs://%s", hostName);
       pItem->SetProperty("isNetwork",true);

       items.Add(pItem);
     }

     CLog::Log(LOGDEBUG, "CNfsDirectory::%s - found %d NFS devices", __func__,  shares.size());
     return true;
  } 

  CStdString hostName = url.GetHostName();
  CStdString fileName = url.GetFileName();
   
  if(fileName.IsEmpty())
  {
    std::vector<CStdString> exports;

    if(false == GetExports(hostName.c_str(), exports)) 
    {
      CLog::Log(LOGERROR, "CNfsDirectory::%s - failed to get export for host [%s]", __func__, hostName.c_str());
      return false;
    }
 
    CLog::Log(LOGDEBUG, "CNfsDirectory::%s - found [%d] exports for [%s] ", __func__,  exports.size(), hostName.c_str());

    for(size_t i=0; i<exports.size(); i++)
    {
      CStdString title = exports[i];
      CFileItemPtr pItem(new CFileItem(title));
      pItem->m_strTitle = title;
      pItem->m_bIsFolder = true;
      pItem->SetProperty("isNetwork",true);

      pItem->m_strPath.Format("nfs://%s%s", hostName, exports[i]);
      
      items.Add(pItem);
    }
   
    bResult = true;
  }
  else
  {
    CFileItem item;
    
    if(false == GetResource(url, item))
    {
      CLog::Log(LOGERROR, "CNfsDirectory::%s - failed to get resource for path [%s]", __func__, url.Get().c_str());
      return false;
    }

    bResult = CUtil::GetHDDDirectory(item.m_strPath,items);

    for(int i=0; i<items.Size(); i++)
    {
      if(items[i]->m_bIsFolder)
      {
        items[i]->SetProperty("isNetwork",true);
      }
       // build nfs path 
       CStdString nfsPath = items[i]->m_strPath;
       nfsPath.Replace(item.m_strPath, strPath);
       
       if (nfsPath.length() >= strPath.length())
       {
         CStdString strNewFilename = nfsPath.substr(strPath.length());

         CStdString strNfsFileName;
         CStdString strFileName = item.GetProperty("filename");
         if (strFileName.IsEmpty())
           strNfsFileName = ":" + strNewFilename;
         else
           strNfsFileName = strNewFilename;

         items[i]->m_strPath.Format("%s%s", strPath.c_str(), strNfsFileName.c_str());

       }
    } 
  }

  return bResult;
}