Esempio n. 1
0
 def get(table, param):
     try:
         return self.profile[table][param]
     except KeyError:
         try:
             # FIXME: profile models
             db.perform("INSERT INTO %s (id) VALUES (%%s);" % \
                        table, [self.id])
         except IntegrityError:
             pass
         res = cache_get('profile:%s:%s' % (table, self.id))
         if res:
             self.profile[table] = res
         else:
             res = db.fetchone("SELECT * FROM %s WHERE id=%%s;" % \
                              table, [self.id])
             log.debug('RES %s %s' % (table, res))
             if res:
                 self.profile[table] = dict(res)
                 cache_store('profile:%s:%s' % (table, self.id),
                             self.profile[table])
             else:
                 #try:
                 #    return cls._profile[param]['default']
                 #except KeyError:
                 #    return None
                 return None
         # FIXME: remove recursive call
         try:
             return self.profile[table][param]
         except KeyError:
             cache_del('profile:%s:%s' % (table, self.id))
             return get(table, param)
Esempio n. 2
0
    def add_subscription_request(self, user):
        if self.check_subscriber(user):
            raise AlreadySubscribed

        if not self.get_profile('private'):
            self.add_subscriber(user)
            return True

        res = db.fetchone("SELECT user_id FROM users.blacklist WHERE "
                         "user_id=%s AND to_user_id=%s;", [self.id, user.id])
        if res:
            raise SubscribeError

        res = db.fetchone("SELECT user_id FROM users.whitelist WHERE "
                         "user_id=%s AND to_user_id=%s;", [self.id, user.id])
        if res:
            self.add_subscriber(user)
            return True

        try:
            db.perform("INSERT INTO subs.requests "
                       "VALUES (%s, %s);", [user.id, self.id])
        except IntegrityError:
            raise AlreadyRequested

        return False
Esempio n. 3
0
    def confirm_account(self, code):
        res = db.fetchone("SELECT id, user_id, type, address, code "
                          "FROM users.accounts_unconfirmed "
                          "WHERE code=%s;",
                          [code.lower()])
        if not res:
            return False

        if res['user_id'] != self.id or res['code'] != str(code).lower():
            return False

        db.perform("DELETE FROM users.accounts_unconfirmed WHERE id=%s;",
                   [res['id']])

        try:
            db.perform("INSERT INTO users.accounts (user_id, type, address) "
                       "VALUES (%s, %s, %s);",
                       [self.id, res['type'], res['address']])
        except IntegrityError:
            log.error("%s %s already exists" % (res['type'], res['address']))
            return False

        cache_del("addr_id_login:%s" % res['address'])

        return True
Esempio n. 4
0
 def get(table, param):
     try:
         return self.profile[table][param]
     except KeyError:
         try:
             # FIXME: profile models
             db.perform("INSERT INTO %s (id) VALUES (%%s);" % \
                        table, [self.id])
         except IntegrityError:
             pass
         res = cache_get('profile:%s:%s' % (table, self.id))
         if res:
             self.profile[table] = res
         else:
             res = db.fetchone("SELECT * FROM %s WHERE id=%%s;" % \
                              table, [self.id])
             log.debug('RES %s %s' % (table, res))
             if res:
                 self.profile[table] = dict(res)
                 cache_store('profile:%s:%s' % (table, self.id),
                             self.profile[table])
             else:
                 #try:
                 #    return cls._profile[param]['default']
                 #except KeyError:
                 #    return None
                 return None
         # FIXME: remove recursive call
         try:
             return self.profile[table][param]
         except KeyError:
             cache_del('profile:%s:%s' % (table, self.id))
             return get(table, param)
Esempio n. 5
0
    def add_subscription_request(self, user):
        if self.check_subscriber(user):
            raise AlreadySubscribed

        if not self.get_profile('private'):
            self.add_subscriber(user)
            return True

        res = db.fetchone(
            "SELECT user_id FROM users.blacklist WHERE "
            "user_id=%s AND to_user_id=%s;", [self.id, user.id])
        if res:
            raise SubscribeError

        res = db.fetchone(
            "SELECT user_id FROM users.whitelist WHERE "
            "user_id=%s AND to_user_id=%s;", [self.id, user.id])
        if res:
            self.add_subscriber(user)
            return True

        try:
            db.perform("INSERT INTO subs.requests "
                       "VALUES (%s, %s);", [user.id, self.id])
        except IntegrityError:
            raise AlreadyRequested

        return False
