#!/usr/bin/env python

"""rssify.py: Generate an RSS XML file from all files in a directory.

https://github.com/tonyborries/YtChannelRss
"""

__author__ = "tonyborries"
__copyright__ = "Copyright 2015, tonyborries"
__credits__ = ["tonyborries"]
__license__ = "MIT"
__maintainer__ = "tonyborries"
__email__ = "<EMAIL>"

import sys
import os
import getopt
import datetime

import PyRSS2Gen

def usage():
    sys.stderr.write(
"""  Usage: %s [ -h ] [ -v ] -o outfile -i inputdir -b url

    -h, --help        Show this usage message and exit.
    -v, --verbose     Verbose Output to StdErr.
    -i, --inputdir    Source Directory of files to build into RSS.
    -o, --output      Output File - where to store the RSS File.
    -b, --basepath    URL path prepended to files to build the full path
""" % sys.argv[0])


class Entry():
    title = ""
    target_url = ""
    abs_filepath = ""

    def __str__(self):
        return self.title + " - " + self.target_url + " (" + self.abs_filepath + ")"

    def getAsRssItem(self):
        statinfo = os.stat(self.abs_filepath)
        file_length = statinfo.st_size

        return PyRSS2Gen.RSSItem(
            title=self.title,
            link=self.target_url,
            description="No Description for " + self.title,
            guid=PyRSS2Gen.Guid(self.target_url),
            pubDate=datetime.datetime.now(),
            enclosure=PyRSS2Gen.Enclosure(self.target_url, file_length, 'audio/mpeg'),
            )


class FoundFiles():
    entries = []

    def addEntry(self, title, target_url, abs_filepath):
        entry = Entry()
        entry.title = title
        entry.target_url = target_url
        entry.abs_filepath = abs_filepath
        self.entries.append(entry)

    def getNumEntries(self):
        return len(self.entries)

    def printEntries(self):
        for entry in self.entries:
            sys.stderr.write(str(entry) + "\n")

    def WriteRss(self, outfile_name, verbose=False):

        # Build RSS
        rssItems = []
        for entry in self.entries:
            rssItems.append(entry.getAsRssItem())

        if verbose:
            sys.stderr.write("Building RSS with " + str(len(rssItems)) + " Items\n")

        rss = PyRSS2Gen.RSS2(
            title="TonyB's casts by rssify",
            link="",
            description="RSS Feed Generated by rssify",
            lastBuildDate=datetime.datetime.now(),
            items=rssItems,
            # image=PyRSS2Gen.Image('example.com/image.jpg', 'My Image', 'hiretonyb.com'),
            )

        with open(outfile_name, 'w') as f:
            rss.write_xml(f)

        return True


def main(argv):

    VERBOSE_MODE = 0
    OUTFILE = None
    INDIR = None
    BASEPATH = None

    # Get Opts
    try:
        opts, args = getopt.getopt(
            argv,
            "hvro:i:b:",
            ["help", "verbose", "recurse", "output=", "inputdir=", "basepath="]
            )
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    # Process Opts
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-v", "--verbose"):
            VERBOSE_MODE = 1
        elif opt in ("-o", "--output"):
            OUTFILE = arg
        elif opt in ("-i", "--inputdir"):
            INDIR = arg
        elif opt in ("-b", "--basepath"):
            BASEPATH = arg
        else:
            sys.stderr.write("Invalid option '%s'" % opt)
            usage()
            sys.exit(2)


    if not OUTFILE:
        sys.stderr.write("Missing Output File\n\n")
        usage()
        sys.exit(2)

    if not INDIR:
        sys.stderr.write("Missing Input Directory\n\n")
        usage()
        sys.exit(2)

    if not BASEPATH:
        sys.stderr.write("Missing Basepath\n\n")
        usage()
        sys.exit(2)

    foundFiles = FoundFiles()

    # Find the files in the directory
    for root, dirs, files in os.walk(INDIR):
        for f in files:
            filepath = os.path.join(root, f)
            rel_file_path = os.path.relpath(filepath, INDIR)
            url = BASEPATH + "/" + rel_file_path
            title = f
            foundFiles.addEntry(title, url, filepath)

    if (VERBOSE_MODE):
        foundFiles.printEntries()
        sys.stderr.write("Found " + str(foundFiles.getNumEntries()) + " Files\n")

    # make RSS
    foundFiles.WriteRss(OUTFILE, VERBOSE_MODE)


if __name__ == "__main__":
    main(sys.argv[1:])


#!/usr/bin/env python

"""rssify.py: Generate an RSS XML file from all files in a directory.

https://github.com/tonyborries/YtChannelRss
"""

__author__ = "tonyborries"
__copyright__ = "Copyright 2015, tonyborries"
__credits__ = ["tonyborries"]
__license__ = "MIT"
__maintainer__ = "tonyborries"
__email__ = "<EMAIL>"

