예제 #1
0
파일: index.py 프로젝트: facesun/anwen
    def get(self, node):
        page = self.get_argument("page", 1)
        share_res = Share.find({'sharetype': node}).sort(
            '_id', DESCENDING).limit(10).skip((int(page) - 1) * 10)
        pagesum = (share_res.count() + 9) / 10

        shares = []
        for share in share_res:
            user = User.by_sid(share.user_id)
            share.name = user.user_name
            share.published = time.strftime(
                '%Y-%m-%d %H:%M:%S', time.localtime(share.published))
            share.domain = user.user_domain
            share.markdown = filter_tags(
                markdown2.markdown(share.markdown))[:100]
            share.gravatar = get_avatar(user.user_email, 16)
            shares.append(share)
        members = User.find().sort('_id', DESCENDING).limit(20)
        members_dict = []
        for member in members:
            member.gravatar = get_avatar(member.user_email, 25)
            members_dict.append(member)
        node_about = options.node_about[node]
        self.render(
            "node.html", shares=shares, members=members_dict,
            pagesum=pagesum, page=page, node=node, node_about=node_about)
예제 #2
0
파일: users.py 프로젝트: anwen/anwen
    def get(self):
        users = User.find({'user_leaf': {'$gt': 20}}).sort('user_leaf', -1)
        l_users = []
        for user in users:
            # print(user)
            # user.user_say = markdown2.markdown(user.user_say)
            # user.user_jointime = time.strftime(
            #     '%Y-%m-%d %H:%M:%S', time.localtime(user.user_jointime))
            # likenum = User.find({'user_id': user._id}).count()
            # user.gravatar = get_avatar(user.user_email, 100)
            # contents = Share.find({'user_id': user.id})
            # if contents.count():
            auser = {}
            auser['user_domain'] = user.user_domain
            auser['user_name'] = user.user_name
            auser['article_num'] = int(
                (user.user_leaf - 20) / 10)  # contents.count()

            if user.user_email.endswith('@wechat'):
                auser['user_img'] = options.site_url + get_avatar_by_wechat(
                    user._id)
            if user.user_email.endswith('@anwensf.com'):
                auser['user_img'] = options.site_url + get_avatar_by_feed(
                    user.id)
            else:
                auser['user_img'] = options.site_url + get_avatar(
                    user.user_email, 100)

            l_users.append(auser)

        self.render('users.html', users=l_users)
예제 #3
0
파일: share.py 프로젝트: bowu8/anwen
 def post(self):
     commentbody = self.get_argument("commentbody", None)
     share_id = self.get_argument("share_id", None)
     html = markdown2.markdown(commentbody)
     comment = Comment
     doc = {}
     doc['user_id'] = self.current_user["user_id"]
     doc['share_id'] = int(share_id)
     doc['commentbody'] = commentbody
     comment.new(doc)
     share = Share.by_sid(share_id)
     share.commentnum += 1
     share.save()
     name = tornado.escape.xhtml_escape(self.current_user["user_name"])
     gravatar = get_avatar(self.current_user["user_email"], 50)
     newcomment = ''.join([
         '<div class="comment">',
         '<div class="avatar">',
         '<img src="', gravatar,
         '</div>',
         '<div class="name">', name,
         '</div>',
         '<div class="date" title="at"></div>', html,
         '</div>',
     ])
     self.write(newcomment)
예제 #4
0
파일: comment.py 프로젝트: anwen/anwen
 def post(self):
     commentbody = self.get_argument("commentbody", None)
     share_id = self.get_argument("share_id", None)
     html = markdown2.markdown(commentbody)
     comment = Comment
     doc = {}
     doc['user_id'] = self.current_user["user_id"]
     doc['share_id'] = int(share_id)
     doc['commentbody'] = commentbody
     comment.new(doc)
     share = Share.by_sid(share_id)
     share.commentnum += 1
     share.save()
     name = tornado.escape.xhtml_escape(self.current_user["user_name"])
     gravatar = get_avatar(self.current_user["user_email"], 50)
     newcomment = ''.join([
         '<div class="comment">',
         '<div class="avatar">',
         '<img src="',
         gravatar,
         '</div>',
         '<div class="name">',
         name,
         '</div>',
         '<div class="date" title="at"></div>',
         html,
         '</div>',
     ])
     self.write(newcomment)
예제 #5
0
파일: user.py 프로젝트: anwen/anwen
 def get(self, name):
     user = User.find_one({"user_domain": name})
     user.user_say = markdown2.markdown(user.user_say)
     user.user_jointime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user.user_jointime))
     likenum = User.find({"user_id": user._id}).count()
     user.gravatar = get_avatar(user.user_email, 100)
     self.render("userhome.html", user=user, likenum=likenum)