Esempio n. 6
0
    def confirm_account(self, code):
        res = db.fetchone(
            "SELECT id, user_id, type, address, code "
            "FROM users.accounts_unconfirmed "
            "WHERE code=%s;", [code.lower()])
        if not res:
            return False

        if res['user_id'] != self.id or res['code'] != str(code).lower():
            return False

        db.perform("DELETE FROM users.accounts_unconfirmed WHERE id=%s;",
                   [res['id']])

        try:
            db.perform(
                "INSERT INTO users.accounts (user_id, type, address) "
                "VALUES (%s, %s, %s);", [self.id, res['type'], res['address']])
        except IntegrityError:
            log.error("%s %s already exists" % (res['type'], res['address']))
            return False

        cache_del("addr_id_login:%s" % res['address'])

        return True
Esempio n. 7
0
    def update(self, text):
        if not self.id:
            raise PostNotFound(None)

        cnt = self.updates_count()

        if cnt >= 3:
            raise PostUpdateError

        db.perform("INSERT INTO posts.updates (post_id, text) " "VALUES (%s, %s);", [unb26(self.id), text])
Esempio n. 8
0
 def add_subscriber(self, user):
     try:
         db.perform("INSERT INTO subs.users (user_id, to_user_id) "
                    "VALUES (%s, %s);",
                    [user.id, self.id])
     except IntegrityError:
         raise AlreadySubscribed
     self.add_rec_subscriber(user)
     user.subs_count(False)
     self.readers_count(False)
Esempio n. 9
0
 def add_subscriber(self, user):
     try:
         db.perform(
             "INSERT INTO subs.users (user_id, to_user_id) "
             "VALUES (%s, %s);", [user.id, self.id])
     except IntegrityError:
         raise AlreadySubscribed
     self.add_rec_subscriber(user)
     user.subs_count(False)
     self.readers_count(False)
Esempio n. 10
0
 def add_to_blacklist(self, user):
     try:
         db.perform("INSERT INTO users.blacklist VALUES (%s, %s);",
                    [self.id, user.id])
     except IntegrityError:
         return False
     db.perform("DELETE FROM subs.requests WHERE "
                "user_id=%s AND to_user_id=%s;", [user.id, self.id])
     self.unsubscribe(user)
     self.del_from_whitelist(user)
     return True
Esempio n. 11
0
 def bind_ulogin(self, network, uid, nickname=None, name=None, profile=None):
     if not self.id:
         raise NotAuthorized
     try:
         db.perform("INSERT INTO users.ulogin_accounts "
                    "(id, network, uid, nickname, name, profile) "
                    "VALUES (%s, %s, %s, %s, %s, %s);",
                    [self.id, network, uid, nickname, name, profile])
     #except IntegrityError:
     #    raise UserExists
     finally: pass
Esempio n. 12
0
    def set_url(self, url):
        self._url = url

        if not self.id:
            return

        key = "feed_url:%s" % self.id
        cache_store(key, self._url, 3600)

        db.perform("UPDATE users.feeds SET url=%s WHERE id=%s;",
                   [self._url, self.id])
Esempio n. 13
0
    def set_url(self, url):
        self._url = url

        if not self.id:
            return

        key = "feed_url:%s" % self.id
        cache_store(key, self._url, 3600)

        db.perform("UPDATE users.feeds SET url=%s WHERE id=%s;",
                   [self._url, self.id])
Esempio n. 14
0
 def add_to_blacklist(self, user):
     try:
         db.perform("INSERT INTO users.blacklist VALUES (%s, %s);",
                    [self.id, user.id])
     except IntegrityError:
         return False
     db.perform("DELETE FROM subs.requests WHERE "
                "user_id=%s AND to_user_id=%s;", [user.id, self.id])
     self.unsubscribe(user)
     self.del_from_whitelist(user)
     return True
Esempio n. 15
0
    def update(self, text):
        if not self.id:
            raise PostNotFound(None)

        cnt = self.updates_count()

        if cnt >= 3:
            raise PostUpdateError

        db.perform("INSERT INTO posts.updates (post_id, text) "
                   "VALUES (%s, %s);", [unb26(self.id), text])
Esempio n. 16
0
 def bind_ulogin(self, network, uid, nickname=None, name=None, profile=None):
     if not self.id:
         raise NotAuthorized
     try:
         db.perform("INSERT INTO users.ulogin_accounts "
                    "(id, network, uid, nickname, name, profile) "
                    "VALUES (%s, %s, %s, %s, %s, %s);",
                    [self.id, network, uid, nickname, name, profile])
     #except IntegrityError:
     #    raise UserExists
     finally: pass
