' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' This file can be replaced  in one of the future versions,
' so please if you want to modify it, make  a copy, do your
' modifications  in that copy and  change Scripts.ini  file 
' appropriately. 
' If you do not do this, you will lose all  your changes in
' this script when you install a new version of MediaMonkey
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Option Explicit     ' report undefined variables, ...

' SDB variable is connected to MediaMonkey application object

Sub ExportOPML
  ' Open inifile and get last used directory
  Dim iniF
  Set iniF = SDB.IniFile

  ' Let user select the output path
  Dim path
  path = iniF.StringValue( "Scripts", "LastExportOPMLDir")

  path = SDB.SelectFolder( path, SDB.Localize( "Select where to export the OPML file."))

  If path="" Then
    Exit Sub
  End If

  If Right( path, 1)<>"\" Then
    path = path & "\"
  End If

  ' Write selected directory to the ini file
  iniF.StringValue( "Scripts", "LastExportOPMLDir") = path
  Set iniF = Nothing

  ' Connect to the FileSystemObject
  Dim fso
  Set fso = SDB.Tools.FileSystem

  ' Use progress to notify user about the current action
  Dim Progress, ExpText
  Set Progress = SDB.Progress
  ExpText = SDB.Localize("Exporting...")
  Progress.Text = ExpText

  Dim fout, title
  title = SDB.Localize("My podcasts")

  ' Create the OPML file for export
  Set fout = fso.CreateTextFile( path & fso.CorrectFilename( title) & ".opml", True)
  fout.WriteLine "<?xml version=""1.0"" encoding=""ISO-8859-1""?>"
  fout.WriteLine "<opml version=""1.0"">"
  fout.WriteLine "<head>"
  fout.WriteLine "<title>" & title & "</title>"
  fout.WriteLine "</head>" 
  fout.WriteLine "<body>" 
 
  ' Write all subscribed podcasts to the OPML file   
  Dim strSQL, qrySQL, outline, i
  strSQL = "SELECT PodcastName, PodcastURL FROM Podcasts ORDER BY PodcastName"
  Set qrySQL = SDB.Database.OpenSQL( strSQL)
  While Not qrySQL.EOF
    if ( qrySQL.StringByName("PodcastURL") <> "") then ' We want only subscribed podcasts
      i = i + 1
      outline = "<outline id = """ & i & """ text=""" & qrySQL.StringByName("PodcastName") & """"
      outline = outline & " type=""rss"" xmlUrl=""" & qrySQL.StringByName("PodcastURL") & """ />"
      fout.WriteLine outline
    end if    
    qrySQL.Next
  Wend

  fout.WriteLine "</body>" 
  fout.WriteLine "</opml>" 
  fout.Close
End Sub
