# Copyright (c) 2003, Itamar Shtull-Trauring.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   1. Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
#   2. Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#   3. The name of the author may not be used to endorse or promote products
#   derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.


"""Chop up shoutcast stream into MP3s and metadata.

MP3s will be stored in current directory.

Main issue - a second or more of previous song might be attached to beginning,
or some of the next song to the end of the song. The higher the bitrate,
the less of a problem this is, and depending on how the shoutcast server works
might never happen.

Requires: Twisted 1.0.2 or CVS as of Jan 12, 2003.

Usage:

   $ chopshop.py <host> <port> [<urlpath>]

<urlpath> defaults to '/', which is what most shoutcast servers seem to use, so
usually you can ommit it.
"""

__version__ = "0.2.1"

# system imports
import os

# twisted imports
from twisted.protocols import shoutcast


class ChopShop(shoutcast.ShoutcastClient):
    """Stores MP3s in current directory."""

    firstSong = 1
    
    def gotMetaData(self, data):
        if self.firstSong:
            log.msg("Skipping first song, since it's probably already started.")
            self.firstSong = 0
            return
        if hasattr(self, "file"):
            self.file.close()
            del self.file
            log.msg("finished")
        title = None
        for key, value in data:
            if key == "StreamTitle":
                title = value.replace("/", "-") + ".mp3"
                break
        if title is None:
            log.msg("No title found, not saving")
            return
        if os.path.exists(title):
            log.msg("File %r exists, not overwriting" % title)
            return
        self.file = open(title, "wb")
        self.filename = title
        log.msg("Starting to download %r ..." % title)
    
    def gotMP3Data(self, data):
        if hasattr(self, "file"):
            self.file.write(data)

    def connectionLost(self, reason):
        if hasattr(self, "file"):
            self.file.close()
            del self.file
            os.remove(self.filename)
            log.msg("cancelled partially downloaded file.")


if __name__ == '__main__':
    import sys
    from twisted.internet import reactor, protocol
    from twisted.python import log
    log.startLogging(sys.stdout)
    
    if len(sys.argv) > 3:
        path = sys.argv[3]
    else:
        path = "/"
        protocol.ClientCreator(reactor, ChopShop, path
                               ).connectTCP(sys.argv[1], int(sys.argv[2]))
    reactor.run()
