Example #1
0
 def delete(self, dbType, environ):
     query = parse_query_string(environ['QUERY_STRING'])
     name = dbType.__name__        
     if "id" in query and "doit" in query:
         dbid = query["id"][0]
         try:
             inst = dbType.select_id(int(dbid))
         except (IndexError, ValueError):
             return "Invalid ID"
         deleteRefs = []
         for ref in dbType.has_many:
             refName = ref.__name__
             if refName in query and query[refName][0] == "on":
                 deleteRefs.append(ref)
         dbType.delete(inst, deleteRefs)
         
         return h1("Deleted instance %s of %s" % (dbid, name))
     elif "id" in query:
         dbid = query["id"][0]
         f = form(action=os.path.join("/", name, "delete"))
         f.add(h1("Delete inst %s of %s" % (dbid, name)))
         if dbType.has_many:
             f.add(fieldset(legend("Delete references"),(blank(ref.__name__, input(type="checkbox", name=ref.__name__)) for ref in dbType.has_many)))
         f.add(input(type="hidden", name="id", value=dbid))
         f.add(br())
         f.add(input(type="submit", value="Really delete?"))
         f.add(input(type="hidden", name="doit", value="doit"))
         return f
     return blank()
Example #2
0
    def __call__(self, environ, start_response):
        query = parse_query_string(environ['QUERY_STRING'])

        import urllib
        path = urllib.unquote(environ["PATH_INFO"][1:])
        filename = os.path.normpath(os.path.join(self.documentRoot, path))

        filenameValid = True
        if os.path.commonprefix([self.documentRoot, filename]) != self.documentRoot:
            filenameValid = False
        if not os.path.exists(filename):
            filenameValid = False
        if not filenameValid:
            status = "404 Not found"
            headers = [('Content-type', 'text/plain')]
            start_response(status, headers)
            yield 'File '
            yield path
            yield ' not found'
        else:
            if os.path.isdir(filename):
                status = "200 OK"
                headers = [('Content-type', 'text/html; charset=UTF-8')]
                start_response(status, headers)
                
                yield PublicDTD("html", "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")()
                
                entries = glob.glob("%s/*" % filename)
                
                parentDir = os.path.split(filename)[0]
                if (parentDir == self.documentRoot) or os.path.commonprefix([self.documentRoot, parentDir]) == parentDir:
                    back = "/"
                else:
                    back = parentDir[len(self.documentRoot):]
                src = \
                html(
                    head(
                        title("MusicBrowser")
                    ),
                    body(
                        h1(os.path.basename(filename)),
                        a("..", href=back),
                        br(),
                        blank(*(blank(a(os.path.basename(entry), href=entry[len(self.documentRoot):]), br()) for entry in sorted(entries, cmp=lambda x,y: cmp(x.lower(), y.lower()))))
                    )
                )
                
                yield str(src)        
            else:

                if "play" in query:
                    status = "200 OK"
                    mimetype, _ = mimetypes.guess_type(filename)
                    headers = [('Content-type', mimetype)]
                    start_response(status, headers)
                    with open(filename) as f:
                        while True:
                            data = f.read(65536)
                            yield data
                            if len(data) < 65536:
                                break
                            
                    
                else:
                    status = "200 OK"
                    headers = [('Content-type', 'text/html; charset=UTF-8')]
                    start_response(status, headers)
                    yield PublicDTD("html", "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")()

                    try:
                        if filename.lower().endswith(".mp3"):
                            info = EasyID3(filename)
                        else:
                            info = mutagen.File(filename)
                    except:
                        info = {}
                    try:
                        trackTitle = ''.join(info['title']).encode("utf-8")
                    except:
                        trackTitle = ''
                    try:
                        trackArtist = ' '.join(info['artist']).encode("utf-8")
                    except:
                        trackArtist = ''

                    if info:
                        src = \
                        html(xmnls="http://www.w3.org/1999/xhtml")(
                            head(
                                title("%s - %s" % (trackArtist, trackTitle))
                            ),
                            body(
                                table(*(tr(td(key.capitalize()), td(' '.join(info[key]).encode("utf-8"))) for key in info.keys())),
                                a("back", href="/"+os.path.split(path)[0]),
                                br(),
                                audio("Your browser does not support the audio tag!", src="/"+path+"?play", controls="controls", autoplay="autoplay", preload="preload")
                            ),
                        )
                        yield str(src)
                    else:
                        yield "No Info"