예제 #6
0
파일: user.py 프로젝트: wendycan/anwen
 def get(self, name):
     user = User.find_one({'user_domain': name})
     user.user_say = markdown2.markdown(user.user_say)
     user.user_jointime = time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(user.user_jointime))
     likenum = User.find({'user_id': user._id}).count()
     user.gravatar = get_avatar(user.user_email, 100)
     self.render('userhome.html', user=user, likenum=likenum)
예제 #7
0
파일: user_setting.py 프로젝트: anwen/anwen
 def get(self):
     user = User.by_sid(self.current_user['user_id'])
     user.user_jointime = time.strftime(
         '%Y-%m-%d %H:%M:%S', time.localtime(user.user_jointime))
     user.gravatar = get_avatar(user.user_email.encode('u8'), 100)
     # print(user)
     # print(user.user_tags)
     self.render('setting.html', user=user)
예제 #8
0
파일: user.py 프로젝트: askender/anwen.in
 def get(self, name):
     try:
         user = User.get(user_domain=name)
     except:
         self.redirect("/404")
     user.user_say = markdown2.markdown(user.user_say)
     likenum = Like.select().where(user_id=user.id).count()
     user.gravatar = get_avatar(user.user_email, 100)
     self.render("userhome.html", user=user, likenum=likenum)
예제 #9
0
파일: user.py 프로젝트: askender/anwen.in
 def get(self):
     if self.current_user:
         user = User.get(id=self.current_user["user_id"])
         if not user:
             self.redirect("/")
         user.gravatar = get_avatar(user.user_email, 100)
         self.render("changepass.html", user=user)
     else:
         self.redirect("/")
예제 #10
0
파일: user.py 프로젝트: facesun/anwen
 def get(self, name):
     user = User.find_one({'user_domain': name})
     user.user_jointime = time.strftime(
         '%Y-%m-%d %H:%M:%S', time.localtime(user.user_jointime))
     likes = User.find({'user_id': user._id})
     likenum = likes.count()
     for like in likes:
         share = Share.by_id(like.share_id)
         like.title = share.title
         like.id = share.id
         like.type = share.sharetype
     user.gravatar = get_avatar(user.user_email, 100)
     self.render("userlike.html", user=user, likenum=likenum, likes=likes)
예제 #11
0
 def get(self, node):
     page = self.get_argument("page", "1")
     realpage = int(page)
     shares = Share.select().where(
         sharetype=node).order_by('id').paginate(realpage, 10)
     sharesum = shares.count()
     pagesum = (sharesum + 9) / 10
     for share in shares:
         user = User.get(id=share.user_id)
         share.name = user.user_name
         share.domain = user.user_domain
         share.markdown = filter_tags(
             markdown.markdown(share.markdown))[:100]
         share.gravatar = get_avatar(user.user_email, 16)
     members = User.select().order_by('id').paginate(1, 20)
     for member in members:
         user = User.get(id=member.id)
         member.gravatar = get_avatar(user.user_email, 35)
     node_about = options.node_about[node]
     self.render(
         "node.html", shares=shares, members=members,
         pagesum=pagesum, page=page, node=node, node_about=node_about)
예제 #12
0
def get_comments(share, like_commentids, dislike_commentids):
    comments = []
    comment_res = Comment.find({'share_id': share.id})
    for comment in comment_res:
        user = User.by_sid(comment.user_id)
        comment.name = user.user_name
        comment.domain = user.user_domain
        comment.gravatar = get_avatar(user.user_email, 50)
        print(like_commentids, comment.id)
        print(dislike_commentids, comment.id)
        comment.is_liking = comment.id in like_commentids
        comment.is_disliking = comment.id in dislike_commentids
        comments.append(comment)
    return comments
예제 #13
0
파일: user.py 프로젝트: askender/anwen.in
 def get(self, name):
     try:
         user = User.get(user_domain=name)
     except:
         self.redirect("/404")
     likes = Like.select().where(user_id=user.id).order_by(('id', 'desc'))
     likenum = likes.count()
     for like in likes:
         share = Share.get(id=like.share_id)
         like.title = share.title
         like.id = share.id
         like.type = share.sharetype
     user.gravatar = get_avatar(user.user_email, 100)
     self.render("userlike.html", user=user, likenum=likenum, likes=likes)
예제 #14
0
def render_commit(commit, organization, repo):
    commit['author_date'] = datetime.fromtimestamp(float(
        commit['author_time'])).date()
    commit['author_time'] = format_time(commit['author_time'])
    author = reqcache.get(commit['author_email'])
    if not author:
        author = get_user_from_alias(commit['author_email'])
        reqcache.set(commit['author_email'], author)
    if not author:
        author = Obj()
        author.email = commit['author_email']
        author.name = None
        author.avatar = lambda size: get_avatar(author.email, size)
    commit['author'] = author
