Beispiel #1
0
 def delete(self):
     session = db.session()
     session.delete(self.obj)
     activity.send(
         self,
         actor=g.user,
         verb="delete",
         object=self.obj,
         target=self.activity_target,
     )
     try:
         session.commit()
     except sa.exc.IntegrityError as e:
         rv = self.handle_commit_exception(e)
         if rv is not None:
             return rv
         session.rollback()
         logger.error(e)
         flash(
             _("This entity is referenced by another object and cannot be deleted."
               ),
             "error",
         )
         return self.redirect_to_view()
     else:
         flash(self.message_success(), "success")
         # FIXME: for DELETE verb response in case of success should be 200, 202
         # (accepted) or 204 (no content)
         return self.redirect_to_index()
Beispiel #2
0
 def delete(self):
     session = db.session()
     session.delete(self.obj)
     activity.send(
         self,
         actor=g.user,
         verb="delete",
         object=self.obj,
         target=self.activity_target,
     )
     try:
         session.commit()
     except sa.exc.IntegrityError as e:
         rv = self.handle_commit_exception(e)
         if rv is not None:
             return rv
         session.rollback()
         logger.error(e)
         flash(
             _("This entity is referenced by another object and cannot be deleted."),
             "error",
         )
         return self.redirect_to_view()
     else:
         flash(self.message_success(), "success")
         # FIXME: for DELETE verb response in case of success should be 200, 202
         # (accepted) or 204 (no content)
         return self.redirect_to_index()
Beispiel #3
0
def create_document(folder, fs):
    check_write_access(folder)

    if isinstance(fs.filename, str):
        name = fs.filename
    else:
        name = str(fs.filename, errors="ignore")

    if not name:
        flash(_("Document name can't be empty."), "error")
        return None

    original_name = name
    name = get_new_filename(folder, name)
    doc = folder.create_document(title=name)
    doc.set_content(fs.read(), fs.content_type)

    if original_name != name:
        # set message after document has been successfully created!
        flash(
            _('"{original}" already present in folder, ' 'renamed "{name}"').format(
                original=original_name, name=name
            ),
            "info",
        )

    # Some unwrapping before posting event
    app = unwrap(current_app)
    community = g.community._model
    activity.send(app, actor=current_user, verb="post", object=doc, target=community)

    return doc
Beispiel #4
0
 def send_activity(self):
     activity.send(
         self,
         actor=g.user,
         verb=self.activity_verb,
         object=self.obj,
         target=self.activity_target)
Beispiel #5
0
def create_document(folder, fs):
    check_write_access(folder)

    if isinstance(fs.filename, text_type):
        name = fs.filename
    else:
        name = text_type(fs.filename, errors="ignore")

    if not name:
        flash(_("Document name can't be empty."), "error")
        return None

    original_name = name
    name = get_new_filename(folder, name)
    doc = folder.create_document(title=name)
    doc.set_content(fs.read(), fs.content_type)

    if original_name != name:
        # set message after document has been successfully created!
        flash(
            _('"{original}" already present in folder, '
              'renamed "{name}"').format(original=original_name, name=name),
            "info",
        )

    # Some unwrapping before posting event
    app = unwrap(current_app)
    community = g.community._model
    activity.send(app,
                  actor=current_user,
                  verb="post",
                  object=doc,
                  target=community)

    return doc
Beispiel #6
0
 def send_activity(self):
     activity.send(
         self,
         actor=g.user,
         verb=self.activity_verb,
         object=self.obj,
         target=self.activity_target,
     )
Beispiel #7
0
 def delete(self):
   session = current_app.db.session()
   session.delete(self.obj)
   activity.send(self, actor=g.user, verb="delete", object=self.obj)
   session.commit()
   flash(self.message_success(), 'success')
   #FIXME: for DELETE verb response in case of success should be 200, 202
   #(accepted) or 204 (no content)
   return self.redirect_to_index()
Beispiel #8
0
 def entity_delete(self, entity_id):
   # TODO: don't really delete, switch state to "deleted"
   entity = self.managed_class.query.get(entity_id)
   assert entity is not None
   db.session.delete(entity)
   activity.send(self, actor=g.user, verb="delete", object=entity)
   db.session.commit()
   flash(_(u"Entity deleted"), "success")
   return redirect(self.url)
Beispiel #9
0
 def delete(self):
     session = current_app.db.session()
     session.delete(self.obj)
     activity.send(self,
                   actor=g.user,
                   verb="delete",
                   object=self.obj,
                   target=self.activity_target)
     session.commit()
     flash(self.message_success(), 'success')
     # FIXME: for DELETE verb response in case of success should be 200, 202
     # (accepted) or 204 (no content)
     return self.redirect_to_index()
