示例#1
0
 def fetch_all_items(self):
     user_id = components.current_user_id()
     return Category.select(Category).join(
         components.BaseUser,
         on=(Category.owner == components.BaseUser.id)).where(
             Category.is_deleted == False,
             components.BaseUser.id == user_id).order_by(Category.path)
示例#2
0
    def search_tags(self, search_query, result_limit):
        result_map = {}
        user_id = components.current_user_id()
        # I admit, it's ineffective in so many ways
        words = [
            word for word in self._make_fuzzy(search_query.split(" ")) if word
        ]
        for word in words:
            tags_select = Tag.select(Tag)\
                .join(FuzzyTag)\
                .join(components.BaseUser, on=(Tag.owner == components.BaseUser.id))\
                .where(
                    FuzzyTag.fuzzy.contains(word),
                    components.BaseUser.id == user_id)
            for tag in tags_select:
                ld = Levenshtein.distance(str(tag.tag), search_query)
                if tag not in result_map or ld < result_map[tag]:
                    result_map[tag] = ld

        # order results by score
        result_map = OrderedDict(
            (k, result_map[k]) for k in sorted(result_map, key=result_map.get))

        logging.debug("result_set_distances=[{}]".format(", ".join(
            [str(k) + "=" + str(v) for k, v in result_map.items()])))

        if result_limit:
            return [tag for tag in result_map.keys()][:result_limit]
        return [tag for tag in result_map.keys()]
示例#3
0
 def delete_item(self, token_id):
     user_id = components.current_user_id()
     item = UserAuthenticator.select(UserAuthenticator).join(
         components.BaseUser,
         on=(UserAuthenticator.owner == components.BaseUser.id)).where(
             UserAuthenticator.id == token_id,
             UserAuthenticator.owner.id == user_id).get()
     item.delete_item()
示例#4
0
    def fetch_and_add_profile(self, service, token_obj):
        config = self._config()

        current_user = components.current_user()
        credentials = Credentials(
            token_obj["access_token"],
            refresh_token=token_obj["access_token"],
            id_token=token_obj["id_token"],
            client_id=config["client_id"],
            client_secret=config["client_secret"],
            scopes=[
                "email", "profile",
                "https://www.googleapis.com/auth/userinfo.email", "openid",
                "https://www.googleapis.com/auth/userinfo.profile"
            ])

        user_info = build("oauth2", "v2",
                          credentials=credentials).userinfo().get().execute()
        user_info_string = json.dumps(user_info)

        # Check if had been added before
        authenticator = None
        try:
            current_user_id = components.current_user_id()

            # Only one instance is supported ATM
            authenticator = UserAuthenticator.select(UserAuthenticator).join(
                components.BaseUser).where(
                    UserAuthenticator.owner.id == current_user_id,
                    UserAuthenticator.idp_id ==
                    GoogleAuthenticator.idp_id).get()

            # If exists, then renew
            authenticator.access_token = token_obj["access_token"]
            authenticator.expires_at = token_obj["expires_at"]
            authenticator.profile = user_info_string
            authenticator.save()

        except UserAuthenticator.DoesNotExist:
            # If not exists, insert
            try:
                authenticator = UserAuthenticator(
                    owner=current_user,
                    idp_id="google",
                    access_token=token_obj["access_token"],
                    id_token=token_obj["id_token"],
                    expires_at=token_obj["expires_at"],
                    profile=user_info_string,
                )
                authenticator.save()
                return True

            except:
                logging.exception("Could not get user info")
                return False
        except:
            logging.exception("Could not get user info")
            return False
示例#5
0
 def fetch_all_items(self, search_query, result_limit):
     if search_query:
         return self.search_tags(search_query, result_limit)
     else:
         user_id = components.current_user_id()
         return Tag.select(Tag)\
             .join(components.BaseUser, on=(Tag.owner == components.BaseUser.id))\
             .where(components.BaseUser.id == user_id)\
             .objects()
示例#6
0
    def fetch_all_items(self, category_filter, milestone_filter):
        user_id = components.current_user_id()

        category_select = categoryService.category_filter_helper(
            Note, user_id, category_filter)
        milestone_select = []
        # milestone_filter == "all"
        # milestone_filter == "unassigned"
        # else ...
        return Note.select(Note).where(
            Note.is_deleted == False, *category_select, *milestone_select,
            Note.owner_id == user_id).order_by(Note.edited.desc()).objects()
示例#7
0
    def fetch_all_items(self, category_filter, milestone_filter):
        user_id = components.current_user_id()
        category_select = categoryService.category_filter_helper(
            Task, user_id, category_filter)
        milestone_select = []
        # milestone_filter == "all"
        # milestone_filter == "unassigned"
        # else ...

        return Task.select(Task).where(
            Task.is_deleted == False, *category_select, *milestone_select,
            Task.owner_id == user_id).order_by(Task.order.asc())
        pass