import sys
import os
import getopt
import datetime

import PyRSS2Gen

def usage():
    sys.stderr.write(
"""  Usage: %s [ -h ] [ -v ] -o outfile -i inputdir -b url

    -h, --help        Show this usage message and exit.
    -v, --verbose     Verbose Output to StdErr.
    -i, --inputdir    Source Directory of files to build into RSS.
    -o, --output      Output File - where to store the RSS File.
    -b, --basepath    URL path prepended to files to build the full path
""" % sys.argv[0])


class Entry():
    title = ""
    target_url = ""
    abs_filepath = ""

    def __str__(self):
        return self.title + " - " + self.target_url + " (" + self.abs_filepath + ")"

    def getAsRssItem(self):
        statinfo = os.stat(self.abs_filepath)
        file_length = statinfo.st_size

        return PyRSS2Gen.RSSItem(
            title=self.title,
            link=self.target_url,
            description="No Description for " + self.title,
            guid=PyRSS2Gen.Guid(self.target_url),
            pubDate=datetime.datetime.now(),
            enclosure=PyRSS2Gen.Enclosure(self.target_url, file_length, 'audio/mpeg'),
            )


class FoundFiles():
    entries = []

    def addEntry(self, title, target_url, abs_filepath):
        entry = Entry()
        entry.title = title
        entry.target_url = target_url
        entry.abs_filepath = abs_filepath
        self.entries.append(entry)

    def getNumEntries(self):
        return len(self.entries)

    def printEntries(self):
        for entry in self.entries:
            sys.stderr.write(str(entry) + "\n")

    def WriteRss(self, outfile_name, verbose=False):

        # Build RSS
        rssItems = []
        for entry in self.entries:
            rssItems.append(entry.getAsRssItem())

        if verbose:
            sys.stderr.write("Building RSS with " + str(len(rssItems)) + " Items\n")

        rss = PyRSS2Gen.RSS2(
            title="TonyB's casts by rssify",
            link="",
            description="RSS Feed Generated by rssify",
            lastBuildDate=datetime.datetime.now(),
            items=rssItems,
            # image=PyRSS2Gen.Image('example.com/image.jpg', 'My Image', 'hiretonyb.com'),
            )

        with open(outfile_name, 'w') as f:
            rss.write_xml(f)

        return True


def main(argv):

    VERBOSE_MODE = 0
    OUTFILE = None
    INDIR = None
    BASEPATH = None

    # Get Opts
    try:
        opts, args = getopt.getopt(
            argv,
            "hvro:i:b:",
            ["help", "verbose", "recurse", "output=", "inputdir=", "basepath="]
            )
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    # Process Opts
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-v", "--verbose"):
            VERBOSE_MODE = 1
        elif opt in ("-o", "--output"):
            OUTFILE = arg
        elif opt in ("-i", "--inputdir"):
            INDIR = arg
        elif opt in ("-b", "--basepath"):
            BASEPATH = arg
        else:
            sys.stderr.write("Invalid option '%s'" % opt)
            usage()
            sys.exit(2)


    if not OUTFILE:
        sys.stderr.write("Missing Output File\n\n")
        usage()
        sys.exit(2)

    if not INDIR:
        sys.stderr.write("Missing Input Directory\n\n")
        usage()
        sys.exit(2)

    if not BASEPATH:
        sys.stderr.write("Missing Basepath\n\n")
        usage()
        sys.exit(2)

    foundFiles = FoundFiles()

    # Find the files in the directory
    for root, dirs, files in os.walk(INDIR):
        for f in files:
            filepath = os.path.join(root, f)
            rel_file_path = os.path.relpath(filepath, INDIR)
            url = BASEPATH + "/" + rel_file_path
            title = f
            foundFiles.addEntry(title, url, filepath)

    if (VERBOSE_MODE):
        foundFiles.printEntries()
        sys.stderr.write("Found " + str(foundFiles.getNumEntries()) + " Files\n")

    # make RSS
    foundFiles.WriteRss(OUTFILE, VERBOSE_MODE)


if __name__ == "__main__":
    main(sys.argv[1:])


#!/usr/bin/env python rssify.py: Generate an RSS XML file from all files in a directory.  https://github.com/tonyborries/YtChannelRss Usage: %s [ -h ] [ -v ] -o outfile -i inputdir -b url      -h, --help        Show this usage message and exit.     -v, --verbose     Verbose Output to StdErr.     -i, --inputdir    Source Directory of files to build into RSS.     -o, --output      Output File - where to store the RSS File.     -b, --basepath    URL path prepended to files to build the full path # Build RSS # image=PyRSS2Gen.Image('example.com/image.jpg', 'My Image', 'hiretonyb.com'), # Get Opts # Process Opts # Find the files in the directory # make RSS