Beispiel #10
0
def document_upload(doc_id):
    doc = get_document(doc_id)
    check_write_access(doc)

    fd = request.files["file"]
    doc.set_content(fd.read(), fd.content_type)
    del doc.lock

    self = unwrap(current_app)
    activity.send(self, actor=current_user, verb="update", object=doc)
    db.session.commit()
    flash(_("New version successfully uploaded"), "success")
    return redirect(url_for(doc))
Beispiel #11
0
def document_upload(doc_id):
    doc = get_document(doc_id)
    check_write_access(doc)

    fd = request.files["file"]
    doc.set_content(fd.read(), fd.content_type)
    del doc.lock

    self = unwrap(current_app)
    activity.send(self, actor=current_user, verb="update", object=doc)
    db.session.commit()
    flash(_("New version successfully uploaded"), "success")
    return redirect(url_for(doc))
Beispiel #12
0
def wizard_saving():
    """Automatically add existing accounts to the current community.

    Create accounts for new emails, add them to the community and send
    them a password reset email.
    """
    community = g.community._model
    existing_accounts = request.form.get("existing_account")
    existing_accounts = json.loads(existing_accounts)
    new_accounts = request.form.get("new_accounts")
    new_accounts = json.loads(new_accounts)

    if not (existing_accounts or new_accounts):
        flash(_("No new members were found"), "warning")
        return redirect(url_for(".members", community_id=g.community.slug))

    if existing_accounts:
        for email, role in existing_accounts.items():
            user = User.query.filter(User.email == email).first()
            community.set_membership(user, role)

            app = unwrap(current_app)
            activity.send(app, actor=user, verb="join", object=community)

            db.session.commit()

    if new_accounts:
        for account in new_accounts:
            email = account["email"]
            first_name = account["first_name"]
            last_name = account["last_name"]
            role = account["role"]

            user = User(
                email=email, last_name=last_name, first_name=first_name, can_login=True
            )
            db.session.add(user)

            community.set_membership(user, role)
            app = unwrap(current_app)
            activity.send(app, actor=user, verb="join", object=community)
            db.session.commit()

            send_reset_password_instructions(user)

    flash(_("New members added successfully"), "success")
    return redirect(url_for(".members", community_id=community.slug))
Beispiel #13
0
def wizard_saving():
    """Automatically add existing accounts to the current community.

    Create accounts for new emails, add them to the community and send
    them a password reset email.
    """
    community = g.community._model
    existing_accounts = request.form.get("existing_account")
    existing_accounts = json.loads(existing_accounts)
    new_accounts = request.form.get("new_accounts")
    new_accounts = json.loads(new_accounts)

    if not (existing_accounts or new_accounts):
        flash(_("No new members were found"), "warning")
        return redirect(url_for(".members", community_id=g.community.slug))

    if existing_accounts:
        for email, role in existing_accounts.items():
            user = User.query.filter(User.email == email).first()
            community.set_membership(user, role)

            app = unwrap(current_app)
            activity.send(app, actor=user, verb="join", object=community)

            db.session.commit()

    if new_accounts:
        for account in new_accounts:
            email = account["email"]
            first_name = account["first_name"]
            last_name = account["last_name"]
            role = account["role"]

            user = User(
                email=email, last_name=last_name, first_name=first_name, can_login=True
            )
            db.session.add(user)

            community.set_membership(user, role)
            app = unwrap(current_app)
            activity.send(app, actor=user, verb="join", object=community)
            db.session.commit()

            send_reset_password_instructions(user)

    flash(_("New members added successfully"), "success")
    return redirect(url_for(".members", community_id=community.slug))
Beispiel #14
0
def page_delete():
    title = request.form["title"].strip()
    try:
        page = get_page_by_title(title)
    except NoResultFound:
        flash(_("This page doesn't exist"), "error")
        return redirect(url_for(".index", community_id=g.community.slug))

    db.session.delete(page)

    app = unwrap(current_app)
    community = g.community._model
    activity.send(app, actor=current_user, verb="delete", object=page, target=community)

    db.session.commit()
    flash(_("Page %(title)s deleted.", title=title))
    return redirect(url_for(".index", community_id=g.community.slug))
Beispiel #15
0
  def edit(self):
    if self.form.validate():
      self.before_populate_obj()
      self.form.populate_obj(self.obj)

      session = current_app.db.session()
      session.add(self.obj)
      try:
        session.flush()
        activity.send(self, actor=g.user, verb="update", object=self.obj)
        session.commit()
      except ValidationError, e:
        session.rollback()
        flash(e.message, "error")
      except sa.exc.IntegrityError, e:
        session.rollback()
        logger.error(e)
        flash(_(u"An entity with this name already exists in the database."),
              "error")
