コード例 #1
0
bool CFTPDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  CCurlFile reader;

  CURL url(strPath);

  CStdString path = url.GetFileName();
  if( !path.IsEmpty() && !path.Right(1).Equals("/") )
  {
    path += "/";
    url.SetFileName(path);
  }

  if (!reader.Open(url))
    return false;


  char buffer[MAX_PATH + 1024];
  while( reader.ReadString(buffer, sizeof(buffer)) )
  {
    CStdString strBuffer = buffer;

    StringUtils::RemoveCRLF(strBuffer);

    CFTPParse parse;
    if (parse.FTPParse(strBuffer))
    {
      if( parse.getName().length() == 0 )
        continue;

      if( parse.getFlagtrycwd() == 0 && parse.getFlagtryretr() == 0 )
        continue;

      /* buffer name */
      CStdString name;
      name.assign(parse.getName());

      if( name.Equals("..") || name.Equals(".") )
        continue;

      /* this should be conditional if we ever add    */
      /* support for the utf8 extension in ftp client */
      g_charsetConverter.unknownToUTF8(name);

      CFileItemPtr pItem(new CFileItem(name));

      pItem->m_bIsFolder = (bool)(parse.getFlagtrycwd() != 0);
      CStdString filePath = path + name;
      if (pItem->m_bIsFolder)
        URIUtils::AddSlashAtEnd(filePath);

      /* qualify the url with host and all */
      url.SetFileName(filePath);
      pItem->SetPath(url.Get());

      pItem->m_dwSize = parse.getSize();
      pItem->m_dateTime=parse.getTime();

      items.Add(pItem);
    }
  }

  return true;
}
コード例 #2
0
ファイル: DirectoryTuxBox.cpp プロジェクト: Gemini88/xbmc-1
bool CDirectoryTuxBox::GetRootAndChildString(const CStdString strPath, CStdString& strBQRequest, CStdString& strXMLRootString, CStdString& strXMLChildString )
{
  //Advanced Settings: RootMode! Movies:
  if(g_advancedSettings.m_iTuxBoxDefaultRootMenu == 3) //Movies! Fixed-> mode=3&submode=4
  {
    CLog::Log(LOGDEBUG, "%s - Default defined RootMenu : (3) Movies", __FUNCTION__);
    strBQRequest = "xml/services?mode=3&submode=4";
    strXMLRootString.Format("movies");
    strXMLChildString.Format("service");
  }
  else if(g_advancedSettings.m_iTuxBoxDefaultRootMenu <= 0 || g_advancedSettings.m_iTuxBoxDefaultRootMenu == 1 ||
    g_advancedSettings.m_iTuxBoxDefaultRootMenu > 4 )
  {
    //Falling Back to the Default RootMenu => 0 Bouquets
    if(g_advancedSettings.m_iTuxBoxDefaultRootMenu < 0 || g_advancedSettings.m_iTuxBoxDefaultRootMenu > 4)
    {
      g_advancedSettings.m_iTuxBoxDefaultRootMenu = 0;
    }

    //Advanced Settings: SubMenu!
    if(g_advancedSettings.m_bTuxBoxSubMenuSelection)
    {
      CLog::Log(LOGDEBUG, "%s SubMenu Channel Selection is Enabled! Requesting Submenu!", __FUNCTION__);
      // DeActivated: Timing Problems, bug in TuxBox.. etc.!
      bool bReqMoRe = true;
      // Detect the RootMode !
      if (strPath.Find("?mode=")>=0)
      {
        CStdString strMode;
        bReqMoRe=false;
        strMode = g_tuxbox.DetectSubMode(strPath, strXMLRootString, strXMLChildString);
      }
      if(bReqMoRe)
      {
        //PopUp Context and Request SubMode with root and child string
        strBQRequest = g_tuxbox.GetSubMode(g_advancedSettings.m_iTuxBoxDefaultRootMenu, strXMLRootString, strXMLChildString);
        if(strBQRequest.IsEmpty())
        {
          strBQRequest = "xml/services?mode=0&submode=4"; //Bouquets
          strXMLRootString.Format("bouquets");
          strXMLChildString.Format("bouquet");
        }
      }
    }
    else
    {
      //Advanced Settings: Set Default Subemnu
      if(g_advancedSettings.m_iTuxBoxDefaultSubMenu == 1)
      {
        CLog::Log(LOGDEBUG, "%s - Default defined SubMenu : (1) Services", __FUNCTION__);
        strBQRequest = "xml/services?mode=0&submode=1"; //Services
        strXMLRootString.Format("services");
        strXMLChildString.Format("service");
      }
      else if(g_advancedSettings.m_iTuxBoxDefaultSubMenu == 2)
      {
        CLog::Log(LOGDEBUG, "%s - Default defined SubMenu : (2) Satellites", __FUNCTION__);
        strBQRequest = "xml/services?mode=0&submode=2"; //Satellites
        strXMLRootString.Format("satellites");
        strXMLChildString.Format("satellite");
      }
      else if(g_advancedSettings.m_iTuxBoxDefaultSubMenu == 3)
      {
        CLog::Log(LOGDEBUG, "%s - Default defined SubMenu : (3) Providers", __FUNCTION__);
        strBQRequest = "xml/services?mode=0&submode=3"; //Providers
        strXMLRootString.Format("providers");
        strXMLChildString.Format("provider");
      }
      else
      {
        CLog::Log(LOGDEBUG, "%s - Default defined SubMenu : (4) Bouquets", __FUNCTION__);
        strBQRequest = "xml/services?mode=0&submode=4"; //Bouquets
        strXMLRootString.Format("bouquets");
        strXMLChildString.Format("bouquet");
      }
    }
  }
  if(strBQRequest.IsEmpty() || strXMLRootString.IsEmpty() || strXMLChildString.IsEmpty())
    return false;
  else
    return true;
}
コード例 #3
0
bool CSysInfo::GetDiskSpace(const CStdString drive,int& iTotal, int& iTotalFree, int& iTotalUsed, int& iPercentFree, int& iPercentUsed)
{
  bool bRet= false;
  ULARGE_INTEGER ULTotal= { { 0 } };
  ULARGE_INTEGER ULTotalFree= { { 0 } };

  if( !drive.IsEmpty() && !drive.Equals("*") )
  {
#ifdef _WIN32
    UINT uidriveType = GetDriveType(( drive + ":\\" ));
    if(uidriveType != DRIVE_UNKNOWN && uidriveType != DRIVE_NO_ROOT_DIR)
#endif
      bRet= ( 0 != GetDiskFreeSpaceEx( ( drive + ":\\" ), NULL, &ULTotal, &ULTotalFree) );
  }
  else
  {
    ULARGE_INTEGER ULTotalTmp= { { 0 } };
    ULARGE_INTEGER ULTotalFreeTmp= { { 0 } };
#ifdef _WIN32
    char* pcBuffer= NULL;
    DWORD dwStrLength= GetLogicalDriveStrings( 0, pcBuffer );
    if( dwStrLength != 0 )
    {
      dwStrLength+= 1;
      pcBuffer= new char [dwStrLength];
      GetLogicalDriveStrings( dwStrLength, pcBuffer );
      int iPos= 0;
      do {
        if( DRIVE_FIXED == GetDriveType( pcBuffer + iPos  ) &&
            GetDiskFreeSpaceEx( ( pcBuffer + iPos ), NULL, &ULTotal, &ULTotalFree ) )
        {
          ULTotalTmp.QuadPart+= ULTotal.QuadPart;
          ULTotalFreeTmp.QuadPart+= ULTotalFree.QuadPart;
        }
        iPos += (strlen( pcBuffer + iPos) + 1 );
      }while( strlen( pcBuffer + iPos ) > 0 );
    }
    delete[] pcBuffer;
#else // for linux and osx
    static const char *drv_letter[] = { "C:\\", "E:\\", "F:\\", "G:\\", "X:\\", "Y:\\", "Z:\\", NULL };
    for( int i = 0; drv_letter[i]; i++)
    {
      if( GetDiskFreeSpaceEx( drv_letter[i], NULL, &ULTotal, &ULTotalFree ) )
      {
        ULTotalTmp.QuadPart+= ULTotal.QuadPart;
        ULTotalFreeTmp.QuadPart+= ULTotalFree.QuadPart;
      }
    }
#endif
    if( ULTotalTmp.QuadPart || ULTotalFreeTmp.QuadPart )
    {
      ULTotal.QuadPart= ULTotalTmp.QuadPart;
      ULTotalFree.QuadPart= ULTotalFreeTmp.QuadPart;
      bRet= true;
    }
  }

  if( bRet )
  {
    iTotal = (int)( ULTotal.QuadPart / MB );
    iTotalFree = (int)( ULTotalFree.QuadPart / MB );
    iTotalUsed = iTotal - iTotalFree;
    if( ULTotal.QuadPart > 0 )
    {
      iPercentUsed = (int)( 100.0f * ( ULTotal.QuadPart - ULTotalFree.QuadPart ) / ULTotal.QuadPart + 0.5f );
    }
    else
    {
      iPercentUsed = 0;
    }
    iPercentFree = 100 - iPercentUsed;
  }

  return bRet;
}
コード例 #4
0
ファイル: WatchDog.cpp プロジェクト: marksuman/boxee
bool WatchDog::CPingJob::InitPingRequest(CStdString& pingUrl,CStdString& strPingVersion)
{
  BOXEE::BXXMLDocument bxinfo;
  CStdString bxinfoFilePath = PTH_IC(BXINFO_FILE_PATH);
  
  //////////////////////////////////
  // Set the current ping version //
  //////////////////////////////////

  if (bxinfo.LoadFromFile(bxinfoFilePath))
  {
    TiXmlHandle handle(bxinfo.GetRoot());
    TiXmlElement* version = handle.FirstChild("ping_version").ToElement();
    
    if (version)
    {
      std::string strVersion = version->GetText();
      if (!strVersion.empty())
      {
        strPingVersion = strVersion;
      }
    }
  }
  
  if(strPingVersion.IsEmpty())
  {
    strPingVersion = "0";
    CLog::Log(LOGDEBUG,"CPingJob::InitPingRequest - Failed to get the PingVersion from [%s], so set the ping version to [%s] (ping)",bxinfoFilePath.c_str(),strPingVersion.c_str());
  }

  //////////////////////
  // Set the ping url //
  //////////////////////
  
  pingUrl = BOXEE::BXConfiguration::GetInstance().GetStringParam("WatchDog.TestServerUrl","http://app.boxee.tv/");
  
  if(g_application.GetInSlideshowScreensaver())
  {
    pingUrl += "idle/";
  }
  else
  {
    pingUrl += "ping/";    
  }
  
  pingUrl += BoxeeUtils::GetPlatformStr();
  pingUrl += "/";
  
  CStdString boxeeCurrentVersion = g_infoManager.GetVersion();
  
  // For debug //
  /*
  if(boxeeCurrentVersion == "SVN")
  {
    boxeeCurrentVersion = g_localizeStrings.Get(53250);
    
    CLog::Log(LOGDEBUG,"CBoxeeVersionUpdateManager::PerformVersionUpdate - boxeeCurrentVersion is [SVN], so it was changed to [%s] (ping)",boxeeCurrentVersion.c_str());
  }
  */
  ///////////////
  
  pingUrl += boxeeCurrentVersion;
  
  pingUrl += "/";
  pingUrl += strPingVersion;
  
  if (g_guiSettings.GetBool("update.allow_beta"))
  {
    pingUrl += "/1";
  }
  else
  {
    pingUrl += "/0";
  }

  return true;
}
コード例 #5
0
/**
 * Look for a thumbnail for pItem.  If one does not exist, look for an autogenerated
 * thumbnail.  If that does not exist, attempt to autogenerate one.  Finally, check
 * for the existance of fanart and set properties accordinly.
 * @return: true if pItem has been modified
 */