예제 #15
0
파일: user.py 프로젝트: anwen/anwen
 def get(self, name):
     user = User.find_one({"user_domain": name})
     user.user_jointime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user.user_jointime))
     like_res = Like.find({"user_id": user.id})
     likenum = like_res.count()
     likes = []
     for like in like_res:
         share = Share.by_sid(like.share_id)
         like.title = share.title
         like.id = share.id
         like.type = share.sharetype
         likes.append(like)
     user.gravatar = get_avatar(user.user_email, 100)
     self.render("userlike.html", user=user, likenum=likenum, likes=likes)
예제 #16
0
파일: user.py 프로젝트: wendycan/anwen
 def get(self, name):
     user = User.find_one({'user_domain': name})
     user.user_jointime = time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(user.user_jointime))
     like_res = Like.find({'user_id': user.id})
     likenum = like_res.count()
     likes = []
     for like in like_res:
         share = Share.by_sid(like.share_id)
         like.title = share.title
         like.id = share.id
         like.type = share.sharetype
         likes.append(like)
     user.gravatar = get_avatar(user.user_email, 100)
     self.render('userlike.html', user=user, likenum=likenum, likes=likes)
예제 #17
0
파일: index.py 프로젝트: bowu8/anwen
    def get(self, node):
        page = self.get_argument("page", 1)
        share_res = Share.find({"sharetype": node}).sort("_id", DESCENDING).limit(11).skip((int(page) - 1) * 11)
        pagesum = (share_res.count() + 10) / 11

        shares = []
        for share in share_res:
            user = User.by_sid(share.user_id)
            share.name = user.user_name
            share.published = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(share.published))
            share.domain = user.user_domain
            share.markdown = filter_tags(markdown2.markdown(share.markdown))[:400]
            share.gravatar = get_avatar(user.user_email, 16)
            shares.append(share)

        node_about = options.node_about[node]
        self.render("node.html", shares=shares, pagesum=pagesum, page=page, node=node, node_about=node_about)
예제 #18
0
파일: index.py 프로젝트: bowu8/anwen
    def get(self, name=None):
        if not name:
            tags = Tag.find()
            self.render("tag.html", tags=tags)
        else:
            tag = Tag.find_one({"name": name})
            shares = []
            for i in tag.share_ids.split(" "):
                share = Share.by_sid(i)

                user = User.by_sid(share.user_id)
                share.name = user.user_name
                share.published = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(share.published))
                share.domain = user.user_domain
                share.markdown = filter_tags(markdown2.markdown(share.markdown))[:100]
                share.gravatar = get_avatar(user.user_email, 16)
                shares.append(share)
            self.render("tage.html", name=name, shares=shares)
예제 #19
0
파일: share.py 프로젝트: askender/anwen.in
 def post(self):
     commentbody = self.get_argument("commentbody", None)
     share_id = self.get_argument("share_id", None)
     html = markdown2.markdown(commentbody)
     Comment.create(
         user_id=self.current_user["user_id"],
         share_id=share_id, commentbody=commentbody)
     Share.update(
         commentnum=F('commentnum') + 1).where(id=share_id).execute()
     name = tornado.escape.xhtml_escape(self.current_user["user_name"])
     gravatar = get_avatar(self.current_user["user_email"], 50)
     newcomment = ''
     newcomment += ' <div class="comment">'
     newcomment += '<div class="avatar">'
     newcomment += '<img src="' + gravatar + '" />'
     newcomment += '</div>'
     newcomment += '<div class="name">' + name + '</div>'
     newcomment += '<div class="date" title="at"></div>'
     newcomment += html
     newcomment += '</div>'
     self.write(newcomment)
예제 #20
0
파일: index.py 프로젝트: vivekjishtu/anwen
    def get(self, node='home'):
        page = self.get_argument("page", 1)
        share_res = Share.find({'status': 0}).sort(
            'score', DESCENDING).limit(11).skip((int(page) - 1) * 11)

        pagesum = (share_res.count() + 10) / 11
        shares = []
        for share in share_res:
            user = User.by_sid(share.user_id)
            share.name = user.user_name
            share.published = time.strftime(
                '%Y-%m-%d %H:%M:%S', time.localtime(share.published))
            share.domain = user.user_domain
            share.markdown = filter_tags(
                markdown2.markdown(share.markdown))[:400]
            share.gravatar = get_avatar(user.user_email, 16)
            shares.append(share)

        self.render(
            "node.html", shares=shares,
            pagesum=pagesum, page=page, node=node,
        )