Beispiel #16
0
def delete_multiple(folder):
    check_write_access(folder)

    folders, docs = get_selected_objects(folder)

    for obj in docs + folders:
        app = unwrap(current_app)
        community = g.community._model
        activity.send(app,
                      actor=current_user,
                      verb="delete",
                      object=obj,
                      target=community)
        repository.delete_object(obj)

    if docs + folders:
        db.session.commit()
        if docs and folders:
            msg = _(
                "%(file_num)d files and %(folder_num)d folders sucessfully "
                "deleted.",
                file_num=len(docs),
                folder_num=len(folders),
            )
        elif docs and not folders:
            msg = _n(
                "1 file sucessfully deleted.",
                "%(num)d files sucessfully deleted.",
                num=len(docs),
            )
        else:
            msg = _n(
                "1 folder sucessfully deleted.",
                "%(num)d folders sucessfully deleted.",
                num=len(folders),
            )

        flash(msg, "success")
    else:
        flash(_("No object deleted"), "error")

    return redirect(url_for(folder))
Beispiel #17
0
def page_delete():
    title = request.form['title'].strip()
    try:
        page = get_page_by_title(title)
    except NoResultFound:
        flash(_(u"This page doesn't exist"), "error")
        return redirect(url_for(".index", community_id=g.community.slug))

    db.session.delete(page)

    app = current_app._get_current_object()
    community = g.community._model
    activity.send(app,
                  actor=g.user,
                  verb="delete",
                  object=page,
                  target=community)

    db.session.commit()
    flash(_(u"Page %(title)s deleted.", title=title))
    return redirect(url_for(".index", community_id=g.community.slug))
Beispiel #18
0
def members_post():
    community = g.community._model
    action = request.form.get("action")

    user_id = request.form.get("user")
    if not user_id:
        flash(_("You must provide a user."), "error")
        return redirect(url_for(".members", community_id=community.slug))
    user_id = int(user_id)
    user = User.query.get(user_id)

    if action in ("add-user-role", "set-user-role"):
        role = request.form.get("role").lower()

        community.set_membership(user, role)

        if action == "add-user-role":
            app = unwrap(current_app)
            activity.send(app, actor=user, verb="join", object=community)

        db.session.commit()
        return redirect(url_for(".members", community_id=community.slug))

    elif action == "delete":
        membership_id = int(request.form["membership"])
        membership = Membership.query.get(membership_id)
        if membership.user_id != user_id:
            raise InternalServerError()

        community.remove_membership(user)

        app = unwrap(current_app)
        activity.send(app, actor=user, verb="leave", object=community)

        db.session.commit()
        return redirect(url_for(".members", community_id=community.slug))

    else:
        raise BadRequest("Unknown action: {}".format(repr(action)))
Beispiel #19
0
def members_post():
    community = g.community._model
    action = request.form.get("action")

    user_id = request.form.get("user")
    if not user_id:
        flash(_(u"You must provide a user."), 'error')
        return redirect(url_for(".members", community_id=community.slug))
    user_id = int(user_id)
    user = User.query.get(user_id)

    if action in ('add-user-role', 'set-user-role'):
        role = request.form.get("role").lower()

        community.set_membership(user, role)

        if action == 'add-user-role':
            app = current_app._get_current_object()
            activity.send(app, actor=user, verb="join", object=community)

        db.session.commit()
        return redirect(url_for('.members', community_id=community.slug))

    elif action == 'delete':
        membership_id = int(request.form['membership'])
        membership = Membership.query.get(membership_id)
        if membership.user_id != user_id:
            raise InternalServerError()

        community.remove_membership(user)

        app = current_app._get_current_object()
        activity.send(app, actor=user, verb="leave", object=community)

        db.session.commit()
        return redirect(url_for(".members", community_id=community.slug))

    else:
        raise BadRequest('Unknown action: {}'.format(repr(action)))