Esempio n. 17
0
    def del_subscriber(self, user):
        retval = bool(user.check_subscriber(env.user))

        db.perform("DELETE FROM subs.users WHERE "
                   "user_id=%s AND to_user_id=%s;", [user.id, self.id])
        db.perform("DELETE FROM subs.requests WHERE "
                   "user_id=%s AND to_user_id=%s;", [user.id, self.id])
        self.del_rec_subscriber(user)
        user.subs_count(False)
        self.readers_count(False)

        return retval
Esempio n. 18
0
    def del_subscriber(self, user):
        retval = bool(user.check_subscriber(env.user))

        db.perform("DELETE FROM subs.users WHERE "
                   "user_id=%s AND to_user_id=%s;", [user.id, self.id])
        db.perform("DELETE FROM subs.requests WHERE "
                   "user_id=%s AND to_user_id=%s;", [user.id, self.id])
        self.del_rec_subscriber(user)
        user.subs_count(False)
        self.readers_count(False)

        return retval
Esempio n. 19
0
    def set_alias(self, alias, command):
        if not self.id:
            raise NotAuthorized

        try:
            db.perform("INSERT INTO users.user_aliases "
                       "(user_id, alias, command) VALUES (%s, %s, %s);",
                       [self.id, alias.lower(), command])
        except IntegrityError:
            db.perform("UPDATE users.user_aliases SET alias=%s, command=%s "
                       "WHERE user_id=%s;", [alias.lower(), command, self.id])
        cache_del('aliases:%s' % self.id)
Esempio n. 20
0
    def add_to_whitelist(self, user):
        try:
            db.perform("INSERT INTO users.whitelist VALUES (%s, %s);",
                       [self.id, user.id])
        except IntegrityError:
            return False

        res = db.fetchone("DELETE FROM subs.requests WHERE "
                          "user_id=%s AND to_user_id=%s "
                          "RETURNING user_id;", [user.id, self.id])
        if res:
            self.add_subscriber(user)
        return True
Esempio n. 21
0
    def add_to_whitelist(self, user):
        try:
            db.perform("INSERT INTO users.whitelist VALUES (%s, %s);",
                       [self.id, user.id])
        except IntegrityError:
            return False

        res = db.fetchone("DELETE FROM subs.requests WHERE "
                          "user_id=%s AND to_user_id=%s "
                          "RETURNING user_id;", [user.id, self.id])
        if res:
            self.add_subscriber(user)
        return True
Esempio n. 22
0
    def set_alias(self, alias, command):
        if not self.id:
            raise NotAuthorized

        try:
            db.perform(
                "INSERT INTO users.user_aliases "
                "(user_id, alias, command) VALUES (%s, %s, %s);",
                [self.id, alias.lower(), command])
        except IntegrityError:
            db.perform(
                "UPDATE users.user_aliases SET alias=%s, command=%s "
                "WHERE user_id=%s;", [alias.lower(), command, self.id])
        cache_del('aliases:%s' % self.id)
Esempio n. 23
0
def del_from_blacklist(taglist, login=None):
    if login:
        user = User('login', login)
        uid = user.id
    else:
        uid = None

    if not isinstance(taglist, (list, tuple)):
        taglist = [taglist]
    if uid:
        db.perform("DELETE FROM posts.tags_blacklist "
                   "WHERE user_id=%s AND to_user_id=%s "
                   "AND tag=ANY(%s);",
                   [env.user.id, uid, taglist])
    else:
        db.perform("DELETE FROM posts.tags_blacklist "
                   "WHERE user_id=%s AND to_user_id IS NULL "
                   "AND tag=ANY(%s);",
                   [env.user.id, taglist])
Esempio n. 24
0
def del_from_blacklist(taglist, login=None):
    if login:
        user = User('login', login)
        uid = user.id
    else:
        uid = None

    if not isinstance(taglist, (list, tuple)):
        taglist = [taglist]
    if uid:
        db.perform(
            "DELETE FROM posts.tags_blacklist "
            "WHERE user_id=%s AND to_user_id=%s "
            "AND tag=ANY(%s);", [env.user.id, uid, taglist])
    else:
        db.perform(
            "DELETE FROM posts.tags_blacklist "
            "WHERE user_id=%s AND to_user_id IS NULL "
            "AND tag=ANY(%s);", [env.user.id, taglist])
Esempio n. 25
0
def subscribe(taglist, login=None):
    if login:
        user = User('login', login)
        uid = user.id

        if user == env.user:
            raise SubscribeError
    else:
        uid = None

    if not isinstance(taglist, (list, tuple)):
        taglist = [taglist]
    for tag in taglist:
        try:
            db.perform("INSERT INTO subs.tags "
                       "(user_id, to_user_id, tag) "
                       "VALUES (%s, %s, %s);",
                       [env.user.id, uid, tag])
        except IntegrityError:
            pass