bool CVideoThumbLoader::LoadItem(CFileItem* pItem)
{
  if (pItem->m_bIsShareOrDrive
  ||  pItem->IsParentFolder())
    return false;

  // resume point
  if (pItem->HasVideoInfoTag() && pItem->GetVideoInfoTag()->m_resumePoint.totalTimeInSeconds == 0)
  {
    CVideoDatabase db;
    db.Open();
    if (db.GetResumePoint(*pItem->GetVideoInfoTag()))
      pItem->SetInvalid();
    db.Close();
  }

  // video db items normally have info in the database
  if (pItem->HasVideoInfoTag() && pItem->GetVideoInfoTag()->m_iDbId > -1 &&
     !pItem->GetVideoInfoTag()->m_type.IsEmpty() && pItem->GetArt().empty())
  {
    CVideoDatabase db;
    db.Open();
    map<string, string> artwork;
    if (db.GetArtForItem(pItem->GetVideoInfoTag()->m_iDbId, pItem->GetVideoInfoTag()->m_type, artwork))
      pItem->SetArt(artwork);
    else
    {
      if (pItem->GetVideoInfoTag()->m_type == "movie" ||
          pItem->GetVideoInfoTag()->m_type == "episode" ||
          pItem->GetVideoInfoTag()->m_type == "tvshow" ||
          pItem->GetVideoInfoTag()->m_type == "musicvideo")
      { // no art in the library, so find it locally and add
        SScanSettings settings;
        ADDON::ScraperPtr info = db.GetScraperForPath(pItem->GetVideoInfoTag()->m_strPath, settings);
        if (info)
        {
          CFileItem item(*pItem);
          item.SetPath(pItem->GetVideoInfoTag()->GetPath());
          CVideoInfoScanner scanner;
          scanner.GetArtwork(&item, info->Content(), settings.parent_name_root, true);
          pItem->SetArt(item.GetArt());
        }
      }
      else if (pItem->GetVideoInfoTag()->m_type == "set")
      { // no art for a set -> use the first movie for this set for art
        CFileItemList items;
        if (db.GetMoviesNav("", items, -1, -1, -1, -1, -1, -1, pItem->GetVideoInfoTag()->m_iDbId) && items.Size() > 0)
        {
          if (db.GetArtForItem(items[0]->GetVideoInfoTag()->m_iDbId, items[0]->GetVideoInfoTag()->m_type, artwork))
            pItem->SetArt(artwork);
        }
      }
      else if (pItem->GetVideoInfoTag()->m_type == "actor" ||
               pItem->GetVideoInfoTag()->m_type == "artist" ||
               pItem->GetVideoInfoTag()->m_type == "writer" ||
               pItem->GetVideoInfoTag()->m_type == "director")
      {
        // We can't realistically get the local thumbs (as we'd need to check every movie that contains this actor)
        // and most users won't have local actor thumbs that are actually different than the scraped ones.
        if (g_guiSettings.GetBool("videolibrary.actorthumbs"))
        {
          pItem->GetVideoInfoTag()->m_strPictureURL.Parse();
          CStdString thumb = CScraperUrl::GetThumbURL(pItem->GetVideoInfoTag()->m_strPictureURL.GetFirstThumb());
          if (!thumb.IsEmpty())
            pItem->SetThumbnailImage(thumb);
        }
      }
      else if (pItem->GetVideoInfoTag()->m_type == "season")
      {
        // season art is fetched on scan from the tvshow root path (m_strPath in the season info tag)
        // or from the show m_strPictureURL member of the tvshow, so grab the tvshow to get this.
        CVideoInfoTag tag;
        db.GetTvShowInfo(pItem->GetVideoInfoTag()->m_strPath, tag, pItem->GetVideoInfoTag()->m_iIdShow);
        map<int, string> seasons;
        CVideoInfoScanner::GetSeasonThumbs(tag, seasons, true);
        map<int, string>::iterator season = seasons.find(pItem->GetVideoInfoTag()->m_iSeason);
        if (season != seasons.end())
          pItem->SetThumbnailImage(season->second);
      }
      // add to the database for next time around
      map<string, string> artwork = pItem->GetArt();
      if (!artwork.empty())
      {
        db.SetArtForItem(pItem->GetVideoInfoTag()->m_iDbId, pItem->GetVideoInfoTag()->m_type, artwork);
        for (map<string, string>::iterator i = artwork.begin(); i != artwork.end(); ++i)
          CTextureCache::Get().BackgroundCacheImage(i->second);
      }
      else // nothing found - set an empty thumb so that next time around we don't hit here again
        db.SetArtForItem(pItem->GetVideoInfoTag()->m_iDbId, pItem->GetVideoInfoTag()->m_type, "thumb", "");
    }
    // For episodes and seasons, we want to set fanart for that of the show
    if (!pItem->HasProperty("fanart_image") && pItem->GetVideoInfoTag()->m_iIdShow >= 0)
    {
      string fanart = db.GetArtForItem(pItem->GetVideoInfoTag()->m_iIdShow, "tvshow", "fanart");
      if (!fanart.empty())
        pItem->SetProperty("fanart_image", fanart);
    }
    db.Close();
  }

  if (pItem->GetVideoInfoTag()->m_type != "movie" &&
      pItem->GetVideoInfoTag()->m_type != "episode" &&
      pItem->GetVideoInfoTag()->m_type != "tvshow" &&
      pItem->GetVideoInfoTag()->m_type != "musicvideo")
    return true; // nothing else to be done

  // fanart
  if (!pItem->HasProperty("fanart_image"))
  {
    CStdString fanart = GetCachedImage(*pItem, "fanart");
    if (fanart.IsEmpty())
    {
      fanart = pItem->GetLocalFanart();
      if (!fanart.IsEmpty()) // cache it
        SetCachedImage(*pItem, "fanart", fanart);
    }
    if (!fanart.IsEmpty())
    {
      CTextureCache::Get().BackgroundCacheImage(fanart);
      pItem->SetProperty("fanart_image", fanart);
    }
  }

  // thumbnails
  if (!pItem->HasThumbnail())
  {
    FillThumb(*pItem);
    if (!pItem->HasThumbnail() && !pItem->m_bIsFolder && pItem->IsVideo())
    {
      // create unique thumb for auto generated thumbs
      CStdString thumbURL = GetEmbeddedThumbURL(*pItem);
      if (!CTextureCache::Get().GetCachedImage(thumbURL).IsEmpty())
      {
        CTextureCache::Get().BackgroundCacheImage(thumbURL);
        pItem->SetProperty("HasAutoThumb", true);
        pItem->SetProperty("AutoThumbImage", thumbURL);
        pItem->SetThumbnailImage(thumbURL);
      }
      else if (g_guiSettings.GetBool("myvideos.extractthumb") &&
               g_guiSettings.GetBool("myvideos.extractflags"))
      {
        CFileItem item(*pItem);
        CStdString path(item.GetPath());
        if (URIUtils::IsInRAR(item.GetPath()))
          SetupRarOptions(item,path);

        CThumbExtractor* extract = new CThumbExtractor(item, path, true, thumbURL);
        AddJob(extract);
        return true;
      }
    }
  }

  // flag extraction
  if (!pItem->m_bIsFolder &&
       pItem->HasVideoInfoTag() &&
       g_guiSettings.GetBool("myvideos.extractflags") &&
       (!pItem->GetVideoInfoTag()->HasStreamDetails() ||
         pItem->GetVideoInfoTag()->m_streamDetails.GetVideoDuration() <= 0))
  {
    CFileItem item(*pItem);
    CStdString path(item.GetPath());
    if (URIUtils::IsInRAR(item.GetPath()))
      SetupRarOptions(item,path);
    CThumbExtractor* extract = new CThumbExtractor(item,path,false);
    AddJob(extract);
  }

  return true;
}
コード例 #6
0
ファイル: TextureManager.cpp プロジェクト: A600/xbmc
void CGUITextureManager::AddTexturePath(const CStdString &texturePath)
{
  CSingleLock lock(m_section);
  if (!texturePath.IsEmpty())
    m_texturePaths.push_back(texturePath);
}
コード例 #7
0
void CGUIWindowDebugInfo::Process(unsigned int currentTime, CDirtyRegionList &dirtyregions)
{
  g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetResInfo(), false);

  g_cpuInfo.getUsedPercentage(); // must call it to recalculate pct values

  static int yShift = 20;
  static int xShift = 40;
  static unsigned int lastShift = time(NULL);
  time_t now = time(NULL);
  if (now - lastShift > 10)
  {
    yShift *= -1;
    if (now % 5 == 0)
      xShift *= -1;
    lastShift = now;
    MarkDirtyRegion();
  }

  if (!m_layout)
  {
    CGUIFont *font13 = g_fontManager.GetDefaultFont();
    CGUIFont *font13border = g_fontManager.GetDefaultFont(true);
    if (font13)
      m_layout = new CGUITextLayout(font13, true, 0, font13border);
  }
  if (!m_layout)
    return;

  CStdString info;
  if (LOG_LEVEL_DEBUG_FREEMEM <= g_advancedSettings.m_logLevel)
  {
    MEMORYSTATUS stat;
    GlobalMemoryStatus(&stat);
    CStdString profiling = CGUIControlProfiler::IsRunning() ? " (profiling)" : "";
    CStdString strCores = g_cpuInfo.GetCoresUsageString();
#if !defined(_LINUX)
    info.Format("LOG: %sxbmc.log\nMEM: %d/%d KB - FPS: %2.1f fps\nCPU: %s%s", g_settings.m_logFolder.c_str(),
                stat.dwAvailPhys/1024, stat.dwTotalPhys/1024, g_infoManager.GetFPS(), strCores.c_str(), profiling.c_str());
#else
    double dCPU = m_resourceCounter.GetCPUUsage();
    info.Format("LOG: %sxbmc.log\nMEM: %"PRIu64"/%"PRIu64" KB - FPS: %2.1f fps\nCPU: %s (CPU-XBMC %4.2f%%%s)", g_settings.m_logFolder.c_str(),
                stat.dwAvailPhys/1024, stat.dwTotalPhys/1024, g_infoManager.GetFPS(), strCores.c_str(), dCPU, profiling.c_str());
#endif
  }

  // render the skin debug info
  if (g_SkinInfo->IsDebugging())
  {
    if (!info.IsEmpty())
      info += "\n";
    CGUIWindow *window = g_windowManager.GetWindow(g_windowManager.GetFocusedWindow());
    CGUIWindow *pointer = g_windowManager.GetWindow(WINDOW_DIALOG_POINTER);
    CPoint point;
    if (pointer)
      point = CPoint(pointer->GetXPosition(), pointer->GetYPosition());
    if (window)
    {
      CStdString windowName = CButtonTranslator::TranslateWindow(window->GetID());
      if (!windowName.IsEmpty())
        windowName += " (" + window->GetProperty("xmlfile") + ")";
      else
        windowName = window->GetProperty("xmlfile");
      info += "Window: " + windowName + "  ";
      // transform the mouse coordinates to this window's coordinates
      g_graphicsContext.SetScalingResolution(window->GetCoordsRes(), true);
      point.x *= g_graphicsContext.GetGUIScaleX();
      point.y *= g_graphicsContext.GetGUIScaleY();
      g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetResInfo(), false);
    }
    info.AppendFormat("Mouse: (%d,%d)  ", (int)point.x, (int)point.y);
    if (window)
    {
      CGUIControl *control = window->GetFocusedControl();
      if (control)
        info.AppendFormat("Focused: %i (%s)", control->GetID(), CGUIControlFactory::TranslateControlType(control->GetControlType()).c_str());
    }
  }

  float w, h;
  if (m_layout->Update(info))
    MarkDirtyRegion();
  m_layout->GetTextExtent(w, h);

  float x = xShift + 0.04f * g_graphicsContext.GetWidth();
  float y = yShift + 0.04f * g_graphicsContext.GetHeight();
  m_renderRegion.SetRect(x, y, x+w, y+h);
}
コード例 #8
0
ファイル: FileScanner.cpp プロジェクト: Kr0nZ/boxee
bool CFileScanner::ShowSourcesStatusKaiDialog(int messageId, const CStdString& sourceName, const CStdString& sourcePath, const CStdString& sourceType)
{
  CLog::Log(LOGDEBUG,"CFileScanner::ShowSourcesStatusKaiDialog - Enter function with [messageId=%d][sourceName=%s][sourcePath=%s][sourceType=%s] (ssk)",messageId,sourceName.c_str(),sourcePath.c_str(),sourceType.c_str());

  bool isPlayingVideo = g_application.IsPlayingVideo();
  if (isPlayingVideo)
  {
    CLog::Log(LOGDEBUG,"CFileScanner::ShowSourcesStatusKaiDialog - don't show SourcesStatusKaiDialog because [isPlayingVideo=%d=TRUE]. [messageId=%d] (ssk)",isPlayingVideo,messageId);
    return true;
  }

  if (sourceName.IsEmpty())
  {
    CLog::Log(LOGERROR,"CFileScanner::ShowSourcesStatusKaiDialog - FAILED to show SourcesStatusKaiDialog because [sourceName=%s] is EMPTY. [messageId=%d] (ssk)",sourceName.c_str(),messageId);
    return false;
  }

  CStdString messageStruct = g_localizeStrings.Get(messageId);

  CStdString messageCaption = "";
  CStdString messageDescription = "";
  CGUIDialogKaiToast::PopupIconEnums messageIcon;
  CStdString messageIconColor = "";
  CStdString messageBgColor = "";

  CStdString validSourceName = sourceName;
  if ((int)validSourceName.size() > MAX_ADDED_SOURCE_NAME_SIZE_IN_KAI)
  {
    validSourceName = validSourceName.Left(MAX_ADDED_SOURCE_NAME_SIZE_IN_KAI - 3);
    validSourceName += "...";
  }

  switch(messageId)
  {
  case 51037:
  {
    messageDescription.Format(messageStruct.c_str(), validSourceName);
    messageIcon = CGUIDialogKaiToast::ICON_SCAN;
    messageIconColor = KAI_GREY_COLOR;
    messageBgColor = KAI_GREY_COLOR;
  }
  break;
  case 51046:
  {
    messageDescription.Format(messageStruct.c_str(), validSourceName);
    messageIcon = CGUIDialogKaiToast::ICON_SCAN;
    messageIconColor = KAI_GREEN_COLOR;
    messageBgColor = KAI_GREEN_COLOR;
  }
  break;
  case 51047:
  {
    if (sourcePath.IsEmpty() || sourceType.IsEmpty())
    {
      CLog::Log(LOGERROR,"CFileScanner::ShowSourcesStatusKaiDialog - FAILED to show SourcesStatusKaiDialog because [sourcePath=%s] or [sourceType=%s] is EMPTY. [messageId=%d] (ssk)",sourcePath.c_str(),sourceType.c_str(),messageId);
      return false;
    }

    int numOfResolvedFiles = 0;

    if (sourceType.CompareNoCase("video") == 0)
    {
      BOXEE::BXVideoDatabase video_db;
      numOfResolvedFiles = video_db.GetShareUnresolvedVideoFilesCount(_P(sourcePath), STATUS_ALL);
    }
    else if (sourceType.CompareNoCase("music") == 0)
    {
      BOXEE::BXAudioDatabase audio_db;
      numOfResolvedFiles = audio_db.GetShareUnresolvedAudioFilesCount(_P(sourcePath), STATUS_ALL);
    }
    else
    {
      CLog::Log(LOGERROR,"CFileScanner::ShowSourcesStatusKaiDialog - FAILED to show SourcesStatusKaiDialog because [sourceType=%s] ISN'T video or audio. [messageId=%d] (ssk)",sourceType.c_str(),messageId);
      return false;
    }

    messageCaption.Format(messageStruct.c_str(),numOfResolvedFiles,validSourceName);
    messageDescription = g_localizeStrings.Get(51048);

    if (numOfResolvedFiles > 0)
    {
      messageIcon = CGUIDialogKaiToast::ICON_CHECK;
      messageIconColor = KAI_GREEN_COLOR;
      messageBgColor = KAI_GREEN_COLOR;
    }
    else
    {
      messageIcon = CGUIDialogKaiToast::ICON_EXCLAMATION;
      messageIconColor = KAI_RED_COLOR;
      messageBgColor = KAI_RED_COLOR;
    }
  }
  break;
  default:
  {
    CLog::Log(LOGERROR,"CFileScanner::ShowSourcesStatusKaiDialog - FAILED to handle [messageId=%d] (ssk)",messageId);
    return false;
  }
  break;
  }

  CLog::Log(LOGDEBUG,"CFileScanner::ShowSourcesStatusKaiDialog - Going to show kai dialog with [messageCaption=%s][messageDescription=%s] (ssk)",messageCaption.c_str(),messageDescription.c_str());

  g_application.m_guiDialogKaiToast.QueueNotification(messageIcon, messageCaption, messageDescription, TOAST_DISPLAY_TIME, messageIconColor , messageBgColor);

  return true;
}
コード例 #9
0
ファイル: FileFactory.cpp プロジェクト: Bobbin007/xbmc
IFile* CFileFactory::CreateLoader(const CURL& url)
{
  CStdString strProtocol = url.GetProtocol();
  strProtocol.MakeLower();

  if (strProtocol == "zip") return new CFileZip();
#ifdef HAS_FILESYSTEM_RAR
  else if (strProtocol == "rar") return new CFileRar();
#endif
  else if (strProtocol == "musicdb") return new CFileMusicDatabase();
  else if (strProtocol == "videodb") return NULL;
  else if (strProtocol == "special") return new CFileSpecialProtocol();
  else if (strProtocol == "multipath") return new CMultiPathFile();
  else if (strProtocol == "file" || strProtocol.IsEmpty()) return new CFileHD();
  else if (strProtocol == "filereader") return new CFileFileReader();
#if defined(HAS_FILESYSTEM_CDDA) && defined(HAS_DVD_DRIVE)
  else if (strProtocol == "cdda") return new CFileCDDA();
#endif
#ifdef HAS_FILESYSTEM
  else if (strProtocol == "iso9660") return new CFileISO();
#endif
  else if(strProtocol == "udf") return new CFileUDF();
  if( g_application.getNetwork().IsAvailable() )
  {
    if (strProtocol == "http"
    ||  strProtocol == "https"
    ||  strProtocol == "dav"
    ||  strProtocol == "davs"
    ||  strProtocol == "ftp"
    ||  strProtocol == "ftpx"
    ||  strProtocol == "ftps"
    ||  strProtocol == "rss") return new CFileCurl();
#ifdef HAS_FILESYSTEM_SFTP
    else if (strProtocol == "sftp" || strProtocol == "ssh") return new CFileSFTP();
#endif
    else if (strProtocol == "shout") return new CFileShoutcast();
    else if (strProtocol == "lastfm") return new CFileLastFM();
    else if (strProtocol == "tuxbox") return new CFileTuxBox();
    else if (strProtocol == "hdhomerun") return new CFileHomeRun();
    else if (strProtocol == "myth") return new CMythFile();
    else if (strProtocol == "cmyth") return new CMythFile();
#ifdef HAS_FILESYSTEM_SMB
#ifdef _WIN32
    else if (strProtocol == "smb") return new CWINFileSMB();
#else
    else if (strProtocol == "smb") return new CFileSMB();
#endif
#endif
#ifdef HAS_FILESYSTEM_CCX
    else if (strProtocol == "xbms") return new CFileXBMSP();
#endif
#ifdef HAS_FILESYSTEM
#ifdef HAS_FILESYSTEM_RTV
    else if (strProtocol == "rtv") return new CFileRTV();
#endif
#ifdef HAS_FILESYSTEM_DAAP
    else if (strProtocol == "daap") return new CFileDAAP();
#endif
#endif
    else if (strProtocol == "myth") return new CMythFile();
    else if (strProtocol == "cmyth") return new CMythFile();
#ifdef HAS_FILESYSTEM_SAP
    else if (strProtocol == "sap") return new CSAPFile();
#endif
#ifdef HAS_FILESYSTEM_VTP
    else if (strProtocol == "vtp") return new CVTPFile();
#endif
  }

  CLog::Log(LOGWARNING, "%s - Unsupported protocol(%s) in %s", __FUNCTION__, strProtocol.c_str(), url.Get().c_str() );
  return NULL;
}
コード例 #10
0
bool CGUIDialogPluginSettings::GetCondition(const CStdString &condition, const int controlId)
{
  if (condition.IsEmpty()) return true;

  bool bCondition = true;
  bool bCompare = true;
  vector<CStdString> conditionVec;
  if (condition.Find("+") >= 0)
    CUtil::Tokenize(condition, conditionVec, "+");
  else
  {
    bCondition = false;
    bCompare = false;
    CUtil::Tokenize(condition, conditionVec, "|");
  }

  for (unsigned int i = 0; i < conditionVec.size(); i++)
  {
    vector<CStdString> condVec;
    if (!TranslateSingleString(conditionVec[i], condVec)) continue;

    const CGUIControl* control2 = GetControl(controlId + atoi(condVec[1]));

    CStdString value;
    switch (control2->GetControlType())
    {
      case CGUIControl::GUICONTROL_BUTTON:
        value = ((CGUIButtonControl*) control2)->GetLabel2();
        break;
      case CGUIControl::GUICONTROL_RADIO:
        value = ((CGUIRadioButtonControl*) control2)->IsSelected() ? "true" : "false";
        break;
      case CGUIControl::GUICONTROL_SPINEX:
        value.Format("%i", ((CGUISpinControlEx*) control2)->GetValue());
        break;
      default:
        break;
    }

    if (condVec[0].Equals("eq"))
    {
      if (bCompare)
        bCondition &= value.Equals(condVec[2]);
      else
        bCondition |= value.Equals(condVec[2]);
    }
    else if (condVec[0].Equals("!eq"))
    {
      if (bCompare)
        bCondition &= !value.Equals(condVec[2]);
      else
        bCondition |= !value.Equals(condVec[2]);
    }
    else if (condVec[0].Equals("gt"))
    {
      if (bCompare)
        bCondition &= (atoi(value) > atoi(condVec[2]));
      else
        bCondition |= (atoi(value) > atoi(condVec[2]));
    }
    else if (condVec[0].Equals("lt"))
    {
      if (bCompare)
        bCondition &= (atoi(value) < atoi(condVec[2]));
      else
        bCondition |= (atoi(value) < atoi(condVec[2]));
    }
  }
  return bCondition;
}
コード例 #11
0
void CRssReader::Process()
{
  while (GetQueueSize())
  {
    CSingleLock lock(*this);

    int iFeed = m_vecQueue.front();
    m_vecQueue.erase(m_vecQueue.begin());

    m_strFeed[iFeed] = "";
    m_strColors[iFeed] = "";

    CFileCurl http;
    http.SetUserAgent(g_settings.m_userAgent);
    http.SetTimeout(2);
    CStdString strXML;
    CStdString strUrl = m_vecUrls[iFeed];
    lock.Leave();

    int nRetries = 3;
    CURL url(strUrl);

    // we wait for the network to come up
    if ((url.GetProtocol() == "http" || url.GetProtocol() == "https") && !g_application.getNetwork().IsAvailable(true))
      strXML = "<rss><item><title>"+g_localizeStrings.Get(15301)+"</title></item></rss>";
    else
    {
      unsigned int starttime = XbmcThreads::SystemClockMillis();
      while ( (!m_bStop) && (nRetries > 0) )
      {
        unsigned int currenttimer = XbmcThreads::SystemClockMillis() - starttime;
        if (currenttimer > 15000)
        {
          CLog::Log(LOGERROR,"Timeout whilst retrieving %s", strUrl.c_str());
          http.Cancel();
          break;
        }
        nRetries--;

        if (url.GetProtocol() != "http" && url.GetProtocol() != "https")
        {
          CFile file;
          if (file.Open(strUrl))
          {
            char *yo = new char[(int)file.GetLength()+1];
            file.Read(yo,file.GetLength());
            yo[file.GetLength()] = '\0';
            strXML = yo;
            delete[] yo;
            break;
          }
        }
        else
          if (http.Get(strUrl, strXML))
          {
            CLog::Log(LOGDEBUG, "Got rss feed: %s", strUrl.c_str());
            break;
          }
      }
      http.Cancel();
    }
    if ((!strXML.IsEmpty()) && m_pObserver)
    {
      // erase any <content:encoded> tags (also unsupported by tinyxml)
      int iStart = strXML.Find("<content:encoded>");
      int iEnd = 0;
      while (iStart > 0)
      {
        // get <content:encoded> end position
        iEnd = strXML.Find("</content:encoded>", iStart) + 18;

        // erase the section
        strXML = strXML.erase(iStart, iEnd - iStart);

        iStart = strXML.Find("<content:encoded>");
      }

      if (Parse((LPSTR)strXML.c_str(),iFeed))
      {
        CLog::Log(LOGDEBUG, "Parsed rss feed: %s", strUrl.c_str());
      }
    }
  }
  UpdateObserver();
}
コード例 #12
0
void CGUIDialogPluginSettings::CreateControls()
{
  CGUISpinControlEx *pOriginalSpin = (CGUISpinControlEx*)GetControl(CONTROL_DEFAULT_SPIN);
  CGUIRadioButtonControl *pOriginalRadioButton = (CGUIRadioButtonControl *)GetControl(CONTROL_DEFAULT_RADIOBUTTON);
  CGUIButtonControl *pOriginalButton = (CGUIButtonControl *)GetControl(CONTROL_DEFAULT_BUTTON);
  CGUIImage *pOriginalImage = (CGUIImage *)GetControl(CONTROL_DEFAULT_SEPARATOR);
  CGUILabelControl *pOriginalLabel = (CGUILabelControl *)GetControl(CONTROL_DEFAULT_LABEL_SEPARATOR);

  if (!pOriginalSpin || !pOriginalRadioButton || !pOriginalButton || !pOriginalImage)
    return;

  pOriginalSpin->SetVisible(false);
  pOriginalRadioButton->SetVisible(false);
  pOriginalButton->SetVisible(false);
  pOriginalImage->SetVisible(false);
  if (pOriginalLabel)
    pOriginalLabel->SetVisible(false);

  // clear the category group
  CGUIControlGroupList *group = (CGUIControlGroupList *)GetControl(CONTROL_AREA);
  if (!group)
    return;

  // set our dialog heading
  SET_CONTROL_LABEL(CONTROL_HEADING_LABEL, m_strHeading);

  // Create our base path, used for type "fileenum" settings
  CStdString basepath = "Q:\\plugins\\";
  CUtil::AddFileToFolder(basepath, m_url.GetHostName(), basepath);
  CUtil::AddFileToFolder(basepath, m_url.GetFileName(), basepath);

  CGUIControl* pControl = NULL;
  int controlId = CONTROL_START_CONTROL;
  TiXmlElement *setting = m_settings.GetPluginRoot()->FirstChildElement("setting");
  while (setting)
  {
    const char *type = setting->Attribute("type");
    const char *id = setting->Attribute("id");
    CStdString values;
    if (setting->Attribute("values"))
      values = setting->Attribute("values");
    CStdString lvalues;
    if (setting->Attribute("lvalues"))
      lvalues = setting->Attribute("lvalues");
    CStdString entries;
    if (setting->Attribute("entries"))
      entries = setting->Attribute("entries");
    CStdString label;
    if (setting->Attribute("label") && atoi(setting->Attribute("label")) > 0)
      label.Format("$LOCALIZE[%s]", setting->Attribute("label"));
    else
      label = setting->Attribute("label");

    if (type)
    {
      if (strcmpi(type, "text") == 0 || strcmpi(type, "ipaddress") == 0 ||
        strcmpi(type, "integer") == 0 || strcmpi(type, "video") == 0 ||
        strcmpi(type, "music") == 0 || strcmpi(type, "pictures") == 0 ||
        strcmpi(type, "folder") == 0 || strcmpi(type, "programs") == 0 ||
        strcmpi(type, "files") == 0 || strcmpi(type, "action") == 0)
      {
        pControl = new CGUIButtonControl(*pOriginalButton);
        if (!pControl) return;
        ((CGUIButtonControl *)pControl)->SettingsCategorySetTextAlign(XBFONT_CENTER_Y);
        ((CGUIButtonControl *)pControl)->SetLabel(label);
        if (id)
          ((CGUIButtonControl *)pControl)->SetLabel2(m_settings.Get(id));
      }
      else if (strcmpi(type, "bool") == 0)
      {
        pControl = new CGUIRadioButtonControl(*pOriginalRadioButton);
        if (!pControl) return;
        ((CGUIRadioButtonControl *)pControl)->SetLabel(label);
        ((CGUIRadioButtonControl *)pControl)->SetSelected(m_settings.Get(id) == "true");
      }
      else if (strcmpi(type, "enum") == 0 || strcmpi(type, "labelenum") == 0)
      {
        vector<CStdString> valuesVec;
        vector<CStdString> entryVec;

        pControl = new CGUISpinControlEx(*pOriginalSpin);
        if (!pControl) return;
        ((CGUISpinControlEx *)pControl)->SetText(label);

        if (!lvalues.IsEmpty())
          CUtil::Tokenize(lvalues, valuesVec, "|");
        else
          CUtil::Tokenize(values, valuesVec, "|");
        if (!entries.IsEmpty())
          CUtil::Tokenize(entries, entryVec, "|");
        for (unsigned int i = 0; i < valuesVec.size(); i++)
        {
          int iAdd = i;
          if (entryVec.size() > i)
            iAdd = atoi(entryVec[i]);
          if (!lvalues.IsEmpty())
          {
            CStdString replace = g_localizeStringsTemp.Get(atoi(valuesVec[i]));
            if (replace.IsEmpty())
              replace = g_localizeStrings.Get(atoi(valuesVec[i]));
            ((CGUISpinControlEx *)pControl)->AddLabel(replace, iAdd);
          }
          else
            ((CGUISpinControlEx *)pControl)->AddLabel(valuesVec[i], iAdd);
        }
        if (strcmpi(type, "labelenum") == 0)
        { // need to run through all our settings and find the one that matches
          ((CGUISpinControlEx*) pControl)->SetValueFromLabel(m_settings.Get(id));
        }
        else
          ((CGUISpinControlEx*) pControl)->SetValue(atoi(m_settings.Get(id)));

      }
      else if (strcmpi(type, "fileenum") == 0)
      {
        pControl = new CGUISpinControlEx(*pOriginalSpin);
        if (!pControl) return;
        ((CGUISpinControlEx *)pControl)->SetText(label);

        //find Folders...
        CFileItemList items;
        CStdString enumpath;
        CUtil::AddFileToFolder(basepath, values, enumpath);
        CStdString mask;
        if (setting->Attribute("mask"))
          mask = setting->Attribute("mask");
        if (!mask.IsEmpty())
          CDirectory::GetDirectory(enumpath, items, mask);
        else
          CDirectory::GetDirectory(enumpath, items);

        int iItem = 0;
        for (int i = 0; i < items.Size(); ++i)
        {
          CFileItemPtr pItem = items[i];
          if ((mask.Equals("/") && pItem->m_bIsFolder) || !pItem->m_bIsFolder)
          {
            ((CGUISpinControlEx *)pControl)->AddLabel(pItem->GetLabel(), iItem);
            if (pItem->GetLabel().Equals(m_settings.Get(id)))
              ((CGUISpinControlEx *)pControl)->SetValue(iItem);
            iItem++;
          }
        }
      }
      else if (strcmpi(type, "lsep") == 0 && pOriginalLabel)
      {
        pControl = new CGUILabelControl(*pOriginalLabel);
        if (pControl)
          ((CGUILabelControl *)pControl)->SetLabel(label);
      }
      else if ((strcmpi(type, "sep") == 0 || strcmpi(type, "lsep") == 0) && pOriginalImage)
        pControl = new CGUIImage(*pOriginalImage);
    }

    if (pControl)
    {
      pControl->SetWidth(group->GetWidth());
      pControl->SetVisible(true);
      pControl->SetID(controlId);
      pControl->AllocResources();
      group->AddControl(pControl);
      pControl = NULL;
    }

    setting = setting->NextSiblingElement("setting");
    controlId++;
  }
  EnableControls();
}
コード例 #13
0
ファイル: PeripheralHID.cpp プロジェクト: maoueh/xbmc
CPeripheralHID::CPeripheralHID(const PeripheralType type, const PeripheralBusType busType, const CStdString &strLocation, const CStdString &strDeviceName, int iVendorId, int iProductId) :
  CPeripheral(type, busType, strLocation, strDeviceName.IsEmpty() ? g_localizeStrings.Get(35001) : strDeviceName, iVendorId, iProductId),
  m_bInitialised(false)
{
  m_features.push_back(FEATURE_HID);
}
コード例 #14
0
ファイル: File.cpp プロジェクト: Foozle303/xbmc
bool CFile::Exists(const CStdString& strFileName, bool bUseCache /* = true */)
{
  CURL url;
  
  try
  {
    if (strFileName.IsEmpty())
      return false;

    if (bUseCache)
    {
      bool bPathInCache;
      if (g_directoryCache.FileExists(strFileName, bPathInCache) )
        return true;
      if (bPathInCache)
        return false;
    }

    url = URIUtils::SubstitutePath(strFileName);
    auto_ptr<IFile> pFile(CFileFactory::CreateLoader(url));
    if (!pFile.get())
      return false;

    return pFile->Exists(url);
  }
#ifndef _LINUX
  catch (const win32_exception &e)
  {
    e.writelog(__FUNCTION__);
  }
#endif
  catch (CRedirectException *pRedirectEx)
  {
    // the file implementation decided this item should use a different implementation.
    // the exception will contain the new implementation and optional a redirected URL.
    CLog::Log(LOGDEBUG,"File::Exists - redirecting implementation for %s", strFileName.c_str());
    if (pRedirectEx && pRedirectEx->m_pNewFileImp)
    {
      auto_ptr<IFile> pImp(pRedirectEx->m_pNewFileImp);
      auto_ptr<CURL> pNewUrl(pRedirectEx->m_pNewUrl);
      delete pRedirectEx;
        
      if (pNewUrl.get())
      {
        if (pImp.get() && !pImp->Exists(*pNewUrl))
        {
          return false;
        }
      }
      else     
      {
        if (pImp.get() && !pImp->Exists(url))
        {
          return false;
        }
      }
    }
  }
  catch(...)
  {
    CLog::Log(LOGERROR, "%s - Unhandled exception", __FUNCTION__);
  }
  CLog::Log(LOGERROR, "%s - Error checking for %s", __FUNCTION__, strFileName.c_str());
  return false;
}
コード例 #15
0
ファイル: Id3Tag.cpp プロジェクト: JohnsonAugustine/xbmc-rbp
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;
}
コード例 #16
0
ファイル: PartyModeManager.cpp プロジェクト: Foozle303/xbmc
bool CPartyModeManager::Enable(PartyModeContext context /*= PARTYMODECONTEXT_MUSIC*/, const CStdString& strXspPath /*= ""*/)
{
  // Filter using our PartyMode xml file
  CSmartPlaylist playlist;
  CStdString partyModePath;
  bool playlistLoaded;

  m_bIsVideo = context == PARTYMODECONTEXT_VIDEO;
  if (!strXspPath.IsEmpty()) //if a path to a smartplaylist is supplied use it
    partyModePath = strXspPath;
  else if (m_bIsVideo)
    partyModePath = g_settings.GetUserDataItem("PartyMode-Video.xsp");
  else
    partyModePath = g_settings.GetUserDataItem("PartyMode.xsp");

  playlistLoaded=playlist.Load(partyModePath);

  if ( playlistLoaded )
  {
    m_type = playlist.GetType();
    if (context == PARTYMODECONTEXT_UNKNOWN)
    {
      //get it from the xsp file
      m_bIsVideo = (m_type.Equals("video") || m_type.Equals("mixed"));
    }

    if (m_type.Equals("mixed"))
      playlist.SetType("songs");

    if (m_type.Equals("mixed"))
      playlist.SetType("video");

    playlist.SetType(m_type);
  }
  else
  {
    m_strCurrentFilterMusic.Empty();
    m_strCurrentFilterVideo.Empty();
    m_type = m_bIsVideo ? "musicvideos" : "songs";
  }

  CGUIDialogProgress* pDialog = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  int iHeading = (m_bIsVideo ? 20250 : 20121);
  int iLine0 = (m_bIsVideo ? 20251 : 20123);
  pDialog->SetHeading(iHeading);
  pDialog->SetLine(0, iLine0);
  pDialog->SetLine(1, "");
  pDialog->SetLine(2, "");
  pDialog->StartModal();

  ClearState();
  unsigned int time = XbmcThreads::SystemClockMillis();
  vector< pair<int,int> > songIDs;
  if (m_type.Equals("songs") || m_type.Equals("mixed"))
  {
    CMusicDatabase db;
    if (db.Open())
    {
      set<CStdString> playlists;
      if ( playlistLoaded )
      {
        m_strCurrentFilterMusic = playlist.GetWhereClause(db, playlists);
        if (!m_strCurrentFilterMusic.empty())
          m_strCurrentFilterMusic = "WHERE " + m_strCurrentFilterMusic;
      }

      CLog::Log(LOGINFO, "PARTY MODE MANAGER: Registering filter:[%s]", m_strCurrentFilterMusic.c_str());
      m_iMatchingSongs = (int)db.GetSongIDs(m_strCurrentFilterMusic, songIDs);
      if (m_iMatchingSongs < 1 && m_type.Equals("songs"))
      {
        pDialog->Close();
        db.Close();
        OnError(16031, (CStdString)"Party mode found no matching songs. Aborting.");
        return false;
      }
    }
    else
    {
      pDialog->Close();
      OnError(16033, (CStdString)"Party mode could not open database. Aborting.");
      return false;
    }
    db.Close();
  }

  if (m_type.Equals("musicvideos") || m_type.Equals("mixed"))
  {
    vector< pair<int,int> > songIDs2;
    CVideoDatabase db;
    if (db.Open())
    {
      set<CStdString> playlists;
      if ( playlistLoaded )
      {
        m_strCurrentFilterVideo = playlist.GetWhereClause(db, playlists);
        if (!m_strCurrentFilterVideo.empty())
          m_strCurrentFilterVideo = "WHERE " + m_strCurrentFilterVideo;
      }

      CLog::Log(LOGINFO, "PARTY MODE MANAGER: Registering filter:[%s]", m_strCurrentFilterVideo.c_str());
      m_iMatchingSongs += (int)db.GetMusicVideoIDs(m_strCurrentFilterVideo, songIDs2);
      if (m_iMatchingSongs < 1)
      {
        pDialog->Close();
        db.Close();
        OnError(16031, (CStdString)"Party mode found no matching songs. Aborting.");
        return false;
      }
    }
    else
    {
      pDialog->Close();
      OnError(16033, (CStdString)"Party mode could not open database. Aborting.");
      return false;
    }
    db.Close();
    songIDs.insert(songIDs.end(),songIDs2.begin(),songIDs2.end());
  }

  // calculate history size
  if (m_iMatchingSongs < 50)
    m_songsInHistory = 0;
  else
    m_songsInHistory = (int)(m_iMatchingSongs/2);
  if (m_songsInHistory > 200)
    m_songsInHistory = 200;

  CLog::Log(LOGINFO,"PARTY MODE MANAGER: Matching songs = %i, History size = %i", m_iMatchingSongs, m_songsInHistory);
  CLog::Log(LOGINFO,"PARTY MODE MANAGER: Party mode enabled!");

  int iPlaylist = m_bIsVideo ? PLAYLIST_VIDEO : PLAYLIST_MUSIC;

  g_playlistPlayer.ClearPlaylist(iPlaylist);
  g_playlistPlayer.SetShuffle(iPlaylist, false);
  g_playlistPlayer.SetRepeat(iPlaylist, PLAYLIST::REPEAT_NONE);

  pDialog->SetLine(0, (m_bIsVideo ? 20252 : 20124));
  pDialog->Progress();
  // add initial songs
  if (!AddInitialSongs(songIDs))
  {
    pDialog->Close();
    return false;
  }
  CLog::Log(LOGDEBUG, "%s time for song fetch: %u",
            __FUNCTION__, XbmcThreads::SystemClockMillis() - time);

  // start playing
  g_playlistPlayer.SetCurrentPlaylist(iPlaylist);
  Play(0);

  pDialog->Close();
  // open now playing window
  if (m_type.Equals("songs"))
  {
    if (g_windowManager.GetActiveWindow() != WINDOW_MUSIC_PLAYLIST)
      g_windowManager.ActivateWindow(WINDOW_MUSIC_PLAYLIST);
  }

  // done
  m_bEnabled = true;
  return true;
}
コード例 #17
0
ファイル: MusicInfoScanner.cpp プロジェクト: mrmills3/xbmc
bool CMusicInfoScanner::DoScan(const CStdString& strDirectory)
{
  if (m_handle)
    m_handle->SetText(Prettify(strDirectory));

  /*
   * remove this path from the list we're processing. This must be done prior to
   * the check for file or folder exclusion to prevent an infinite while loop
   * in Process().
   */
  set<CStdString>::iterator it = m_pathsToScan.find(strDirectory);
  if (it != m_pathsToScan.end())
    m_pathsToScan.erase(it);

  // Discard all excluded files defined by m_musicExcludeRegExps

  CStdStringArray regexps = g_advancedSettings.m_audioExcludeFromScanRegExps;

  if (CUtil::ExcludeFileOrFolder(strDirectory, regexps))
    return true;

  // load subfolder
  CFileItemList items;
  CDirectory::GetDirectory(strDirectory, items, g_settings.m_musicExtensions + "|.jpg|.tbn|.lrc|.cdg");

  // sort and get the path hash.  Note that we don't filter .cue sheet items here as we want
  // to detect changes in the .cue sheet as well.  The .cue sheet items only need filtering
  // if we have a changed hash.
  items.Sort(SORT_METHOD_LABEL, SortOrderAscending);
  CStdString hash;
  GetPathHash(items, hash);

  // check whether we need to rescan or not
  CStdString dbHash;
  if ((m_flags & SCAN_RESCAN) || !m_musicDatabase.GetPathHash(strDirectory, dbHash) || dbHash != hash)
  { // path has changed - rescan
    if (dbHash.IsEmpty())
      CLog::Log(LOGDEBUG, "%s Scanning dir '%s' as not in the database", __FUNCTION__, strDirectory.c_str());
    else
      CLog::Log(LOGDEBUG, "%s Rescanning dir '%s' due to change", __FUNCTION__, strDirectory.c_str());

    // filter items in the sub dir (for .cue sheet support)
    items.FilterCueItems();
    items.Sort(SORT_METHOD_LABEL, SortOrderAscending);

    // and then scan in the new information
    if (RetrieveMusicInfo(items, strDirectory) > 0)
    {
      if (m_handle)
        OnDirectoryScanned(strDirectory);
    }

    // save information about this folder
    m_musicDatabase.SetPathHash(strDirectory, hash);
  }
  else
  { // path is the same - no need to rescan
    CLog::Log(LOGDEBUG, "%s Skipping dir '%s' due to no change", __FUNCTION__, strDirectory.c_str());
    m_currentItem += CountFiles(items, false);  // false for non-recursive

    // updated the dialog with our progress
    if (m_handle)
    {
      if (m_itemCount>0)
        m_handle->SetPercentage(m_currentItem/(double)m_itemCount*100);
      OnDirectoryScanned(strDirectory);
    }
  }

  // now scan the subfolders
  for (int i = 0; i < items.Size(); ++i)
  {
    CFileItemPtr pItem = items[i];

    if (m_bStop)
      break;
    // if we have a directory item (non-playlist) we then recurse into that folder
    if (pItem->m_bIsFolder && !pItem->IsParentFolder() && !pItem->IsPlayList())
    {
      CStdString strPath=pItem->GetPath();
      if (!DoScan(strPath))
      {
        m_bStop = true;
      }
    }
  }

  return !m_bStop;
}
コード例 #18
0
int CDVDVideoCodecFFmpeg::FilterOpen(const CStdString& filters)
{
  int result;

  if (m_pFilterGraph)
    FilterClose();

  if (filters.IsEmpty())
    return 0;

  if (!(m_pFilterGraph = m_dllAvFilter.avfilter_graph_alloc()))
  {
    CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - unable to alloc filter graph");
    return -1;
  }

  // CrHasher HACK (if an alternative becomes available use it!): In order to display the output
  // produced by a combination of filters we insert "nullsink" as the last filter and we use
  // its input pin as our output pin.
  //
  // input --> .. --> last_filter --> [in] nullsink [null]     [in] --> output
  //                                   |                        |
  //                                   |                        |
  //                                   +------------------------+
  //
  AVFilter* srcFilter = m_dllAvFilter.avfilter_get_by_name("buffer");
  AVFilter* outFilter = m_dllAvFilter.avfilter_get_by_name("nullsink"); // should be last filter in the graph for now

  CStdString args;

  args.Format("%d:%d:%d:%d:%d:%d:%d",
    m_pCodecContext->width,
    m_pCodecContext->height,
    m_pCodecContext->pix_fmt,
    m_pCodecContext->time_base.num,
    m_pCodecContext->time_base.den,
    m_pCodecContext->sample_aspect_ratio.num,
    m_pCodecContext->sample_aspect_ratio.den);

  if ((result = m_dllAvFilter.avfilter_graph_create_filter(&m_pFilterIn, srcFilter, "src", args, NULL, m_pFilterGraph)) < 0)
  {
    CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_graph_create_filter: src");
    return result;
  }

  if ((result = m_dllAvFilter.avfilter_graph_create_filter(&m_pFilterOut, outFilter, "out", NULL, NULL/*nullsink=>NULL*/, m_pFilterGraph)) < 0)
  {
    CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_graph_create_filter: out");
    return result;
  }

  if (!filters.empty())
  {
    AVFilterInOut* outputs = m_dllAvFilter.avfilter_inout_alloc();
    AVFilterInOut* inputs  = m_dllAvFilter.avfilter_inout_alloc();

    outputs->name    = m_dllAvUtil.av_strdup("in");
    outputs->filter_ctx = m_pFilterIn;
    outputs->pad_idx = 0;
    outputs->next    = NULL;

    inputs->name    = m_dllAvUtil.av_strdup("out");
    inputs->filter_ctx = m_pFilterOut;
    inputs->pad_idx = 0;
    inputs->next    = NULL;

    if ((result = m_dllAvFilter.avfilter_graph_parse(m_pFilterGraph, (const char*)m_filters.c_str(), &inputs, &outputs, NULL)) < 0)
    {
      CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_graph_parse");
      return result;
    }

    m_dllAvFilter.avfilter_inout_free(&outputs);
    m_dllAvFilter.avfilter_inout_free(&inputs);
  }
  else
  {
    if ((result = m_dllAvFilter.avfilter_link(m_pFilterIn, 0, m_pFilterOut, 0)) < 0)
    {
      CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_link");
      return result;
    }
  }

  if ((result = m_dllAvFilter.avfilter_graph_config(m_pFilterGraph, NULL)) < 0)
  {
    CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_graph_config");
    return result;
  }

  return result;
}
コード例 #19
0
ファイル: Autorun.cpp プロジェクト: Schischu/xbmc
/**
 * This method tries to determine what type of disc is located in the given drive and starts to play the content appropriately.
 */
