Example #1
0
    def __call__(self, environ, start_response):
        path = urllib.unquote(environ["PATH_INFO"])
        dirname, basename = os.path.split(path)
        if dirname in self.modules:
            module = self.modules[dirname]
            if basename == "style.css":
                status = "200 OK"
                headers = [("Content-Type", "text/css")]
                start_response(status, headers)
                yield module.css(environ)  
            else:
                status = "200 OK"
                headers = [("Content-Type", "text/xml; charset=UTF-8")]
                yield str(XHTML10DTD())
                src = \
                html(
                    self.header(dirname),
                    body(
                        module.html(environ)
                    )
                )
                yield str(src)

        else:
            status = "404 Not found"
            headers = [("Content-Type", "text/plain")]
            start_response(status, headers)
            yield "Not found"
Example #2
0
 def __call__(self, environ, start_response):
     path = urllib.unquote(environ["PATH_INFO"])
     dirname, basename = os.path.split(path)
     innerhtml = blank()
     if path == "/":
         pathValid = True
         innerhtml = ""
     elif basename in self.dbTypes:
         pathValid = True
         innerhtml = self.showEntries(self.dbTypes[basename])
     elif dirname[1:] in self.dbTypes:
         pathValid = True
         dbType = self.dbTypes[dirname[1:]]
         action = basename.split("?")[0]
         if action == "new":
             innerhtml = self.new(dbType, environ)
         elif action == "delete":
             innerhtml = self.delete(dbType, environ)
         elif action == "edit":
             innerhtml = self.edit(dbType, environ)
     else:
         pathValid = False
         status = "404 Not found"
         headers = [("Content-Type", "text/plain")]
         start_response(status, headers)
         yield status
         
     if pathValid:
         status = "200 OK"
         headers = [("Content-Type", "text/xml; charset=UTF-8")]
         yield unicode(XHTML10DTD())
         src = \
         html(
             head(
                 meta(charset="UTF-8")
             ),
             body(
                 self.menu(),
                 innerhtml
             )
         )
         yield src.toStr()
Example #3
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 #4
0
File: blog.py Project: daineX/PyTTP
    def __call__(self, environ, start_response):
        status = "200 OK"
        headers = [("Content-Type", "text/html; charset=UTF-8")]
        start_response(status, headers)

        try:
            payloadLength = int(environ["CONTENT_LENGTH"])
            pquery = urlparse.parse_qs(environ["wsgi.input"].read(payloadLength))
        except KeyError:
            pquery = {}
        query = urlparse.parse_qs(environ["QUERY_STRING"])
        path = urllib.unquote(environ["PATH_INFO"][1:])

        yield str(XHTML10DTD())
        base = lambda *childs, **attrs: html(xmlns="http://www.w3.org/1999/xhtml")(
            head(
                title("The pythonic way of life"), css, link(rel="icon", href="/data/favicon.ico", type="image/x-icon")
            ),
            body(*childs, **attrs),
        )
        cell = lambda *childs, **attrs: tr(td(*childs, **attrs))

        wrap = div(id="frame")

        header = div(img(src="/data/header.png", alt="Ich bin ein Platzhalter!"), id="kopf")

        content = div(id="content")

        ctext = ""
        cemail = ""
        cauthor = ""

        if path == "submitComment" and "eid" in query:
            try:
                submitFailed = False
                eid = int(query["eid"][0])
                entry = BlogEntry.select_id(eid)
                try:
                    ctext = pquery["text"][0]
                except:
                    ctext = ""
                    content.add(b("Text missing!"))
                    submitFailed = True
                try:
                    cauthor = pquery["author"][0]
                except:
                    cauthor = ""
                    content.add(b("Author missing!"))
                    submitFailed = True
                try:
                    cemail = pquery["email"][0]
                    mailExp = re.compile(r"(?:^|\s)[-a-z0-9_.][email protected](?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", re.IGNORECASE)
                    if cemail != re.match(mailExp, cemail).group(0):
                        submitFailed = True
                        content.add(b("Invalid email address!"))
                except:
                    cemail = ""
                    content.add(b("Invalid email address!"))
                    submitFailed = True
                if not submitFailed:
                    theComment = BlogComment.new(author=cauthor, text=ctext, email=cemail)
                    entry.setRef(theComment)
            except Exception, e:
                print e
                submitFailed = True

            if not submitFailed:
                ctext = ""
                cemail = ""
                cauthor = ""