예제 #21
0
파일: api_user.py 프로젝트: anwen/anwen
    def get(self):
        user = User.by_sid(self.current_user['user_id'])
        # 删除敏感信息
        auser = dict(user)
        auser.pop('_id')
        auser.pop('user_pass')
        # 获取头像
        if user.user_email.endswith('@wechat'):
            user['gravatar'] = get_avatar_by_wechat(user._id)
        else:
            auser['gravatar'] = get_avatar(user.user_email, 100)

        # auser['user_tags'] = []
        auser['user_tags_info'] = []
        for tag in auser['user_tags']:
            info = {}
            info['name'] = tag
            if tag in d_tag_desc:
                info['desc'] = d_tag_desc[tag]
            else:
                info['desc'] = '...'
            if tag in d_tag_lang:
                eng = d_tag_lang[tag]
                # info['img'] = 'https://anwensf.com/static/info/_{}.jpg'.format(eng.lower())
                info['img'] = 'https://anwen.cc/static/info/_{}_100.jpg'.format(eng.lower())
            else:
                # https://search.creativecommons.org/photos/27c13378-faf4-4d9e-ad0d-0b9459403aeb
                # https://live.staticflickr.com/7291/11240475435_ce223d84e2_b.jpg
                # the img is in public domain
                info['img'] = 'https://anwen.cc/static/info/public_domain_100.jpg'
            auser['user_tags_info'].append(info)
        # 添加管理员信息
        auser['is_admin'] = admin.is_admin(auser['id'])
        if auser['id'] in wx_admin_ids:
            auser['is_admin'] = True
        # 输出
        self.res = auser
        return self.write_json()
예제 #22
0
파일: share.py 프로젝트: facesun/anwen
 def post(self):
     commentbody = self.get_argument("commentbody", None)
     share_id = self.get_argument("share_id", None)
     html = markdown2.markdown(commentbody)
     comment = Comment
     comment['user_id'] = self.current_user["user_id"]
     comment['share_id'] = int(share_id)
     comment['commentbody'] = commentbody
     comment.save()
     share = Share.by_sid(share_id)
     share.commentnum += 1
     share.save()
     name = tornado.escape.xhtml_escape(self.current_user["user_name"])
     gravatar = get_avatar(self.current_user["user_email"], 50)
     newcomment = ''
     newcomment += ' <div class="comment">'
     newcomment += '<div class="avatar">'
     newcomment += '<img src="' + gravatar + '" />'
     newcomment += '</div>'
     newcomment += '<div class="name">' + name + '</div>'
     newcomment += '<div class="date" title="at"></div>'
     newcomment += html
     newcomment += '</div>'
     self.write(newcomment)
예제 #23
0
 def get_url(self, obj, view_name, request, format):
     return get_avatar(request, obj)
예제 #24
0
파일: share.py 프로젝트: bowu8/anwen
    def get(self, slug):
        share = None
        if slug.isdigit():
            share = Share.by_sid(slug)
        else:
            share = Share.by_slug(slug)
        if share:
            share.hitnum += 1
            share.save()
            share.markdown = markdown2.markdown(share.markdown)
            user = User.by_sid(share.user_id)
            share.user_name = user.user_name
            share.user_domain = user.user_domain
            tags = ''

            if share.tags:
                tags += 'tags:'
                for i in share.tags.split(' '):
                    tags += '<a href="/tag/%s">%s</a>  ' % (i, i)
            share.tags = tags
            user_id = int(
                self.current_user["user_id"]) if self.current_user else None
            like = Like.find_one(
                {'share_id': share.id, 'user_id': user_id})
            share.is_liking = bool(like.likenum % 2) if like else None
            share.is_disliking = bool(like.dislikenum % 2) if like else None
            comments = []
            comment_res = Comment.find({'share_id': share.id})
            for comment in comment_res:
                user = User.by_sid(comment.user_id)
                comment.name = user.user_name
                comment.domain = user.user_domain
                comment.gravatar = get_avatar(user.user_email, 50)
                comments.append(comment)

            if user_id:
                hit = Hit.find(
                    {'share_id': share.id},
                    {'user_id': int(self.current_user["user_id"])},
                )
                if hit.count() == 0:
                    hit = Hit
                    hit['share_id'] = share.id
                    hit['user_id'] = int(self.current_user["user_id"])
                    hit.save()
            else:
                if not self.get_cookie(share.id):
                    self.set_cookie(str(share.id), "1")
            posts = Share.find()
            suggest = []
            for post in posts:
                post.score = 100 + post.id - post.user_id + post.commentnum * 3
                post.score += post.likenum * 4 + post.hitnum * 0.01
                post.score += randint(1, 999) * 0.001
                common_tags = [i for i in post.tags.split(
                    ' ') if i in share.tags.split(' ')]
                # list(set(b1) & set(b2))
                post.score += len(common_tags)
                if post.sharetype == share.sharetype:
                    post.score += 5
                if self.current_user:
                    is_hitted = Hit.find(
                        {'share_id': share._id},
                        {'user_id': int(self.current_user["user_id"])},
                    ).count() > 0
                else:
                    is_hitted = self.get_cookie(share.id)
                if is_hitted:
                    post.score -= 50
                suggest.append(post)
            suggest.sort(key=lambda obj: obj.get('score'))
            suggest = suggest[:5]
            self.render(
                "sharee.html", share=share, comments=comments,
                suggest=suggest)
        else:
            old = 'http://blog.anwensf.com/'
            for i in options.old_links:
                if slug in i:
                    self.redirect('%s%s' % (old, i), permanent=True)
                    break
                    return
            self.redirect("/404")