Example #3
0
    def edit(self, dbType, environ):
        query = parse_query_string(environ['QUERY_STRING'])
        
        if "id" in query:
            dbid = query["id"][0]
            try:
                inst = dbType.select_id(int(dbid))
            except (IndexError, ValueError):
                return "Invalid ID"
            name = dbType.__name__            
            if environ["REQUEST_METHOD"] == "POST":
                pquery = parseURLEncoded(environ)
                for field in dbType.fieldTypes:
                    if field not in ("cdate", "id"):
                        if field in pquery:
                            value = pquery[field][0]
                            inst.__setattr__(field, value)
                inst.save()
                for ref in dbType.has_many:
                    refName = ref.__name__
                    if refName in pquery:
                        refIDs = [int(_) for _ in pquery[refName]]
                        if ref in dbType.singular_refs:
                            try:
                                refInst = list(inst.getRefs(ref))[0]
                                inst.deleteRef(refInst)
                            except:
                                pass
                            refID = int(pquery[refName][0])
                            if refID:
                                refInst = ref.select_id(refID)
                                inst.setRef(refInst)
                        else:
                            for refInst in inst.getRefs(ref):
                                    inst.deleteRef(refInst)
                            for refID in refIDs:
                                if not refID: continue
                                refInst = ref.select_id(refID)
                                inst.setRef(refInst)
                                print inst.getRefCount(ref)
                        

            
            inst = dbType.select_id(int(dbid))
            
            biggerScript = noEscapeBlank(
            """<script type="text/javascript">
               function bigger(id) {
                   document.getElementById(id).rows *= 2;
               }</script>""")

            f = form(action=os.path.join("/",name, "edit?id=%s" % inst.id), method="POST")
            f.add(biggerScript)
            t = table()
            for field in dbType.fieldTypes:
                if field not in ("cdate", "id"):
                    t.add(tr(td(field), td(textarea(id="text_%s" % field, rows="1", cols="80", name=field)(inst.__getattr__(field))), td(button(type="button", onmousedown="bigger('text_%s')" % field)("+")) ))
            for ref in dbType.has_many:
                refName = ref.__name__
                refIDs = []#
                try:
                    for refInst in inst.getRefs(ref):
                        refIDs.append(refInst.id)
                except:
                    pass

                if ref not in dbType.singular_refs:
                    selection = select(name=refName, multiple="multiple")
                else:
                    selection = select(name=refName)
                selection.add(option(value=0)("--"))
                attr = self.displayValues.get(ref, "id")
                selection.add(option(value=refInst.id)(refInst.__getattr__(attr)) for refInst in ref if refInst.id not in refIDs)
                selection.add(option(value=refInst.id, selected="selected")(refInst.__getattr__(attr)) for refInst in ref if refInst.id in refIDs)
                t.add(tr(td(refName), td(selection)))
            f.add(t)
            f.add(input(type="submit"))
            return blank(h1(' '.join(("edit", name, unicode(inst.id)))), f)
        return blank()
