Ejemplo n.º 1
0
    def __init__(self,path=None,parent=None,file_name=None):
        """Create asset based on the original file path
        file_name can be with or without extension
        
        top,area,file_name = path"""
        if path:
            st,top,area,file_name = StaticPath(path)
        else:
            st,top,area = StaticPath(parent.path)

        self.upload_directory = join(structure.MEDIASITE_DIRS[0],top,area)
        if not exists(self.upload_directory):
            self.original = None
            return #TODO use unsupported file
        name,ext = splitext(file_name)
        if ext is '':
            originals = fs.listdir(self.upload_directory,filters=(fs.filters.fnmatch(file_name+".*"),fs.filters.no_hidden,fs.filters.no_system))
            if len(originals)==0:
                self.original = None
                return #TODO use unsupported file
            file_name = originals[0]
            
        self.download_directory = join(structure.DOWNLOADS_DIR,"static",top,area,name)
        fs.makedirs(self.download_directory)
        
        self.original = AssetFile(self,join(self.upload_directory,file_name))
        self.original_category = self.original.filetype[1]
        self.caption = self.original.caption
        self.path = "/%s/%s/%s/%s"  % ('static',top,area,name)
Ejemplo n.º 2
0
def setLogger(
    name=None,
    level=logging.INFO,
    stream=sys.stdout,
    dir_=None,
    filenamefmt=f'{datefmt}.log',
    logfmt='[%(asctime)s] %(pathname)s:%(lineno)d: %(levelname)s: %(message)s',
    datetimefmt=datetimefmt,
):
    logger = logging.getLogger(name=name)
    logger.setLevel(level)
    while logger.handlers:
        logger.removeHandler(logger.handlers[-1])

    formatter = logging.Formatter(fmt=logfmt, datefmt=datetimefmt)

    if stream:
        stream_handler = logging.StreamHandler(stream=stream)
        stream_handler.setFormatter(formatter)
        logger.addHandler(stream_handler)

    if dir_:
        fs.makedirs(dir_)
        filename = time.strftime(filenamefmt)
        path = os.path.join(dir_, filename)
        file_handler = logging.FileHandler(path, encoding='utf-8')
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

    return logger
Ejemplo n.º 3
0
 def _generate_assets(self,**options):
     filenames = []
     media_target_dir = os.path.join(structure.TARGET_DIR,"mediasite")
     makedirs(os.path.join(media_target_dir,"css"))
     makedirs(os.path.join(media_target_dir,"js"))
     for d in listdir(structure.CSS_DIR):
         if os.path.splitext(d)[1] == ".css" and os.path.isdir(os.path.join(structure.CSS_DIR,d)):
             filenames.append(d)
             target = os.path.join(structure.MEDIASITE_DIRS[-1],"css",d)
             src = os.path.join(structure.CSS_DIR,d)
         	sources = listdir(src,full_path=True,recursed=True)
             lines = combine_asset_sources(sources,structure.CSS_DIR,source_node=CssSourceNode)	
             with open(os.path.join(media_target_dir, "css", d), 'w') as handle:
                 handle.write(''.join(lines))
                 handle.flush()
     for d in listdir(structure.JS_DIR):
         if os.path.splitext(d)[1] == ".js" and os.path.isdir(os.path.join(structure.JS_DIR,d)):
             filenames.append(d)
             target = os.path.join(structure.MEDIASITE_DIRS[-1],"js",d)
             src = os.path.join(structure.JS_DIR,d)
         	sources = listdir(src,full_path=True,recursed=True)
             lines = combine_asset_sources(sources,structure.JS_DIR,source_node=JsSourceNode)	
             with open(os.path.join(media_target_dir, "js", d), 'w') as handle:
                 handle.write(''.join(lines))
                 handle.flush() 
     print "Generating", ' '.join(filenames), '->', media_target_dir