Esempio n. 26
0
    def save(self):
        is_new = not self.id

        if is_new and not self._url:
            raise InvalidFeedUrl("Cannot save feed without URL")

        if not self.login:
            self.login = self._generate_login()

        User.save(self)

        if is_new:
            db.perform("INSERT INTO users.feeds (id, url) VALUES (%s, %s);",
                       [self.id, self._url])

            self.fetch()

            for p in self.posts():
                p.save()
            self.update_task()
Esempio n. 27
0
    def save(self):
        is_new = not self.id

        if is_new and not self._url:
            raise InvalidFeedUrl("Cannot save feed without URL")

        if not self.login:
            self.login = self._generate_login()

        User.save(self)

        if is_new:
            db.perform("INSERT INTO users.feeds (id, url) VALUES (%s, %s);",
                       [self.id, self._url])

            self.fetch()

            for p in self.posts():
                p.save()
            self.update_task()
Esempio n. 28
0
def subscribe(taglist, login=None):
    if login:
        user = User('login', login)
        uid = user.id

        if user == env.user:
            raise SubscribeError
    else:
        uid = None

    if not isinstance(taglist, (list, tuple)):
        taglist = [taglist]
    for tag in taglist:
        try:
            db.perform(
                "INSERT INTO subs.tags "
                "(user_id, to_user_id, tag) "
                "VALUES (%s, %s, %s);", [env.user.id, uid, tag])
        except IntegrityError:
            pass
Esempio n. 29
0
    def rename(self, login):
        if not self.id:
            raise NotAuthorized
        if cache_get('renamed:%s' % self.id):
            raise RenameError

        if not validate_nickname(login):
            raise UserLoginError

        old_login = self.login
        self.login = login

        try:
            db.perform("UPDATE users.logins SET login=%s WHERE id=%s;",
                       [login, self.id])
        except IntegrityError:
            raise UserExists

        cache_store('renamed:%s' % self.id, 1, settings.user_rename_timeout)
        cache_del('id_login:%s' % old_login.lower())

        for t in ACCOUNT_TYPES:
            for addr in self.get_accounts(t):
                cache_del("addr_id_login:%s" % addr)
Esempio n. 30
0
    def rename(self, login):
        if not self.id:
            raise NotAuthorized
        if cache_get('renamed:%s' % self.id):
            raise RenameError

        if not validate_nickname(login):
            raise UserLoginError

        old_login = self.login
        self.login = login

        try:
            db.perform("UPDATE users.logins SET login=%s WHERE id=%s;",
                       [login, self.id])
        except IntegrityError:
            raise UserExists

        cache_store('renamed:%s' % self.id, 1, settings.user_rename_timeout)
        cache_del('id_login:%s' % old_login.lower())

        for t in ACCOUNT_TYPES:
            for addr in self.get_accounts(t):
                cache_del("addr_id_login:%s" % addr)
Esempio n. 31
0
 def _set_private(self):
     res = [u['id'] for u in \
         db.fetchall("SELECT user_id AS id FROM subs.users "
                     "WHERE to_user_id=%(id)s "
                     "EXCEPT "
                     "SELECT to_user_id AS id FROM users.whitelist "
                     "WHERE user_id=%(id)s;", {'id': self.id})]
     db.perform("DELETE FROM subs.users "
                "WHERE user_id=ANY(%s) AND to_user_id=%s;",
                [res, self.id])
     db.batch("INSERT INTO subs.requests VALUES(%(u)s, %(to)s);",
              [{'u':u, 'to':self.id} for u in res])
     db.perform("DELETE FROM subs.posts s USING posts.posts p "
                "WHERE s.post_id=p.id "
                "AND s.user_id=ANY(%s) AND p.author=%s;",
                [res, self.id])
     db.perform("DELETE FROM subs.tags_user "
                "WHERE to_user_id=%s AND user_id=ANY(%s);",
                [self.id, res])
Esempio n. 32
0
 def _set_private(self):
     res = [u['id'] for u in \
         db.fetchall("SELECT user_id AS id FROM subs.users "
                     "WHERE to_user_id=%(id)s "
                     "EXCEPT "
                     "SELECT to_user_id AS id FROM users.whitelist "
                     "WHERE user_id=%(id)s;", {'id': self.id})]
     db.perform("DELETE FROM subs.users "
                "WHERE user_id=ANY(%s) AND to_user_id=%s;",
                [res, self.id])
     db.batch("INSERT INTO subs.requests VALUES(%(u)s, %(to)s);",
              [{'u':u, 'to':self.id} for u in res])
     db.perform("DELETE FROM subs.posts s USING posts.posts p "
                "WHERE s.post_id=p.id "
                "AND s.user_id=ANY(%s) AND p.author=%s;",
                [res, self.id])
     db.perform("DELETE FROM subs.tags_user "
                "WHERE to_user_id=%s AND user_id=ANY(%s);",
                [self.id, res])