Example #4
0
    def __call__(self, environ, start_response):
      
        path = urllib.unquote(environ["PATH_INFO"])
        
        innerhtml = blank()
        status = "200 OK"
        headers = headers = [('Content-type', 'text/html; charset=UTF-8')]
        if path == "/" or path == "/list":
            query = helpers.parse_query_string(environ['QUERY_STRING'])
            if "delid" in query:
                try:
                    delid = int(query.get("delid")[0])
                    inst = DownloadEntry.select_id(delid)
                    DownloadEntry.delete(inst)
                except:
                    pass
            if "retryid" in query:
                try:
                    retryid = int(query.get("retryid")[0])
                    inst = DownloadEntry.select_id(retryid)
                    inst.error=''
                except:
                    pass       
            if "clearErrors" in query:
                for entry in DownloadEntry.select_cond(cond="NOT error=''"):
                    DownloadEntry.delete(entry)
            if "clearFinished" in query:
                for entry in DownloadEntry.select(finished=1):
                    DownloadEntry.delete(entry)
                    
           
            errorButton = form(action="/list")(input(type="submit", value="Clear errors"), input(type="hidden", name="clearErrors"))
            finishButton = form(action="/list?clearFinished")(input(type="submit", value="Clear finished downloads"), input(type="hidden", name="clearFinished"))
            
            dlist = self.downloadList()
            dlist.add(tr(td(finishButton), td(colspan="5")(errorButton)))
            innerhtml = dlist

        elif path == "/create":
            if environ["REQUEST_METHOD"] == "POST":
                msg = blank()
                query = helpers.parseURLEncoded(environ)
                print query
                url = query.get("url")
                destination = query.get("destination")
                ratelimit = query.get("ratelimit")
                if not "edit" in query:
                    if not url:
                        msg = b("No URL given!")
                    else:
                        if not destination:
                            msg = b("No destination given!")
                        else:
                            if not ratelimit:
                                ratelimit = 0
                            else:
                                ratelimit = ratelimit[0]
                            url = url[0]
                            destination = destination[0]
                            
                            if not url.startswith("http://"):
                                url = "http://"+url                       
                            dl = DownloadEntry.new(url=url,
                                                    destination=destination,
                                                    ratelimit=ratelimit,
                                                    active=0,
                                                    finished=0,
                                                    error='')
                            msg = "Added Entry"
                    innerhtml = blank(p(msg), self.creationForm())
                else:
                    innerhtml = self.creationForm(url[0], destination[0], ratelimit[0])
            else:
                innerhtml = self.creationForm()
                
        elif path == "/config":
            defaults = Defaults.select_id(1)
            msg = blank()
            if environ["REQUEST_METHOD"] == "POST":
                query = helpers.parseURLEncoded(environ)
                print query

                destination = query.get("destination")
                if not destination:
                    msg = b("Destination not given!")
                else:
                    ratelimit = query.get("ratelimit")
                    if ratelimit is None:
                        msg = b("Rate Limit not given!")
                    else:
                        destination = destination[0]
                        try:
                            ratelimit = int(ratelimit[0])
                            defaults.ratelimit = ratelimit
                        except ValueError:
                            msg = b("Rate Limit must be a number!")
                            ratelimit = defaults.ratelimit
                        if not os.path.isdir(destination):
                            try:
                                os.makedirs(destination)
                                defaults.destination = destination
                            except OSError:
                                msg = b("Invalid destination!")
                        else:
                            defaults.destination = destination
                               
            innerhtml = blank(
            h1("Defaults"), msg,
            form(action="/config", method="POST")(
                table(
                    tr(
                        td("Destination"), td(input(type="text", name="destination", value=defaults.destination))
                    ), 
                    tr(
                        td("Rate Limit (in B)"), td(input(type="text", name="ratelimit", value=defaults.ratelimit))
                    ),
                    tr(
                        td(input(type="submit"))
                    )
                )
            ))
        else:
            status = "404 Not found"
            headers = [('Content-type', 'text/html; charset=UTF-8')]
            innerhtml= b("404 File not found.")
        yield str(XHTML10DTD())
        src = \
            html(
                noEscapeBlank('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'),
                body(
                    table(
                        tr(
                            td(self.menu()), td(innerhtml)
                        )
                    )
                )
            )
        yield str(src)