bool CAutorun::RunDisc(IDirectory* pDir, const CStdString& strDrive, int& nAddedToPlaylist, bool bRoot, bool bypassSettings /* = false */, bool startFromBeginning /* = false */)
{
  bool bPlaying(false);
  CFileItemList vecItems;

  if ( !pDir->GetDirectory( strDrive, vecItems ) )
  {
    return false;
  }

  bool bAllowVideo = true;
//  bool bAllowPictures = true;
  bool bAllowMusic = true;
  if (!g_passwordManager.IsMasterLockUnlocked(false))
  {
    bAllowVideo = !g_settings.GetCurrentProfile().videoLocked();
//    bAllowPictures = !g_settings.GetCurrentProfile().picturesLocked();
    bAllowMusic = !g_settings.GetCurrentProfile().musicLocked();
  }

  // is this a root folder we have to check the content to determine a disc type
  if( bRoot )
  {
    // check root folders next, for normal structured dvd's
    for (int i = 0; i < vecItems.Size(); i++)
    {
      CFileItemPtr pItem = vecItems[i];

      // is the current item a (non system) folder?
      if (pItem->m_bIsFolder && pItem->GetPath() != "." && pItem->GetPath() != "..")
      {
        CStdString name = pItem->GetPath();
        URIUtils::RemoveSlashAtEnd(name);
        name = URIUtils::GetFileName(name);

        // Check if the current foldername indicates a DVD structure (name is "VIDEO_TS")
        if (name.Equals("VIDEO_TS") && bAllowVideo
        && (bypassSettings || g_guiSettings.GetBool("dvds.autorun")))
        {
          CStdString path = URIUtils::AddFileToFolder(pItem->GetPath(), "VIDEO_TS.IFO");
          if(!CFile::Exists(path))
            path = URIUtils::AddFileToFolder(pItem->GetPath(), "video_ts.ifo");
          CFileItem item(path, false);
          item.SetLabel(g_mediaManager.GetDiskLabel(strDrive));
          item.GetVideoInfoTag()->m_strFileNameAndPath = g_mediaManager.GetDiskUniqueId(strDrive);

          if (!startFromBeginning && !item.GetVideoInfoTag()->m_strFileNameAndPath.IsEmpty())
            item.m_lStartOffset = STARTOFFSET_RESUME;

          g_application.PlayFile(item, false);
          bPlaying = true;
          return true;
        }

        // Check if the current foldername indicates a Blu-Ray structure (default is "BDMV").
        // A BR should also include an "AACS" folder for encryption, Sony-BRs can also include update folders for PS3 (PS3_UPDATE / PS3_VPRM).
        // ToDo: for the time beeing, the DVD autorun settings are used to determine if the BR should be started automatically.
        if (name.Equals("BDMV") && bAllowVideo
        && (bypassSettings || g_guiSettings.GetBool("dvds.autorun")))
        {
          CFileItem item(URIUtils::AddFileToFolder(pItem->GetPath(), "index.bdmv"), false);
          item.SetLabel(g_mediaManager.GetDiskLabel(strDrive));
          item.GetVideoInfoTag()->m_strFileNameAndPath = g_mediaManager.GetDiskUniqueId(strDrive);

          if (!startFromBeginning && !item.GetVideoInfoTag()->m_strFileNameAndPath.IsEmpty())
            item.m_lStartOffset = STARTOFFSET_RESUME;

          g_application.PlayFile(item, false);
          bPlaying = true;
          return true;
        }

        // Video CDs can have multiple file formats. First we need to determine which one is used on the CD
        CStdString strExt;
        if (name.Equals("MPEGAV"))
          strExt = ".dat";
        if (name.Equals("MPEG2"))
          strExt = ".mpg";

        // If a file format was extracted we are sure this is a VCD. Autoplay if settings indicate we should.
        if (!strExt.IsEmpty() && bAllowVideo
             && (bypassSettings || g_guiSettings.GetBool("dvds.autorun")))
        {
          CFileItemList items;
          CDirectory::GetDirectory(pItem->GetPath(), items, strExt);
          if (items.Size())
          {
            items.Sort(SORT_METHOD_LABEL, SortOrderAscending);
            g_playlistPlayer.ClearPlaylist(PLAYLIST_VIDEO);
            g_playlistPlayer.Add(PLAYLIST_VIDEO, items);
            g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_VIDEO);
            g_playlistPlayer.Play(0);
            bPlaying = true;
            return true;
          }
        }
        /* Probably want this if/when we add some automedia action dialog...
        else if (pItem->GetPath().Find("PICTURES") != -1 && bAllowPictures
              && (bypassSettings))
        {
          bPlaying = true;
          CStdString strExec;
          strExec.Format("XBMC.RecursiveSlideShow(%s)", pItem->GetPath().c_str());
          CBuiltins::Execute(strExec);
          return true;
        }
        */
      }
    }
  }

  // check video first
  if (!nAddedToPlaylist && !bPlaying && (bypassSettings || g_guiSettings.GetBool("dvds.autorun")))
  {
    // stack video files
    CFileItemList tempItems;
    tempItems.Append(vecItems);
    if (g_settings.m_videoStacking)
      tempItems.Stack();
    CFileItemList itemlist;

    for (int i = 0; i < tempItems.Size(); i++)
    {
      CFileItemPtr pItem = tempItems[i];
      if (!pItem->m_bIsFolder && pItem->IsVideo())
      {
        bPlaying = true;
        if (pItem->IsStack())
        {
          // TODO: remove this once the app/player is capable of handling stacks immediately
          CStackDirectory dir;
          CFileItemList items;
          dir.GetDirectory(pItem->GetPath(), items);
          itemlist.Append(items);
        }
        else
          itemlist.Add(pItem);
      }
    }
    if (itemlist.Size())
    {
      if (!bAllowVideo)
      {
        if (!bypassSettings)
          return false;

        if (g_windowManager.GetActiveWindow() != WINDOW_VIDEO_FILES)
          if (!g_passwordManager.IsMasterLockUnlocked(true))
            return false;
      }
      g_playlistPlayer.ClearPlaylist(PLAYLIST_VIDEO);
      g_playlistPlayer.Add(PLAYLIST_VIDEO, itemlist);
      g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_VIDEO);
      g_playlistPlayer.Play(0);
    }
  }
  // then music
  if (!bPlaying && (bypassSettings || g_guiSettings.GetInt("audiocds.autoaction") == AUTOCD_PLAY) && bAllowMusic)
  {
    for (int i = 0; i < vecItems.Size(); i++)
    {
      CFileItemPtr pItem = vecItems[i];
      if (!pItem->m_bIsFolder && pItem->IsAudio())
      {
        nAddedToPlaylist++;
        g_playlistPlayer.Add(PLAYLIST_MUSIC, pItem);
      }
    }
  }
  /* Probably want this if/when we add some automedia action dialog...
  // and finally pictures
  if (!nAddedToPlaylist && !bPlaying && bypassSettings && bAllowPictures)
  {
    for (int i = 0; i < vecItems.Size(); i++)
    {
      CFileItemPtr pItem = vecItems[i];
      if (!pItem->m_bIsFolder && pItem->IsPicture())
      {
        bPlaying = true;
        CStdString strExec;
        strExec.Format("XBMC.RecursiveSlideShow(%s)", strDrive.c_str());
        CBuiltins::Execute(strExec);
        break;
      }
    }
  }
  */

  // check subdirs if we are not playing yet
  if (!bPlaying)
  {
    for (int i = 0; i < vecItems.Size(); i++)
    {
      CFileItemPtr  pItem = vecItems[i];
      if (pItem->m_bIsFolder)
      {
        if (pItem->GetPath() != "." && pItem->GetPath() != ".." )
        {
          if (RunDisc(pDir, pItem->GetPath(), nAddedToPlaylist, false, bypassSettings, startFromBeginning))
          {
            bPlaying = true;
            break;
          }
        }
      } // if (non system) folder
    } // for all items in directory
  } // if root folder

  return bPlaying;
}
コード例 #20
0
bool CAddonsDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  CStdString path1(strPath);
  URIUtils::RemoveSlashAtEnd(path1);
  CURL path(path1);
  items.ClearProperties();

  items.SetContent("addons");

  VECADDONS addons;
  // get info from repository
  bool reposAsFolders = true;
  if (path.GetHostName().Equals("enabled"))
  {
    CAddonMgr::Get().GetAllAddons(addons, true);
    items.SetProperty("reponame",g_localizeStrings.Get(24062));
    items.SetLabel(g_localizeStrings.Get(24062));
  }
  else if (path.GetHostName().Equals("disabled"))
  { // grab all disabled addons, including disabled repositories
    reposAsFolders = false;
    CAddonMgr::Get().GetAllAddons(addons, false, true, false);
    items.SetProperty("reponame",g_localizeStrings.Get(24039));
    items.SetLabel(g_localizeStrings.Get(24039));
  }
  else if (path.GetHostName().Equals("outdated"))
  {
    reposAsFolders = false;
    CAddonMgr::Get().GetAllOutdatedAddons(addons);
    items.SetProperty("reponame",g_localizeStrings.Get(24043));
    items.SetLabel(g_localizeStrings.Get(24043));
  }
  else if (path.GetHostName().Equals("repos"))
  {
    CAddonMgr::Get().GetAddons(ADDON_REPOSITORY,addons,true);
    items.SetLabel(g_localizeStrings.Get(24033)); // Get Add-ons
  }
  else if (path.GetHostName().Equals("sources"))
  {
    return GetScriptsAndPlugins(path.GetFileName(), items);
  }
  else if (path.GetHostName().Equals("all"))
  {
    CAddonDatabase database;
    database.Open();
    database.GetAddons(addons);
    items.SetProperty("reponame",g_localizeStrings.Get(24032));
    items.SetLabel(g_localizeStrings.Get(24032));
  }
  else if (path.GetHostName().Equals("search"))
  {
    CStdString search(path.GetFileName());
    if (search.IsEmpty() && !GetKeyboardInput(16017, search))
      return false;

    items.SetProperty("reponame",g_localizeStrings.Get(283));
    items.SetLabel(g_localizeStrings.Get(283));

    CAddonDatabase database;
    database.Open();
    database.Search(search, addons);
    GenerateListing(path, addons, items, true);

    path.SetFileName(search);
    items.SetPath(path.Get());
    return true;
  }
  else
  {
    reposAsFolders = false;
    AddonPtr addon;
    CAddonMgr::Get().GetAddon(path.GetHostName(),addon);
    if (!addon)
      return false;

    // ensure our repos are up to date
    CAddonInstaller::Get().UpdateRepos(false, true);
    CAddonDatabase database;
    database.Open();
    database.GetRepository(addon->ID(),addons);
    items.SetProperty("reponame",addon->Name());
    items.SetLabel(addon->Name());
  }

  if (path.GetFileName().IsEmpty())
  {
    if (!path.GetHostName().Equals("repos"))
    {
      for (int i=ADDON_UNKNOWN+1;i<ADDON_VIZ_LIBRARY;++i)
      {
        for (unsigned int j=0;j<addons.size();++j)
        {
          if (addons[j]->IsType((TYPE)i))
          {
            CFileItemPtr item(new CFileItem(TranslateType((TYPE)i,true)));
            item->SetPath(URIUtils::AddFileToFolder(strPath,TranslateType((TYPE)i,false)));
            item->m_bIsFolder = true;
            CStdString thumb = GetIcon((TYPE)i);
            if (!thumb.IsEmpty() && g_TextureManager.HasTexture(thumb))
              item->SetThumbnailImage(thumb);
            items.Add(item);
            break;
          }
        }
      }
      items.SetPath(strPath);
      return true;
    }
  }
  else
  {
    TYPE type = TranslateType(path.GetFileName());
    items.SetProperty("addoncategory",TranslateType(type, true));
    items.SetLabel(TranslateType(type, true));
    items.SetPath(strPath);

    // FIXME: Categorisation of addons needs adding here
    for (unsigned int j=0;j<addons.size();++j)
    {
      if (!addons[j]->IsType(type))
        addons.erase(addons.begin()+j--);
    }
  }

  items.SetPath(strPath);
  GenerateListing(path, addons, items, reposAsFolders);
  // check for available updates
  if (path.GetHostName().Equals("enabled"))
  {
    CAddonDatabase database;
    database.Open();
    for (int i=0;i<items.Size();++i)
    {
      AddonPtr addon2;
      database.GetAddon(items[i]->GetProperty("Addon.ID").asString(),addon2);
      if (addon2 && addon2->Version() > AddonVersion(items[i]->GetProperty("Addon.Version").asString())
                 && !database.IsAddonBlacklisted(addon2->ID(),addon2->Version().c_str()))
      {
        items[i]->SetProperty("Addon.Status",g_localizeStrings.Get(24068));
        items[i]->SetProperty("Addon.UpdateAvail", true);
      }
    }
  }
  if (path.GetHostName().Equals("repos") && items.Size() > 1)
  {
    CFileItemPtr item(new CFileItem("addons://all/",true));
    item->SetLabel(g_localizeStrings.Get(24032));
    items.Add(item);
  }

  return true;
}
コード例 #21
0
ファイル: WatchDog.cpp プロジェクト: marksuman/boxee
void WatchDog::CPingJob::DoWork()
{
  if (!m_jobHandler)
  {
    CLog::Log(LOGWARNING,"CPingJob::DoWork - Can't execute the job. [jobHandler=NULL] (ping)");
    return;
  }

  CLog::Log(LOGDEBUG,"CPingJob::DoWork - Enter function. [server=%d][internet=%d] (ping)",m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());


  if (!m_jobHandler->IsConnectedToInternet())
  {
    CLog::Log(LOGDEBUG,"CPingJob::DoWork - There is no internet connection -> Don't try to send ping. [server=%d][internet=%d] (ping)",m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());
    return;
  }

  std::set<CStdString> allowedPaths;
  std::set<CStdString> allowedExt;

  allowedPaths.insert("special://xbmc");
  allowedPaths.insert("special://home");
  allowedPaths.insert("special://temp");

  allowedExt.insert(".xml");
  allowedExt.insert(".png");
  allowedExt.insert(".gif");
  allowedExt.insert(".jpg");
  allowedExt.insert(".tbn");

  // test boxee
  BOXEE::BXCurl curl;

  CStdString strClientPingVersion = "";
  CStdString pingUrl = "";

  bool succeed = InitPingRequest(pingUrl,strClientPingVersion);

  CLog::Log(LOGDEBUG,"CPingJob::DoWork - Call to InitPingRequest() returned [%d]. [strClientPingVersion=%s][pingUrl=%s] (ping)",succeed,strClientPingVersion.c_str(),pingUrl.c_str());

  if(!succeed)
  {
    CLog::Log(LOGERROR,"CPingJob::DoWork - Call to InitPingParams() FAILED. [retVal=%d] (ping)",succeed);
    return;
  }

  int nClientPingVersion = atoi(strClientPingVersion.c_str());

  CLog::Log(LOGWARNING,"CPingJob::DoWork - Going to check ping. [server=%d][internet=%d] (ping)",m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());

  std::string strResp = curl.HttpGetString(pingUrl, false);
  g_application.SetBoxeeServerIP(curl.GetServerIP());

  long retCode = curl.GetLastRetCode();
  CLog::Log(LOGWARNING,"CPingJob::DoWork - Check ping returned [retCode=%ld][Response-IsEmpty=%d]. [server=%d][internet=%d] (ping)",retCode,strResp.empty(),m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());

  m_jobHandler->SetIsConnectedToServer((retCode == 200));

  BOXEE::BXXMLDocument reader;
  if (strResp.empty())
  {
    CLog::Log(LOGDEBUG,"WatchDog::Process - Not handling server response to [pingUrl=%s] because it is empty (ping)",pingUrl.c_str());
    return;
  }

  if(!reader.LoadFromString(strResp))
  {
    CLog::Log(LOGERROR,"WatchDog::Process - Not handling server response to [pingUrl=%s] because failed to load it to BXXMLDocument (ping)",pingUrl.c_str());
    return;
  }

  TiXmlElement* root = reader.GetRoot();

  if(!root)
  {
    CLog::Log(LOGERROR,"WatchDog::Process - Failed to get root from BXXMLDocument of the ping response (ping)");
    return;
  }

  if((strcmp(root->Value(),"ping") != 0))
  {
    CLog::Log(LOGERROR,"WatchDog::Process - Failed to parse ping response because the root tag ISN'T <ping> (ping)");
    return;
  }

  CLog::Log(LOGDEBUG,"CPingJob::DoWork - The root tag <ping> was found. Going to parse the ping response (ping)");

  TiXmlElement* pingChildElem = NULL;
  pingChildElem = root->FirstChildElement();

  while (pingChildElem)
  {
    if (strcmp(pingChildElem->Value(), "cmds") == 0)
    {
      CLog::Log(LOGDEBUG,"CPingJob::DoWork - The <cmds> tag was found (ping)");

      CStdString strServerPingVersion = "";
      strServerPingVersion = pingChildElem->Attribute("ping_version");
      int nServerPingVersion = atoi(strServerPingVersion.c_str());

      if (nServerPingVersion > nClientPingVersion)
      {
        CLog::Log(LOGDEBUG,"CPingJob::DoWork - Because [nServerPingVersion=%d] > [%d=nClientPingVersion] going to parse the <cmds> tag (ping)",nServerPingVersion,nClientPingVersion);

        TiXmlElement* cmdsChildElem = NULL;
        cmdsChildElem = pingChildElem->FirstChildElement();

        while (cmdsChildElem)
        {
          if (strcmp(cmdsChildElem->Value(), "download") == 0)
          {
            CStdString url = cmdsChildElem->Attribute("url");
            CStdString local = cmdsChildElem->Attribute("local");
            CStdString hash = cmdsChildElem->Attribute("hash");

            CLog::Log(LOGDEBUG,"CPingJob::DoWork - Found <download> tag with attributes [url=%s][local=%s][hash=%s] (ping)",url.c_str(),local.c_str(),hash.c_str());

            if (!url.IsEmpty() && !local.IsEmpty())
            {
              CStdString strDir;
              CStdString strLocal = local;
              CStdString ext = CUtil::GetExtension(strLocal);
              CStdString strName = CUtil::GetFileName(strLocal);
              CUtil::GetDirectory(strLocal, strDir);
              if (allowedExt.find(ext.c_str()) != allowedExt.end() && allowedPaths.find(CUtil::GetSpecialPathPrefix(local).c_str()) != allowedPaths.end() && CUtil::CreateDirectoryEx(strDir))
              {
                CLog::Log(LOGDEBUG,"CPingJob::DoWork - Going to download [url=%s] (ping)",url.c_str());
                BoxeeUtils::SafeDownload(url.c_str(), strLocal.c_str(), hash);
              }
            }
          }
          else if (strcmp(cmdsChildElem->Value(), "remove") == 0)
          {
            CStdString local = cmdsChildElem->Attribute("path");

            CLog::Log(LOGDEBUG,"CPingJob::DoWork - Found <remove> tag with attributes [local=%s] (ping)",local.c_str());

            CStdString strLocal = local;
            CStdString ext = CUtil::GetExtension(strLocal);
            if (allowedExt.find(ext.c_str()) != allowedExt.end() && allowedPaths.find(CUtil::GetSpecialPathPrefix(local).c_str()) != allowedPaths.end())
            {
              CLog::Log(LOGDEBUG,"CPingJob::DoWork - Going to delete [strLocal=%s] (ping)",strLocal.c_str());
              ::DeleteFile(strLocal);
            }
          }

          cmdsChildElem = cmdsChildElem->NextSiblingElement();
        }

        if (!strServerPingVersion.IsEmpty())
        {
          // currently - version is the only info kept so we take a shortcut...
          TiXmlDocument *infoDoc = NULL;
          CStdString strInfoDoc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><info><ping_version>"+strServerPingVersion+"</ping_version></info>";
          BOXEE::BXXMLDocument newinfo;
          if (newinfo.LoadFromString(strInfoDoc))
          {
            infoDoc = newinfo.GetRoot()->GetDocument();
          }

          if (infoDoc)
          {
            infoDoc->SaveFile(PTH_IC(BXINFO_FILE_PATH));
          }
        }
      }
      else
      {
        CLog::Log(LOGDEBUG,"CPingJob::DoWork - Because [nServerPingVersion=%d] <= [%d=nClientPingVersion] NOT going to parse the <cmds> tag (ping)",nServerPingVersion,nClientPingVersion);
      }
    }
#ifndef HAS_EMBEDDED
    else if (strcmp(pingChildElem->Value(),"version_update") == 0)
    {
      CLog::Log(LOGDEBUG,"CPingJob::DoWork - The <version_update> tag was found (ping)");

      succeed = g_boxeeVersionUpdateManager.HandleVersionUpdate(root, pingChildElem);
      CLog::Log(LOGDEBUG,"CPingJob::DoWork - Call to CBoxeeVersionUpdateManager::HandleVersionUpdate returned [%d]",succeed);
    }
#else
    else if (strcmp(pingChildElem->Value(),"timestamp") == 0)
    {
      time_t currentTime = time(NULL);
      time_t timeStamp = 0;
      char *endptr;

      CLog::Log(LOGDEBUG,"CPingJob::DoWork - The <timestamp> tag was found (ping)");

      CStdString strTimestamp = pingChildElem->Attribute("utc");

      timeStamp = strtol(strTimestamp.c_str(), &endptr, 10);

      if(abs(currentTime - timeStamp) > 60 * 60 )
      {
        IHalServices& client = CHalServicesFactory::GetInstance();
        client.SetTime(strTimestamp);
      }
    }
#endif

    pingChildElem = pingChildElem->NextSiblingElement();
  }

  //CLog::Log(LOGDEBUG,"CPingJob::DoWork - Exit function. [server=%d][internet=%d] (ping)",m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());
}
コード例 #22
0
ファイル: GUIMediaWindow.cpp プロジェクト: mbosner/xbmc
bool CGUIMediaWindow::OnMessage(CGUIMessage& message)
{
  switch ( message.GetMessage() )
  {
  case GUI_MSG_WINDOW_DEINIT:
    {
      m_iSelectedItem = m_viewControl.GetSelectedItem();
      m_iLastControl = GetFocusedControlID();
      CGUIWindow::OnMessage(message);
      // Call ClearFileItems() after our window has finished doing any WindowClose
      // animations
      ClearFileItems();
      return true;
    }
    break;

  case GUI_MSG_CLICKED:
    {
      int iControl = message.GetSenderId();
      if (iControl == CONTROL_BTNVIEWASICONS)
      {
        // view as control could be a select button
        int viewMode = 0;
        const CGUIControl *control = GetControl(CONTROL_BTNVIEWASICONS);
        if (control && control->GetControlType() != CGUIControl::GUICONTROL_BUTTON)
        {
          CGUIMessage msg(GUI_MSG_ITEM_SELECTED, GetID(), CONTROL_BTNVIEWASICONS);
          OnMessage(msg);
          viewMode = m_viewControl.GetViewModeNumber(msg.GetParam1());
        }
        else
          viewMode = m_viewControl.GetNextViewMode();

        if (m_guiState.get())
          m_guiState->SaveViewAsControl(viewMode);

        UpdateButtons();
        return true;
      }
      else if (iControl == CONTROL_BTNSORTASC) // sort asc
      {
        if (m_guiState.get())
          m_guiState->SetNextSortOrder();
        UpdateFileList();
        return true;
      }
      else if (iControl == CONTROL_BTNSORTBY) // sort by
      {
        if (m_guiState.get())
          m_guiState->SetNextSortMethod();
        UpdateFileList();
        return true;
      }
      else if (iControl == CONTROL_BTN_FILTER)
      {
        if (GetControl(iControl)->GetControlType() == CGUIControl::GUICONTROL_EDIT)
        { // filter updated
          CGUIMessage selected(GUI_MSG_ITEM_SELECTED, GetID(), CONTROL_BTN_FILTER);
          OnMessage(selected);
          OnFilterItems(selected.GetLabel());
          return true;
        }
        if (GetProperty("filter").IsEmpty())
        {
          CStdString filter = GetProperty("filter");
          CGUIDialogKeyboard::ShowAndGetFilter(filter, false);
          SetProperty("filter", filter);
        }
        else
          OnFilterItems("");
        return true;
      }
      else if (m_viewControl.HasControl(iControl))  // list/thumb control
      {
        int iItem = m_viewControl.GetSelectedItem();
        int iAction = message.GetParam1();
        if (iItem < 0) break;
        if (iAction == ACTION_SELECT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK)
        {
          OnSelect(iItem);
        }
        else if (iAction == ACTION_CONTEXT_MENU || iAction == ACTION_MOUSE_RIGHT_CLICK)
        {
          OnPopupMenu(iItem);
          return true;
        }
      }
    }
    break;

  case GUI_MSG_SETFOCUS:
    {
      if (m_viewControl.HasControl(message.GetControlId()) && m_viewControl.GetCurrentControl() != message.GetControlId())
      {
        m_viewControl.SetFocused();
        return true;
      }
    }
    break;

  case GUI_MSG_NOTIFY_ALL:
    { // Message is received even if this window is inactive
      if (message.GetParam1() == GUI_MSG_WINDOW_RESET)
      {
        m_vecItems->m_strPath = "?";
        return true;
      }
      else if ( message.GetParam1() == GUI_MSG_REFRESH_THUMBS )
      {
        for (int i = 0; i < m_vecItems->Size(); i++)
          m_vecItems->Get(i)->FreeMemory(true);
        break;  // the window will take care of any info images
      }
      else if (message.GetParam1() == GUI_MSG_REMOVED_MEDIA)
      {
        if (m_vecItems->IsVirtualDirectoryRoot() && IsActive())
        {
          int iItem = m_viewControl.GetSelectedItem();
          Update(m_vecItems->m_strPath);
          m_viewControl.SetSelectedItem(iItem);
        }
        else if (m_vecItems->IsRemovable())
        { // check that we have this removable share still
          if (!m_rootDir.IsInSource(m_vecItems->m_strPath))
          { // don't have this share any more
            if (IsActive()) Update("");
            else
            {
              m_history.ClearPathHistory();
              m_vecItems->m_strPath="";
            }
          }
        }

        return true;
      }
      else if (message.GetParam1()==GUI_MSG_UPDATE_SOURCES)
      { // State of the sources changed, so update our view
        if (m_vecItems->IsVirtualDirectoryRoot() && IsActive())
        {
          int iItem = m_viewControl.GetSelectedItem();
          Update(m_vecItems->m_strPath);
          m_viewControl.SetSelectedItem(iItem);
        }
        return true;
      }
      else if (message.GetParam1()==GUI_MSG_UPDATE && IsActive())
      {
        if (message.GetNumStringParams())
        {
          m_vecItems->m_strPath = message.GetStringParam();
          if (message.GetParam2()) // param2 is used for resetting the history
            SetHistoryForPath(m_vecItems->m_strPath);
        }
        // clear any cached listing
        m_vecItems->RemoveDiscCache(GetID());
        Update(m_vecItems->m_strPath);
      }
      else if (message.GetParam1()==GUI_MSG_UPDATE_ITEM && message.GetItem())
      {
        CFileItemPtr newItem = boost::static_pointer_cast<CFileItem>(message.GetItem());
        if (IsActive())
        {
          if (m_vecItems->UpdateItem(newItem.get()) && message.GetParam2() == 1)
          { // need the list updated as well
            UpdateFileList();
          }
        }
        else if (newItem)
        { // need to remove the disc cache
          CFileItemList items;
          URIUtils::GetDirectory(newItem->m_strPath, items.m_strPath);
          items.RemoveDiscCache(GetID());
        }
      }
      else if (message.GetParam1()==GUI_MSG_UPDATE_PATH)
      {
        if (IsActive())
        {
          if((message.GetStringParam() == m_vecItems->m_strPath) ||
             (m_vecItems->IsMultiPath() && XFILE::CMultiPathDirectory::HasPath(m_vecItems->m_strPath, message.GetStringParam())))
          {
            Update(m_vecItems->m_strPath);
          }
        }
      }
      else if (message.GetParam1() == GUI_MSG_FILTER_ITEMS && IsActive())
      {
        CStdString filter(GetProperty("filter"));
        if (message.GetParam2() == 1) // append
          filter += message.GetStringParam();
        else if (message.GetParam2() == 2)
        { // delete
          if (filter.size())
            filter = filter.Left(filter.size() - 1);
        }
        else
          filter = message.GetStringParam();
        OnFilterItems(filter);
        return true;
      }
      else
        return CGUIWindow::OnMessage(message);

      return true;
    }
    break;
  case GUI_MSG_PLAYBACK_STARTED:
  case GUI_MSG_PLAYBACK_ENDED:
  case GUI_MSG_PLAYBACK_STOPPED:
  case GUI_MSG_PLAYLIST_CHANGED:
  case GUI_MSG_PLAYLISTPLAYER_STOPPED:
  case GUI_MSG_PLAYLISTPLAYER_STARTED:
  case GUI_MSG_PLAYLISTPLAYER_CHANGED:
    { // send a notify all to all controls on this window
      CGUIMessage msg(GUI_MSG_NOTIFY_ALL, GetID(), 0, GUI_MSG_REFRESH_LIST);
      OnMessage(msg);
      break;
    }
  case GUI_MSG_CHANGE_VIEW_MODE:
    {
      int viewMode = 0;
      if (message.GetParam1())  // we have an id
        viewMode = m_viewControl.GetViewModeByID(message.GetParam1());
      else if (message.GetParam2())
        viewMode = m_viewControl.GetNextViewMode((int)message.GetParam2());

      if (m_guiState.get())
        m_guiState->SaveViewAsControl(viewMode);
      UpdateButtons();
      return true;
    }
    break;
  case GUI_MSG_CHANGE_SORT_METHOD:
    {
      if (m_guiState.get())
      {
        if (message.GetParam1())
          m_guiState->SetCurrentSortMethod((int)message.GetParam1());
        else if (message.GetParam2())
          m_guiState->SetNextSortMethod((int)message.GetParam2());
      }
      UpdateFileList();
      return true;
    }
    break;
  case GUI_MSG_CHANGE_SORT_DIRECTION:
    {
      if (m_guiState.get())
        m_guiState->SetNextSortOrder();
      UpdateFileList();
      return true;
    }
    break;
  case GUI_MSG_WINDOW_INIT:
    {
      if (m_vecItems->m_strPath == "?")
        m_vecItems->m_strPath.Empty();
      CStdString dir = message.GetStringParam(0);
      const CStdString &ret = message.GetStringParam(1);
      bool returning = ret.CompareNoCase("return") == 0;
      if (!dir.IsEmpty())
      {
        m_history.ClearPathHistory();
        // ensure our directory is valid
        dir = GetStartFolder(dir);
        if (!returning || m_vecItems->m_strPath.Left(dir.GetLength()) != dir)
        { // we're not returning to the same path, so set our directory to the requested path
          m_vecItems->m_strPath = dir;
        }
        // check for network up
        if (URIUtils::IsRemote(m_vecItems->m_strPath) && !WaitForNetwork())
          m_vecItems->m_strPath.Empty();
        SetHistoryForPath(m_vecItems->m_strPath);
      }
      if (message.GetParam1() != WINDOW_INVALID)
      { // first time to this window - make sure we set the root path
        m_startDirectory = returning ? dir : "";
      }
    }
    break;
  }

  return CGUIWindow::OnMessage(message);
}
コード例 #23
0
bool URIUtils::GetParentPath(const CStdString& strPath, CStdString& strParent)
{
  strParent = "";

  CURL url(strPath);
  CStdString strFile = url.GetFileName();
  if ( URIUtils::ProtocolHasParentInHostname(url.GetProtocol()) && strFile.IsEmpty())
  {
    strFile = url.GetHostName();
    return GetParentPath(strFile, strParent);
  }
  else if (url.GetProtocol() == "stack")
  {
    CStackDirectory dir;
    CFileItemList items;
    dir.GetDirectory(strPath,items);
    GetDirectory(items[0]->GetPath(),items[0]->m_strDVDLabel);
    if (items[0]->m_strDVDLabel.Mid(0,6).Equals("rar://") || items[0]->m_strDVDLabel.Mid(0,6).Equals("zip://"))
      GetParentPath(items[0]->m_strDVDLabel, strParent);
    else
      strParent = items[0]->m_strDVDLabel;
    for( int i=1;i<items.Size();++i)
    {
      GetDirectory(items[i]->GetPath(),items[i]->m_strDVDLabel);
      if (items[0]->m_strDVDLabel.Mid(0,6).Equals("rar://") || items[0]->m_strDVDLabel.Mid(0,6).Equals("zip://"))
        items[i]->SetPath(GetParentPath(items[i]->m_strDVDLabel));
      else
        items[i]->SetPath(items[i]->m_strDVDLabel);

      GetCommonPath(strParent,items[i]->GetPath());
    }
    return true;
  }
  else if (url.GetProtocol() == "multipath")
  {
    // get the parent path of the first item
    return GetParentPath(CMultiPathDirectory::GetFirstPath(strPath), strParent);
  }
  else if (url.GetProtocol() == "plugin")
  {
    if (!url.GetOptions().IsEmpty())
    {
      url.SetOptions("");
      strParent = url.Get();
      return true;
    }
    if (!url.GetFileName().IsEmpty())
    {
      url.SetFileName("");
      strParent = url.Get();
      return true;
    }
    if (!url.GetHostName().IsEmpty())
    {
      url.SetHostName("");
      strParent = url.Get();
      return true;
    }
    return true;  // already at root
  }
  else if (url.GetProtocol() == "special")
  {
    if (HasSlashAtEnd(strFile) )
      strFile = strFile.Left(strFile.size() - 1);
    if(strFile.ReverseFind('/') < 0)
      return false;
  }
  else if (strFile.size() == 0)
  {
    if (url.GetHostName().size() > 0)
    {
      // we have an share with only server or workgroup name
      // set hostname to "" and return true to get back to root
      url.SetHostName("");
      strParent = url.Get();
      return true;
    }
    return false;
  }

  if (HasSlashAtEnd(strFile) )
  {
    strFile = strFile.Left(strFile.size() - 1);
  }

  int iPos = strFile.ReverseFind('/');
#ifndef _LINUX
  if (iPos < 0)
  {
    iPos = strFile.ReverseFind('\\');
  }
#endif
  if (iPos < 0)
  {
    url.SetFileName("");
    strParent = url.Get();
    return true;
  }

  strFile = strFile.Left(iPos);

  AddSlashAtEnd(strFile);

  url.SetFileName(strFile);
  strParent = url.Get();
  return true;
}
コード例 #24
0
ファイル: SpecialProtocol.cpp プロジェクト: morristech/xbmc
CStdString CSpecialProtocol::TranslatePath(const CURL &url)
{
  // check for special-protocol, if not, return
  if (!url.GetProtocol().Equals("special"))
  {
#if defined(_LINUX) && defined(_DEBUG)
    CStdString path(url.Get());
    if (path.length() >= 2 && path[1] == ':')
    {
      CLog::Log(LOGWARNING, "Trying to access old style dir: %s\n", path.c_str());
     // printf("Trying to access old style dir: %s\n", path.c_str());
    }
#endif

    return url.Get();
  }

  CStdString FullFileName = url.GetFileName();

  CStdString translatedPath;
  CStdString FileName;
  CStdString RootDir;

  // Split up into the special://root and the rest of the filename
  int pos = FullFileName.Find('/');
  if (pos != -1 && pos > 1)
  {
    RootDir = FullFileName.Left(pos);

    if (pos < FullFileName.GetLength())
      FileName = FullFileName.Mid(pos + 1);
  }
  else
    RootDir = FullFileName;

  if (RootDir.Equals("subtitles"))
    URIUtils::AddFileToFolder(g_guiSettings.GetString("subtitles.custompath"), FileName, translatedPath);
  else if (RootDir.Equals("userdata"))
    URIUtils::AddFileToFolder(CProfilesManager::Get().GetUserDataFolder(), FileName, translatedPath);
  else if (RootDir.Equals("database"))
    URIUtils::AddFileToFolder(CProfilesManager::Get().GetDatabaseFolder(), FileName, translatedPath);
  else if (RootDir.Equals("thumbnails"))
    URIUtils::AddFileToFolder(CProfilesManager::Get().GetThumbnailsFolder(), FileName, translatedPath);
  else if (RootDir.Equals("recordings") || RootDir.Equals("cdrips"))
    URIUtils::AddFileToFolder(g_guiSettings.GetString("audiocds.recordingpath", false), FileName, translatedPath);
  else if (RootDir.Equals("screenshots"))
    URIUtils::AddFileToFolder(g_guiSettings.GetString("debug.screenshotpath", false), FileName, translatedPath);
  else if (RootDir.Equals("musicplaylists"))
    URIUtils::AddFileToFolder(CUtil::MusicPlaylistsLocation(), FileName, translatedPath);
  else if (RootDir.Equals("videoplaylists"))
    URIUtils::AddFileToFolder(CUtil::VideoPlaylistsLocation(), FileName, translatedPath);
  else if (RootDir.Equals("skin"))
    URIUtils::AddFileToFolder(g_graphicsContext.GetMediaDir(), FileName, translatedPath);
  else if (RootDir.Equals("logpath"))
    URIUtils::AddFileToFolder(g_settings.m_logFolder, FileName, translatedPath);


  // from here on, we have our "real" special paths
  else if (RootDir.Equals("xbmc") ||
           RootDir.Equals("xbmcbin") ||
           RootDir.Equals("home") ||
           RootDir.Equals("userhome") ||
           RootDir.Equals("temp") ||
           RootDir.Equals("profile") ||
           RootDir.Equals("masterprofile") ||
           RootDir.Equals("frameworks"))
  {
    CStdString basePath = GetPath(RootDir);
    if (!basePath.IsEmpty())
      URIUtils::AddFileToFolder(basePath, FileName, translatedPath);
    else
      translatedPath.clear();
  }

  // check if we need to recurse in
  if (URIUtils::IsSpecial(translatedPath))
  { // we need to recurse in, as there may be multiple translations required
    return TranslatePath(translatedPath);
  }

  // Validate the final path, just in case
  return CUtil::ValidatePath(translatedPath);
}
コード例 #25
0
ファイル: DVDVideoCodecFFmpeg.cpp プロジェクト: jdelon02/xbmc
int CDVDVideoCodecFFmpeg::FilterOpen(const CStdString& filters, bool scale)
{
  int result;
  AVBufferSinkParams *buffersink_params;

  if (m_pFilterGraph)
    FilterClose();

  if (filters.IsEmpty() && !scale)
    return 0;

  if (m_pHardware)
  {
    CLog::Log(LOGWARNING, "CDVDVideoCodecFFmpeg::FilterOpen - skipped opening filters on hardware decode");
    return 0;
  }

  if (!(m_pFilterGraph = m_dllAvFilter.avfilter_graph_alloc()))
  {
    CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - unable to alloc filter graph");
    return -1;
  }

  AVFilter* srcFilter = m_dllAvFilter.avfilter_get_by_name("buffer");
  AVFilter* outFilter = m_dllAvFilter.avfilter_get_by_name("buffersink"); // should be last filter in the graph for now

  CStdString args;

  args.Format("%d:%d:%d:%d:%d:%d:%d",
    m_pCodecContext->width,
    m_pCodecContext->height,
    m_pCodecContext->pix_fmt,
    m_pCodecContext->time_base.num,
    m_pCodecContext->time_base.den,
    m_pCodecContext->sample_aspect_ratio.num,
    m_pCodecContext->sample_aspect_ratio.den);

  if ((result = m_dllAvFilter.avfilter_graph_create_filter(&m_pFilterIn, srcFilter, "src", args, NULL, m_pFilterGraph)) < 0)
  {
    CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_graph_create_filter: src");
    return result;
  }

  buffersink_params = m_dllAvFilter.av_buffersink_params_alloc();
  buffersink_params->pixel_fmts = &m_formats[0];
#ifdef FF_API_OLD_VSINK_API
  if ((result = m_dllAvFilter.avfilter_graph_create_filter(&m_pFilterOut, outFilter, "out", NULL, (void*)buffersink_params->pixel_fmts, m_pFilterGraph)) < 0)
#else
  if ((result = m_dllAvFilter.avfilter_graph_create_filter(&m_pFilterOut, outFilter, "out", NULL, buffersink_params, m_pFilterGraph)) < 0)
#endif
  {
    m_dllAvUtil.av_freep(&buffersink_params);
    CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_graph_create_filter: out");
    return result;
  }
  m_dllAvUtil.av_freep(&buffersink_params);

  if (!filters.empty())
  {
    AVFilterInOut* outputs = m_dllAvFilter.avfilter_inout_alloc();
    AVFilterInOut* inputs  = m_dllAvFilter.avfilter_inout_alloc();

    outputs->name    = m_dllAvUtil.av_strdup("in");
    outputs->filter_ctx = m_pFilterIn;
    outputs->pad_idx = 0;
    outputs->next    = NULL;

    inputs->name    = m_dllAvUtil.av_strdup("out");
    inputs->filter_ctx = m_pFilterOut;
    inputs->pad_idx = 0;
    inputs->next    = NULL;

    if ((result = m_dllAvFilter.avfilter_graph_parse(m_pFilterGraph, (const char*)m_filters.c_str(), &inputs, &outputs, NULL)) < 0)
    {
      CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_graph_parse");
      return result;
    }

    m_dllAvFilter.avfilter_inout_free(&outputs);
    m_dllAvFilter.avfilter_inout_free(&inputs);
  }
  else
  {
    if ((result = m_dllAvFilter.avfilter_link(m_pFilterIn, 0, m_pFilterOut, 0)) < 0)
    {
      CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_link");
      return result;
    }
  }

  if ((result = m_dllAvFilter.avfilter_graph_config(m_pFilterGraph, NULL)) < 0)
  {
    CLog::Log(LOGERROR, "CDVDVideoCodecFFmpeg::FilterOpen - avfilter_graph_config");
    return result;
  }

  return result;
}
コード例 #26
0
ファイル: GUIMediaWindow.cpp プロジェクト: Kr0nZ/boxee
/*!
  \brief Overwrite to fill fileitems from a source
  \param strDirectory Path to read
  \param items Fill with items specified in \e strDirectory
  */
