Ejemplo n.º 1
0
    def handle_exception_raised(cls, event):

        # Redirect the user to the backoffice root when failing to load an edit
        # stack node
        if isinstance(event.exception, WrongEditStackError):
            notify_user(translations(event.exception), "error")
            raise cherrypy.HTTPRedirect(event.source.contextual_uri())
Ejemplo n.º 2
0
 def handle_exception_raised(event):                                                                                                                                                                   
     if isinstance(
         event.exception,
         RunningMailingError
     ):  
         notify_user(translations(event.exception), "error")
         raise cherrypy.HTTPRedirect(event.source.contextual_uri())
Ejemplo n.º 3
0
    def submit(self):

        # TODO: cycle prevention
        # TODO: support for inserting before a sibling
        # TODO: dropping objects on objects (inferring/asking the target member)

        @transactional()
        def relate():
            dragged_object = self.dragged_object
            target_object = self.target_object
            target_member = self.target_member

            user = get_current_user()
            user.require_permission(ModifyPermission, target=dragged_object)
            user.require_permission(ModifyPermission, target=target_object)

            with changeset_context(user):
                if isinstance(target_member, schema.Reference):
                    target_object.set(target_member, dragged_object)
                else:
                    collection = target_object.get(target_member)

                    sibling = self.sibling
                    relative_placement = self.relative_placement

                    if sibling:
                        try:
                            current_index = collection.index(dragged_object)
                        except ValueError:
                            current_index = None
                        index = collection.index(sibling)

                        if relative_placement == "before":
                            if current_index is not None and current_index < index:
                                index -= 1
                        elif relative_placement == "after":
                            if current_index is None or current_index >= index:
                                index += 1

                        if isinstance(collection,
                                      (OrderedSet, InstrumentedOrderedSet)):
                            kwargs = {"relocate": True}
                        else:
                            kwargs = {}

                        collection.insert(index, dragged_object, **kwargs)
                    else:
                        collection.append(dragged_object)

        relate()

        notify_user(translations(
            "woost.controllers.backoffice.DragAndDropController"
            ".drop_notification",
            dragged_object=self.dragged_object,
            target_object=self.target_object,
            target_member=self.target_member),
                    "success",
                    transient=False)
Ejemplo n.º 4
0
 def submit(self):
     Basket.empty()
     notify_user(
         translations("woost.extensions.ecommerce."
                      "empty_basket_notice"),
         category = "success"
     )
     Location.get_current().go("GET")
Ejemplo n.º 5
0
 def item_saved_notification(self, is_new, change):
     if change and "enabled" in change.changed_members:
         notify_user(
             translations("woost.controllers.backoffice.ExtensionEditNode "
                          "%s extension needs reloading" %
                          ("enabled" if self.item.enabled else "disabled"),
                          extension=self.item),
             "notice",
             transient=False)
     else:
         EditNode.item_saved_notification(self, is_new, change)
Ejemplo n.º 6
0
    def invoke(self, controller, selection):

        if selection is None:
            app.cache.clear()
        else:
            for item in selection:
                item.clear_cache()

        notify_user(
            translations("woost.cache_invalidated_notice", subset = selection),
            "success"
        )
    def handle_committed(cls, event):

        item = event.source.item
        try:
            item.update()
        except Exception, e:
            notify_user(translations(
                "woost.extensions.campaignmonitorlisteditnode.CampaignMonitorListEditNode failed synchronization",
                item=item,
                exception=e),
                        "error",
                        transient=False)
Ejemplo n.º 8
0
    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)
Ejemplo n.º 9
0
 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")
Ejemplo n.º 10
0
        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")
Ejemplo n.º 11
0
        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")