Example #5
0
File: blog.py Project: daineX/PyTTP
    def __call__(self, environ, start_response):
        if not environ.has_key("REMOTE_USER"):
            status = "401 Unauthorized"
            headers = [("Content-type", "text/html"), ("WWW-Authenticate", 'Basic realm="Administration"')]
            start_response(status, headers)
        else:
            status = "200 OK"
            headers = [("Content-Type", "text/html; charset=UTF-8")]
            start_response(status, headers)

            try:
                payloadLength = int(environ["CONTENT_LENGTH"])
                pquery = urlparse.parse_qs(environ["wsgi.input"].read(payloadLength))
            except KeyError:
                pquery = {}
            query = urlparse.parse_qs(environ["QUERY_STRING"])
            path = urllib.unquote(environ["PATH_INFO"][1:])

            yield str(XHTML10DTD())
            base = lambda *childs, **attrs: html(xmlns="http://www.w3.org/1999/xhtml")(
                head(
                    title("The pythonic way of life"),
                    css,
                    link(rel="icon", href="/data/favicon.ico", type="image/x-icon"),
                ),
                body(*childs, **attrs),
            )
            cell = lambda *childs, **attrs: tr(td(*childs, **attrs))

            menu = div(id="menu")
            menuTable = table()
            menuTable.add(cell("Menu"))
            menuTable.add(cell(a("Authors", href="/admin/authors")))
            menuTable.add(cell(a("Entries", href="/admin/entries")))
            menuTable.add(cell(a("Comments", href="/admin/comments")))
            menu.add(menuTable)

            wrap = div(id="frame")

            header = div(img(src="/data/header.png", alt="Ich bin ein Platzhalter!"), id="kopf")

            content = div(id="content")

            if path == "admin/entries":
                content.add(a(href="/admin/entries/new")("New Entry"), br(), br())

                for entry in BlogEntry.select_creation(asc=False):

                    dateString = datetime.datetime.fromtimestamp(entry.cdate).strftime("%d.%m.%Y %H:%M")

                    if entry.title:
                        content.add(a(href="/admin/entries/edit?eid=%s" % entry.id)(entry.title))
                    else:
                        content.add(a(href="/admin/entries/edit?eid=%s" % entry.id)("<ID: %s>" % entry.id))
                    content.add(" %s written by %s" % (dateString, entry.author.name))
                    content.add(
                        br(),
                        a(href="/admin/entries/delete?eid=%s" % entry.id, onClick="return confirm('Delete entry?')")(
                            "Delete Entry"
                        ),
                        br(),
                        br(),
                    )
            elif path == "admin/entries/new":

                theAuthors = select(name="author", size="1")
                for author in BlogAuthor:
                    theAuthors.add(option(value=(author.id))(author.name))
                submit = form(action="/admin/entries/submit", method="post")(
                    "Author: ",
                    theAuthors,
                    br(),
                    "Title: ",
                    input(name="title"),
                    br(),
                    "Text: ",
                    textarea("", name="text", cols="50", rows="10"),
                    br(),
                    input(type="submit", value="submit"),
                )
                content.add(submit)

            elif path == "admin/entries/edit":
                try:
                    eid = int(query["eid"][0])
                    entry = BlogEntry.select_id(eid)
                except:
                    content.add(b("Invalid entry id!"))
                    eid = None
                if eid is not None:

                    authorID = entry.author.id
                    theAuthors = select(name="author", size="1")
                    for author in BlogAuthor:
                        if author.id == authorID:
                            theAuthors.add(option(value=(author.id), selected=None)(author.name))
                        else:
                            theAuthors.add(option(value=(author.id))(author.name))

                    submit = form(action="/admin/entries/change", method="post")(
                        "Author: ",
                        theAuthors,
                        br(),
                        "Title: ",
                        input(name="title", value=entry.title),
                        br(),
                        "Text: ",
                        textarea(entry.text, name="text", cols="50", rows="10"),
                        br(),
                        input(type="submit", value="submit"),
                        input(type="hidden", name="eid", value=str(eid)),
                    )

                    content.add(submit)

                    if entry.getRefCount("comments"):
                        content.add(br(), "Comments:", br())
                        for comment in entry.comments:
                            content.add(comment.author, br())
                            content.add(datetime.datetime.fromtimestamp(comment.cdate).strftime("%d.%m.%Y %H:%M"), br())
                            content.add(comment.email, br())
                            content.add(
                                a(
                                    href="/admin/comments/delete?eid=%s&cid=%s" % (eid, comment.id),
                                    onClick="return confirm('Delete comment?')",
                                )("Delete comment")
                            )
                            content.add(br(), br())

            elif path == "admin/comments/delete":
                try:
                    cid = int(query["cid"][0])
                    comment = BlogComment.select_id(cid)
                except:
                    content.add(b("Invalid comment id!"), br())
                    cid = None
                if cid is not None:
                    BlogComment.delete(comment)
                    content.add("Deleted comment. ID: %s" % cid)

                    try:
                        eid = int(query["eid"][0])
                        content.add(br(), a(href="/admin/entries/edit?eid=%s" % eid)("Back"))
                    except:
                        pass

            elif path == "admin/entries/delete":
                try:
                    eid = int(query["eid"][0])
                    entry = BlogEntry.select_id(eid)
                except:
                    content.add(b("Invalid entry id!"), br())
                    eid = None
                if eid is not None:
                    BlogEntry.delete(entry)

                    content.add("Deleted entry. ID: %s" % eid)

            elif path == "admin/entries/submit":
                try:
                    _title = pquery["title"][0]
                except:
                    content.add(b("WARNING: No title given!"), br())
                    _title = ""
                try:
                    author = int(pquery["author"][0])
                    theAuthor = BlogAuthor.select_id(author)
                except:
                    content.add(b("Error: No author given!"), br())
                    author = None
                try:
                    text = pquery["text"][0]
                except:
                    text = ""

                if author is not None:
                    entry = BlogEntry.new(text=text, title=_title)
                    entry.setRef(theAuthor)

                    content.add("Added entry. ID: %s" % entry.id)

            elif path == "admin/entries/change":
                try:
                    _title = pquery["title"][0]
                except:
                    content.add(b("WARNING: No title given!"), br())
                    _title = ""
                try:
                    author = int(pquery["author"][0])
                    theAuthor = BlogAuthor.select_id(author)
                except:
                    content.add(b("Error: No author given!"), br())
                    author = None
                try:
                    text = pquery["text"][0]
                except:
                    text = ""
                try:
                    eid = int(pquery["eid"][0])
                    entry = BlogEntry.select_id(eid)
                except:
                    content.add(b("Invalid entry id!"))
                    eid = None
                if eid is not None:

                    entry.text = text
                    entry.title = _title

                    try:
                        entry.deleteRef(entry.author)
                    except:
                        pass
                    entry.setRef(theAuthor)

                    content.add("Changed entry. ID: %s" % entry.id)

            elif path == "admin/authors":

                content.add(a(href="/admin/authors/new")("New author"), br(), br())

                for author in BlogAuthor:
                    content.add(a(href="/admin/authors/edit?aid=%s" % author.id)(author.name), br())

            elif path == "admin/authors/new":

                submit = form(action="/admin/authors/submit", method="post")(
                    "Name",
                    input(name="name"),
                    br(),
                    "Website",
                    input(name="website"),
                    br(),
                    input(type="submit", value="submit"),
                )

                content.add(submit)

            elif path == "admin/authors/submit":

                try:
                    name = pquery["name"][0]
                except:
                    content.add(b("WARNING: No name given!"), br())
                    name = ""
                try:
                    website = pquery["website"][0]
                except:
                    content.add(b("WARNING: No website given!"), br())
                    website = ""

                author = BlogAuthor.new(name=name, website=website)
                content.add("Added author. ID: %s" % author.id)

            elif path == "admin/authors/edit":

                try:
                    aid = int(query["aid"][0])
                    theAuthor = BlogAuthor.select_id(aid)
                except:
                    content.add(b("Invalid author id!"))
                    aid = None

                if aid is not None:
                    submit = form(action="/admin/authors/change", method="post")(
                        "Name",
                        input(name="name", value=theAuthor.name),
                        br(),
                        "Website",
                        input(name="website", value=theAuthor.website),
                        br(),
                        input(type="submit", value="submit"),
                        input(type="hidden", name="aid", value=str(aid)),
                    )
                    content.add(submit)

            elif path == "admin/authors/change":
                try:
                    aid = int(pquery["aid"][0])
                    theAuthor = BlogAuthor.select_id(aid)
                except:
                    content.add(b("Invalid author id!"))
                    aid = None
                if aid is not None:
                    try:
                        name = pquery["name"][0]
                    except:
                        content.add(b("WARNING: No name given!"), br())
                        name = ""
                    try:
                        website = pquery["website"][0]
                    except:
                        content.add(b("WARNING: No website given!"), br())
                        website = ""

                    theAuthor.name = name
                    theAuthor.website = website
                    content.add("Changed author. ID: %s" % theAuthor.id)

            yield str(base(wrap(header, menu, content)))
