def post(self): """""" # TODO check for bearer token or session cookie try: form = web.form("h") except web.BadRequest: try: resource = web.form() except AttributeError: # FIXME fix web.form() raise Exc resource = web.tx.request.body._data else: h = form.pop("h") properties = { k.rstrip("[]"): (v if isinstance(v, list) else [v]) for k, v in form.items() } resource = {"type": [f"h-{h}"], "properties": properties} try: action = resource.pop("action") except KeyError: permalink, mentions = web.tx.posts.create( resource["type"][0].partition("-")[2], **resource["properties"]) # web.header("Link", '</blat>; rel="shortlink"', add=True) # web.header("Link", '<https://twitter.com/angelogladding/status/' # '30493490238590234>; rel="syndication"', add=True) # XXX web.braid(permalink, ...) for mention in mentions: web.enqueue(store_mention, f"{web.tx.origin}{permalink}", mention) web.enqueue( websub.publish, f"{web.tx.origin}/subscriptions", f"{web.tx.origin}", str(content.Homepage().get()), ) raise web.Created("post created", permalink) if action == "update": url = resource.pop("url") web.tx.posts.update(url, **resource) return elif action == "delete": url = resource.pop("url") web.tx.posts.delete(url) return "deleted" elif action == "undelete": pass
def get(self): url = web.form(url=None).url web.header("Content-Type", "application/json") if not url: return {} resource = web.get(url) return resource.entry
def get(self): """""" media = web.tx.posts.get_media() try: query = web.form("q").q except web.BadRequest: pass else: if query == "source": # { # "url": "https://media.aaronpk.com/2020/07/file-20200726XXX.jpg", # "published": "2020-07-26T09:51:11-07:00", # "mime_type": "image/jpeg" # } return { "items": [{ "url": (f"{web.tx.request.uri.scheme}://{web.tx.request.uri.netloc}" f"/media/{filepath.name}"), "published": "TODO", "mime_type": "TODO", } for filepath in media] } return app.view.media(media)
def post(self): """""" media_dir = pathlib.Path(web.tx.host.name) media_dir.mkdir(exist_ok=True, parents=True) while True: mid = web.nbrandom(4) filename = media_dir / mid if not filename.exists(): filename = web.form("file").file.save(filename) break if str(filename).endswith(".heic"): subprocess.Popen([ "convert", filename, "-set", "filename:base", "%[basename]", f"{media_dir}/%[filename:base].jpg", ]) sha256 = subprocess.getoutput(f"sha256sum {filename}").split()[0] try: web.tx.db.insert("media", mid=mid, sha256=sha256, size=filename.stat().st_size) except web.tx.db.IntegrityError: mid = web.tx.db.select("media", where="sha256 = ?", vals=[sha256])[0]["mid"] filename.unlink() path = f"/posts/media/{mid}" raise web.Created(f"File can be found at <a href={path}>{path}</a>", path)
def get(self): """Complete a sign-in by requesting a token.""" form = web.form("state", "code") response = authorize_sign_in(form.state, form.code, "profile") tx.user.session["uid"] = [response["me"]] tx.user.session["name"] = [response["profile"]["name"]] raise web.SeeOther(tx.user.session["return_to"])
def POST(self): """complete an identification""" form = web.form("identifier", "endpoint", return_to="/") for ident_type, (prefix, handler, _) in canopy.auth_handlers.items(): if form.endpoint.startswith(prefix): return handler(form.endpoint, form.identifier) raise web.BadRequest("identification endpoint not supported")
def POST(self): # passphrase = web.secure_form("passphrase").passphrase passphrase = web.form("passphrase").passphrase if canopy.authenticates(passphrase): tx.user.session["uri"] = tx.host.name raise web.SeeOther(tx.user.session.pop("return_to", "/")) return view.identification.bad_auth()
def POST(self): i = web.input() f = form() f.username if i.username == 'sax' and i.passwords == '123': return 'Usuario valido' else: return 'Verifique usuario y clave'
def GET(self): form = formTwitter() session.tercera = session.segunda session.segunda = session.primera session.primera = "<a href='twitter'>Twitter</a>" return templates.twitter(titulo="Twitter", message=insert_message(session.user), ultimas=insert_last(), form=form().render())
def GET(self): cm.readConfig() form = self.reloadMyForm() self.myform = form() # make sure you create a copy of the form by calling it (line above) # Otherwise changes will appear globally msg = readMessage() writeMessage("") return render.index(form, "Canpi Configuration", msg)
def GET(self): cm.readConfig() form = self.reloadMyForm() self.myform = form() # make sure you create a copy of the form by calling it (line above) # Otherwise changes will appear globally msg = readMessage() writeMessage("") return render.index(form,"Canpi Configuration",msg)
def GET(self): try: query = web.form("query")["query"] except web.BadRequest: return view.search.index() results = {} for handler in canopy.query_handlers: results[handler.__name__] = handler(query) return view.search.results(view.search.index, query, results)
def get(self): """Initiate a sign-in.""" form = web.form("me", return_to="/") tx.user.session["return_to"] = form.return_to raise web.SeeOther( initiate_sign_in(tx.origin, "guests/authorize", form.me, scopes=("profile", "email")))
def POST(self): form = web.form("frequency", "multiplier", active="off") if not form.multiplier.endswith(tuple("smhdw")): raise web.BadRequest("repeat interval `{}` " "not supported".format(form.multiplier)) repeat = form.frequency + form.multiplier active = form.active == "on" swarm.configure(self.task, repeat, active) return view.admin.tasks.updated(self.task, active, repeat)
def GET(self): # TODO /objects -> /parser and include repr-hcard try: url = web.form("url").url except web.BadRequest: return view.admin.tools.semantic_explorer() if not url.startswith(("http://", "https://")): url = "http://" + url web.header("Content-Type", "application/json") return json.dumps(mf.parse(url=url))
def GET(self): global hits, content_list, ignore_words, unknown_search_words, readUntilHere form = myform() if not form.validates(): return render.page_1(form) #do search query readUntilHere = 10 hits, content_list, ignore_words, unknown_search_words = search( form["query:"].value) return render.page_2(hits, content_list, readUntilHere, data, ignore_words, unknown_search_words, form(), next_button_myform())
def post(self): form = web.form("content", context=None) rendered = str( web.mkdn(form.content, form.context, globals=micropub.markdown_globals)) web.header("Content-Type", "application/json") return { "content": rendered, "readability": micropub.readability.Readability(form.content).metrics, }
def POST(self): if not web.tx.user.is_owner: raise web.Unauthorized("""I'm sorry Dave, I'm afraid I can't do that""") form = web.form("access", "tag") if form.tag in kvdb["tags"]: return "already exists" kvdb["tags"].add(form.tag) kvdb["tags", form.tag] = {"access": form.access} canopy.post(form.access, "tags.added_tag", form.tag) raise web.Created(view.tags.created(form.tag), "/tags/{}".format(form.tag))
def GET(self): if 'user' not in session: form = formLogin() return templates.template(titulo = "Modificar datos", form = form) else: form = insert_form_data() session.tercera = session.segunda session.segunda = session.primera session.primera = "<a href='modifica-datos'>Modificar datos</a>" return templates.template(titulo = "Modificar datos", message = insert_message(session.user), ultimas = insert_last(), formEdit = form().render())
def GET(self): if 'user' not in session: form = formLogin() return templates.template(titulo="Modificar datos", form=form) else: form = insert_form_data(session.user_id) session.tercera = session.segunda session.segunda = session.primera session.primera = "<a href='modifica-datos'>Modificar datos</a>" return templates.template(titulo="Modificar datos", message=insert_message(session.user), ultimas=insert_last(), formEdit=form().render())
def get_microformats(): try: website = web.form("url").url except web.BadRequest: raise web.OK(view.admin.tools.semantic_explorer()) if website.startswith(("http://", "https://")): website = website.partition("//")[2] try: url = "https://" + website data = mf.parse(url=url) except (requests.ConnectionError, requests.Timeout): try: url = "http://" + website data = mf.parse(url=url) except (requests.ConnectionError, requests.Timeout): raise web.NotFound("couldn't reach endpoint") return url, data
def post(self): """""" destinations = web.form() if "twitter_username" in destinations: un = destinations.twitter_username # TODO pw = destinations.twitter_password # TODO sign in user_photo = "" # TODO doc.qS(f"a[href=/{un}/photo] img").src destination = { "uid": f"//twitter.com/{un}", "name": f"{un} on Twitter", "service": { "name": "Twitter", "url": "//twitter.com", "photo": "//abs.twimg.com/favicons/" "twitter.ico", }, "user": { "name": un, "url": f"//twitter.com/{un}", "photo": user_photo }, } web.tx.db.insert("syndication", destination=destination) if "github_username" in destinations: un = destinations.github_username # TODO token = destinations.github_token # TODO check the token user_photo = "" # TODO doc.qS("img.avatar-user.width-full").src destination = { "uid": f"//github.com/{un}", "name": f"{un} on GitHub", "service": { "name": "GitHub", "url": "//github.com", "photo": "//github.githubassets.com/" "favicons/favicon.png", }, "user": { "name": un, "url": f"//github.com/{un}", "photo": user_photo }, } web.tx.db.insert("syndication", destination=destination)
def POST(self): global hits, content_list, ignore_words, unknown_search_words, readUntilHere form = myform() if not form.validates(): return render.page_1(form) web_data = web.input(doc_id="") if web_data.button == 'next': if readUntilHere + 10 <= len(content_list): readUntilHere = readUntilHere + 10 else: readUntilHere = readUntilHere elif web_data.button == 'last': if readUntilHere - 10 >= 10: readUntilHere = readUntilHere - 10 else: readUntilHere = readUntilHere #do search query return render.page_2(hits, content_list, readUntilHere, data, ignore_words, unknown_search_words, form(), next_button_myform())
def get(self): """""" try: form = web.form("q") except web.BadRequest: return app.view.activity( web.tx.posts.get_channels(), web.tx.posts.get_media(), web.tx.posts.get_posts(), ) def generate_channels(): return [{ "name": r["name"][0], "uid": r["uid"][0] } for r in web.tx.posts.get_channels()] # TODO XXX elif form.q == "channel": # TODO XXX response = {"channels": generate_channels()} if form.q == "config": response = get_config() elif form.q == "source": response = {} if "search" in form: response = { "items": [{ "url": [r["resource"]["url"]] } for r in web.tx.posts.search(form.search)] } elif "url" in form: response = dict(web.tx.posts.read(form.url)) else: pass # TODO list all posts elif form.q == "category": response = {"categories": web.tx.posts.get_categories()} else: raise web.BadRequest( "unsupported query. check `q=config` for support.") web.header("Content-Type", "application/json") return response
def GET(self): """initiate an identification""" try: form = web.form("identifier", return_to="/") except web.BadRequest: return view.identification.index() if not form.identifier: return view.identification.index() tx.user.session["return_to"] = form.return_to identifier = form.identifier http_schemas = ("http:", "https:") if not identifier.startswith(http_schemas): if "email" in canopy.auth_handlers: at_sign_pos = identifier.find("@") if at_sign_pos > 1 and "/" not in identifier[at_sign_pos:]: match = re.match(r"(.+)@(.+)", identifier) if match: return canopy.auth_handlers["email"][1](identifier) if "phone" in canopy.auth_handlers: if identifier.startswith("+"): return canopy.auth_handlers["phone"][1](identifier) identity_uri = web.uri.parse(identifier) if identity_uri.host == tx.host.name: raise web.SeeOther("identification/authentication") elif not identity_uri.suffix: raise web.BadRequest("invalid domain name suffix") endpoints = [] supported_outofband = ("mailto:", "sms:", "tel:") supported_endpoints = ("twitter.com",) for rel_me in mf.parse(url=str(identity_uri))["rels"]["me"]: if not rel_me.startswith(supported_outofband + http_schemas): continue if rel_me.startswith(http_schemas): if web.uri.parse(rel_me).host in supported_endpoints: endpoints.append(rel_me) else: endpoints.append(rel_me) return view.identification.choose_auth(identity_uri.host, endpoints, form.return_to)
def GET(self): global hits, content_list, ignore_words, unknown_search_words, readUntilHere form = myform() if not form.validates(): return render.page_1(form) #do search query readUntilHere = 10 hits, content_list, ignore_words, unknown_search_words = search(form["query:"].value) return render.page_2(hits, content_list, readUntilHere, data, ignore_words, unknown_search_words, form(), next_button_myform())
def entity_form(mname, refresh=False): form = _entity_form(mname, refresh) return form()
def post(self): """Sign the guest out.""" form = web.form(return_to="") sign_out(tx.user.session["uid"]) tx.user.session = None raise web.SeeOther(f"/{form.return_to}")
def POST(self): # TODO log session to db and expire from current del tx.user.session["uri"] tx.user.session["roles"] = [] return_to = getattr(web.form(), "return_to", "") raise web.SeeOther(return_to)
def POST(self): global hits, content_list, ignore_words, unknown_search_words, readUntilHere form = myform() if not form.validates(): return render.page_1(form) web_data = web.input(doc_id = "") if web_data.button == 'next': if readUntilHere+10 <= len(content_list): readUntilHere = readUntilHere + 10 else: readUntilHere = readUntilHere elif web_data.button == 'last': if readUntilHere-10 >= 10: readUntilHere = readUntilHere - 10 else: readUntilHere = readUntilHere #do search query return render.page_2(hits, content_list, readUntilHere, data, ignore_words, unknown_search_words, form(), next_button_myform())
def POST(self): url = web.form("repository").repository web.kvdb["reload-lock"] = True canopy.kvdb["pending-install"] = url swarm.prioritize("canopy.__web__:Packages.add_package") return view.admin.packages.added(url)
def POST(self): canopy.epiphytes[self.service].kv["credentials"] = web.form() return view.admin.services.updated(self.service)
def POST(self): public = bool(web.form(public=False).public) kvdb["branches", self.app]["public"] = public return view.admin.applications.publicized(self.app, public)