Esempio n. 33
0
 def unbind_ulogin(self, network, uid):
     if not self.id:
         raise NotAuthorized
     db.perform(
         "DELETE FROM users.ulogin_accounts "
         "WHERE id=%s AND network=%s AND uid=%s;", [self.id, network, uid])
Esempio n. 34
0
    def save(self, update=False):
        if not self.post.id:
            raise PostNotFound
        if isinstance(self.author, AnonymousUser):
            anon_login = self.author.login
        else:
            anon_login = None

        if not self.created:
            self.created = datetime.now()

        if isinstance(self.text, str):
            self.text = self.text.decode('utf-8', 'ignore')

        if update:
            res = db.perform("""
                UPDATE posts.comments SET (text, updated) = (%s, now())
                WHERE post_id = %s AND comment_id = %s;
                """, [self.text,
                    unb26(self.post.id) if isinstance(self.post.id, basestring) else self.post.id,
                    self.id])
            comment_id = self.id
        else:
            if self.archive and self.id:
                comment_id = self.id
                res = db.fetchone("INSERT INTO posts.comments "
                                  "(post_id, comment_id, author, created,"
                                  "to_comment_id, anon_login, text, files) "
                                  "VALUES (%s, %s, %s, %s, %s, %s, %s, %s) "
                                  "RETURNING comment_id;",
                                  [unb26(self.post.id), self.id, self.author.id,
                                   self.created,
                                   self.to_comment_id, anon_login, self.text,
                                   self.files])
            else:
                redis = RedisPool(settings.storage_socket)
                while True:
                    try:
                        comment_id = redis.incr('cmnt.%s' % self.post.id)
                        res = db.fetchone("INSERT INTO posts.comments "
                                         "(post_id, comment_id, author, created,"
                                         "to_comment_id, anon_login, text, files) "
                                         "VALUES (%s, %s, %s, %s, %s, %s, %s, %s) "
                                         "RETURNING comment_id;",
                                         [unb26(self.post.id), comment_id,
                                          self.author.id, self.created,
                                          self.to_comment_id,
                                          anon_login, self.text, self.files])
                        break
                    except IntegrityError:
                        pass

                if res:
                    redis.incr('cmnt_cnt.%s' % unb26(self.post.id))

        #try:
        #    es = elasticsearch.Elasticsearch(host=settings.elasticsearch_host, port=settings.elasticsearch_port)
        #    es.index(index='point-comments',
        #             id='%s-%s' % (self.post.id, self.id),
        #             doc_type='post', body={
        #        'post_id': self.post.id,
        #        'comment_id': self.id,
        #        'post_type': self.post.type,
        #        'created': self.created,
        #        'private': self.post.private,
        #        'user_id': self.author.id,
        #        'login': self.author.login,
        #        'text': self.text,
        #    })
        #except elasticsearch.ConnectionError, e:
        #    log.error('Elasticsearch: %s' % e)

        self.id = comment_id

        return comment_id
Esempio n. 35
0
 def add_subscriber(self, user):
     try:
         db.perform("INSERT INTO subs.posts VALUES (%s, %s);",
                    [user.id, unb26(self.id)])
     except IntegrityError:
         raise AlreadySubscribed