bool CGUIMediaWindow::GetDirectory(const CStdString &strDirectory, CFileItemList &items)
{
  // cleanup items
  if (items.Size())
    items.Clear();

  CStdString strParentPath=m_history.GetParentPath();

  CLog::Log(LOGDEBUG,"CGUIMediaWindow::GetDirectory (%s)", strDirectory.c_str());
  CLog::Log(LOGDEBUG,"  ParentPath = [%s]", strParentPath.c_str());

  // see if we can load a previously cached folder
  CFileItemList cachedItems(strDirectory);
  if (!strDirectory.IsEmpty() && cachedItems.Load())
  {
    items.Assign(cachedItems);
  }
  else
  {
    unsigned int time = CTimeUtils::GetTimeMS();

    if (!m_rootDir.GetDirectory(strDirectory, items))
      return false;

    // took over a second, and not normally cached, so cache it
    if (time + 1000 < CTimeUtils::GetTimeMS() && items.CacheToDiscIfSlow())
      items.Save();

    // if these items should replace the current listing, then pop it off the top
    if (items.GetReplaceListing())
      m_history.RemoveParentPath();
  }

  if (m_guiState.get() && !m_guiState->HideParentDirItems() && !items.m_strPath.IsEmpty())
  {
    CFileItemPtr pItem(new CFileItem(".."));
    pItem->m_strPath = strParentPath;
    pItem->m_bIsFolder = true;
    pItem->m_bIsShareOrDrive = false;
    items.AddFront(pItem, 0);
  }

  int iWindow = GetID();
  CStdStringArray regexps;

  if (iWindow == WINDOW_VIDEO_FILES)
    regexps = g_advancedSettings.m_videoExcludeFromListingRegExps;
  if (iWindow == WINDOW_MUSIC_FILES)
    regexps = g_advancedSettings.m_audioExcludeFromListingRegExps;
  if (iWindow == WINDOW_PICTURES)
    regexps = g_advancedSettings.m_pictureExcludeFromListingRegExps;

  if (regexps.size())
  {
    for (int i=0; i < items.Size();)
    {
      if (CUtil::ExcludeFileOrFolder(items[i]->m_strPath, regexps))
        items.Remove(i);
      else
        i++;
    }
  }

  // clear window properties at root or plugin root
  if (items.IsVirtualDirectoryRoot() || items.IsPluginRoot())
    ClearProperties();

  return true;
}
コード例 #27
0
ファイル: DirectoryTuxBox.cpp プロジェクト: Gemini88/xbmc-1
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;
  URIUtils::RemoveSlashAtEnd(strRoot);

  //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
      CXBMCTinyXML 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
    }
  }
  items.SetContent("movies");
  return result;
}
コード例 #28
0
ファイル: GUIMediaWindow.cpp プロジェクト: Kr0nZ/boxee
// \brief Set window to a specific directory
// \param strDirectory The directory to be displayed in list/thumb control
// This function calls OnPrepareFileItems() and OnFinalizeFileItems()
bool CGUIMediaWindow::Update(const CStdString &strDirectory)
{
  // get selected item
  int iItem = m_viewControl.GetSelectedItem();
  CStdString strSelectedItem = "";
  if (iItem >= 0 && iItem < m_vecItems->Size())
  {
    CFileItemPtr pItem = m_vecItems->Get(iItem);
    if (!pItem->IsParentFolder())
    {
      GetDirectoryHistoryString(pItem.get(), strSelectedItem);
    }
  }

  CStdString strOldDirectory = m_vecItems->m_strPath;

  m_history.SetSelectedItem(strSelectedItem, strOldDirectory);

  ClearFileItems();
  m_vecItems->ClearProperties();
  m_vecItems->SetThumbnailImage("");

  if (!GetDirectory(strDirectory, *m_vecItems))
  {
    CLog::Log(LOGWARNING,"CGUIMediaWindow::GetDirectory(%s) failed", strDirectory.c_str());
    // if the directory is the same as the old directory, then we'll return
    // false.  Else, we assume we can get the previous directory
    if (strDirectory.Equals(strOldDirectory))
      return false;

    // We assume, we can get the parent
    // directory again, but we have to
    // return false to be able to eg. show
    // an error message.
    CStdString strParentPath = m_history.GetParentPath();
    m_history.RemoveParentPath();
    Update(strParentPath);
    return false;
  }

  // if we're getting the root source listing
  // make sure the path history is clean
  if (strDirectory.IsEmpty())
    m_history.ClearPathHistory();

  int iWindow = GetID();
  bool bOkay = (iWindow == WINDOW_MUSIC_FILES || iWindow == WINDOW_VIDEO_FILES || iWindow == WINDOW_FILES || iWindow == WINDOW_PICTURES || iWindow == WINDOW_PROGRAMS);
  if (strDirectory.IsEmpty() && bOkay && (m_vecItems->Size() == 0 || !m_guiState->DisableAddSourceButtons())) // add 'add source button'
  {
    CStdString strLabel = g_localizeStrings.Get(1026);
    CFileItemPtr pItem(new CFileItem(strLabel));
    pItem->m_strPath = "add";
    pItem->SetThumbnailImage("DefaultAddSource.png");
    pItem->SetLabel(strLabel);
    pItem->SetLabelPreformated(true);
    m_vecItems->Add(pItem);
  }
  m_iLastControl = GetFocusedControlID();

  //  Ask the derived class if it wants to load additional info
  //  for the fileitems like media info or additional
  //  filtering on the items, setting thumbs.
  OnPrepareFileItems(*m_vecItems);

  m_vecItems->FillInDefaultIcons();

  m_guiState.reset(CGUIViewState::GetViewState(GetID(), *m_vecItems));

  FormatAndSort(*m_vecItems);

  // Ask the devived class if it wants to do custom list operations,
  // eg. changing the label
  OnFinalizeFileItems(*m_vecItems);
  UpdateButtons();

  m_viewControl.SetItems(*m_vecItems);

  strSelectedItem = m_history.GetSelectedItem(m_vecItems->m_strPath);

  bool bSelectedFound = false;
  //int iSongInDirectory = -1;
  for (int i = 0; i < m_vecItems->Size(); ++i)
  {
    CFileItemPtr pItem = m_vecItems->Get(i);

    // Update selected item
    if (!bSelectedFound)
    {
      CStdString strHistory;
      GetDirectoryHistoryString(pItem.get(), strHistory);
      if (strHistory == strSelectedItem)
      {
        m_viewControl.SetSelectedItem(i);
        bSelectedFound = true;
      }
    }
  }

  // if we haven't found the selected item, select the first item
  if (!bSelectedFound)
    m_viewControl.SetSelectedItem(0);

  m_history.AddPath(m_vecItems->m_strPath);

  //m_history.DumpPathHistory();

  return true;
}
コード例 #29
0
ファイル: SmartPlayList.cpp プロジェクト: mindcorrosive/xbmc
CStdString CSmartPlaylistRule::GetWhereClause(CDatabase &db, const CStdString& strType) const
{
  SEARCH_OPERATOR op = m_operator;
  if ((strType == "tvshows" || strType == "episodes") && m_field == FieldYear)
  { // special case for premiered which is a date rather than a year
    // TODO: SMARTPLAYLISTS do we really need this, or should we just make this field the premiered date and request a date?
    if (op == OPERATOR_EQUALS)
      op = OPERATOR_CONTAINS;
    else if (op == OPERATOR_DOES_NOT_EQUAL)
      op = OPERATOR_DOES_NOT_CONTAIN;
  }

  CStdString operatorString, negate;
  if (GetFieldType(m_field) == TEXTIN_FIELD)
  {
    if (op == OPERATOR_DOES_NOT_EQUAL)
      negate = " NOT";
  }
  else
  {
    // the comparison piece
    switch (op)
    {
    case OPERATOR_CONTAINS:
      operatorString = " LIKE '%%%s%%'"; break;
    case OPERATOR_DOES_NOT_CONTAIN:
      negate = " NOT"; operatorString = " LIKE '%%%s%%'"; break;
    case OPERATOR_EQUALS:
      operatorString = " LIKE '%s'"; break;
    case OPERATOR_DOES_NOT_EQUAL:
      negate = " NOT"; operatorString = " LIKE '%s'"; break;
    case OPERATOR_STARTS_WITH:
      operatorString = " LIKE '%s%%'"; break;
    case OPERATOR_ENDS_WITH:
      operatorString = " LIKE '%%%s'"; break;
    case OPERATOR_AFTER:
    case OPERATOR_GREATER_THAN:
    case OPERATOR_IN_THE_LAST:
      operatorString = " > '%s'"; break;
    case OPERATOR_BEFORE:
    case OPERATOR_LESS_THAN:
    case OPERATOR_NOT_IN_THE_LAST:
      operatorString = " < '%s'"; break;
    case OPERATOR_TRUE:
      operatorString = " = 1"; break;
    case OPERATOR_FALSE:
      negate = " NOT "; operatorString = " = 0"; break;
    default:
      break;
    }
  }

  // FieldInProgress does not have any values in m_parameter, it works on the operator
  if (m_field == FieldInProgress && (strType == "movies" || strType == "episodes"))
    return "idFile " + negate + " in (select idFile from bookmark where type = 1)";

  // now the query parameter
  CStdString wholeQuery;
  for (vector<CStdString>::const_iterator it = m_parameter.begin(); it != m_parameter.end(); /* it++ is done further down */)
  {
    CStdString parameter;
    if (GetFieldType(m_field) == TEXTIN_FIELD)
    {
      CStdStringArray split;
      StringUtils::SplitString(*it, ",", split);
      for (CStdStringArray::iterator itIn = split.begin(); itIn != split.end(); ++itIn)
      {
        if (!parameter.IsEmpty())
          parameter += ",";
        parameter += db.PrepareSQL("'%s'", (*itIn).Trim().c_str());
      }
      parameter = " IN (" + parameter + ")";
    }
    else
      parameter = db.PrepareSQL(operatorString.c_str(), it->c_str());

    if (GetFieldType(m_field) == DATE_FIELD)
    {
      if (m_operator == OPERATOR_IN_THE_LAST || m_operator == OPERATOR_NOT_IN_THE_LAST)
      { // translate time period
        CDateTime date=CDateTime::GetCurrentDateTime();
        CDateTimeSpan span;
        span.SetFromPeriod(*it);
        date-=span;
        parameter = db.PrepareSQL(operatorString.c_str(), date.GetAsDBDate().c_str());
      }
    }
    else if (m_field == FieldTime)
    { // translate time to seconds
      CStdString seconds; seconds.Format("%i", StringUtils::TimeStringToSeconds(*it));
      parameter = db.PrepareSQL(operatorString.c_str(), seconds.c_str());
    }

    CStdString query;
    CStdString table;
    if (strType == "songs")
    {
      table = "songview";

      if (m_field == FieldGenre)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT idSong FROM song_genre, genre WHERE song_genre.idGenre = genre.idGenre AND genre.strGenre" + parameter + ")";
      else if (m_field == FieldArtist)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT idSong FROM song_artist, artist WHERE song_artist.idArtist = artist.idArtist AND artist.strArtist" + parameter + ")";
      else if (m_field == FieldAlbumArtist)
        query = negate + " (" + table + ".idAlbum IN (SELECT idAlbum FROM album_artist, artist WHERE album_artist.idArtist = artist.idArtist AND artist.strArtist" + parameter + ")";
      else if (m_field == FieldLastPlayed && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = "lastPlayed is NULL or lastPlayed" + parameter;
    }
    else if (strType == "albums")
    {
      table = "albumview";

      if (m_field == FieldGenre)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT song.idAlbum FROM song, song_genre, genre WHERE song.idSong = song_genre.idGenre AND song_genre.idGenre = genre.idGenre AND genre.strGenre" + parameter + ")";
      else if (m_field == FieldArtist)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT song.idAlbum FROM song, song_artist, artists WHERE song.idSong = song_artist.idSong AND song_artist.idArtist = artist.idArtist AND artist.strArtist" + parameter + ")";
      else if (m_field == FieldAlbumArtist)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT album_artist.idAlbum FROM album_artist, artist WHERE album_artist.idArtist = artist.idArtist AND artist.strArtist" + parameter + ")";
    }
    else if (strType == "movies")
    {
      table = "movieview";

      if (m_field == FieldGenre)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM genrelinkmovie JOIN genre ON genre.idGenre=genrelinkmovie.idGenre WHERE genre.strGenre" + parameter + ")";
      else if (m_field == FieldDirector)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM directorlinkmovie JOIN actors ON actors.idActor=directorlinkmovie.idDirector WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldActor)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM actorlinkmovie JOIN actors ON actors.idActor=actorlinkmovie.idActor WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldWriter)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM writerlinkmovie JOIN actors ON actors.idActor=writerlinkmovie.idWriter WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldStudio)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM studiolinkmovie JOIN studio ON studio.idStudio=studiolinkmovie.idStudio WHERE studio.strStudio" + parameter + ")";
      else if (m_field == FieldCountry)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM countrylinkmovie JOIN country ON country.idCountry=countrylinkmovie.idCountry WHERE country.strCountry" + parameter + ")";
      else if (m_field == FieldTrailer)
        query = negate + GetField(m_field, strType) + "!= ''";
      else if ((m_field == FieldLastPlayed || m_field == FieldDateAdded) && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = GetField(m_field, strType) + " IS NULL OR " + GetField(m_field, strType) + parameter;
      else if (m_field == FieldInProgress)
        query = table + ".idFile " + negate + " IN (SELECT idFile FROM bookmark WHERE type = 1)";
      else if (m_field == FieldSet)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM setlinkmovie JOIN sets ON sets.idSet=setlinkmovie.idSet WHERE sets.strSet" + parameter + ")";
      else if (m_field == FieldTag)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMedia FROM taglinks JOIN tag ON tag.idTag = taglinks.idTag WHERE tag.strTag" + parameter + " AND taglinks.media_type = 'movie')";
    }
    else if (strType == "musicvideos")
    {
      table = "musicvideoview";

      if (m_field == FieldGenre)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMVideo FROM genrelinkmusicvideo JOIN genre ON genre.idGenre=genrelinkmusicvideo.idGenre WHERE genre.strGenre" + parameter + ")";
      else if (m_field == FieldArtist)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMVideo FROM artistlinkmusicvideo JOIN actors ON actors.idActor=artistlinkmusicvideo.idArtist WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldStudio)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMVideo FROM studiolinkmusicvideo JOIN studio ON studio.idStudio=studiolinkmusicvideo.idStudio WHERE studio.strStudio" + parameter + ")";
      else if (m_field == FieldDirector)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMVideo FROM directorlinkmusicvideo JOIN actors ON actors.idActor=directorlinkmusicvideo.idDirector WHERE actors.strActor" + parameter + ")";
      else if ((m_field == FieldLastPlayed || m_field == FieldDateAdded) && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = GetField(m_field, strType) + " IS NULL OR " + GetField(m_field, strType) + parameter;
    }
    else if (strType == "tvshows")
    {
      table = "tvshowview";

      if (m_field == FieldGenre)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM genrelinktvshow JOIN genre ON genre.idGenre=genrelinktvshow.idGenre WHERE genre.strGenre" + parameter + ")";
      else if (m_field == FieldDirector)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM directorlinktvshow JOIN actors ON actors.idActor=directorlinktvshow.idDirector WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldActor)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM actorlinktvshow JOIN actors ON actors.idActor=actorlinktvshow.idActor WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldStudio)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM tvshowview WHERE " + GetField(m_field, strType) + parameter + ")";
      else if (m_field == FieldMPAA)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM tvshowview WHERE " + GetField(m_field, strType) + parameter + ")";
      else if (m_field == FieldDateAdded && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = GetField(FieldDateAdded, strType) + " IS NULL OR " + GetField(FieldDateAdded, strType) + parameter;
    }
    else if (strType == "episodes")
    {
      table = "episodeview";

      if (m_field == FieldGenre)
        query = table + ".idShow" + negate + " IN (SELECT idShow FROM genrelinktvshow JOIN genre ON genre.idGenre=genrelinktvshow.idGenre WHERE genre.strGenre" + parameter + ")";
      else if (m_field == FieldDirector)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM directorlinkepisode JOIN actors ON actors.idActor=directorlinkepisode.idDirector WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldActor)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM actorlinkepisode JOIN actors ON actors.idActor=actorlinkepisode.idActor WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldWriter)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM writerlinkepisode JOIN actors ON actors.idActor=writerlinkepisode.idWriter WHERE actors.strActor" + parameter + ")";
      else if ((m_field == FieldLastPlayed || m_field == FieldDateAdded) && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = GetField(m_field, strType) + " IS NULL OR " + GetField(m_field, strType) + parameter;
      else if (m_field == FieldInProgress)
        query = table + ".idFile " + negate + " IN (SELECT idFile FROM bookmark WHERE type = 1)";
      else if (m_field == FieldStudio)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM episodeview WHERE strStudio" + parameter + ")";
      else if (m_field == FieldMPAA)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM episodeview WHERE mpaa" + parameter + ")";
    }
    if (m_field == FieldVideoResolution)
      query = table + ".idFile" + negate + GetVideoResolutionQuery(*it);
    else if (m_field == FieldAudioChannels)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE iAudioChannels " + parameter + ")";
    else if (m_field == FieldVideoCodec)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE strVideoCodec " + parameter + ")";
    else if (m_field == FieldAudioCodec)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE strAudioCodec " + parameter + ")";
    else if (m_field == FieldAudioLanguage)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE strAudioLanguage " + parameter + ")";
    else if (m_field == FieldSubtitleLanguage)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE strSubtitleLanguage " + parameter + ")";
    else if (m_field == FieldVideoAspectRatio)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE fVideoAspect " + parameter + ")";
    if (m_field == FieldPlaycount && strType != "songs" && strType != "albums")
    { // playcount IS stored as NULL OR number IN video db
      if ((m_operator == OPERATOR_EQUALS && it->Equals("0")) ||
          (m_operator == OPERATOR_DOES_NOT_EQUAL && !it->Equals("0")) ||
          (m_operator == OPERATOR_LESS_THAN))
      {
        CStdString field = GetField(FieldPlaycount, strType);
        query = field + " IS NULL OR " + field + parameter;
      }
    }

    if (query.IsEmpty() && m_field != FieldNone)
      query = GetField(m_field,strType) + negate + parameter;
    
    it++;
    if (query.Equals(negate + parameter))
      query = "1";

    query = "(" + query + ")";
    if (it != m_parameter.end())
      query += " OR ";

    wholeQuery += query;
  }

  return wholeQuery;
}
コード例 #30
0
bool CPlayListXML::Load( const CStdString& strFileName )
{
  CXBMCTinyXML xmlDoc;

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

  Clear();

  // Try to load the file as XML. If it does not load, return an error.
  if ( !xmlDoc.LoadFile( strFileName ) )
  {
    CLog::Log(LOGERROR, "Playlist %s has invalid format/malformed xml", strFileName.c_str());
    return false;
  }

  TiXmlElement *pRootElement = xmlDoc.RootElement();

  // If the stream does not contain "streams", still ok. Not an error.
  if ( !pRootElement || stricmp( pRootElement->Value(), "streams" ) )
  {
    CLog::Log(LOGERROR, "Playlist %s has no <streams> root", strFileName.c_str());
    return false;
  }

  TiXmlElement* pSet = pRootElement->FirstChildElement("stream");

  while ( pSet )
  {
    // Get parameters
    CStdString url = GetString( pSet, "url" );
    CStdString name = GetString( pSet, "name" );
    CStdString category = GetString( pSet, "category" );
    CStdString lang = GetString( pSet, "lang" );
    CStdString channel = GetString( pSet, "channel" );
    CStdString lockpass = GetString( pSet, "lockpassword" );

    // If url is empty, it doesn't make any sense
    if ( !url.IsEmpty() )
    {
       // If the name is empty, use url
       if ( name.IsEmpty() )
         name = url;

       // Append language to the name, and also set as metadata
       if ( !lang.IsEmpty() )
         name += " [" + lang + "]";

       CStdString info = name;
       CFileItemPtr newItem( new CFileItem(info) );
       newItem->SetPath(url);

       // Set language as metadata
       if ( !lang.IsEmpty() )
         newItem->SetProperty("language", lang.c_str() );

       // Set category as metadata
       if ( !category.IsEmpty() )
         newItem->SetProperty("category", category.c_str() );

       // Set channel as extra info and as metadata
       if ( !channel.IsEmpty() )
       {
         newItem->SetProperty("remotechannel", channel.c_str() );
         newItem->SetExtraInfo( "Channel: " + channel );
       }

       if ( !lockpass.IsEmpty() )
       {
         newItem->m_strLockCode = lockpass;
         newItem->m_iHasLock = 2;
         newItem->m_iLockMode = LOCK_MODE_NUMERIC;
       }

       Add(newItem);
    }
    else
       CLog::Log(LOGERROR, "Playlist entry %s in file %s has missing <url> tag", name.c_str(), strFileName.c_str());

    pSet = pSet->NextSiblingElement("stream");
  }

  return true;
}