예제 #25
0
파일: user.py 프로젝트: anwen/anwen
    def get(self, name):
        user = User.find_one({'user_domain': name})
        user.user_say = markdown2.markdown(user.user_say)
        user.user_jointime = time.strftime('%Y-%m-%d %H:%M:%S',
                                           time.localtime(user.user_jointime))
        likenum = User.find({'user_id': user._id}).count()
        user.gravatar = get_avatar(user.user_email, 100)
        shares = Share.find({
            'user_id': user.id
        }, {
            'markdown': 0,
            'summary': 0
        }).sort('_id', -1).limit(100)

        likes = set()
        dislikes = set()
        collects = set()
        if self.current_user:
            user_id = self.current_user["user_id"]
            _likes = Like.find({
                'entity_type': 'share',
                'user_id': user_id
            }, {
                '_id': 0,
                'entity_id': 1,
                'likenum': 1,
                'dislikenum': 1
            })
            _likes = list(_likes)
            print(_likes[0])
            likes = set(i.entity_id for i in _likes if i.likenum > 0)
            dislikes = set(i.entity_id for i in _likes if i.dislikenum > 0)
            collects = Collect.find(
                {
                    'entity_type': 'share',
                    'user_id': user_id
                }, {
                    '_id': 0,
                    'entity_id': 1,
                    'collectnum': 1
                })
            collects = set(i.entity_id for i in collects if i.collectnum > 0)

        l_share = []
        print(shares[0])
        for share in shares:
            # d_share = dict(share)
            # d_share = share
            # if self.current_user:
            #     user_id = self.current_user["user_id"]
            #     like = Like.find_one(
            #         {'entity_id': share.id, 'entity_type': 'share', 'user_id': user_id})
            #     collect = Collect.find_one(
            #         {'entity_id': share.id, 'entity_type': 'share', 'user_id': user_id})
            #     d_share.is_liking = bool(like.likenum) if like else False
            #     d_share.is_disliking = bool(like.dislikenum) if like else False
            #     d_share.is_collecting = bool(collect.collectnum) if collect else False
            # print(d_share.id, len(likes))
            share.is_liking = True if likes and share.id in likes else False
            share.is_disliking = True if dislikes and share.id in dislikes else False
            share.is_collecting = True if collects and share.id in collects else False
            l_share.append(share)

        self.render('userhome.html',
                    user=user,
                    shares=l_share,
                    is_login=bool(self.current_user),
                    likenum=likenum)
예제 #26
0
파일: user_setting.py 프로젝트: anwen/anwen
 def get(self):
     user = User.by_sid(self.current_user['user_id'])
     user.user_jointime = time.strftime(
         '%Y-%m-%d %H:%M:%S', time.localtime(user.user_jointime))
     user.gravatar = get_avatar(user.user_email.encode('u8'), 100)
     self.render('setting.html', user=user)
예제 #27
0
 def get(self):
     realpath = self.request.path[1:]
     try:
         share = Share.get(slug=realpath)
     except:
         self.redirect("/404")
     share.markdown = markdown.markdown(share.markdown)
     if self.current_user:
         share.is_liking = Like.select().where(
             share_id=share.id,
             user_id=self.current_user["user_id"]).count() > 0
     comments = Comment.select().where(share_id=share.id)
     for comment in comments:
         user = User.get(id=comment.user_id)
         comment.name = user.user_name
         comment.domain = user.user_domain
         comment.gravatar = get_avatar(user.user_email, 50)
     Share.update(hitnum=F('hitnum') + 1).where(
         id=share.id).execute()
     if self.current_user:
         is_hitted = Hit.select().where(
             share_id=share.id,
             user_id=self.current_user["user_id"]).count() > 0
         Hit.create(
             hitnum=1, share_id=share.id,
             user_id=self.current_user["user_id"], )
     else:
         is_hitted = self.get_cookie(share.id)
         if not is_hitted:
             self.set_cookie(str(share.id), "1")
     posts = Share.select()
     suggest = {}
     for post in posts:
         post.score = 100 + post.id - post.user_id + post.commentnum * 3
         post.score += post.likenum * 4 + post.hitnum * 0.01
         post.score += randint(1, 999) * 0.001
         if post.sharetype == share.sharetype:
             post.score += 5
         if self.current_user:
             is_hitted = Hit.select().where(
                 share_id=post.id,
                 user_id=self.current_user["user_id"]).count() > 0
         else:
             is_hitted = self.get_cookie(share.id)
         if is_hitted:
             post.score -= 50
         suggest[post.score] = post.id
         print(post.id)
         print(post.score)
     realsuggest = []
     i = 1
     for key in sorted(suggest.iterkeys(), reverse=True):
         post = Share.get(id=suggest[key])
         share_post = {'id': post.id,
                       'title': post.title, }
         realsuggest.append(share_post)
         i = i + 1
         if i > 3:
             break
     self.render(
         "sharee.html", share=share, comments=comments,
         realsuggest=realsuggest)