Example #6
0
    def webInterface(self, environ, start_response):
        try:
            status = "200 OK"
            headers = [("Content-Type", "text/html")]
            start_response(status, headers)
            
            inner = blank()
            css = style("""
            table, td {
                vertical-align: top;
            }
            """
            )
            
            src = \
            html(
                head(
                    title("Webinterface"),
                    css
                ),
                body(
                    h1("Webinterface"),
                    inner
                )
            )
            
            import urlparse
            query = urlparse.parse_qs(environ["QUERY_STRING"])


            for name, cls in self._plugins.items():
                disableStr = "disable_%s" % name
                enableStr = "enable_%s" % name
                if disableStr in query:
                    self.enabled = [n for n in self.enabled[:] if n != name]
                if enableStr in query:
                    if name not in self.enabled:
                        self.enabled += [name]
                        self._buildInst(name)
                cfg = cls._config()
                args = self._pluginCfg[name]
                configChanged = False
                for idx, arg in enumerate(args):
                    cfgname = cfg[idx].description
                    opt = "%s_%s" % (name, cfgname)
                    if opt in query:
                        try:
                            value = cfg[idx].fromString(urllib.unquote(query[opt][0]))
                        except: continue
                        if arg != value:
                            self._pluginCfg[name][idx] = value
                            configChanged = True
                            
                if configChanged:
                    self._buildInst(name)
                    
                pathVar = "%s__path" % name
                if pathVar in query:
                    newPath = urllib.unquote(query[pathVar][0])
                    if newPath:
                        self._paths[name] = newPath
                        
                splitVar = "%s__split" % name
                if splitVar in query:
                    newSplit = urllib.unquote(query[splitVar][0])
                    try:
                        newSplit = int(newSplit)
                        self._splits[name] = newSplit
                    except:
                        pass

            if "save" in query:
                print "Saving configuration .. ",
                self._saveAll()
                print "done."
                                

            enableForm = form(action=self.interfacePath)
            pluginList = table()
            pluginList.add(tr(td("Service"), td("Enable/Disable"), td("RequestPath"), td("Split"), td("Config")))
            
            for name, cls in self._plugins.items():
                if name in self.enabled:
                    checkbox = input(type="submit", name="disable_%s" % name, value="Disable")
                else:
                    checkbox = input(type="submit", name="enable_%s" % name, value="Enable")
                
                cfg = cls._config()
                args = self._pluginCfg[name]
                if len(args):
                    argsCont = table()
                    for idx, arg in enumerate(args):
                        cfgname = cfg[idx].description
                        argsCont.add(tr(td(cfgname), td(input(name="%s_%s" % (name, cfgname), type="text", value=str(arg)))))
                else:
                    argsCont = blank()
                pathname = td(input(name="%s__path" % name, type="text", value=self._paths[name]))
                splitVar = td(input(name="%s__split" % name, type="text", value=str(self._splits[name]), size=2))
                pluginList.add(tr(td(name), td(checkbox), pathname, splitVar, td(argsCont)))
            enableForm.add(pluginList, br())
    #        enableForm.add(input(type="submit", value="Refresh"))
            enableForm.add(input(type="submit", name="save", value="Save config"))
            refreshForm = form(action=self.interfacePath)
            refreshForm.add(input(type="submit", value="Refresh"))
            inner.add(enableForm, br(), refreshForm)
            
            return [str(XHTML10DTD()), str(src)]
        except Exception, e:
            status = "500 Internal Error"
            headers = [("Content-Type", "text/plain")]
            start_response(status, headers, sys.exc_info())