Ejemplo n.º 12
0
    def invoke(self, controller, selection):
        clipboard = get_block_clipboard_contents()

        if not clipboard:
            notify_user(
                translations("woost.block_clipboard.empty"),
                "error"
            )
        else:
            try:
                block = Block.require_instance(clipboard["block"])
                src_parent = Item.require_instance(clipboard["block_parent"])
                src_slot = type(src_parent).get_member(clipboard["block_slot"])
            except:
                notify_user(
                    translations("woost.block_clipboard.error"),
                    "error"
                )
            else:
                # Remove the block from the source location
                if clipboard["mode"] == "cut":
                    if isinstance(src_slot, schema.Reference):
                        src_parent.set(src_slot, None)
                    elif isinstance(src_slot, schema.Collection):
                        src_collection = src_parent.get(src_slot)
                        schema.remove(src_collection, block)
                # Or copy it
                elif clipboard["mode"] == "copy":
                    block = block.create_copy()
                    block.insert()

                # Add the block to its new position
                add_block(
                    block, 
                    controller.block_parent,
                    controller.block_slot,
                    positioning = self.block_positioning,
                    anchor = controller.block
                )

                datastore.commit()
                del session[BLOCK_CLIPBOARD_SESSION_KEY]
                focus_block(block)
Ejemplo n.º 13
0
    def _synchronize(self):
        cmp = self.comparision
        get_param = cherrypy.request.params.get
        file_downloads = set()
        selection = self.sync_selection

        with changeset_context(get_current_user()):

            for obj in cmp["incomming"]:
                if obj.global_id in selection:
                    obj.insert()

                    if isinstance(obj, File):
                        file_downloads.add(obj)

            for global_id, change in cmp["modified"].iteritems():
                if global_id in selection:
                    local = change["local"]
                    remote = change["remote"]

                    for member, lang in change["diff"]:
                        value = schema.get(remote, member, language=lang)
                        local.set(member, value, lang)

                        if member in (File.file_hash, File.file_size):
                            file_downloads.add(local)

        # Download files from the remote copy
        for file in file_downloads:
            self.synchronization.download_file(file)

        # Find importable content again
        self.comparision = self.synchronization.compare_content()

        notify_user(
            translations(
                "woost.controllers.InstallationSyncController.success"),
            "success")
Ejemplo n.º 14
0
    def item_saved_notification(self, is_new, change):
        """Notifies the user that the node's item has been saved.

        @param is_new: Indicates if the save operation consisted of an
            insertion (True) or an update of an existing item (False).
        @type is_new: bool

        @param change: A change object describing the save operation.
        @type change: L{Change<woost.models.changeset.Change>}            
        """
        item = self.item
        msg = translations("woost.views.BackOfficeEditView Changes saved",
                           item=item,
                           is_new=is_new)
        transient = True

        if is_new and self.parent_node is None:
            controller = cherrypy.request.handler_chain[-1]
            msg += '. <a href="%s">%s</a>.' % (
                controller.edit_uri(item.__class__, edit_stack=None),
                translations("woost.views.BackOfficeEditView Create another"))
            transient = False

        notify_user(msg, "success", transient)
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
0
 def _handle_user_action_error(self, action, selection, error):
     if isinstance(error, tuple(self._graceful_user_action_errors)):
         notify_user(translations(error), "error")
         self.go_back()
     else:
         raise error
#-*- coding: utf-8 -*-
u"""

.. moduleauthor:: Jordi Fernández <*****@*****.**>
"""
from cocktail.events import event_handler
from cocktail.translations import translations
from woost.controllers.backoffice.editstack import EditNode
from woost.controllers.notifications import notify_user


class CampaignMonitorListEditNode(EditNode):
    @event_handler
    def handle_committed(cls, event):

        item = event.source.item
        try:
            item.update()
        except Exception, e:
            notify_user(translations(
                "woost.extensions.campaignmonitorlisteditnode.CampaignMonitorListEditNode failed synchronization",
                item=item,
                exception=e),
                        "error",
                        transient=False)
        else:
            notify_user(
                translations(
                    "woost.extensions.campaignmonitorlisteditnode.CampaignMonitorListEditNode synchronized changes",
                    item=item), "success")
Ejemplo n.º 18
0
                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)
        else:
            notify_user(translations("woost.extensions.twitterpublication."
                                     "successful_authorization_notice"),
                        category="success")


TwitterAuthUserAction("twitter_auth").register()