예제 #28
0
파일: api_shares.py 프로젝트: anwen/anwen
    def get(self):
        token = self.request.headers.get('Authorization', '')
        page = self.get_argument("page", 1)
        per_page = self.get_argument("per_page", 10)
        tag = self.get_argument('tag', '')
        filter_type = self.get_argument("filter_type", '')  # my_tags my_likes
        last_suggested = self.get_argument("last_suggested", 0)
        read_status = self.get_argument('read_status', 1)
        meta_info = self.get_argument("meta_info", 1)

        read_status = int(read_status)
        per_page = int(per_page)
        page = int(page)
        if not last_suggested:
            last_suggested = 0
        last_suggested = float(last_suggested) / 1000 + 1

        user = self.get_user_dict(token)

        cond = {}
        tags = None
        if user and filter_type == 'my_tags':
            d_user = User.by_sid(user['user_id'])
            if d_user:
                tags = d_user['user_tags']
        # 按照tag来过滤
        if tags:
            cond['tags'] = {"$in": tags}
        elif tag:
            cond['tags'] = tag

        # 不同的用户显示不同级别的推荐
        # if user and user['user_id'] in wx_admin_ids:
        if user and user['user_id'] == 1:
            cond['status'] = {'$gte': 1}
        else:
            cond['status'] = {'$gte': 1}

        # 已读列表 20ms
        l_hitted_share_id = []
        if user and read_status:
            hits = Hit.find({'user_id': user['user_id']}, {
                '_id': 0,
                'share_id': 1
            })
            l_hitted_share_id = [i['share_id'] for i in hits]

        filter_d = {}
        filter_d['_id'] = 0
        # 白名单里的属性才展示
        filter_d['id'] = 1
        filter_d['images'] = 1
        filter_d['title'] = 1
        filter_d['user_id'] = 1
        filter_d['tags'] = 1
        filter_d['published'] = 1
        filter_d['post_img'] = 1
        shares = Share.find(cond, filter_d).sort('suggested',
                                                 -1).limit(per_page).skip(
                                                     (page - 1) * per_page)
        # 过滤
        new_shares = []
        for share in shares:
            user = User.by_sid(share.user_id)
            # share = dict(share)
            share['type'] = 1
            # if share.post_img:
            # if hasattr(share, 'post_img'):
            if share.get('post_img'):
                share['type'] = 2
                share['images'] = [
                    IMG_BASE +
                    share['post_img'].replace('_1200.jpg', '_260.jpg')
                ]
                share.pop('post_img')
            else:
                share['images'] = []
            share['author'] = user.user_name
            share['published'] = int(share['published'] *
                                     1000)  # share.published
            if read_status:
                share['read'] = bool(share['id'] in l_hitted_share_id)

            if 0:  # 不展示作者头像
                if user.user_email.endswith('@wechat'):
                    share['user_img'] = options.site_url + \
                        get_avatar_by_wechat(user._id)
                if user.user_email.endswith('@anwensf.com'):
                    share['user_img'] = options.site_url + \
                        get_avatar_by_feed(user.id)
                else:
                    share['user_img'] = options.site_url + \
                        get_avatar(user.user_email, 100)
            new_shares.append(share)

        if meta_info:
            meta = {}
            if last_suggested:
                cond_update = copy.deepcopy(cond)
                cond_update['suggested'] = {'$gt': last_suggested}
                number_of_update = Share.find(cond_update, {
                    '_id': 0,
                    'id': 1
                }).count()
                meta['number_of_update'] = number_of_update
            if tag:  # 子标签的文章数量
                d_tags = get_tags()
                d_tags_parents = get_tags_parents()  # get_tags_parent
                if tag in d_tags:
                    sub_tags = []
                    for name in d_tags[tag]:
                        info = {}
                        info['name'] = name
                        # num = Share.find({'tags': name}, {'_id': 0}).count()
                        # num_recent = Share.find(
                        #     {'tags': name, 'published': {'$gt': time.time() - 86400 * 30}}, {'_id': 0}).count()
                        # info['num'] = num
                        # info['num_recent'] = num_recent
                        sub_tags.append(info)
                    meta['sub_tags'] = sub_tags
                meta['parent_tags'] = []
                if tag in d_tags_parents:
                    # meta['parent_tags'].append(d_tags_parent[tag])
                    meta['parent_tags'] = d_tags_parents[tag]  # hypernym
            number = Share.find(cond, {'_id': 0}).count()  # 'id': 1
            meta['number'] = number
            # if filter_type == 'my_tags':
            #     meta['tags'] = tags

        self.res = {'articles': new_shares}
        self.meta = meta
        return self.write_json()