示例#8
0
    def update_item(self, item_id, item_json):
        old_item = None
        try:
            old_item = self.read_item(item_id)
        except Category.DoesNotExist:
            raise components.ResourceNotFoundError()
        old_parent_id = old_item.parent.id if old_item.parent else None
        old_order = old_item.order

        parent = None
        if "parent" in item_json and item_json["parent"]:
            if item_json["parent"] == item_id:
                raise components.BadRequestError(
                    payload={
                        "reason": "You can't be your own parent, you moron."
                    })
            try:
                parent = self.read_item(item_json["parent"])
            except Category.DoesNotExist:
                raise components.BadRequestError()
            del item_json["parent"]

        parent_id = parent.id if parent else None

        item_json = self.sanitize_fields(item_json)
        item = dict_to_model(Category, item_json)

        path = self._fetch_path(parent.id if parent else None)
        path = "%s.%d" % (parent, item.order) if path else str(item.order)

        item.id = item_id
        item.parent = parent
        item.path = path
        item.save(only=item.dirty_fields)

        if (item.order != old_order) or (item.parent
                                         and item.parent.id != old_parent_id):
            user_id = components.current_user_id()
            self._reorder_branch(item, user_id=user_id, parent_id=parent_id)
            self._reorder_path(user_id=user_id, parent_id=parent_id)

            if item.parent and item.parent.id != old_parent_id:
                self._reorder_branch(None,
                                     user_id=user_id,
                                     parent_id=old_parent_id)
                self._reorder_path(user_id=user_id, parent_id=old_parent_id)

            # self._flatten_tree_order(user_id)

        return item
示例#9
0
    def bulk_search_or_insert(self, tags):
        tag_set = set(tags)
        user_id = components.current_user_id()

        tag_items = set(
            Tag.select(Tag).join(components.BaseUser,
                                 on=(components.BaseUser.id == user_id)).where(
                                     Tag.tag << tag_set,
                                     Tag.owner.id == user_id).objects())

        created_tags = []
        created_fuzzies = []
        # TODO: this part sucks for some reason:
        for new_tag in tag_set.difference(set(tag.tag for tag in tag_items)):
            (tag, fuzzies) = self._create_tag_from_string(new_tag)
            created_tags.append(tag)
            created_fuzzies.extend(fuzzies)

        with components.DB.atomic():
            user = components.current_user()
            if created_tags:
                for tag in created_tags:
                    tag.owner = user
                    tag.save()
                logging.debug("New tags:" +
                              ", ".join([str(tag.tag)
                                         for tag in created_tags]))

            if created_fuzzies:
                for fuzzy_tag in created_fuzzies:
                    fuzzy_tag.save()
                logging.debug(
                    "New fuzzies:" +
                    ", ".join([str(fuzzy.fuzzy) for fuzzy in created_fuzzies]))

        return list(tag_items) + created_tags
示例#10
0
    def delete_item(self, item_id):
        from app.notes.model import Note
        from app.tasks.model import Task
        # from app.milestones.model import Milestone
        # from app.worklog.model import Worklog

        # --- delete -> merge all the stuff to its parents
        category = None
        try:
            category = self.read_item(item_id)
            # if category.parent:
            # parent = self.read_item(category.parent)
        except Category.DoesNotExist:
            raise components.ResourceNotFoundError()

        parent = category.parent

        # merge
        # We need to have an event dispatch-thingy to notify all the depending modules to move around
        user_id = components.current_user_id()
        with components.DB.atomic():
            for clazz in [Note, Task
                          # , Milestone
                          ]:
                # Why can't you just simply update?
                # clazz.update(
                #     category=parent,  # parent.id if parent else None,
                #     edited=datetime.now()
                # ).where(
                #     clazz.category == category,  # under normal circumstances, it can't be None
                # ).execute()
                for obj in clazz.select(clazz).join(
                        components.BaseUser,
                        on=(clazz.owner == components.BaseUser.id)
                ).join(Category, on=(clazz.category == Category.id)).where(
                        clazz.category.id == category.
                        id,  # under normal circumstances, it can't be None
                        clazz.owner.id == user_id):
                    obj.category = parent
                    obj.changed()
                    obj.save()  # :/

            # Why can't you simply update?
            # Category.update(
            #     parent_id=parent.id,
            #     edited=datetime.now()
            # ).where(
            #     Category.parent == category,
            # ).execute()

            Parent = Category.alias()
            for child in Category.select(Category).join(
                    components.BaseUser,
                    on=(Category.owner == components.BaseUser.id)).join(
                        Parent, on=(Category.parent == Parent.id)).where(
                            Parent.id == category.
                            id,  # under normal circumstances, it can't be None
                            Category.owner.id == user_id):
                child.parent = parent
                child.changed()
                child.save()

            category.is_deleted = True
            category.changed()
            category.save()

            # TODO: recalculate path for parent
            # self._flatten_tree_order(user_id)
            return category