Source

jwskin2js / jwskin2js.py

#!/usr/bin/env python
#
# Copyright (c) 2012 David Bennett
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import argparse, os, re, sys
from xml.dom.minidom import parseString
from zipfile import ZipFile


# http://developer.longtailvideo.com/trac/browser/trunk/fl5/js/src/html5/jwplayer.html5.defaultskin.js?format=raw
JS_TEMPLATE = """\
/**
 * JW Player {name} skin
 */
(function(jwplayer) {{
    jwplayer.html5.defaultSkin = function() {{
        this.text = '{text}';
        this.xml = null;

        //http://www.w3schools.com/Dom/dom_parser.asp
        if (window.DOMParser) {{
            parser = new DOMParser();
            this.xml = parser.parseFromString(this.text, 'text/xml');
        }} else {{
            //IE
            this.xml = new ActiveXObject('Microsoft.XMLDOM');
            this.xml.async = false;
            this.xml.loadXML(this.text);
        }}
        return this;
    }};

}})(jwplayer);
"""

def process(zipfile, jsfile, embed=None):
    """
    Process a zip file and output a js file. Both arguments should be
    file-like objects.
    """
    skin_name = ''
    skin_xml = None
    images = {}
    with ZipFile(zipfile) as zip:
        for info in zip.infolist():
            path, filename = os.path.split(info.filename)
            if filename.endswith('.xml'):
                skin_xml = parseString(zip.read(info))
                skin_name = skin_xml.getElementsByTagName(
                    'skin')[0].getAttribute('name')
            elif filename.endswith('.png'):
                _, component = os.path.split(path)
                images.setdefault(component, {})[filename] = (
                    'data:image/png;base64,{0}'.format(
                        zip.read(info).encode('base64').replace('\n', '')))
    for component in skin_xml.getElementsByTagName('component'):
        component_name = component.getAttribute('name')
        for element in component.getElementsByTagName('element'):
            element_src = element.getAttribute('src')
            element.setAttribute('src', images[component_name][element_src])
    text = ''.join(l.strip() for l in skin_xml.toxml().splitlines())
    if embed:
        text, subs = re.subn(r'<\?xml .*?</skin>', text, embed.read())
        if subs < 1:
            sys.stderr.write(
                "Couldn't find any xml files to replace in the embed file.")
            exit(1)
        elif subs > 1:
            sys.stderr.write(
                "Found too many xml files to replace in the embed file.")
            exit(2)
        jsfile.write(text)
    else:
        jsfile.write(JS_TEMPLATE.format(name=skin_name, text=text))

def main():
    parser = argparse.ArgumentParser(
        description='Compile a JW Player 5 skin to JavaScript.')
    parser.add_argument(
        'zipfile', type=argparse.FileType(), help='source skin zip file')
    parser.add_argument(
        '-e', '--embed', type=argparse.FileType(), metavar='jwplayer',
        help='optionally embed into existing jwplayer.js (default is to '
        'create a standalone JavaScript file)')
    parser.add_argument(
        '-o', '--output', default=sys.stdout, type=argparse.FileType('w'),
        metavar='jsfile', dest='jsfile', help='optionally save to a file '
        '(default is to write to STDOUT)')
    args = parser.parse_args()
    process(args.zipfile, args.jsfile, args.embed)


if __name__ == '__main__':
    main()