Beispiel #20
0
def delete_multiple(folder):
    check_write_access(folder)

    folders, docs = get_selected_objects(folder)

    for obj in docs + folders:
        app = unwrap(current_app)
        community = g.community._model
        activity.send(
            app, actor=current_user, verb="delete", object=obj, target=community
        )
        repository.delete_object(obj)

    if docs + folders:
        db.session.commit()
        if docs and folders:
            msg = _(
                "%(file_num)d files and %(folder_num)d folders sucessfully " "deleted.",
                file_num=len(docs),
                folder_num=len(folders),
            )
        elif docs and not folders:
            msg = _n(
                "1 file sucessfully deleted.",
                "%(num)d files sucessfully deleted.",
                num=len(docs),
            )
        else:
            msg = _n(
                "1 folder sucessfully deleted.",
                "%(num)d folders sucessfully deleted.",
                num=len(folders),
            )

        flash(msg, "success")
    else:
        flash(_("No object deleted"), "error")

    return redirect(url_for(folder))
Beispiel #21
0
def members_post():
    community = g.community._model
    action = request.form.get("action")

    user_id = request.form.get("user")
    if not user_id:
        flash(_("You must provide a user."), "error")
        return redirect(url_for(".members", community_id=community.slug))
    user_id = int(user_id)
    user = User.query.get(user_id)

    if action in ("add-user-role", "set-user-role"):
        role = request.form.get("role").lower()

        community.set_membership(user, role)

        if action == "add-user-role":
            app = unwrap(current_app)
            activity.send(app, actor=user, verb="join", object=community)

        db.session.commit()
        return redirect(url_for(".members", community_id=community.slug))

    elif action == "delete":
        membership_id = int(request.form["membership"])
        membership = Membership.query.get(membership_id)
        if membership.user_id != user_id:
            raise InternalServerError()

        community.remove_membership(user)

        app = unwrap(current_app)
        activity.send(app, actor=user, verb="leave", object=community)

        db.session.commit()
        return redirect(url_for(".members", community_id=community.slug))

    else:
        raise BadRequest("Unknown action: {}".format(repr(action)))
Beispiel #22
0
  def entity_new_put(self):
    form = self.edit_form_class()
    entity = self.managed_class()
    action = request.form.get('_action')

    if action == 'cancel':  # FIXME: what if action is None?
      return redirect("%s/" % self.url)

    if form.validate():
      form.populate_obj(entity)
      db.session.add(entity)
      try:
        db.session.flush()
        activity.send(self, actor=g.user, verb="post", object=entity)
        db.session.commit()
      except ValidationError, e:
        db.session.rollback()
        flash(e.message, "error")
      except IntegrityError, e:
        db.session.rollback()
        flash(_(u"An entity with this name already exists in the database"),
              "error")
Beispiel #23
0
  def entity_edit_post(self, entity_id):
    entity = self.managed_class.query.get(entity_id)
    assert entity is not None
    form = self.edit_form_class(obj=entity)

    if request.form.get('_action') == 'cancel':
      return redirect("%s/%d" % (self.url, entity_id))
    elif form.validate():
      form.populate_obj(entity)
      try:
        db.session.flush()
        activity.send(self, actor=g.user, verb="update", object=entity)
        db.session.commit()
        flash(_(u"Entity successfully edited"), "success")
        return redirect("%s/%d" % (self.url, entity_id))
      except ValidationError, e:
        db.session.rollback()
        flash(e.message, "error")
      except IntegrityError, e:
        db.session.rollback()
        logger.error(e)
        flash(_(u"An entity with this name already exists in the database."),
              "error")
Beispiel #24
0
def process_email(message):
    # type: (email.message.Message) -> bool
    """Email.Message object from command line script Run message (parsed
    email).

    Processing chain extract community thread post member from reply_to
    persist post in db.
    """
    app = unwrap(current_app)
    # Extract post destination from To: field, (community/forum/thread/member)
    to_address = message["To"]

    assert isinstance(to_address, text_type)

    if not (has_subtag(to_address)):
        logger.info("Email %r has no subtag, skipping...", to_address)
        return False

    try:
        infos = extract_email_destination(to_address)
        locale = infos[0]
        thread_id = infos[1]
        user_id = infos[2]
    except BaseException:
        logger.error(
            "Recipient %r cannot be converted to locale/thread_id/user.id",
            to_address,
            exc_info=True,
        )
        return False

    # Translate marker with locale from email address
    rq_headers = [("Accept-Language", locale)]
    with app.test_request_context("/process_email", headers=rq_headers):
        marker = text_type(MAIL_REPLY_MARKER)

    # Extract text and attachments from message
    try:
        newpost, attachments = process(message, marker)
    except BaseException:
        logger.error("Could not Process message", exc_info=True)
        return False

    # Persist post
    with current_app.test_request_context("/process_email",
                                          headers=rq_headers):
        g.user = User.query.get(user_id)
        thread = Thread.query.get(thread_id)
        community = thread.community
        # FIXME: check membership, send back an informative email in case of an
        # error
        post = thread.create_post(body_html=newpost)
        obj_meta = post.meta.setdefault("abilian.sbe.forum", {})
        obj_meta["origin"] = "email"
        obj_meta["send_by_email"] = True
        activity.send(app,
                      actor=g.user,
                      verb="post",
                      object=post,
                      target=community)

        for desc in attachments:
            attachment = PostAttachment(name=desc["filename"])
            attachment.post = post
            attachment.set_content(desc["data"], desc["content_type"])
            db.session.add(attachment)
        db.session.commit()

    # Notify all parties involved
    send_post_by_email.delay(post.id)
    return True
