from django.conf import settings
import os
import re

JS_MIMETYPES = (
    "application/javascript",
    "text/javascript", # obsolete, see RFC 4329
)
CSS_MIMETYPES = (
    "text/css",
)
TYPES_TO_COMPRESS = (
    "application/json",
    "application/xml",
    "text/html",
    "text/plain",
    "text/xml",
) + JS_MIMETYPES + CSS_MIMETYPES

def listdir_recursive(dir):
    for root, dirs, files in os.walk(dir):
        basename = os.path.basename(root)
        if not (basename.startswith('.') or basename.startswith('_')):
            for file in files:
                fname = os.path.join(root, file).replace(dir, '', 1)
                if fname.startswith('/'):
                    fname = fname[1:]
                yield fname
        else:
             pass # "Skipping directory %s" % root

def sync(bucket=None, prefix=''):
    """ Let's face it... pushing this stuff to S3 is messy.
        A lot of different things need to be calculated for each file
        and they have to be in a certain order as some variables rely
        on others.
    """
    
    from django.conf import settings
    from mediasync import backends
    import cStringIO
    
    assert hasattr(settings, "MEDIA_ROOT")
    assert hasattr(settings, "MEDIASYNC")
    
    CSS_PATH = settings.MEDIASYNC.get("CSS_PATH", "").strip('/')
    JS_PATH = settings.MEDIASYNC.get("JS_PATH", "").strip('/')
    
    # create s3 connection
    client = backends.client()

    #
    # sync joined media
    #
    
    joined = settings.MEDIASYNC.get("JOINED", {})
    
    for joinfile, sourcefiles in joined.iteritems():
        
        joinfile = joinfile.strip('/')
        
        if joinfile.endswith('.css'):
            dirname = CSS_PATH
        elif joinfile.endswith('.js'):
            dirname = JS_PATH
        else:
            continue # bypass this file since we only join css and js
        
        buffer = cStringIO.StringIO()
        
        for sourcefile in sourcefiles:
            
            sourcepath = os.path.join(settings.MEDIA_ROOT, dirname, sourcefile)
            if os.path.isfile(sourcepath):
                f = open(sourcepath)
                buffer.write(f.read())
                f.close()
                buffer.write('\n')        
        
        filedata = buffer.getvalue()
        buffer.close()
        
        remote_path = joinfile
        if dirname:
            remote_path = "%s/%s" % (dirname, remote_path)
        
        _sync_file(client, joinfile, remote_path, filedata)
        
    #
    # sync static media
    #

    for dirname in os.listdir(settings.MEDIA_ROOT):
        
        dirpath = os.path.abspath(os.path.join(settings.MEDIA_ROOT, dirname))
        
        if os.path.isdir(dirpath):
           
            for filename in listdir_recursive(dirpath):
                
                # calculate local and remote paths
                filepath = os.path.join(dirpath, filename)
                remote_path = "%s/%s" % (dirname, filename)
                
                if filename.startswith('.') or not os.path.isfile(filepath):
                    continue # hidden file or directory, do not upload
                
                _sync_file(client, filepath, remote_path)
                

def _sync_file(client, filepath, remote_path, filedata=None):
    
    from django.conf import settings
    from mediasync.utils import cssmin, jsmin
    import mimetypes
                
    # load file data from local path
    if not filedata:
        filedata = open(filepath, 'rb').read()
    
    # guess the content type
    content_type = mimetypes.guess_type(filepath)[0]
    if not content_type:
        content_type = "text/plain"

    # check to see if cssmin or jsmin should be run
    if content_type in CSS_MIMETYPES:
        filedata = cssmin.cssmin(filedata)
    elif content_type in JS_MIMETYPES:
        filedata = jsmin.jsmin(filedata)
    
    # rewrite CSS if the user chooses
    if getattr(settings, "MEDIASYNC_REWRITE_CSS", False): 
        if content_type == "text/css" or filepath.endswith('.htc'):
            MEDIA_URL_RE = re.compile(r"/media/\w+/")
            filedata = MEDIA_URL_RE.sub(r'%s/\1/' % media_url, filedata)
    
    if client.put(filedata, content_type, remote_path):
        print "[%s] %s" % (content_type, remote_path)

__all__ = ['MEDIA_URL','sync']

@@ -3905,305 +3905,8 @@
    %0A
-    # rewrite CSS if the user chooses%0A    if getattr(settings, %22MEDIASYNC_REWRITE_CSS%22, False): %0A        if content_type == %22text/css%22 or filepath.endswith('.htc'):%0A            MEDIA_URL_RE = re.compile(r%22/media/%5Cw+/%22)%0A            filedata = MEDIA_URL_RE.sub(r'%25s/%5C1/' %25 media_url, filedata)%0A    %0A
     

remove CSS rewriting