Esempio n. 36
0
    def save(self):
        if self.tags:
            self.tags = [ t[:64] for t in filter(None, self.tags)[:10] ]

        try:
            if not isinstance(self.files, (list, tuple)):
                self.files = None
        except AttributeError:
            self.files = None

        if self.id:
            db.perform("DELETE FROM posts.tags WHERE post_id=%s;",
                       [unb26(self.id)])
            if self.tags:
                for t in self.tags:
                    if isinstance(t, str):
                        t = t.decode('utf-8')
                    db.perform("INSERT INTO posts.tags "
                               "(post_id, user_id, tag) VALUES (%s, %s, %s);",
                               [unb26(self.id), self.author.id, t])

            db.perform("UPDATE posts.posts SET tags=%s, private=%s,"
                       "text=%s, edited=%s, archive=%s, pinned=%s, files=%s "
                       "WHERE id=%s;",
                       [self.tags, bool(self.private), self.text,
                        self.edited, self.archive, self.pinned, self.files,
                        unb26(self.id)])

        else:
            if not self.created:
                self.created = datetime.now()

            res = db.fetchone("INSERT INTO posts.posts "
                             "(author, type, private, tags, title, link, text, "
                             "created, edited, archive, pinned, tune, files) "
                             "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
                             "RETURNING id;",
                             [self.author.id, self.type, bool(self.private),
                              self.tags, self.title, self.link, self.text,
                              self.created, self.edited, self.archive, self.pinned, Json(self.tune), self.files])
            if not res:
                raise PostError

            self.id = b26(res[0])

            if self.tags:
                for t in self.tags:
                    try:
                        db.perform("INSERT INTO posts.tags "
                                   "(post_id, user_id, tag) "
                                   "VALUES (%s, %s, %s);",
                                   [unb26(self.id), self.author.id, t])
                    except IntegrityError:
                        pass

        #try:
        #    es = elasticsearch.Elasticsearch(host=settings.elasticsearch_host, port=settings.elasticsearch_port)
        #    es.index(index='point-posts', id=self.id, doc_type='post', body={
        #        'post_id': self.id,
        #        'post_type': self.type,
        #        'created': self.created,
        #        'private': self.private,
        #        'user_id': self.author.id,
        #        'login': self.author.login,
        #        'title': self.title,
        #        'tags':  self.tags,
        #        'text': self.text,
        #    })
        #except elasticsearch.ConnectionError, e:
        #    log.error('Elasticsearch: %s' % e)

        return self.id
Esempio n. 37
0
    def save(self):
        if not self.login:
            raise UserError("Cannot save anonymous user")

        is_new = False

        # create user
        if not self.id:
            if not self.login or not validate_nickname(self.login):
                raise UserError('Invalid Login: "******"' % self.login)
            self.id = db.fetchone("INSERT INTO users.logins (login, type) "
                                 "VALUES (%s, %s) RETURNING id;",
                                 [self.login, self.type])[0]
            db.perform("INSERT INTO users.info (id, name) VALUES (%s, %s);",
                       [self.id, self.login])
            db.perform("INSERT INTO users.profile (id, private, lang) "
                       "VALUES (%s, false, 'en');", [self.id])

            self.accounts_add = self.accounts
            is_new = True

        if not is_new:
            try:
                if self._private == True:
                    self._set_private()
                elif self._private == False:
                    self._set_public()
            except AttributeError:
                pass

        # save accounts
        for acc in self.accounts_add:
            try:
                if len(acc) == 3:
                    db.perform("INSERT INTO users.accounts_unconfirmed "
                               "(user_id, type, address, code) "
                               "VALUES (%s, %s, %s, %s);",
                               [self.id, acc[0], acc[1], acc[2]])
                else:
                    db.perform("INSERT INTO users.accounts "
                               "(user_id, type, address) "
                               "VALUES (%s, %s, %s);",
                               [self.id, acc[0], acc[1]])


            except IntegrityError:
                log.error("%s %s already exists" % (acc[0], acc[1]))

        self.accounts_add = []

        for type, address in self.accounts_del:
            db.perform("DELETE FROM users.accounts WHERE "
                       "user_id=%s AND type=%s AND address=%s;",
                       [self.id, type, address])

            db.perform("DELETE FROM users.accounts_unconfirmed WHERE "
                       "user_id=%s AND type=%s AND address=%s;",
                       [self.id, type, address])

        self.accounts_del = []

        # save profile
        if self.profile_upd:
            for table in self.profile_upd:
                f = []
                for k in self.profile_upd[table]:
                    f.append("%s=%%(%s)s" % (k, k))
                try:
                    try:
                        db.perform("INSERT INTO %s (id) VALUES (%%s);" % \
                                   table, [self.id])
                    except IntegrityError:
                        pass
                    db.perform("UPDATE %s SET %s WHERE id=%s;" % \
                               (table, ','.join(f), self.id),
                               self.profile_upd[table])
                    cache_del('profile:%s:%s' % (table, self.id))
                except ProgrammingError:
                    raise KeyError
                except DataError:
                    raise ValueError
            self.profile_upd = {}

        if self.info_upd:
            f = []
            for k in self.info_upd:
                #if not self.info_upd[k]:
                #    self.info_upd[k] = None
                f.append("%s=%%(%s)s" % (k, k))
            db.perform("UPDATE users.info SET %s WHERE id=%s;" % \
                       (','.join(f), self.id),
                       self.info_upd)
            self.info_upd = {}
            cache_del('userinfo:%s' % self.id)

        if self.password:
            db.perform("UPDATE users.logins SET password=%s WHERE id=%s;",
                       (self.password, self.id))
Esempio n. 38
0
 def del_rec_subscriber(self, user):
     db.perform(
         "DELETE FROM subs.recommendations WHERE "
         "user_id=%s AND to_user_id=%s;", [user.id, self.id])