#            import traceback
            return ["An Error occured: %s" % traceback.format_exc(sys.exc_info())]
Example #7
0
 html(
     title(
         "Template Test"
     ),
     style(type="text/css")(
         css
     ),
     body(
         div(id="full")(
             div(id="outershell")(
                 div(id="headerdiv")(
                     "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,"
                 ),
                 div(id="menudiv")(
                     menu(entries, current=1, id="tabmenue")
                 ),
                 div(id="innerdiv")(
                     div(id="headingdiv")(
                         h1("This is a heading.")
                     ),
                     "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,"
                 ),
                 div(id="rightbox")(
                     "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,"
                 ),
                 div(id="footerdiv")(
                     "This is footerbox!"
                 )
             )
         )
     )
 )
Example #8
0
    def __call__(self, environ, start_response):
        path = urllib.unquote(environ["PATH_INFO"][1:])

        if environ["REQUEST_METHOD"] == "POST":
            status = "200 OK"
            headers = [('Content-type', 'text/html; charset=UTF-8')]
            start_response(status, headers)

            ctype, boundary = pyttp.helpers.parseMultipartHeader(environ)
            atEnd = pyttp.helpers.jumpToNextMultipartBoundary(environ, boundary)
            
            inner = blank()
            
            nParts = 0
            while not atEnd:
                partInfo = pyttp.helpers.parseMultipartInfo(environ)
                contentDispo, attrs = partInfo['Content-Disposition']
                filename = attrs['filename'].decode("utf-8")
                atEnd, data = pyttp.helpers.readUntilNextMultipartBoundary(environ, boundary)
                print "Read %s Bytes of data" % len(data)
                
                f = open(os.path.join(self.documentRoot, os.path.basename(filename)), "w")
                f.write(data)
                f.close()
                inner.add("Written %s bytes of data to file %s\n" % (len(data), filename.encode("utf-8")), br())

            yield str(XHTML10DTD())          
            src = \
            html(
                body(
                    inner,
                    a(href="/")("Back"), br(),
                    a(href="/upload")("Upload")
                )
            )
            
            yield str(src)

        elif path == "upload":
            status = "200 OK"
            headers = [('Content-type', 'text/html; charset=UTF-8')]
            start_response(status, headers)
            
            yield str(XHTML10DTD())
            src = \
            html(
                body(
                    form(action="/", method="POST", enctype="multipart/form-data")(
                        input(type="file", size="50", name="Datei"),
                        input(type="submit")
                    )
                )
            )
            
            yield str(src)
        elif path.endswith("favicon.ico"):
            favicon = open(os.path.join(os.path.expanduser("~/.pyttp"), "favicon.ico"))
            status = "200 OK"
            headers = [('Content-type', 'image/x-icon')]
            start_response(status, headers)
            yield ''.join(favicon.readlines())
            favicon.close()
        else:
            yield ''.join(self.fileServer(environ, start_response))
Example #9
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)