예제 #29
0
 def avatar(self, size=48):
     return get_avatar(self.email, size)
예제 #30
0
    def get(self):
        page = self.get_argument("page", 1)
        per_page = self.get_argument("per_page", 10)
        filter_type = self.get_argument("filter_type", '')  # my_tags
        tag = self.get_argument('tag', '')
        meta_info = self.get_argument("meta_info", 1)
        last_suggested = self.get_argument("last_suggested", 0)
        read_status = self.get_argument('read_status', 1)
        token = self.request.headers.get('Authorization', '')
        # has_vote = self.get_argument("has_vote", None)
        # vote_open = self.get_argument("vote_open", None)

        read_status = int(read_status)
        per_page = int(per_page)
        page = int(page)
        last_suggested = float(last_suggested) / 1000 + 1
        user = self.get_user_dict(token)

        cond = {}
        # 按照tags来过滤
        tags = None
        if user and filter_type == 'my_tags':
            d_user = User.by_sid(user['user_id'])
            if d_user:
                tags = d_user['user_tags']
        # 按照tag来过滤
        if tags:
            cond['tags'] = {"$in": tags}
        elif tag:
            cond['tags'] = tag

        # 不同的用户显示不同级别的推荐
        if user and user['user_id'] in wx_admin_ids:
            cond['status'] = {'$gte': 1}
        else:
            cond['status'] = {'$gte': 1}

        l_hitted_share_id = []
        if user and read_status:
            hits = Hit.find({'user_id': user['user_id']})
            l_hitted_share_id = [i['share_id'] for i in hits]

        # if vote_open:
        #     if not vote_open.isdigit():
        #         return self.write_error(422)
        #     cond['vote_open'] = int(vote_open)
        # if has_vote:
        #     cond['vote_title'] = {'$ne': ''}

        number = Share.find(cond, {'_id': 0}).count()
        # sort: _id
        if last_suggested:
            cond_update = copy.deepcopy(cond)
            cond_update['suggested'] = {'$gt': last_suggested}
            number_of_update = Share.find(cond_update, {'_id': 0}).sort(
                'suggested', -1).count()
            logger.info('number_of_update 1: {}'.format(number_of_update))

        num_shares = Share.find(cond, {'_id': 0, 'id': 1}).count()

        shares = Share.find(cond, {'_id': 0}).sort(
            'suggested', -1).limit(per_page).skip((page - 1) * per_page)
        # shares = [fix_share(share) for share in shares]
        new_shares = []
        for share in shares:
            share = fix_share(share)
            user = User.by_sid(share.user_id)
            share = dict(share)
            share['user_name'] = user.user_name
            share['markdown'] = ''
            if read_status:
                share['read'] = bool(share['id'] in l_hitted_share_id)

            soup = BeautifulSoup(share['content'], "lxml")
            # kill all script and style elements
            for script in soup(["script", "style"]):
                script.extract()    # rip it out

            # get text
            text = soup.get_text()

            # break into lines and remove leading and trailing space on each
            lines = (line.strip() for line in text.splitlines())
            # break multi-headlines into a line each
            chunks = (phrase.strip()
                      for line in lines for phrase in line.split("  "))
            # drop blank lines
            text = '\n'.join(chunk for chunk in chunks if chunk)
            # print(text)
            share['summary'] = text[:150]
            share['content'] = ''

            if user.user_email.endswith('@wechat'):
                share['user_img'] = options.site_url + \
                    get_avatar_by_wechat(user._id)
            if user.user_email.endswith('@anwensf.com'):
                share['user_img'] = options.site_url + \
                    get_avatar_by_feed(user.id)
            else:
                share['user_img'] = options.site_url + \
                    get_avatar(user.user_email, 100)
            new_shares.append(share)

        # if tag:
        #     shares = [share for share in shares if tag in share['tags']]
        meta = {}
        meta['page'] = page
        meta['articleNumber'] = num_shares
        if meta_info and last_suggested:
            meta['number_of_update'] = number_of_update
        if meta_info and tag:
            d_tags = get_tags()
            # d_tags_parent = get_tags_parent()
            d_tags_parents = get_tags_parents()
            if tag in d_tags:
                sub_tags = []
                for name in d_tags[tag]:
                    num = Share.find({'tags': name}, {'_id': 0}).count()
                    num_recent = Share.find(
                        {'tags': name, 'published': {'$gt': time.time() - 86400 * 30}}, {'_id': 0}).count()
                    info = {}
                    info['name'] = name
                    info['num'] = num
                    info['num_recent'] = num_recent
                    sub_tags.append(info)
                meta['sub_tags'] = sub_tags
            meta['parent_tags'] = []
            if tag in d_tags_parents:
                # hypernym
                # meta['parent_tags'].append(d_tags_parent[tag])
                meta['parent_tags'] = d_tags_parents[tag]

        logger.info('last_suggested time: {}'.format(last_suggested))

        if new_shares:
            logger.info('new_shares[0] time: {}'.format(new_shares[0]['title']))
            logger.info('new_shares[0] published time: {}'.format(
                new_shares[0]['published']))
            logger.info('new_shares[0] suggested time: {}'.format(
                new_shares[0]['suggested']))

        self.res = {'articles': list(new_shares)}
        self.meta = meta
        # number=len(self.res)
        # number=number
        return self.write_json()
