def _update_issuu_document_metadata(self, timeout=5): if self.issuu_document_url: metadata = extract_issuu_document_metadata(self.issuu_document_url) self.issuu_document_username = metadata.get("username") self.issuu_document_name = metadata.get("docname") self.issuu_config_id = metadata.get("configid") if self.issuu_document_username and self.issuu_document_name: response = urlopen( "http://search.issuu.com/api/2_0/document?q=docname:%s&username=%s" % (self.issuu_document_name, self.issuu_document_username), timeout=timeout) status = response.getcode() body = response.read() if status < 200 or status > 299: raise IssuuSearchAPIError(body) data = loads(body) try: self.issuu_document_id = \ data["response"]["docs"][0]["documentId"] except (KeyError, IndexError): self.issuu_document_id = None if self.issuu_config_id is None: url = Location(self.issuu_document_url) url.query_string.update(e=0) response = urlopen(url.get_url(), timeout=timeout) status = response.getcode() body = response.read() if status >= 200 and status <= 299: url = Location(response.geturl()) issuu_config_id = url.query_string.get("e") if issuu_config_id: self.issuu_config_id = issuu_config_id[0]
def submit(self): Basket.empty() notify_user( translations("woost.extensions.ecommerce." "empty_basket_notice"), category = "success" ) Location.get_current().go("GET")
def invoke(self, controller, selection): """Delegates control of the current request to the action. Actions can override this method to implement their own response logic; by default, users are redirected to an action specific controller. @param controller: The controller that invokes the action. @type controller: L{Controller<cocktail.controllers.controller.Controller>} """ location = Location(self.get_url(controller, selection)) location.go(client_redirect = self.client_redirect)
def submit(self): Form.submit(self) purchase = self.instance["purchase"] product = purchase.product purchase.delete() Basket.store() notify_user( translations( "woost.extensions.ecommerce.delete_purchase_notice", product = product ), category = "success" ) Location.get_current().go("GET")
def _fix_uri(self, uri, host, encode): if encode: uri = percent_encode_uri(uri) if "://" in uri: host = None if host: website = get_current_website() policy = website and website.https_policy if (policy == "always" or (policy == "per_page" and (getattr(self, 'requires_https', False) or not get_current_user().anonymous))): scheme = "https" else: scheme = "http" if host == ".": location = Location.get_current_host() location.scheme = scheme host = str(location) elif not "://" in host: host = "%s://%s" % (scheme, host) uri = make_uri(host, uri) elif "://" not in uri: uri = make_uri("/", uri) return uri
def __call__(self, **parameters): # Get references to the gateway and payment gateway = get_parameter( schema.Reference("gateway_id", type=DummyPaymentGateway)) if gateway is None: raise ValueError("Wrong payment gateway") payment_id = get_parameter(schema.String("payment_id")) payment = payment_id and gateway.get_payment(payment_id) or None if payment is None: raise ValueError("Wrong payment id (%s)" % payment_id) # Notify the payment to the application cms = self.context["cms"] notification_uri = Location.get_current_host() notification_uri.path_info = cms.application_uri( "payment_notification", payment_id=payment_id) urlopen(str(notification_uri)) # Redirect the user after the transaction's over redirection = None if gateway.payment_status == "accepted": redirection = gateway.payment_successful_page elif gateway.payment_status == "failed": redirection = gateway.payment_failed_page raise cherrypy.HTTPRedirect((redirection and cms.uri(redirection) or cms.application_uri()).encode("utf-8"))
def __call__(self): output = [] write = output.append write(u"<?xml version='1.0' encoding='utf-8'?>") write(u"<urlset xmlns='%s'>" % self.namespace) base_url = str(Location.get_current_host()).rstrip(u"/") uri = self.context["cms"].uri for item in self.items: write(u"\t<url>") item_uri = base_url + u"/" + uri(item).lstrip(u"/") write(u"\t\t<loc>%s</loc>" % item_uri) date = item.last_update_time.strftime("%Y-%m-%d") write(u"\t\t<lastmod>%s</lastmod>" % date) frequency = item.sitemap_change_frequency if frequency: write(u"\t\t<changefreq>%s</changefreq>" % frequency) priority = item.sitemap_priority if priority: write(u"\t\t<priority>%s</priority>" % priority) write(u"\t</url>") write(u"</urlset>") return u"\n".join(output)
def _establish_active_website(self): location = Location.get_current_host() website = Configuration.instance.get_website_by_host(location.host) set_current_website(website) if website is None: raise cherrypy.HTTPError(404, "Unknown hostname: " + location.host)
def render_pdf(self): # Create a temporary folder to hold the PDF temp_path = mkdtemp() pdf_file_path = os.path.join(temp_path, "file.pdf") try: location = Location.get_current(relative = False) location.query_string["format"] = "html" # Create the file command = extension.command % { "url": unicode(location), "output_file": pdf_file_path } proc = Popen(command.encode("utf-8"), shell = True) stdout, stderr = proc.communicate() if proc.returncode: raise OSError("Error generating PDF" + (": " + stderr) if stderr else "" ) # Serve the file cherrypy.response.headers["Content-Type"] = "application/x-pdf" return serve_file( pdf_file_path, content_type = "application/x-pdf", disposition = "attachment", name = translations(self.context["publishable"]) + ".pdf" ) finally: rmtree(temp_path)
def get_content_cache_key(self, publishable, **context): user = get_current_user() cache_key = ( str(Location.get_current(relative = False)), None if user is None or user.anonymous else tuple(role.id for role in user.roles) ) key_qualifier = None expression = self.cache_key_expression if expression: expression = expression.replace("\r", "") context["publishable"] = publishable exec expression in context key_qualifier = context.get("cache_key") else: request = context.get("request") if request: key_qualifier = tuple(request.params.items()) if key_qualifier: cache_key = cache_key + (key_qualifier,) return cache_key
def focus_block(block): location = Location.get_current() location.hash = "block" + str(block.id) location.query_string.pop("action", None) location.query_string.pop("block_parent", None) location.query_string.pop("block_slot", None) location.query_string.pop("block", None) location.go("GET")
def submit(self): Form.submit(self) for purchase, quantity in zip( Basket.get().purchases, self.instance["quantity"] ): purchase.quantity = quantity Basket.store() notify_user( translations("woost.extensions.ecommerce." "set_quantities_notice"), category = "success" ) if self.controller.action != "proceed": Location.get_current().go("GET")
def submit(self): Form.submit(self) Basket.get().add_purchase(self.instance) Basket.store() notify_user(translations( "woost.extensions.ecommerce.product_added_notice", product=self.product), "product_added", transient=False) if self.redirect_to_basket: raise cherrypy.HTTPRedirect( Publishable.require_instance( qname="woost.extensions.ecommerce.basket_page"). get_uri()) else: Location.get_current().go("GET")
def _apply_https_policy(self, publishable): policy = Configuration.instance.get_setting("https_policy") website = get_current_website() if policy == "always": Location.require_https() elif policy == "never": Location.require_http() elif policy == "per_page": if publishable.requires_https or not get_current_user().anonymous: Location.require_https() elif not website.https_persistence: Location.require_http()
def resolve(self, path): # Allow application modules (ie. language) to process the URI before # resolving the requested publishable item self._process_path(path) request = cherrypy.request # Item resolution publishable = self._resolve_path(path) self.context["publishable"] = publishable # HTTP/HTTPS check self._apply_https_policy(publishable) # Check maintenance mode self._maintenance_check(publishable) # Controller resolution controller = publishable.resolve_controller() if controller is None: raise cherrypy.NotFound() # Add the selected language to the current URI if publishable.per_language_publication: if not request.language_specified: location = Location.get_current() location.path_info = app.language.translate_uri() location.go() # Remove the language selection from the current URI elif request.language_specified: location = Location.get_current() location.path_info = \ "/" + "/".join(location.path_info.strip("/").split("/")[1:]) location.go() return controller
def get_payment_url(self, *args, **kwargs): website = get_current_website() location = Location() location.relative = False if website.https_policy != "never": location.scheme = "https" location.host = website.hosts[0] location.path_info = "payments/" + str(self.id) location.join_path(*args) location.query_string.update(kwargs) return unicode(location)
def invoke(self, controller, selection): target = selection[0] consumer = Consumer(target.app_id, target.app_secret) def request(client, *args, **kwargs): response, body = client.request(*args, **kwargs) if response["status"] != "200": raise TwitterAPIError(body) return body try: oauth_token = cherrypy.request.params.get("oauth_token") oauth_verifier = cherrypy.request.params.get("oauth_verifier") oauth_secret_session_key = "twitter_auth.%s.oauth_secret" % self.id if not oauth_token or not oauth_verifier: # Obtain a request token client = Client(consumer) location = Location.get_current(relative=False) location.query_string["item_action"] = self.id callback = quote_plus(str(location)) body = request( client, "https://api.twitter.com/oauth/request_token" "?oauth_callback=" + callback, "GET") data = dict(parse_qsl(body)) session[oauth_secret_session_key] = data["oauth_token_secret"] # Redirect the user to the login form auth_url = ("https://api.twitter.com/oauth/authorize?" "oauth_token=%s" "&oauth_callback=%s" % (data["oauth_token"], callback)) raise cherrypy.HTTPRedirect(auth_url) else: token = Token(oauth_token, session[oauth_secret_session_key]) token.set_verifier(oauth_verifier) client = Client(consumer, token) body = request(client, 'https://api.twitter.com/oauth/access_token', "POST") data = dict(parse_qsl(body)) target.auth_token = data["oauth_token"] target.auth_secret = data["oauth_token_secret"] datastore.commit() except TwitterAPIError, ex: notify_user(translations(ex), category="error", transient=False)
def initializer(session): if open_browser: # Find the web console document webconsole = Publishable.require_instance( qname="woost.extensions.webconsole.page") # Determine the URI for the breakpoint session webconsole_location = Location.get_current_host() webconsole_location.path_info = webconsole.get_uri() webconsole_location.query_string["session_id"] = session.id # Open a web browser tab pointing at the URI from webbrowser import open open(str(webconsole_location))
def process_login(self): params = cherrypy.request.params if "authenticate" in params: self.login( params.get("user"), params.get("password") ) # Request the current location again, with all authentication # parameters stripped location = Location.get_current() for params in (location.query_string, location.form_data): params.pop("user", None) params.pop("password", None) params.pop("authenticate", None) location.go("GET")
def extract_video_id(string): try: if string.startswith("http"): location = Location(string) return location.query_string["v"][0] except: pass try: if "youtu.be" in string: return string[string.rfind("/") + 1:] except: pass return string
def initiate_payment(self, payment_id): """Begin a payment transaction, redirecting the user to the payment gateway. @param payment_id: The identifier of the payment to execute. """ url, params = self.get_payment_form_data(payment_id, get_language()) location = Location(url) location.method = "POST" location.form_data = OrderedDict(params) location.go()
def invoke(self, controller, selection): publication_target = selection[0] code = cherrypy.request.params.get("code") error = cherrypy.request.params.get("error") error_reason = cherrypy.request.params.get("error_reason") error_description = cherrypy.request.params.get("error_description") # Authorization failed if error: notify_user(translations( "woost.extensions.facebookauthentication." "fbpublish_auth.error", ), category="error", transient=False) # Authorization successful elif code: location = Location.get_current(relative=False) del location.query_string["code"] auth_url = ("https://graph.facebook.com/oauth/access_token?" "client_id=%s" "&redirect_uri=%s" "&client_secret=%s" "&code=%s" % (publication_target.app_id, quote_plus(str(location)), publication_target.app_secret, code)) response = urlopen(auth_url) response_status = response.getcode() response_body = response.read() if response_status < 200 or response_status > 299: notify_user(translations( "woost.extensions.facebookauthentication." "fbpublish_auth.oauth_error", response=response_body), category="error", transient=False) return auth_token = response_body.split("&")[0].split("=")[1] # Facebook pages require an additional authentication step fb_page_id = cherrypy.request.params.get("fb_page") if fb_page_id: accounts_url = ( "https://graph.facebook.com/%s/accounts?access_token=%s" % (publication_target.administrator_id, auth_token)) response_data = urlopen(accounts_url).read() json = loads(response_data) for account in json["data"]: if account["id"] == fb_page_id: auth_token = account["access_token"] break else: auth_token = None publication_target.auth_token = auth_token datastore.commit() notify_user(translations("woost.extensions.facebookauthentication." "fbpublish_auth.success"), category="success") # Begin authorization request else: # Determine if the selected graph URL is a Facebook Page graph_url = "http://graph.facebook.com/%s?metadata=1" \ % publication_target.graph_object_id response_data = urlopen(graph_url).read() json = loads(response_data) fb_page_id = json["metadata"]["type"] == "page" and json["id"] location = Location.get_current(relative=False) location.query_string["item_action"] = self.id permissions = "publish_stream,offline_access,user_photos" if fb_page_id: location.query_string["fb_page"] = fb_page_id permissions += ",manage_pages" auth_url = ("https://www.facebook.com/dialog/oauth?" "client_id=%s" "&redirect_uri=%s" "&scope=%s" % (publication_target.app_id, quote_plus(str(location)), permissions)) raise cherrypy.HTTPRedirect(auth_url)
def _after_process_comments(self, comment): raise cherrypy.HTTPRedirect( "%s#comment-%s" % (unicode(Location.get_current()).encode('utf-8'), str(comment.id)))
def _require_edit_node(self): redirect = False context_item = self.context["cms_item"] edit_stacks_manager = self.context["edit_stacks_manager"] edit_stack = edit_stacks_manager.current_edit_stack # Spawn a new edit stack if edit_stack is None: edit_stack = edit_stacks_manager.create_edit_stack() edit_stacks_manager.current_edit_stack = edit_stack redirect = True else: # Integral part; add a new relation node (won't be shown to the # user) member_name = self.params.read(schema.String("member")) if member_name: node = RelationNode() node.member = edit_stack[-1].content_type[member_name] # Preserve the selected tab group = node.member.member_group if group: pos = group.find(".") if pos != -1: group = group[:pos] edit_stack[-1].tab = group edit_stack.push(node) redirect = True # Make sure the top node of the stack is an edit node if not edit_stack \ or not isinstance(edit_stack[-1], EditNode) \ or (context_item and context_item.id != edit_stack[-1].item.id): # New item if context_item is None: content_type = get_parameter( schema.Reference("item_type", class_family=Item)) item = content_type() # Existing item else: item = context_item node_class = resolve(item.edit_node_class) node = node_class(item) edit_stack.push(node) redirect = True if not item.is_inserted: node.initialize_new_item(item, self.visible_languages) # If the stack is modified a redirection is triggered so that any # further request mentions the new stack position in its parameters. # However, the redirection won't occur if the controller itself is the # final target of the current request - if that is the case, submit() # will end up redirecting the user to the default section anyway if redirect and self is not cherrypy.request.handler: location = Location.get_current() location.method = "GET" location.params["edit_stack"] = edit_stack.to_param() location.params.pop("member", None) location.hash = Location.empty_hash location.go() return edit_stack