Esempio n. 39
0
 def del_rec_subscriber(self, user):
     db.perform("DELETE FROM subs.recommendations WHERE "
                "user_id=%s AND to_user_id=%s;", [user.id, self.id])
Esempio n. 40
0
 def add_rec_subscriber(self, user):
     try:
         db.perform("INSERT INTO subs.recommendations VALUES (%s, %s);",
                    [user.id, self.id])
     except IntegrityError:
         raise AlreadySubscribed
Esempio n. 41
0
    def save(self):
        if not self.login:
            raise UserError("Cannot save anonymous user")

        is_new = False

        # create user
        if not self.id:
            if not self.login or not validate_nickname(self.login):
                raise UserError('Invalid Login: "******"' % self.login)
            self.id = db.fetchone(
                "INSERT INTO users.logins (login, type) "
                "VALUES (%s, %s) RETURNING id;", [self.login, self.type])[0]
            db.perform("INSERT INTO users.info (id, name) VALUES (%s, %s);",
                       [self.id, self.login])
            db.perform(
                "INSERT INTO users.profile (id, private, lang) "
                "VALUES (%s, false, 'en');", [self.id])

            self.accounts_add = self.accounts
            is_new = True

        if not is_new:
            try:
                if self._private == True:
                    self._set_private()
                elif self._private == False:
                    self._set_public()
            except AttributeError:
                pass

        # save accounts
        for acc in self.accounts_add:
            try:
                if len(acc) == 3:
                    db.perform(
                        "INSERT INTO users.accounts_unconfirmed "
                        "(user_id, type, address, code) "
                        "VALUES (%s, %s, %s, %s);",
                        [self.id, acc[0], acc[1], acc[2]])
                else:
                    db.perform(
                        "INSERT INTO users.accounts "
                        "(user_id, type, address) "
                        "VALUES (%s, %s, %s);", [self.id, acc[0], acc[1]])

            except IntegrityError:
                log.error("%s %s already exists" % (acc[0], acc[1]))

        self.accounts_add = []

        for type, address in self.accounts_del:
            db.perform(
                "DELETE FROM users.accounts WHERE "
                "user_id=%s AND type=%s AND address=%s;",
                [self.id, type, address])

            db.perform(
                "DELETE FROM users.accounts_unconfirmed WHERE "
                "user_id=%s AND type=%s AND address=%s;",
                [self.id, type, address])

        self.accounts_del = []

        # save profile
        if self.profile_upd:
            for table in self.profile_upd:
                f = []
                for k in self.profile_upd[table]:
                    f.append("%s=%%(%s)s" % (k, k))
                try:
                    try:
                        db.perform("INSERT INTO %s (id) VALUES (%%s);" % \
                                   table, [self.id])
                    except IntegrityError:
                        pass
                    db.perform("UPDATE %s SET %s WHERE id=%s;" % \
                               (table, ','.join(f), self.id),
                               self.profile_upd[table])
                    cache_del('profile:%s:%s' % (table, self.id))
                except ProgrammingError:
                    raise KeyError
                except DataError:
                    raise ValueError
            self.profile_upd = {}

        if self.info_upd:
            f = []
            for k in self.info_upd:
                #if not self.info_upd[k]:
                #    self.info_upd[k] = None
                f.append("%s=%%(%s)s" % (k, k))
            db.perform("UPDATE users.info SET %s WHERE id=%s;" % \
                       (','.join(f), self.id),
                       self.info_upd)
            self.info_upd = {}
            cache_del('userinfo:%s' % self.id)

        if self.password:
            db.perform("UPDATE users.logins SET password=%s WHERE id=%s;",
                       (self.password, self.id))
Esempio n. 42
0
 def unbind_ulogin(self, network, uid):
     if not self.id:
         raise NotAuthorized
     db.perform("DELETE FROM users.ulogin_accounts "
                "WHERE id=%s AND network=%s AND uid=%s;",
                [self.id, network, uid])