예제 #31
0
 def get_url(self, obj, view_name, request, format):
     return get_avatar(request, obj)
예제 #32
0
파일: user.py 프로젝트: wendycan/anwen
 def get(self):
     user = User.by_sid(self.current_user['user_id'])
     user.user_jointime = time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(user.user_jointime))
     user.gravatar = get_avatar(user.user_email, 100)
     self.render('changepass.html', user=user)
예제 #33
0
파일: user.py 프로젝트: anwen/anwen
 def get(self):
     user = User.by_sid(self.current_user["user_id"])
     user.user_jointime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user.user_jointime))
     user.gravatar = get_avatar(user.user_email, 100)
     self.render("changepass.html", user=user)
예제 #34
0
    def get(self, slug):
        share = None
        if slug.isdigit():
            share = Share.by_sid(slug)
        else:
            share = Share.by_slug(slug)
        if share:
            share.hitnum += 1
            share.save()
            if share.markdown:
                share.content = markdown2.markdown(share.markdown)
            user = User.by_sid(share.user_id)
            share.user_name = user.user_name
            share.user_domain = user.user_domain
            tags = ''

            if share.tags:
                tags += 'tags:'
                for i in share.tags.split(' '):
                    tags += '<a href="/tag/%s">%s</a>  ' % (i, i)
            share.tags = tags
            user_id = int(
                self.current_user["user_id"]) if self.current_user else None
            like = Like.find_one(
                {'share_id': share.id, 'user_id': user_id})
            share.is_liking = bool(like.likenum % 2) if like else None
            share.is_disliking = bool(like.dislikenum % 2) if like else None
            comments = []
            comment_res = Comment.find({'share_id': share.id})
            for comment in comment_res:
                user = User.by_sid(comment.user_id)
                comment.name = user.user_name
                comment.domain = user.user_domain
                comment.gravatar = get_avatar(user.user_email, 50)
                comments.append(comment)

            if user_id:
                hit = Hit.find(
                    {'share_id': share.id},
                    {'user_id': int(self.current_user["user_id"])},
                )
                if hit.count() == 0:
                    hit = Hit
                    hit['share_id'] = share.id
                    hit['user_id'] = int(self.current_user["user_id"])
                    hit.save()
            else:
                if not self.get_cookie(share.id):
                    self.set_cookie(str(share.id), "1")
            posts = Share.find()
            suggest = []
            for post in posts:
                post.score = 100 + post.id - post.user_id + post.commentnum * 3
                post.score += post.likenum * 4 + post.hitnum * 0.01
                post.score += randint(1, 999) * 0.001
                common_tags = [i for i in post.tags.split(
                    ' ') if i in share.tags.split(' ')]
                # list(set(b1) & set(b2))
                post.score += len(common_tags)
                if post.sharetype == share.sharetype:
                    post.score += 5
                if self.current_user:
                    is_hitted = Hit.find(
                        {'share_id': share._id},
                        {'user_id': int(self.current_user["user_id"])},
                    ).count() > 0
                else:
                    is_hitted = self.get_cookie(share.id)
                if is_hitted:
                    post.score -= 50
                suggest.append(post)
            suggest.sort(key=lambda obj: obj.get('score'))
            suggest = suggest[:5]
            self.render(
                "sharee.html", share=share, comments=comments,
                suggest=suggest)
        else:
            old = 'http://blog.anwensf.com/'
            for i in options.old_links:
                if slug in i:
                    self.redirect('%s%s' % (old, i), permanent=True)
                    break
                    return
            self.redirect("/404")
예제 #35
0
파일: avatar.py 프로젝트: zinhaa/keepswin
def avatar(context, user, requested_size=None, bg_shade=0):
    return get_avatar(context['request'], user, requested_size, bg_shade)