Beispiel #25
0
def process_email(message):
    # type: (email.message.Message) -> bool
    """Email.Message object from command line script Run message (parsed
    email).

    Processing chain extract community thread post member from reply_to
    persist post in db.
    """
    app = unwrap(current_app)
    # Extract post destination from To: field, (community/forum/thread/member)
    to_address = message["To"]

    assert isinstance(to_address, str)

    if not (has_subtag(to_address)):
        logger.info("Email %r has no subtag, skipping...", to_address)
        return False

    try:
        infos = extract_email_destination(to_address)
        locale = infos[0]
        thread_id = infos[1]
        user_id = infos[2]
    except BaseException:
        logger.error(
            "Recipient %r cannot be converted to locale/thread_id/user.id",
            to_address,
            exc_info=True,
        )
        return False

    # Translate marker with locale from email address
    rq_headers = [("Accept-Language", locale)]
    with app.test_request_context("/process_email", headers=rq_headers):
        marker = str(MAIL_REPLY_MARKER)

    # Extract text and attachments from message
    try:
        newpost, attachments = process(message, marker)
    except BaseException:
        logger.error("Could not Process message", exc_info=True)
        return False

    # Persist post
    with current_app.test_request_context("/process_email", headers=rq_headers):
        g.user = User.query.get(user_id)
        thread = Thread.query.get(thread_id)
        community = thread.community
        # FIXME: check membership, send back an informative email in case of an
        # error
        post = thread.create_post(body_html=newpost)
        obj_meta = post.meta.setdefault("abilian.sbe.forum", {})
        obj_meta["origin"] = "email"
        obj_meta["send_by_email"] = True
        activity.send(app, actor=g.user, verb="post", object=post, target=community)

        for desc in attachments:
            attachment = PostAttachment(name=desc["filename"])
            attachment.post = post
            attachment.set_content(desc["data"], desc["content_type"])
            db.session.add(attachment)
        db.session.commit()

    # Notify all parties involved
    send_post_by_email.delay(post.id)
    return True
Beispiel #26
0
def process_email(message):
    """
    Email.Message object from command line script Run message (parsed email).

    Processing chain extract community thread post member from reply_to persist
    post in db.
    """
    app = current_app._get_current_object()
    # Extract post destination from To: field, (community/forum/thread/member)
    to_address = message['To']

    if not (has_subtag(to_address)):
        logger.info('Email %r has no subtag, skipping...', to_address)
        return False

    try:
        infos = extract_email_destination(to_address)
        locale = infos[0]
        thread_id = infos[1]
        user_id = infos[2]
    except:
        logger.error(
            'Recipient %r cannot be converted to locale/thread_id/user.id',
            to_address,
            exc_info=True)
        return False

    # Translate marker with locale from email address
    rq_headers = [('Accept-Language', locale)]
    with app.test_request_context('/process_email', headers=rq_headers):
        marker = text_type(MAIL_REPLY_MARKER)

    # Extract text and attachments from message
    try:
        newpost, attachments = process(message, marker)
    except:
        logger.error('Could not Process message', exc_info=True)
        return False

    # Persist post
    with current_app.test_request_context('/process_email',
                                          headers=rq_headers):
        g.user = User.query.get(user_id)
        thread = Thread.query.get(thread_id)
        community = thread.community
        # FIXME: check membership, send back an informative email in case of an error
        post = thread.create_post(body_html=newpost)
        obj_meta = post.meta.setdefault('abilian.sbe.forum', {})
        obj_meta['origin'] = u'email'
        obj_meta['send_by_email'] = True
        activity.send(app,
                      actor=g.user,
                      verb='post',
                      object=post,
                      target=community)

        for desc in attachments:
            attachment = PostAttachment(name=desc['filename'])
            attachment.post = post
            attachment.set_content(desc['data'], desc['content_type'])
            db.session.add(attachment)
        db.session.commit()

    # Notify all parties involved
    send_post_by_email.delay(post.id)
    return True