Esempio n. 43
0
    def save(self):
        if self.tags:
            self.tags = [t[:64] for t in filter(None, self.tags)[:10]]

        try:
            if not isinstance(self.files, (list, tuple)):
                self.files = None
        except AttributeError:
            self.files = None

        if self.id:
            db.perform("DELETE FROM posts.tags WHERE post_id=%s;", [unb26(self.id)])
            if self.tags:
                for t in self.tags:
                    if isinstance(t, str):
                        t = t.decode("utf-8")
                    db.perform(
                        "INSERT INTO posts.tags " "(post_id, user_id, tag) VALUES (%s, %s, %s);",
                        [unb26(self.id), self.author.id, t],
                    )

            db.perform(
                "UPDATE posts.posts SET tags=%s, private=%s,"
                "text=%s, edited=%s, archive=%s, pinned=%s, files=%s "
                "WHERE id=%s;",
                [
                    self.tags,
                    bool(self.private),
                    self.text,
                    self.edited,
                    self.archive,
                    self.pinned,
                    self.files,
                    unb26(self.id),
                ],
            )

        else:
            if not self.created:
                self.created = datetime.now()

            res = db.fetchone(
                "INSERT INTO posts.posts "
                "(author, type, private, tags, title, link, text, "
                "created, edited, archive, pinned, files) "
                "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
                "RETURNING id;",
                [
                    self.author.id,
                    self.type,
                    bool(self.private),
                    self.tags,
                    self.title,
                    self.link,
                    self.text,
                    self.created,
                    self.edited,
                    self.archive,
                    self.pinned,
                    self.files,
                ],
            )
            if not res:
                raise PostError

            self.id = b26(res[0])

            if self.tags:
                for t in self.tags:
                    try:
                        db.perform(
                            "INSERT INTO posts.tags " "(post_id, user_id, tag) " "VALUES (%s, %s, %s);",
                            [unb26(self.id), self.author.id, t],
                        )
                    except IntegrityError:
                        pass

        try:
            es = elasticsearch.Elasticsearch()
            es.index(
                index="point-posts",
                id=self.id,
                doc_type="post",
                body={
                    "post_id": self.id,
                    "post_type": self.type,
                    "created": self.created,
                    "private": self.private,
                    "user_id": self.author.id,
                    "login": self.author.login,
                    "title": self.title,
                    "tags": self.tags,
                    "text": self.text,
                },
            )
        except elasticsearch.ConnectionError, e:
            log.error("Elasticsearch: %s" % e)
Esempio n. 44
0
 def add_rec_subscriber(self, user):
     try:
         db.perform("INSERT INTO subs.recommendations VALUES (%s, %s);",
                    [user.id, self.id])
     except IntegrityError:
         raise AlreadySubscribed
Esempio n. 45
0
    def save(self, update=False):
        if not self.post.id:
            raise PostNotFound
        if isinstance(self.author, AnonymousUser):
            anon_login = self.author.login
        else:
            anon_login = None

        if not self.created:
            self.created = datetime.now()

        if isinstance(self.text, str):
            self.text = self.text.decode("utf-8", "ignore")

        if update:
            res = db.perform(
                """
                UPDATE posts.comments SET (text, updated) = (%s, now())
                WHERE post_id = %s AND comment_id = %s;
                """,
                [self.text, unb26(self.post.id) if isinstance(self.post.id, basestring) else self.post.id, self.id],
            )
            comment_id = self.id
        else:
            if self.archive and self.id:
                comment_id = self.id
                res = db.fetchone(
                    "INSERT INTO posts.comments "
                    "(post_id, comment_id, author, created,"
                    "to_comment_id, anon_login, text, files) "
                    "VALUES (%s, %s, %s, %s, %s, %s, %s, %s) "
                    "RETURNING comment_id;",
                    [
                        unb26(self.post.id),
                        self.id,
                        self.author.id,
                        self.created,
                        self.to_comment_id,
                        anon_login,
                        self.text,
                        self.files,
                    ],
                )
            else:
                redis = RedisPool(settings.storage_socket)
                while True:
                    try:
                        comment_id = redis.incr("cmnt.%s" % self.post.id)
                        res = db.fetchone(
                            "INSERT INTO posts.comments "
                            "(post_id, comment_id, author, created,"
                            "to_comment_id, anon_login, text, files) "
                            "VALUES (%s, %s, %s, %s, %s, %s, %s, %s) "
                            "RETURNING comment_id;",
                            [
                                unb26(self.post.id),
                                comment_id,
                                self.author.id,
                                self.created,
                                self.to_comment_id,
                                anon_login,
                                self.text,
                                self.files,
                            ],
                        )
                        break
                    except IntegrityError:
                        pass

                if res:
                    redis.incr("cmnt_cnt.%s" % unb26(self.post.id))

        try:
            es = elasticsearch.Elasticsearch()
            es.index(
                index="point-comments",
                id="%s-%s" % (self.post.id, self.id),
                doc_type="post",
                body={
                    "post_id": self.post.id,
                    "comment_id": self.id,
                    "post_type": self.post.type,
                    "created": self.created,
                    "private": self.post.private,
                    "user_id": self.author.id,
                    "login": self.author.login,
                    "text": self.text,
                },
            )
        except elasticsearch.ConnectionError, e:
            log.error("Elasticsearch: %s" % e)