예제 #1
0
def sharewikify(value):
    if value is not None:
        
        WIKI_WORD = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\)\|,]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
        wikifier = re.compile(r'\b(%s)\b' % WIKI_WORD)
        value = wikifier.sub(r'<a href="\1" target="_blank">\1</a>', value)

        # happy :) :-) 
        emot1 = re.compile(r'\:[\-]?\)', re.VERBOSE)
        value = emot1.sub(r'<img src="%simage/emots/tinymce_smiley-smile18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # wink ;) ;-) 
        emot11 = re.compile(r'\;[\-]?\)', re.VERBOSE)
        value = emot11.sub(r'<img src="%simage/emots/tinymce_smiley-wink18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # very sad :-(( :(( 
        emot22 = re.compile(r'\:[\-]?\(\(', re.VERBOSE)
        value = emot22.sub(r'<img src="%simage/emots/tinymce_smiley-cry18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # sad :( :-( 
        emot2 = re.compile(r'\:[\-]?\(', re.VERBOSE)
        value = emot2.sub(r'<img src="%simage/emots/tinymce_smiley-frown18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # kiss =* :-* :* 
        emot3 = re.compile(r'[=\:][\-]?\*', re.VERBOSE)
        value = emot3.sub(r'<img src="%simage/emots/tinymce_smiley-kiss18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # big smile :-D :D 
        emot4 = re.compile(r'\:[\-]?[dD]', re.VERBOSE)
        value = emot4.sub(r'<img src="%simage/emots/tinymce_smiley-laughing18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # tongue sticking out :-P :P :-p :p 
        emot5 = re.compile(r'\:[\-]?[pP]', re.VERBOSE)
        value = emot5.sub(r'<img src="%simage/emots/tinymce_smiley-tongue-out18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # surprised / o, no :-o :O 
        emot6 = re.compile(r'\:[\-]?[oO]', re.VERBOSE)
        value = emot6.sub(r'<img src="%simage/emots/tinymce_smiley-surprised18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # embarrassed :"> 
        emot7 = re.compile(r'\:\"\>', re.VERBOSE)
        value = emot7.sub(r'<img src="%simage/emots/tinymce_smiley-embarassed18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # wearing sunglasses B-) 
        emot8 = re.compile(r'B\-\)', re.VERBOSE)
        value = emot8.sub(r'<img src="%simage/emots/tinymce_smiley-cool18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # confused :-/ :-\ 
        emot9 = re.compile(r'\:\-[\\/]', re.VERBOSE)
        value = emot9.sub(r'<img src="%simage/emots/tinymce_smiley-undecided18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # angry X-( x-( X( x(
        emot9 = re.compile(r'[xX][\-]?\(', re.VERBOSE)
        value = emot9.sub(r'<img src="%simage/emots/tinymce_smiley-yell18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)
        
        # TODO: Beta 4.1
        #quote = re.compile(r'\[quote\](.*)\[/quote\]', re.DOTALL)
        #value = quote.sub(r'<p class="quote">\1</p>', value)
        
    return value
예제 #2
0
def sharewikify(value):
    if value is not None:
        
        WIKI_WORD = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\)\|,]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
        wikifier = re.compile(r'\b(%s)\b' % WIKI_WORD)
        value = wikifier.sub(r'<a href="\1" target="_blank">\1</a>', value)

        # happy :) :-) 
        emot1 = re.compile(r'\:[\-]?\)', re.VERBOSE)
        value = emot1.sub(r'<img src="%simage/emots/tinymce_smiley-smile18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # wink ;) ;-) 
        emot11 = re.compile(r'\;[\-]?\)', re.VERBOSE)
        value = emot11.sub(r'<img src="%simage/emots/tinymce_smiley-wink18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # very sad :-(( :(( 
        emot22 = re.compile(r'\:[\-]?\(\(', re.VERBOSE)
        value = emot22.sub(r'<img src="%simage/emots/tinymce_smiley-cry18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # sad :( :-( 
        emot2 = re.compile(r'\:[\-]?\(', re.VERBOSE)
        value = emot2.sub(r'<img src="%simage/emots/tinymce_smiley-frown18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # kiss =* :-* :* 
        emot3 = re.compile(r'[=\:][\-]?\*', re.VERBOSE)
        value = emot3.sub(r'<img src="%simage/emots/tinymce_smiley-kiss18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # big smile :-D :D 
        emot4 = re.compile(r'\:[\-]?[dD]', re.VERBOSE)
        value = emot4.sub(r'<img src="%simage/emots/tinymce_smiley-laughing18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # tongue sticking out :-P :P :-p :p 
        emot5 = re.compile(r'\:[\-]?[pP]', re.VERBOSE)
        value = emot5.sub(r'<img src="%simage/emots/tinymce_smiley-tongue-out18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # surprised / o, no :-o :O 
        emot6 = re.compile(r'\:[\-]?[oO]', re.VERBOSE)
        value = emot6.sub(r'<img src="%simage/emots/tinymce_smiley-surprised18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # embarrassed :"> 
        emot7 = re.compile(r'\:\"\>', re.VERBOSE)
        value = emot7.sub(r'<img src="%simage/emots/tinymce_smiley-embarassed18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # wearing sunglasses B-) 
        emot8 = re.compile(r'B\-\)', re.VERBOSE)
        value = emot8.sub(r'<img src="%simage/emots/tinymce_smiley-cool18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # confused :-/ :-\ 
        emot9 = re.compile(r'\:\-[\\/]', re.VERBOSE)
        value = emot9.sub(r'<img src="%simage/emots/tinymce_smiley-undecided18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)

        # angry X-( x-( X( x(
        emot9 = re.compile(r'[xX][\-]?\(', re.VERBOSE)
        value = emot9.sub(r'<img src="%simage/emots/tinymce_smiley-yell18.gif" />' % PrefixNode.handle_simple("STATIC_URL"), value)
        
        # TODO: Beta 4.1
        #quote = re.compile(r'\[quote\](.*)\[/quote\]', re.DOTALL)
        #value = quote.sub(r'<p class="quote">\1</p>', value)
        
    return value
예제 #3
0
 def get_context_data(self, **kwargs):
     context = super(ElementBaseView, self).get_context_data(**kwargs)
     context["element"] = self.element
     context["static_root"] = urljoin(
         PrefixNode.handle_simple("STATIC_URL"),
         self.element.aspect.relative_path)
     return context
예제 #4
0
 def handle_simple(cls, path):
     static_dipstrap = getattr(settings, 'DIPSTRAP_STATIC_URL', '')
     if static_dipstrap:
         return urljoin(PrefixNode.handle_simple('DIPSTRAP_STATIC_URL'),
                        path)
     else:
         return super(DipstrapNode, cls).handle_simple(path)
예제 #5
0
def render_js_files(file_location):
    """
    Loads js files references from 'file_location' parameter.

    Usage::

        {% render_js_files file_location %}

    Example::

        {% render_js_files 'js/general.json' %}

    This method is assuming 'file_location' is under settings.STATIC_DIR dir.

    """
    result = ""
    static_base_path = settings.STATIC_DIR
    json_js_files_path = os.path.join(static_base_path, file_location)
    json_data = open(json_js_files_path)
    data = json.load(json_data)
    files_dirs = data['files']
    json_data.close()
    src_template = "<script src='%s'></script>\n"
    for js_file_path in files_dirs:
        result += src_template % urljoin(
            PrefixNode.handle_simple("STATIC_URL"), js_file_path)

    return result
예제 #6
0
def render_js_files(file_location):
    """
    Loads js files references from 'file_location' parameter.

    Usage::

        {% render_js_files file_location %}

    Example::

        {% render_js_files 'js/general.json' %}

    This method is assuming 'file_location' is under settings.STATIC_DIR dir.

    """
    result = ""
    static_base_path = settings.STATIC_DIR
    json_js_files_path = os.path.join(static_base_path, file_location)
    json_data = open(json_js_files_path)
    data = json.load(json_data)
    files_dirs = data['files']
    json_data.close()
    src_template = "<script src='%s'></script>\n"
    for js_file_path in files_dirs:
        result += src_template % urljoin(
            PrefixNode.handle_simple("STATIC_URL"),
            js_file_path)

    return result
예제 #7
0
 def handle_simple(cls, path):
     static_dipstrap = getattr(settings, 'DIPSTRAP_STATIC_URL', '')
     if static_dipstrap:
         return urljoin(PrefixNode.handle_simple('DIPSTRAP_STATIC_URL'),
                        path)
     else:
         return super(DipstrapNode, cls).handle_simple(path)
예제 #8
0
def get_treemenus_static_prefix():
    if django.VERSION >= (1, 3):
        from django.templatetags.static import PrefixNode
        return PrefixNode.handle_simple("STATIC_URL") + 'treemenus/img'
    else:
        from django.contrib.admin.templatetags.adminmedia import admin_media_prefix
        return admin_media_prefix() + 'img/admin/'
def get_treemenus_static_prefix():
    if django.VERSION >= (1, 3):
        from django.templatetags.static import PrefixNode
        return PrefixNode.handle_simple("STATIC_URL") + 'img/treemenus'
    else:
        from django.contrib.admin.templatetags.adminmedia import admin_media_prefix
        return admin_media_prefix() + 'img/admin/'
예제 #10
0
    def handle_simple(cls, path):
        if apps.is_installed("django.contrib.staticfiles"):
            from django.contrib.staticfiles.storage import staticfiles_storage

            return staticfiles_storage.url(path)
        else:
            return urljoin(PrefixNode.handle_simple("STATIC_URL"), quote(path))
예제 #11
0
def fiduswriter_config_js(context):
    """
    Add Fidus Writer config variables to the window object in JavaScript.
    Usage::
        {% fiduswriter_config_js %}
    """
    if apps.is_installed('django.contrib.staticfiles'):
        from django.contrib.staticfiles.storage import staticfiles_storage
        static_url = staticfiles_storage.base_url
    else:
        static_url = PrefixNode.handle_simple("STATIC_URL")
    if 'WS_PORT' in settings.SERVER_INFO:
        ws_port = settings.SERVER_INFO['WS_PORT']
    else:
        ws_port = ''
    if 'WS_SERVER' in settings.SERVER_INFO:
        ws_server = settings.SERVER_INFO['WS_SERVER']
    else:
        ws_server = ''
    if 'user' in context:
        username = context['user'].get_username()
    else:
        username = ''
    return {
        'static_url': static_url,
        'ws_port': ws_port,
        'ws_server': ws_server,
        'username': username
    }
예제 #12
0
def flag(country_code):
    filename = ''
    for flag in getattr(settings, 'FLAGS'):
        if flag[0] == country_code:
            filename = flag[1]

    path = getattr(settings, 'FLAGS_ROOT') + filename
    return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)
예제 #13
0
def admin_media_prefix():
    """
    Returns the string contained in the setting ADMIN_MEDIA_PREFIX.
    """
    warnings.warn(
        "The admin_media_prefix template tag is deprecated. "
        "Use the static template tag instead.", PendingDeprecationWarning)
    return PrefixNode.handle_simple("ADMIN_MEDIA_PREFIX")
예제 #14
0
 def handle_simple(cls, path):
     site = Site.objects.get_current()
     path = os.path.join(site.domain, path)
     if apps.is_installed('django.contrib.staticfiles'):
         from django.contrib.staticfiles.storage import staticfiles_storage
         return staticfiles_storage.url(path)
     else:
         return urljoin(PrefixNode.handle_simple("STATIC_URL"), quote(path))
예제 #15
0
def admin_media_prefix():
    """
    Returns the string contained in the setting ADMIN_MEDIA_PREFIX.
    """
    warnings.warn(
        "The admin_media_prefix template tag is deprecated. "
        "Use the static template tag instead.", PendingDeprecationWarning)
    return PrefixNode.handle_simple("ADMIN_MEDIA_PREFIX")
예제 #16
0
    def handle_simple(cls, path):
        path = re.sub(r"^js/(.*)\.mjs", r"js/\1.js", path)
        if apps.is_installed("django.contrib.staticfiles"):
            from django.contrib.staticfiles.storage import staticfiles_storage

            return staticfiles_storage.url(
                path) + "?v=%s" % get_last_run("transpile")
        else:
            return urljoin(PrefixNode.handle_simple("STATIC_URL"),
                           quote(path)) + "?v=%s" % get_last_run("transpile")
예제 #17
0
 def handle_simple(cls, path):
     if apps.is_installed('django.contrib.staticfiles'):
         from django.contrib.staticfiles.storage import staticfiles_storage
         return (
             staticfiles_storage.url(path) +
             '?v=%s' % LAST_RUN['version']
         )
     else:
         return (
             urljoin(
                 PrefixNode.handle_simple("STATIC_URL"),
                 quote(path)
             ) + '?v=%s' % LAST_RUN['version']
         )
예제 #18
0
def get_thumb(image, thumb_format):
    try:
        thumb = image.get_thumb(thumb_format=thumb_format)
    except AttributeError:
        thumb =  ''

    if thumb:
        return thumb
    else:
        for default_thumb in settings.IMAGE_THUMB_DEFAULTS:
            if default_thumb[0] == thumb_format:
                return urljoin(PrefixNode.handle_simple("STATIC_URL"), default_thumb[1])

    return ''
예제 #19
0
def static(path):
    """
    Joins the given path with the STATIC_URL setting.

    Usage::

        {% static path %}

    Examples::

        {% static "myapp/css/base.css" %}
        {% static variable_with_path %}

    """
    return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)
예제 #20
0
def get_static_webadmin_prefix(parser, token):
    """
    Populates a template variable with the static prefix,
    ``settings.WEBADMIN_STATIC_URL``.

    Usage::

        {% get_static_webadmin_prefix [as varname] %}

    Examples::

        {% get_static_webadmin_prefix %}
        {% get_static_webadmin_prefix as STATIC_WEBADMIN_PREFIX %}

    """
    return PrefixNode.handle_token(parser, token, "STATIC_WEBADMIN_URL")
예제 #21
0
def get_static_webclient_prefix(parser, token):
    """
    Populates a template variable with the static prefix,
    ``settings.WEBCLIENT_STATIC_URL``.

    Usage::

        {% get_static_webclient_prefix [as varname] %}

    Examples::

        {% get_static_webclient_prefix %}
        {% get_static_webclient_prefix as STATIC_WEBCLIENT_PREFIX %}

    """
    return PrefixNode.handle_token(parser, token, "STATIC_WEBCLIENT_URL")
예제 #22
0
def get_static_feedback_prefix(parser, token):
    """
    Populates a template variable with the static prefix,
    ``settings.FEEDBACK_STATIC_URL``.

    Usage::

        {% get_static_feedback_prefix [as varname] %}

    Examples::

        {% get_static_feedback_prefix %}
        {% get_static_feedback_prefix as STATIC_FEEDBACK_PREFIX %}

    """
    return PrefixNode.handle_token(parser, token, "STATIC_FEEDBACK_URL")
예제 #23
0
    def handle_simple(cls, path):
        static_url = urljoin(PrefixNode.handle_simple("STATIC_URL"),
                             quote(path))

        # Adding static version to url
        params = {'v': STATIC_VERSION}

        url_parts = list(urlparse(static_url))
        query = dict(parse_qsl(url_parts[4]))
        query.update(params)

        url_parts[4] = urlencode(query)
        static_url = urlunparse(url_parts)
        # End Adding static version to url

        return static_url
예제 #24
0
def get_static_feedback_prefix(parser, token):
    """
    Populates a template variable with the static prefix,
    ``settings.FEEDBACK_STATIC_URL``.

    Usage::

        {% get_static_feedback_prefix [as varname] %}

    Examples::

        {% get_static_feedback_prefix %}
        {% get_static_feedback_prefix as STATIC_FEEDBACK_PREFIX %}

    """
    return PrefixNode.handle_token(parser, token, "STATIC_FEEDBACK_URL")
예제 #25
0
def static_urls_js():
    """
    Add global variables to JavaScript about the location and latest version of
    transpiled files.
    Usage::
        {% static_urls_js %}
    """
    if apps.is_installed('django.contrib.staticfiles'):
        from django.contrib.staticfiles.storage import staticfiles_storage
        static_base_url = staticfiles_storage.base_url
    else:
        static_base_url = PrefixNode.handle_simple("STATIC_URL")
    transpile_base_url = urljoin(static_base_url, 'js/transpile/')
    return {
        'static_base_url': static_base_url,
        'transpile_base_url': transpile_base_url,
        'version': LAST_RUN['version']
    }
예제 #26
0
def fiduswriter_config_js(context):
    """
    Add Fidus Writer config variables to the window object in JavaScript.
    Usage::
        {% fiduswriter_config_js %}
    """
    if apps.is_installed('django.contrib.staticfiles'):
        from django.contrib.staticfiles.storage import staticfiles_storage
        static_url = staticfiles_storage.base_url
    else:
        static_url = PrefixNode.handle_simple("STATIC_URL")
    if hasattr(settings, 'WS_PORT'):
        ws_port = settings.WS_PORT
    else:
        ws_port = ''
    if hasattr(settings, 'WS_SERVER'):
        ws_server = settings.WS_SERVER
    else:
        ws_server = ''
    socialaccount_providers = []
    for provider in providers.registry.get_list():
        socialaccount_providers.append({
            'id':
            provider.id,
            'name':
            provider.name,
            'login_url':
            provider.get_login_url(context['request'])
        })
    return {
        'static_url': static_url,
        'ws_port': ws_port,
        'ws_server': ws_server,
        'contact_email': settings.CONTACT_EMAIL,
        'test_server': ('true' if settings.TEST_SERVER else 'false'),
        'is_free': ('true' if settings.IS_FREE else 'false'),
        'registration_open':
        ('true' if settings.REGISTRATION_OPEN else 'false'),
        'language': context['request'].LANGUAGE_CODE,
        'socialaccount_providers': socialaccount_providers,
        'debug': ('true' if settings.DEBUG else 'false')
    }
예제 #27
0
def sitetree_admin_img_url_prefix():
    """Returns static admin images URL prefix. """
    if DJANGO_VERSION_INT >= 140:
        return '%sadmin/img' % PrefixNode.handle_simple('STATIC_URL')

    return '%simg/admin' % PrefixNode.handle_simple('ADMIN_MEDIA_PREFIX')
예제 #28
0
 def icon_src(self, instance):
     path = 'img/aldryn_video/video-32x32.png'
     prefix = PrefixNode.handle_simple("STATIC_URL") or PrefixNode.handle_simple("MEDIA_URL")
     return urljoin(prefix, path)
예제 #29
0
def get_treemenus_static_prefix():
    return PrefixNode.handle_simple("STATIC_URL") + 'img/treemenus'
예제 #30
0
파일: adminmedia.py 프로젝트: lapbay/milan
def admin_media_prefix():
	"""
	Returns the string contained in the setting ADMIN_MEDIA_PREFIX.
	"""
	return PrefixNode.handle_simple("ADMIN_MEDIA_PREFIX")
예제 #31
0
 def handle_simple(cls, path):
     return os.path.join(PrefixNode.handle_simple('STATIC_ROOT'), path)
예제 #32
0
    def handle(self, *args, **options):
        if options["force"]:
            force = True
        else:
            force = False
        start = int(round(time.time()))
        npm_install = install_npm(force, self.stdout)
        js_paths = finders.find("js/", True)
        # Remove paths inside of collection dir
        js_paths = [
            x for x in js_paths if not x.startswith(settings.STATIC_ROOT)
        ]

        transpile_path = os.path.join(PROJECT_PATH, "static-transpile")

        if os.path.exists(transpile_path):
            files = []
            for js_path in js_paths:
                for root, dirnames, filenames in os.walk(js_path):
                    for filename in filenames:
                        files.append(os.path.join(root, filename))
            newest_file = max(files, key=os.path.getmtime)
            if (os.path.commonprefix([newest_file, transpile_path])
                    == transpile_path and not npm_install and not force):
                # Transpile not needed as nothing has changed and not forced
                return
            # Remove any previously created static output dirs
            shutil.rmtree(transpile_path, ignore_errors=True)
        self.stdout.write("Transpiling...")
        if not os.path.exists(TRANSPILE_CACHE_PATH):
            os.makedirs(TRANSPILE_CACHE_PATH)
        # We reload the file as other values may have changed in the meantime
        set_last_run("transpile", start)
        # Create a static output dir
        out_dir = os.path.join(transpile_path, "js/")
        os.makedirs(out_dir)
        with open(os.path.join(transpile_path, "README.txt"), "w") as f:
            f.write(("These files have been automatically generated. "
                     "DO NOT EDIT THEM! \n Changes will be overwritten. Edit "
                     "the original files in one of the django apps, and run "
                     "./manage.py transpile."))

        mainfiles = []
        sourcefiles = []
        lib_sourcefiles = []
        for path in js_paths:
            for mainfile in (subprocess.check_output(
                ["find", path, "-type", "f", "-name", "*.mjs",
                 "-print"]).decode("utf-8").split("\n")[:-1]):
                mainfiles.append(mainfile)
            for sourcefile in (subprocess.check_output(
                ["find", path, "-type", "f", "-wholename",
                 "*js"]).decode("utf-8").split("\n")[:-1]):
                if "static/js" in sourcefile:
                    sourcefiles.append(sourcefile)
                if "static-libs/js" in sourcefile:
                    lib_sourcefiles.append(sourcefile)
        # Collect all JavaScript in a temporary dir (similar to
        # ./manage.py collectstatic).
        # This allows for the modules to import from oneanother, across Django
        # Apps.

        cache_path = os.path.join(TRANSPILE_CACHE_PATH, "js/")
        if not os.path.exists(cache_path):
            os.makedirs(cache_path)
        # Note all cache files so that we can remove outdated files that no
        # longer are in the prject.
        cache_files = []
        # Note all plugin dirs and the modules inside of them to crate index.js
        # files inside of them.
        plugin_dirs = {}
        for sourcefile in sourcefiles:
            relative_path = sourcefile.split("static/js/")[1]
            outfile = os.path.join(cache_path, relative_path)
            cache_files.append(outfile)
            dirname = os.path.dirname(outfile)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
                shutil.copyfile(sourcefile, outfile)
            elif not os.path.isfile(outfile):
                shutil.copyfile(sourcefile, outfile)
            elif os.path.getmtime(outfile) < os.path.getmtime(sourcefile):
                shutil.copyfile(sourcefile, outfile)
            # Check for plugin connectors
            if relative_path[:8] == "plugins/":
                if dirname not in plugin_dirs:
                    plugin_dirs[dirname] = []
                module_name = os.path.splitext(
                    os.path.basename(relative_path))[0]
                if module_name != "init" and module_name not in plugin_dirs[
                        dirname]:
                    plugin_dirs[dirname].append(module_name)

        for sourcefile in lib_sourcefiles:
            relative_path = sourcefile.split("static-libs/js/")[1]
            outfile = os.path.join(cache_path, relative_path)
            cache_files.append(outfile)
            dirname = os.path.dirname(outfile)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
                shutil.copyfile(sourcefile, outfile)
            elif not os.path.isfile(outfile):
                shutil.copyfile(sourcefile, outfile)
            elif os.path.getmtime(outfile) < os.path.getmtime(sourcefile):
                shutil.copyfile(sourcefile, outfile)

        # Write an index.js file for every plugin dir
        for plugin_dir in plugin_dirs:
            index_js = ""
            for module_name in plugin_dirs[plugin_dir]:
                index_js += 'export * from "./%s"\n' % module_name
            outfile = os.path.join(plugin_dir, "index.js")
            cache_files.append(outfile)
            if not os.path.isfile(outfile):
                index_file = open(outfile, "w")
                index_file.write(index_js)
                index_file.close()
            else:
                index_file = open(outfile, "r")
                old_index_js = index_file.read()
                index_file.close()
                if old_index_js != index_js:
                    index_file = open(outfile, "w")
                    index_file.write(index_js)
                    index_file.close()

        # Check for outdated files that should be removed
        for existing_file in (subprocess.check_output(
            ["find", cache_path, "-type",
             "f"]).decode("utf-8").split("\n")[:-1]):
            if existing_file not in cache_files:
                self.stdout.write("Removing %s" % existing_file)
                os.remove(existing_file)
        if apps.is_installed("django.contrib.staticfiles"):
            from django.contrib.staticfiles.storage import staticfiles_storage

            static_base_url = staticfiles_storage.base_url
        else:
            static_base_url = PrefixNode.handle_simple("STATIC_URL")
        transpile_base_url = urljoin(static_base_url, "js/")
        if (hasattr(settings, "WEBPACK_CONFIG_TEMPLATE")
                and settings.WEBPACK_CONFIG_TEMPLATE):
            webpack_config_template_path = settings.WEBPACK_CONFIG_TEMPLATE
        else:
            webpack_config_template_path = os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                "webpack.config.template.js",
            )
        entries = {}
        for mainfile in mainfiles:
            basename = os.path.basename(mainfile)
            modulename = basename.split(".")[0]
            file_path = os.path.join(cache_path, basename)
            entries[modulename] = file_path
        find_static = CSCommand()
        find_static.set_options(
            **{
                "interactive": False,
                "verbosity": 0,
                "link": False,
                "clear": False,
                "dry_run": True,
                "ignore_patterns": ["js/", "admin/"],
                "use_default_ignore_patterns": True,
                "post_process": True,
            })
        found_files = find_static.collect()
        static_frontend_files = (found_files["modified"] +
                                 found_files["unmodified"] +
                                 found_files["post_processed"])
        transpile = {
            "OUT_DIR":
            out_dir,
            "VERSION":
            get_last_run("transpile"),
            "BASE_URL":
            transpile_base_url,
            "ENTRIES":
            entries,
            "STATIC_FRONTEND_FILES":
            list(
                map(
                    lambda x: urljoin(static_base_url, x),
                    static_frontend_files,
                )),
        }
        with open(webpack_config_template_path, "r") as f:
            webpack_config_template = f.read()
        settings_dict = {}
        for var in dir(settings):
            if var in ["DATABASES", "SECRET_KEY"]:
                # For extra security, we do not copy DATABASES or SECRET_KEY
                continue
            try:
                settings_dict[var] = getattr(settings, var)
            except AttributeError:
                pass
        webpack_config_js = webpack_config_template.replace(
            "window.transpile", json.dumps(transpile)).replace(
                "window.settings",
                json.dumps(settings_dict, default=lambda x: False),
            )

        if webpack_config_js is not OLD_WEBPACK_CONFIG_JS:
            with open(WEBPACK_CONFIG_JS_PATH, "w") as f:
                f.write(webpack_config_js)
        call(["./node_modules/.bin/webpack"], cwd=TRANSPILE_CACHE_PATH)
        end = int(round(time.time()))
        self.stdout.write("Time spent transpiling: " + str(end - start) +
                          " seconds")
        signals.post_transpile.send(sender=None)
예제 #33
0
def admin_media_prefix():
    """
    Returns the string contained in the setting ADMIN_MEDIA_PREFIX.
    """
    return PrefixNode.handle_simple("ADMIN_MEDIA_PREFIX")
예제 #34
0
 def handle_simple(cls, path):
     return urljoin(PrefixNode.handle_simple("APP_STATIC_IMAGES_URL"), path)
예제 #35
0
 def handle_simple(cls, path):
     return urljoin(PrefixNode.handle_simple("MEDIA_URL"), path)
예제 #36
0
 def handle_simple(cls, path):
     return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)
 def handle_simple(cls, path):
     return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)
예제 #38
0
 def handle_simple(cls, path):
     return urljoin(PrefixNode.handle_simple("MEDIA_URL"), path)
예제 #39
0
    def handle(self, *args, **options):
        global LAST_RUN
        if options["force"]:
            force = True
        else:
            force = False
        start = int(round(time.time()))
        npm_install = install_npm()
        self.stdout.write("Transpiling...")
        js_paths = finders.find('js/', True)
        # Remove paths inside of collection dir
        js_paths = [
            x for x in js_paths if not x.startswith(settings.STATIC_ROOT)
        ]

        transpile_path = os.path.join(PROJECT_PATH, "static-transpile")

        if os.path.exists(transpile_path):
            files = []
            for js_path in js_paths:
                for root, dirnames, filenames in os.walk(js_path):
                    for filename in filenames:
                        files.append(os.path.join(root, filename))
            newest_file = max(files, key=os.path.getmtime)
            if (os.path.commonprefix([newest_file, transpile_path])
                    == transpile_path and not npm_install and not force):
                # Transpile not needed as nothing has changed and not forced
                return
            # Remove any previously created static output dirs
            shutil.rmtree(transpile_path)
        LAST_RUN['version'] = start
        with open(os.path.join(PROJECT_PATH, ".transpile-time"), 'wb') as f:
            pickle.dump(LAST_RUN['version'], f)
        # Create a static output dir
        out_dir = os.path.join(transpile_path, "js/transpile")
        os.makedirs(out_dir)
        with open(os.path.join(transpile_path, "README.txt"), 'w') as f:
            f.write(('These files have been automatically generated. '
                     'DO NOT EDIT THEM! \n Changes will be overwritten. Edit '
                     'the original files in one of the django apps, and run '
                     './manage.py transpile.'))

        mainfiles = []
        sourcefiles = []
        for path in js_paths:
            for mainfile in subprocess.check_output(
                ["find", path, "-type", "f", "-name", "*.mjs",
                 "-print"]).decode('utf-8').split("\n")[:-1]:
                mainfiles.append(mainfile)
            for sourcefile in subprocess.check_output(
                ["find", path, "-type", "f", "-wholename",
                 "*js"]).decode('utf-8').split("\n")[:-1]:
                if 'static/js' in sourcefile:
                    sourcefiles.append(sourcefile)
        # Collect all JavaScript in a temporary dir (similar to
        # ./manage.py collectstatic).
        # This allows for the modules to import from oneanother, across Django
        # Apps.
        # Create a cache dir for collecting JavaScript files

        cache_path = os.path.join(PROJECT_PATH, ".transpile-cache")
        if not os.path.exists(cache_path):
            os.makedirs(cache_path)
        # Note all cache files so that we can remove outdated files that no
        # longer are in the prject.
        cache_files = []
        # Note all plugin dirs and the modules inside of them to crate index.js
        # files inside of them.
        plugin_dirs = {}
        for sourcefile in sourcefiles:
            relative_path = sourcefile.split('static/js/')[1]
            outfile = os.path.join(cache_path, relative_path)
            cache_files.append(outfile)
            dirname = os.path.dirname(outfile)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
                shutil.copyfile(sourcefile, outfile)
            elif not os.path.isfile(outfile):
                shutil.copyfile(sourcefile, outfile)
            elif os.path.getmtime(outfile) < os.path.getmtime(sourcefile):
                shutil.copyfile(sourcefile, outfile)
            # Check for plugin connectors
            if relative_path[:8] == 'plugins/':
                if dirname not in plugin_dirs:
                    plugin_dirs[dirname] = []
                module_name = os.path.splitext(
                    os.path.basename(relative_path))[0]
                if (module_name != 'init'
                        and module_name not in plugin_dirs[dirname]):
                    plugin_dirs[dirname].append(module_name)

        # Write an index.js file for every plugin dir
        for plugin_dir in plugin_dirs:
            index_js = ""
            for module_name in plugin_dirs[plugin_dir]:
                index_js += 'export * from "./%s"\n' % module_name
            outfile = os.path.join(plugin_dir, 'index.js')
            cache_files.append(outfile)
            if not os.path.isfile(outfile):
                index_file = open(outfile, 'w')
                index_file.write(index_js)
                index_file.close()
            else:
                index_file = open(outfile, 'r')
                old_index_js = index_file.read()
                index_file.close()
                if old_index_js != index_js:
                    index_file = open(outfile, 'w')
                    index_file.write(index_js)
                    index_file.close()

        # Check for outdated files that should be removed
        for existing_file in subprocess.check_output(
            ["find", cache_path, "-type",
             "f"]).decode('utf-8').split("\n")[:-1]:
            if existing_file not in cache_files:
                if existing_file[-10:] == "cache.json":
                    if not existing_file[:-10] + "mjs" in cache_files:
                        self.stdout.write("Removing %s" % existing_file)
                        os.remove(existing_file)
                else:
                    self.stdout.write("Removing %s" % existing_file)
                    os.remove(existing_file)
        if apps.is_installed('django.contrib.staticfiles'):
            from django.contrib.staticfiles.storage import staticfiles_storage
            static_base_url = staticfiles_storage.base_url
        else:
            static_base_url = PrefixNode.handle_simple("STATIC_URL")
        transpile_base_url = urljoin(static_base_url, 'js/transpile/')
        if settings.DEBUG:
            browserify_path = os.path.join(PROJECT_PATH,
                                           'node_modules/.bin/browserifyinc')
        else:
            browserify_path = os.path.join(PROJECT_PATH,
                                           'node_modules/.bin/browserify')
        uglify_path = os.path.join(PROJECT_PATH, 'node_modules/.bin/uglifyjs')
        for mainfile in mainfiles:
            dirname = os.path.dirname(mainfile)
            basename = os.path.basename(mainfile)
            outfilename = basename.split('.')[0] + ".js"
            relative_dir = dirname.split('static/js')[1]
            infile = os.path.join(cache_path, relative_dir, basename)
            outfile = os.path.join(out_dir, relative_dir, outfilename)
            self.stdout.write("Transpiling %s." % basename)
            browserify_call = [
                browserify_path, infile, "--ignore-missing", "-t", "babelify"
            ]
            if settings.DEBUG:
                cachefile = os.path.join(
                    cache_path,
                    basename.split('.')[0] + ".cache.json")
                transpile_output = subprocess.check_output(
                    browserify_call + ["-d", "--cachefile", cachefile])
            else:
                browserify_output = subprocess.check_output(
                    browserify_call +
                    ["-p", "common-shakeify", "-g", "uglifyify"])
                uglify_process = subprocess.Popen(
                    [
                        uglify_path,
                        "-c",
                        "-m",
                        # "--source-map", "content=inline"
                    ],
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE)
                transpile_output, error = uglify_process.communicate(
                    browserify_output)
            file_output = transpile_output.decode('utf-8').replace(
                "$StaticUrls.base$", "'%s'" % static_base_url).replace(
                    "$StaticUrls.transpile.base$",
                    "'%s'" % transpile_base_url).replace(
                        "$StaticUrls.transpile.version$",
                        "'%s'" % str(LAST_RUN['version']))
            with open(outfile, 'w', encoding="utf-8") as f:
                f.write(file_output)
        end = int(round(time.time()))
        self.stdout.write("Time spent transpiling: " + str(end - start) +
                          " seconds")
        signals.post_transpile.send(sender=None)
예제 #40
0
 def icon_src(self, instance):
     path = 'img/aldryn_video/video-32x32.png'
     prefix = PrefixNode.handle_simple(
         "STATIC_URL") or PrefixNode.handle_simple("MEDIA_URL")
     return urljoin(prefix, path)
 def handle_simple(cls, path):
     return urljoin(PrefixNode.handle_simple("ASSETS_URL"), path)
예제 #42
0
def static(path):
    return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)
예제 #43
0
def get_treemenus_static_prefix():
    if django.VERSION >= (1, 3):
        from django.templatetags.static import PrefixNode
        return PrefixNode.handle_simple("STATIC_URL") + 'img/treemenus'
예제 #44
0
def sitetree_admin_img_url_prefix():
    """Returns static admin images URL prefix. """
    if DJANGO_VERSION_INT >= 140:
        return '%sadmin/img' % PrefixNode.handle_simple('STATIC_URL')

    return '%simg/admin' % PrefixNode.handle_simple('ADMIN_MEDIA_PREFIX')
예제 #45
0
 def handle_simple(cls, mimetype, size=icons.SIZE_DEFAULT):
     path = icons.get_icon(mimetype, size=size)
     return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)
예제 #46
0
 def handle_simple(cls, path):
     return os.path.join(PrefixNode.handle_simple('STATIC_ROOT'), path)