Ejemplo n.º 4
0
def nginx_installed():

    nginx_path = Popen('which nginx', shell=True, stdout=PIPE).communicate()[0]
    if not nginx_path:
        raise EnvironmentError(1,'Please install nginx')
    # print 'nginx', nginx_path

        
    # Check that there is an 'nginx.conf' file to load
    # Check that there is an 'mime.types' file to load
    d = _make_from_examples()
    
    # Check that there is a 'enabled' directory
    
    # Check that there is an 'error.log' file
        
    # TODO how to run -t while nginx is loaded
    
    #run 'sudo nginx -t' and verify result
    output,stderr = Popen('sudo nginx -t', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate()

    #the configuration file /opt/local/etc/nginx/nginx.conf syntax is ok
    #configuration file /opt/local/etc/nginx/nginx.conf test is successful
    # print syntax
    print >>sys.stderr, str(stderr) #, str(stderr)
    #raise EnvironmentError(2,output) #"nginx isn't properly configured"

    if d is not None:
        fs.makedirs("/opt/local/etc/nginx/sites-enabled")       #TODO correct access attributes
Ejemplo n.º 5
0
 def _gather_assets(self):
     media_target_dir = os.path.join(structure.TARGET_DIR,"mediasite")
     makedirs(media_target_dir)
     for source in sources:
         images_dir = os.path.join(os.path.dirname(source.__file__),'images')
         if os.path.exists(images_dir):
             copy_tree(images_dir,os.path.join(media_target_dir,"images"))
         embed_dir = os.path.join(os.path.dirname(source.__file__),'embed')
         if os.path.exists(embed_dir):
             copy_tree(embed_dir,os.path.join(media_target_dir,"embed"))
         print os.path.dirname(source.__file__)
     print 'Copying application assets ->', media_target_dir
Ejemplo n.º 6
0
def copy_template(style, template_prefix, name, directory, other_name=''):
    """
    Copies either a Thepian application layout template or a Thepian project
    layout template into the specified directory.
    """
    # style -- A color style object (see django.core.management.color).
    # template_prefix -- The string 'app' or 'project'.
    # name -- The name of the application or project.
    # directory -- The directory to which the layout template should be copied.
    # other_name -- When copying an application layout, this should be the name
    #               of the project.
    import themaestro.conf
    from thepian.conf import structure
    from thepian.utils.fs import make_writeable
    if not re.search(r'^\w+$', name): # If it's not a valid directory name.
        raise CommandError("%r is not a valid %s name. Please use only numbers, letters and underscores." % (name, template_name))

    template_name = template_prefix + "_template"
    try:
        template_dir = join(themaestro.conf.__path__[0],template_name)
        for d, subdirs, files in fs.walk(template_dir):
            relative_dir = d[len(template_dir)+1:].replace('%s_name' % template_prefix, name)
            if relative_dir:
                fs.makedirs(join(directory, relative_dir))
            for i, subdir in enumerate(subdirs):    # this bit seems to serve no purpose
                if subdir.startswith('.'):
                    del subdirs[i]
            for f in files:
                if f.endswith('.pyc'):
                    continue
                if f.startswith('.'):
                    continue
                path_old = join(d, f)
                path_new = join(directory, relative_dir, f)
                fp_old = open(path_old, 'r')
                fp_new = open(path_new, 'w')
                fp_new.write(fp_old.read().replace('{{ project_name }}', name)
                                          .replace('{{ admin_name }}',structure.ADMIN_NAME)
                                          .replace('{{ admin_email }}',structure.ADMIN_EMAIL)
                                          .replace('{{ dev_machines }}', str(structure.DEV_MACHINES))
                                          .replace('{{ django_port }}', str(structure.DJANGO_PORT))
                                          )
                fp_old.close()
                fp_new.close()
                try:
                    shutil.copymode(path_old, path_new)
                    make_writeable(path_new)
                except OSError:
                    sys.stderr.write(style.NOTICE("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new))
    except Exception,e:
        print "Skipping '%s', not found (%s)" % (template_name,e)
Ejemplo n.º 7
0
def require_directory(path, uid, gid, mod = stat.S_IRUSR+stat.S_IWUSR+stat.S_IXUSR+stat.S_IRGRP+stat.S_IWGRP+stat.S_IXGRP+stat.S_IROTH+stat.S_IXOTH):
    """default mod = user:rwx group:rwx other:rx"""
    fs.makedirs(path)
    os.chown(path, uid, gid)
    os.chmod(path, mod)
Ejemplo n.º 8
0
def ensure_presets():
    home = expanduser("~/.ffmpeg")
    makedirs(home)
    presets = listdir(structure.CONF_DIR,filters=(filters.no_hidden,filters.no_system,filters.fnmatch("*.ffpreset")))
    for preset in presets:
        copy_file(src=join(structure.CONF_DIR,preset),dst=join(home,preset))
Ejemplo n.º 9
0
 def link_dependencies(self):
     makedirs(os.path.join(structure.TARGET_DIR,"python"))
     for mod in dependency.MODULE_PATHS:
         python_target = os.path.join(structure.TARGET_DIR,"python",mod)
         symlink(dependency.MODULE_PATHS[mod],python_target)
     print "Linking dependencies", ",".join(dependency.MODULE_PATHS.keys()), "->", os.path.join(structure.TARGET_DIR,"python")
Ejemplo n.º 10
0
 def __init__(self,path):
     self.path = path
     self.upload_directory = structure.MEDIASITE_DIRS[0] + "/%s/%s" % (self.path[1],self.path[2])
     makedirs(self.upload_directory)
     self.download_directory = structure.DOWNLOADS_DIR + str(self.path)
     makedirs(self.download_directory)
Ejemplo n.º 11
0
 def __init__(self,**kwargs):
     super(AssetEntity,self).__init__(**kwargs)
     self.upload_directory = structure.UPLOADS_DIR + str(self.path)
     makedirs(self.upload_directory)
     self.download_directory = structure.DOWNLOADS_DIR + str(self.path)
     makedirs(self.download_directory)