SW/pygolem/web.py

#!/usr/bin/python2

"""
AUTHOR: Michal Odstrcil 2012
Provide simple web interface for pygolem for data downloading
"""



from numpy import *
import os, re, sys
from utilities import *


###################### WEB PAGES  ##############################

def get_page_paths(shot, page, default_path = 'shots'):
    """
    Return basic paths need for web pages generation
    """

    base_path = default_path + '/'  + str(shot)+'/'
    [ page_path, page] = os.path.split(page)
    page_path = base_path + page_path

    return page_path,base_path, page


def emph(text):
    return '<tt class="file docutils literal"><span class="pre">'+str(text)+'</span></tt>'

def modified(file):
    try:
        return datetime.datetime.fromtimestamp(os.stat(file)[-1]).strftime('%Y-%m-%d')
    except:
        return 'N/A'



def make_image(img_path, name = ""):
    """ Show image from `img_path` with title `name`. Use loading animation of not avalible. Use svgz if possible and if the browser is capable to load.
    """

    img_path = re.sub("(.+)(\.[\w]{3,4})$",r"\1",  img_path)  # remove file ending (.png)
    out = ""

    if name is not "":
        out += "<h4>"+name+"</h4>\n"

    #full_path =  './'+img_path
    full_path =  img_path

    rand_end = "?%s"%random.randint(1e6)
    out += """<?php
    $u_agent = $_SERVER['HTTP_USER_AGENT'];

    if (file_exists("%s.png") || file_exists("%s.svgz") )
    {
	// in firefox use svgz images !!
        if (file_exists("%s.svgz") && (preg_match('/Firefox/i',$u_agent) ||  preg_match('/Chrome/i',$u_agent) ))
        {
            echo "<img src='%s.svgz%s' alt='%s' align='middle'/><br/>";
        }
        else
        {
            echo "<img src='%s.png%s' alt='%s' align='middle'/><br/>";
        }
    }
    else
    {
        echo "<img src='/_static/loading.gif'/><br/>";
        echo "<!-- Missing file %s.png  or %s.svgz  --> " ;
    }
    ?>""" % (full_path,full_path, full_path,full_path,rand_end,name,full_path,rand_end,name,full_path,full_path)


    return out


def make_zoom_image(img_path, name = "", group = ""):
    """ Load image from `img_path` with title 'name`. Make image zoomable, if possible use svgz version.
    """

    rand_end = "?%s"%random.randint(1e6)
    img_path = re.sub("(.+)(\.[\w]{3,4})$",r"\1",  img_path)  # remove file ending (.png)
    out = ""
    if name is not "":
        out += "<h4>"+name+"</h4>\n"

    out +=  """<?php
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    if (file_exists('""" + img_path + ".svgz" + """')   && (preg_match('/Firefox/i',$u_agent) ||  preg_match('/Chrome/i',$u_agent) ) )
    {
    $path='"""+ img_path +".svgz"+rand_end+"""'; }
    else {
    $path='"""+ img_path + ".png"+rand_end+"""'; }
     ?> """ + \
     "<a href='<?php echo $path ?>' rel='lightbox"+group+"'><img  src='"+  img_path + ".png"+rand_end + "'  alt='"+name + ("' title='"+name if name != "" else "")  + "'/></a> "

    return out

def make_config(path):
    """ Try to nicely load and show config from text file in shape
    value = 1
    value2 = 3
    """
    try:
        cfg = cat(path, [], True)
        out ="""
            <table class="docutils field-list" frame="void" rules="none">
            <col class="field-name" />
            <col class="field-body" />
            <tbody valign="top">
            """

        for line in cfg:
            # replace  : or =  by new cell
            out += ' <tr class="field"><th class="field-name"> ' + re.sub('(.+)(\:|=)(.+)', r'\1 </th><td class="field-body"> \3',   line) + ' </td> </tr>'
        out += "</tbody></table>"
    except:
        out = "<h4> Missing config file " + path + "</h4>"

    return out

def wiki(link):
    """
    Short cat to geenrate link to wiki
    """
    if re.match("^\/", link):  # link to internal wiki, starts with /
	return "<a href='http://golem.fjfi.cvut.cz/wiki"+link+"'><font size=1><b><sup>WIKI</sup></b></font></a>"
    else:
	return "<a href='"+link+"'><font size=1><b><sup>WIKI</sup></b></font></a>"



def source_link(path , revision,default_path, link, name):
    """
    Link to formatted link in bitbucket.org
    """
    path  = re.sub("^"+default_path+"\/[\d]+\/", "", path)
    path  = re.sub("\/\/", "\/", path + '/')   # remove shots/ + shot_number from path

    return  '<a href="https://bitbucket.org/michalodstrcil/golem_velin/src/'+ revision +'/includes/'+link+ '">[' +name+ ']</a>'