Ejemplo n.º 1
0
    def search_dicts(query, category):
        '''
			category in ('share', 'event', 'club')
			返回 yield 体
		'''
        if category == 'share':
            for i in ShareSnap.share_search(query):
                yield {
                 'data': i,
                 'avatar':
                  ShareSnap.thumbnail_find(i.attach_uuid, 'medium') or \
                  AvatarSnap.avatar_find \
                      (i.relation, i.account_id, 'medium'),
                }
        elif category == 'event':
            for i in EventSnap.event_search(query):
                yield {
                    'data': i,
                    'avatar': AvatarSnap.avatar_all(i.relation, i.account_id),
                }
        else:
            for i in ClubSnap.club_search(query):
                yield {
                    'data': i,
                    'avatar': AvatarSnap.avatar_all('club', i.id),
                }
Ejemplo n.º 2
0
 def club_picture(cid, request=('qrcode', 'latest', 'mixed')):
     '得到图片板块的图片'
     dict_render = {}
     sname = ClubSnap.sname_find_by_cid(cid)
     img_qry = ShareSnap.image_list_by_aid('club', cid)
     if 'qrcode' in request:  #二维码
         dict_render['qrcode'] = QrcodeSnap.qrcode_find(sname, "club")
         if len(img_qry) == 0:
             dict_render['latest'] = None
             dict_render['mixed'] = None
             return dict_render
     if 'latest' in request:  #获取最新
         dict_render['latest'] = ShareSnap.url_find_by_attach(img_qry[0])
     if 'mixed' in request:  #获取杂烩
         dict_render['mixed'] = ShareSnap.mix_find(sname)
     return dict_render
Ejemplo n.º 3
0
    def link_find(message):
        '''
			查找链接
		'''
        from quan_account.views import UserSnap, ClubSnap, AccountSnap
        relation = message.conn_relation
        minor_id = message.send_id
        try:
            if relation in ('event', 'signup'):
                return '/event/%d/' % minor_id
            elif relation == 'badge':
                from quan_badge.views import BadgeSnap
                qry = BadgeSnap.badge_find_by_bid(bid)
                return '/club/%s/' % ClubSnap.sname_find_by_cid(qry.account_id)
            elif relation in ('member', 'club'):
                sname = ClubSnap.sname_find_by_cid(minor_id)
                return '/club/%s/' % sname
            elif relation in ('share', 'comment'):
                suid = ShareSnap.uuid_find_by_sid(minor_id)
                return '/share/%s/' % suid
            elif relation == 'user':
                sname = UserSnap.sname_find_by_uid(major_id)
                return '/user/%s/' % sname
            elif relation == 'news':
                return '/news/%d/' % minor_id
            else:
                return '#'
        except Exception as e:
            print(e)
            return '#error'
Ejemplo n.º 4
0
 def total_rank(club, detail=False):
     'event + share + watch, 当三无时返回0'
     cid = club.id
     cache_key = 'SquareSnap__total_rank__%d' % cid
     cached = cache.get(cache_key)
     if cached:
         if detail:
             return cached
         else:
             return cached['rank']
     rank = 0
     event_num = EventSnap.event_find_by_cid('club', cid).count()
     share_num = ShareSnap.share_find_by_aid('club', cid).count()
     follower_num = ClubSnap.follower_total(cid)
     avatar_num = int(bool(AvatarSnap.avatar_find('club', cid, '', True)))
     rank += 20 * event_num
     rank += 15 * share_num
     rank += 10 * follower_num
     rank += 30 * avatar_num
     answer = {
         'rank': rank,
         'event_num': event_num,
         'share_num': share_num,
         'follower_num': follower_num,
         'avatar_num': avatar_num,
     }
     cache.set(cache_key, answer, random.randint(800000, 900000))
     if detail:
         return answer
     else:
         return rank
Ejemplo n.º 5
0
	def event_share_relate(request, evid) :
		'关联 event 和 share'
		dict_render = UserAgentSnap.record(request)
		event = EventSnap.event_find_by_evid(evid)
		if not event or not ClubSnap.cid_verify(request, event.account_id, True):
			raise Http403('您没有活动的管理权限')
		evid = int(evid)
		from quan_share.views import ShareSnap
		try :
			sid = int(request.POST.get('sid', ''))
			share = ShareSnap.share_find_by_sid(sid)
			if not share :
				raise ValueError
			if share.account_id != event.account_id :
				raise ValueError
			if share.relation != event.relation :
				raise ValueError
		except ValueError :
			raise Http403('您没有分享的管理权限')
		if request.POST.get('relate', '') == 'true' :
			ShareEventRelation(share_id=share.id, event_id=event.id).save()
			return Snap.success(request, '成功关联分享')
		else :
			ShareEventRelation.objects.filter \
					(share_id=share.id, event_id=event.id).update(status=1)
			return Snap.success(request, '成功取消分享关联')
Ejemplo n.º 6
0
    def star_calc(cid,
                  event_qry=None,
                  member_makeup=None,
                  share_qry=None,
                  return_score=False):
        '''
			计算星级
				本学期活动数量	* 10 		|	8	6	4	3	2
				发布分享数量	* 10		|	4	3	2	1	0
				成员数量		* 4			|	15	12	9	6	3
				成员年级数量	* 20		|	5	4	3	2	1
				类加后,使用以下评分标准
				五星: >= 80				|	max: 280
				四星: >= 70				|	max: 218
				三星: >= 60				|	max: 156
				二星: >= 50				|	max: 104
				一星: >= 40				|	max: 52
		'''
        #准备
        if event_qry == None:
            event_qry = EventSnap.event_semester_find_by_cid('club', cid).order_by \
             ('time_set')
        if member_makeup == None:
            member_makeup = [0, 0, 0, 0, 0, 0, 0, 0]
            for i in ClubSnap.grade_list_by_cid(cid):
                member_makeup[i] += 1
        if share_qry == None:
            start = EventSnap.semester_start()
            share_qry = ShareSnap.share_find_by_aid('club', cid)
            share_qry = share_qry.filter(time_create__gte=start)
        #开始计算
        member_sum = sum(member_makeup[:-1])
        member_grade_num = 0
        for i in member_makeup:
            member_grade_num += int(bool(i))
        event_num = event_qry.count()
        share_num = share_qry.count()
        #开始累加
        score = event_num * 10 + share_num * 10 + \
          member_sum * 4 + member_grade_num * 20
        if return_score:
            return score
        #返回
        if score >= 80:
            return 5
        if score >= 70:
            return 4
        if score >= 60:
            return 3
        if score >= 50:
            return 2
        if score >= 40:
            return 1
        return 0
Ejemplo n.º 7
0
 def home_dict(request):
     '得到/页面的字典,喜欢=关注'
     dict_render = {}
     #得到3个最新活动
     dict_render['event_list'] = []
     event_qry = SquareSnap.event_newest()
     for i in event_qry:
         event_date, event_time = ChineseSnap.datetime_simp(i.time_set)
         dict_render['event_list'].append({
             'data':
             i,
             'nice':
             EventSnap.nice_total(i.id),
             'date':
             event_date,
             'time':
             event_time,
             'niced':
             EventSnap.niced_find_by_request(request, i.id),
             'sname':
             ClubSnap.sname_find_by_cid(i.account_id),
             'fname':
             ClubSnap.fname_find_by_cid(i.account_id),
         })
     dict_render['club_list'] = []
     club_all = ClubSnap.club_all_find()
     club_list = []
     for i in club_all:
         club_list.append((i, SquareSnap.total_rank(i, True)))
     club_filtered = list(filter(lambda x: all(x[1].values()), club_list))
     # 抵制三无社团
     club_filtered.sort(key=lambda x: x[1]['rank'], reverse=True)
     num = min(3, max(0, len(club_filtered) - 3))
     club_qry = club_filtered[:3] + random.sample(club_filtered[3:], num)
     for club, rank in club_qry:
         dict_render['club_list'].append({
          'data':  club,
          'avatar': AvatarSnap.avatar_find('club', club.id, 'medium'),
          'follower': ClubSnap.follower_total(club.id),
          'followee': ', '.join(itertools.islice \
                (ClubSnap.follower_list(club.id), 3)),
          'category': ClubSnap.category_exchange(club.category),
         })
     # 得到社联通知列表
     dict_render['note'] = ShareSnap.union_record_find()
     if AuthSnap.notice_check(UserSnap.uid_find_by_request(request),
                              dict_render['note']):
         dict_render['note_read'] = True
     return dict_render
Ejemplo n.º 8
0
 def attach_wrap(suid):
     '通过 qry 中的 attach_uuid 找到附件并计算 dict_render'
     if not suid:
         return []
     if not ShareInfo.objects.filter(attach_uuid=suid, status=0).exists():
         return []
     qry = ShareAttach.objects.filter(attach_uuid=suid)
     attach_list = []
     for index, i in enumerate(qry, 1):
         url = ShareSnap.url_find_by_attach(i)
         attach_list.append({
          'url': url,
          'data': i,
          'name': i.name_raw,
          'thumbnail': ShareSnap.thumbnail_find \
                 (suid, 'exlarge', i.second_uuid),
          'index2': index % 2,
          'index3': index % 3,
          'index4': index % 4,
         })
     return attach_list
Ejemplo n.º 9
0
 def user_show(request, sname):
     dict_render = UserAgentSnap.record(request)
     uid = UserSnap.uid_find_by_sname(sname)
     user = UserSnap.user_find_by_uid(uid)
     visitor_id = UserSnap.uid_find_by_request(request)
     if not user:
         raise Http404('找不到用户')
     dict_render['title'] = t_(' - %s的主页') % user.first_name
     dict_render['user'] = user
     dict_render['club_join'] = []
     dict_render['club_follow'] = []
     club = list(ClubSnap.club_find_by_uid(uid))
     club += list(ClubSnap.club_find_by_uid(uid, False))
     for i in set(club):
         event = EventSnap.event_find_by_cid('club', i.id)
         event_list = []
         for j in list(event)[-3:]:
             evtime = ChineseSnap.datetime_simp(j.time_create)
             event_list.append({
                 'data': j,
                 'datetime': evtime[0] + evtime[1],
                 'join': EventSnap.signup_total(j.id),
             })
         member = ClubSnap.member_all(i.id)
         member_nickname = []
         for j in list(member)[:3]:
             member_nickname.append(UserSnap.nickname_find_by_uid(j))
         follower_qry = ClubSnap.follower_find(i.id)
         follower_nickname = []
         for j in follower_qry[:3]:
             follower_nickname.append \
              (UserSnap.nickname_find_by_uid(j.account_id_A))
         position = ClubSnap.club_position_by_uid(i.id, uid)
         club_dict = {
          'data': i,
          'position': position[1],
          'event_list': sorted(event_list,
             key=lambda x: x['data'].time_set, reverse=True),
          'event_num': event.count(),
          'member_nickname': t_(',').join(member_nickname),
          'member_num': len(member),
          'member_gt_3': len(member) > 3,
          'follower_nickname': t_(',').join(follower_nickname),
          'follower_num': follower_qry.count(),
          'follower_gt_3': follower_qry.count() > 3,
          'avatar': AvatarSnap.avatar_all('club', i.id),
          'visitor_join': ClubSnap.club_position_by_uid \
           (i.id, UserSnap.uid_find_by_request(request))[0] != 'none',
         }
         if position[0] != 'none':
             dict_render['club_join'].append(club_dict)
         if ClubSnap.club_followed_by_uid(uid, i.id):
             dict_render['club_follow'].append(club_dict)
     dict_render['title'] = t_(' - %s的主页') % user.first_name
     account = UserSnap.account_find_by_uid(uid)
     dict_render['visit_count'] = AccountSnap.visit_count_by_account(
         account)
     dict_render['join_time'] = ChineseSnap.timedelta_simp \
      (datetime.now() - user.date_joined)
     if UserSnap.sname_find_by_request(request) == sname:  # user_admin
         dict_render['inc_admin'] = True
         dict_render['user_avatar'] = AvatarSnap.avatar_all('user', uid)
         if dict_render['user_avatar']['raw'].startswith('/static/'):
             if random.randint(1, 3000) % 3 == 0:  # 强制上传头像
                 return Snap.redirect('/avatar/user/%s/' % sname)
         dict_render.update(BadgeDicts.intro('user', uid))
         dict_render.update(CenterDicts.club_find(uid))
         dict_render['nickname'] = UserSnap.nickname_find_by_uid(uid)
         dict_render['badge_list'] = BadgeDicts.badge_find('user', uid)
         dict_render['contact_club'] = dict_render['club_join']
         dict_render['contact_user'] = []
         for i in UserSnap.contact_list(uid):
             data = UserSnap.user_find_by_uid(i)
             dict_render['contact_user'].append({
                 'data':
                 data,
                 'avatar':
                 AvatarSnap.avatar_all('user', i),
                 'nickname':
                 UserSnap.nickname_find_by_uid(i),
             })
         dict_render['share_list'] = []
         share_qry = ShareSnap.share_find_by_aid('user', uid)
         for i in share_qry:
             dict_render['share_list'].append({
                 'data':
                 i,
                 'date':
                 ChineseSnap.datetime_simp(i.time_create),
             })
         dict_render['tab_active'] = request.GET.get('tag', 'messages')
         dict_render['tab_list'] = [
             (
                 'messages',
                 '消息',
             ),
             (
                 'club',
                 '我的社团',
             ),
             (
                 'follow',
                 '订阅列表',
             ),
             (
                 'footprint',
                 '我的足迹',
             ),
             (
                 'friends',
                 '好友动态',
             ),
             (
                 'share',
                 '我的分享',
             ),
             (
                 'settings',
                 '设置',
             ),
         ]
         dict_render['system_avatar'] = AvatarSnap.avatar_all('system', 0)
         return Snap.render('user_admin.html', dict_render)
     else:  # user_view
         user = UserSnap.user_find_by_uid(uid)
         club = list(ClubSnap.club_find_by_uid(uid, True)) + \
           list(ClubSnap.club_find_by_uid(uid, False))
         dict_render['followed'] = UserSnap.is_follower(uid, visitor_id)
         dict_render['friend'] = UserSnap.is_friend(uid, visitor_id)
         friend_status = UserSnap.friend_status_find(uid, visitor_id)
         dict_render['friend_status'] = friend_status
         if friend_status == 'friend':
             dict_render['friend_status_text'] = t_('取消好友')
             dict_render['friend_active_tag'] = ''
             dict_render['friends'] = True
         elif friend_status == 'friend-waiting':  #visitor等待
             dict_render['friend_status_text'] = t_('正在等待对方审核')
             dict_render['friend_active_tag'] = 'active'
         elif friend_status == 'friend-waiting-reverse':  #visitor需要确认
             dict_render['friend_status_text'] = t_('同意申请')
             dict_render['friend_active_tag'] = ''
             dict_render['friend_need_verify'] = True
         else:  # none
             dict_render['friend_status_text'] = t_('加为好友')
             dict_render['friend_active_tag'] = ''
         event_list = []
         for event in list(EventSnap.event_find_by_uid(uid))[:10]:
             event_time = list(ChineseSnap.datetime_simp(event.time_set))
             event_time[0] = event_time[0][:-1]
             event_dict = {
              'club': ClubSnap.club_find_by_cid(event.account_id),
              'club_avatar': AvatarSnap.avatar_all \
               ('club', event.account_id),
              'data': event,
              'join_num': EventSnap.signup_total(event.id),
              'datetime': event_time,
             }
             if event.time_set < datetime.now():
                 event_list.append(event_dict)
             elif not 'event_next' in dict_render:
                 dict_render['event_next'] = event_dict
         dict_render['event_list'] = event_list
         dict_render['nickname'] = UserSnap.nickname_find_by_uid(uid)
         dict_render['avatar'] = AvatarSnap.avatar_all('user', uid)
         return Snap.render('user_view.html', dict_render)
Ejemplo n.º 10
0
    def club_show(request, sname):
        '显示社团主页'
        # 思考:如果增加一个_admin反而需要给社长的模板上加一个按钮去访问
        dict_render = UserAgentSnap.record(request)
        dict_render['inc_list'] = []
        real_name = ClubSnap.alias_find_by_sname(sname)
        if real_name != sname and real_name:
            return Snap.redirect('/club/%s/' % real_name)
        club = ClubSnap.club_find_by_sname(sname)

        if club == None:
            raise Http404("或许你希望创建一个社团?")

        dict_render['visitors'] = AccountSnap.visit_count_by_account(club)
        if request.GET.get('qrcode') == 'true':  # 统计 qrcode 访问
            log_file_path = settings.MEDIA_ROOT + 'club-qrcode-log.txt'
            log_file = open(log_file_path, 'a', encoding="UTF-8")
            try:
                print(club.id,
                      sname,
                      club.full_name,
                      datetime.now(),
                      request.user.id,
                      request.user.first_name,
                      sep='\t',
                      file=log_file)
            except AttributeError:
                print(club.id,
                      sname,
                      club.full_name,
                      datetime.now(),
                      0,
                      '',
                      sep='\t',
                      file=log_file)
        # 社团页面存在
        time_update = ChineseSnap.datetime_simp(club.time_update)
        dict_render.update({
            'club': club,
            'time_update': time_update,
        })
        dict_render.update(BadgeDicts.intro('club', club.id))
        dict_render.update(CenterDicts.status(club))
        dict_render['title'] = t_(' - %s的主页') % dict_render['club'].full_name
        dict_render['club_follower_total'] = ClubSnap.follower_total(club.id)
        dict_render['share_box'] = []
        for i in ShareSnap.share_find_by_aid('club', club.id)[:10]:
            date_time = ChineseSnap.datetime_simp(i.time_create)
            dict_render['share_box'].append({
                'link': '/share/%s/' % i.attach_uuid,
                'date': date_time[0],
                'data': i,
                'time': date_time[1],
            })
        dict_render['presentation_list'] = ShareSnap.presentation_find_by_aid \
         ('club', club.id, 'large', 10)
        dict_render['picture'] = CenterDicts.club_picture(
            club.id, ('qrcode', ))

        # follower_list
        follower_qry = ClubSnap.follower_find(club.id)
        follower_nickname = []
        for i in follower_qry[:6]:
            follower_nickname.append({
             'nickname': UserSnap.nickname_find_by_uid(i.account_id_A)[:5],
             'avatar': AvatarSnap.avatar_find \
              ('user', i.account_id_A, 'medium'),
             'sname': UserSnap.sname_find_by_uid(i.account_id_A),
            })
        dict_render['follower_list'] = follower_nickname
        dict_render['title'] = t_(' - %s') % club.full_name
        dict_render['club_member_total'] = ClubSnap.member_total(club.id)
        if ClubSnap.sname_verify(request, sname, True) == True:
            # 用户为社长并且不需要预览
            if ClubSnap.sname_verify(request, sname) == True:
                if dict_render['avatar'].startswith('/static/'):
                    if random.randint(1, 3000) % 2:  # 强制上传头像
                        return Snap.redirect('/avatar/club/%s/' % sname)
            dict_render['inc_admin'] = ClubSnap.sname_verify(request, sname)
            dict_render['joined'] = True
            dict_render.update(EventDicts.club_admin(club, dict_render))
            dict_render.update(ShareDicts.club_admin(club, dict_render))
            dict_render['alias_list'] = ClubSnap.alias_all_by_cid(club.id)
            return Snap.render('club_admin.html', dict_render)
        else:
            dict_render['inc_admin'] = False
            dict_render.update(EventDicts.club(request, club))
            uid = UserSnap.uid_find_by_request(request)
            dict_render['followed'] = ClubSnap.club_followed_by_uid(
                uid, club.id)
            dict_render['joined'] = ClubSnap.club_joined_by_uid(
                uid, club.id).exists()
            dict_render['core'] = \
             ClubSnap.club_position_by_uid(club.id, uid)[0] == 'core'
            return Snap.render('club_view.html', dict_render)
Ejemplo n.º 11
0
    def chat_wrap(qry, recv_id):
        '''
			为 PrivateMessage 写的 qry->list 函数
			其中 send_src 和 send_id 表明期望的 host_id
			返回 yield 体
		'''
        from quan_event.views import EventSnap
        from quan_avatar.views import AvatarSnap
        from quan_account.views import ClubSnap, AccountSnap, UserSnap
        from quan_ua.views import ChineseSnap
        message_list = []
        for i in qry:
            # user A = 自身
            # user B = 好友
            # club C = 一个社团
            # 可能出现的情况	host	avatar
            #	user
            #		A -> B	 B		A
            #		B -> A	 B		B
            #	club
            #		C -> A	 C		C
            #		A -> C	 C		A
            #		B -> C	 C		B
            host_src, host_id = PrivateMessageAction.get_host(i, recv_id)
            src = i.conn_relation
            if i.send_id == recv_id and i.send_relation == 'user':
                if src == 'share':
                    src = 'share-self'
                else:
                    src = 'self'
            elif src == 'none':
                src = 'other'
            if i.send_relation == 'user' and src == 'share':
                src = 'share-other'
            message_dict = {
                'content': i.content,
                'time_update': ChineseSnap.datetime_simp(i.time_create),
                'url': PrivateMessageAction.link_find(i),
                'avatar': AvatarSnap.avatar_all(i.send_relation, i.send_id),
                'type': src,
                'host_id': host_id,
                'host_src': host_src,
                'time_stamp': i.time_create.timestamp(),
            }
            aid = i.conn_id
            if src in ('share', 'share-self', 'share-other'):
                from quan_share.views import ShareSnap
                qry = ShareSnap.share_find_by_sid(aid)
                if qry:
                    from quan_share.views import ShareSnap
                    message_dict.update({
                     'data': {
                      'subject': qry.subject,
                      'uuid': qry.attach_uuid
                     },
                     'attach': ShareSnap.file_list_find_by_suid \
                            (qry.attach_uuid, True),
                    })
            elif src in ('event', 'event-signup'):
                from quan_event.views import EventSnap
                qry = EventSnap.event_find_by_evid(aid)
                if not qry:
                    continue
                club = ClubSnap.club_find_by_cid(qry.account_id)
                if not club:
                    continue
                message_dict.update({
                    'data': {
                        'subject': qry.subject,
                        'location': qry.location,
                        'content': qry.content,
                        'id': qry.id,
                    },
                    'avatar':
                    AvatarSnap.avatar_all(qry.relation, qry.account_id),
                    'club': {
                        'full_name': club.full_name
                    },
                    'date':
                    ChineseSnap.datetime_simp(qry.time_set),
                })
            elif src == 'badge':
                from quan_badge.views import BadgeSnap
                qry = BadgeSnap.badge_find_by_bid(aid)
                if not qry:
                    continue
                club = ClubSnap.club_find_by_cid(qry.account_id)
                if not club:
                    continue
                message_dict.update({
                    'name': qry.name,
                    'club': {
                        'simp_name': club.simp_name
                    },
                })
            elif src in ('friend', 'hi'):
                aid = i.send_id
                message_dict.update({
                    'avatar':
                    AvatarSnap.avatar_all('user', aid),
                    'nickname':
                    UserSnap.nickname_find_by_uid(aid),
                    'id':
                    aid,
                    'sname':
                    UserSnap.sname_find_by_uid(aid),
                    'disable':
                    '',
                })
                if AccountSnap.relation_check \
                 (recv_id, aid, ('uu-friend', 'uu-friend-wait')) :
                    message_dict['disable'] = 'disabled="disabled"'
            elif src == 'leave':
                message_dict.update({
                    'cname':
                    ClubSnap.fname_find_by_cid(i.conn_id),
                    'fname':
                    UserSnap.fname_find_by_uid(i.send_id),
                })
            else:  # other, self
                message_dict.update({
                 'avatar': AvatarSnap.avatar_all(i.send_relation, i.send_id),
                 'nickname': AccountSnap.nickname_find_by_aid \
                  (i.send_relation, i.send_id),
                })
                if i.send_id == recv_id and i.send_relation == 'user':
                    message_dict['type'] = 'self'
            yield message_dict
Ejemplo n.º 12
0
    def account_info_find(src, aid):
        '''
			得到用户/社团的信息字典(为了返回json消息)
		'''
        from quan_avatar.views import AvatarSnap
        from quan_account.views import UserSnap, ClubSnap, AccountSnap
        from quan_forum.views import ForumSnap
        default = {
            'link': '',
            'text': '',
            'image': '',
        }
        if src == 'club':
            return {
                'link': '/club/%s/' % ClubSnap.sname_find_by_cid(aid),
                'text': ClubSnap.fname_find_by_cid(aid),
                'image': AvatarSnap.avatar_find('club', aid, 'small'),
            }
        elif src == 'user':
            return {
                'link': '/user/%s/' % UserSnap.sname_find_by_uid(aid),
                'text': UserSnap.nickname_find_by_uid(aid),
                'image': AvatarSnap.avatar_find('user', aid, 'small'),
            }
        elif src == 'event':
            from quan_event.views import EventSnap
            event = EventSnap.event_find_by_evid(aid)
            if not event:
                return default
            cid = event.account_id
            return {
                'link': '/event/%d/' % aid,
                'text': event.subject,
                'image': AvatarSnap.avatar_find('club', cid, 'small'),
            }
        elif src == 'share':
            from quan_share.views import ShareSnap
            share = ShareSnap.share_find_by_sid(aid)
            if not share:
                return default
            suid = share.attach_uuid
            return {
             'link':  '/share/%s/' % suid,
             'text':  share.subject,
             'image': ShareSnap.thumbnail_find(suid, 'small') or \
                AvatarSnap.avatar_find \
                 (share.relation, share.account_id, 'small'),
            }
        elif src == 'badge':
            from quan_badge.views import BadgeSnap
            badge = BadgeSnap.badge_find_by_bid(aid)
            if not badge:
                return default
            sname = ClubSnap.sname_find_by_cid(badge.account_id)
            return {
                'link': '/club/%s/' % sname,
                'text': badge.name,
                'image': None,
            }
        elif src == 'news':
            from quan_news.views import NewsSnap
            news = NewsSnap.news_find(aid)
            if not news:
                return default
            return {
                'link': '/news/%d/' % aid,
                'text': news.subject,
                'image': None,
            }
        elif src == 'signature':
            user = UserSnap.user_find_by_uid(aid)
            if not user:
                return default
            return {
                'link': '/user/%s/' % user.last_name,
                'text': UserSnap.signature_find_by_uid(aid),
                'image': None,
            }
        elif src == 'nickname':
            user = UserSnap.user_find_by_uid(aid)
            if not user:
                return default
            return {
                'link': '/user/%s/' % user.last_name,
                'text': UserSnap.nickname_find_by_uid(aid),
                'image': None,
            }
        elif src == 'forum_thread':
            thread = ForumSnap.thread_find_by_thid(aid)
            sname = ForumSnap.sname_find_by_gid(thread.group_id)
            return {
                'link': '/forum/%s/%d/' % (sname, aid),
                'text': thread.subject,
                'image': None,
            }
        elif src == 'forum_response':
            thid = ForumSnap.thid_find_by_rid(aid)
            thread = ForumSnap.thread_find_by_thid(thid)
            sname = ForumSnap.sname_find_by_gid(thread.group_id)
            return {
             'link':  '/forum/%s/%d/?response=%d#response-%d' % \
                    (sname, thid, aid, aid),
             'text':  thread.subject,
             'image': None,
            }
        else:
            return default
Ejemplo n.º 13
0
    def empty_view(request, sname):
        dict_render = UserAgentSnap.record(request)
        cid = ClubSnap.cid_find_by_sname(sname)
        is_head = AccountSnap.aid_verify(request, 'club', cid)
        is_union = AccountSnap.aid_verify(
            request, 'club', ClubSnap.cid_find_by_sname('club-union'), True,
            True)
        category_list = AuthSnap.category_list \
         (UserSnap.uid_find_by_request(request))
        club = ClubSnap.club_find_by_cid(cid)
        if not is_head and not is_union and not category_list:
            raise Http403 \
             ('根据社联方面的要求,只有社长和社联成员才能查看此页面。请确认登录状态')
        if not club:
            raise Http404('数据错误,请联系HCC社团')
        is_category_admin = club.category in category_list
        performance_qry = AuthInfo.objects.filter(
            relation='performance',
            account_id=cid,
            time_update__gte=EventSnap.semester_start())
        # get performance
        if performance_qry:
            performance = performance_qry[0]
        else:
            performance = AuthInfo \
             (relation='performance', account_id=cid, data='preparing')
            performance.save()
        if not is_head and not is_union and performance.data == 'preparing':
            raise Http403('表格尚未公开')
        if request.method == 'GET':
            # 处理提交的表单
            dict_render['performance'] = performance
            dict_render['changeable'] = performance.data in \
             ('waiting', 'preparing')
            dict_render['event_location'] = request.GET.get(
                'event_location', '')
            dict_render['event_subject'] = request.GET.get('event_subject', '')
            dict_render['time_set'] = request.GET.get('time_set', '')
            dict_render['shareSubject'] = request.GET.get('shareSubject', '')
            impact_val = []
            for i in range(5):
                impact_val.append(request.GET.get('impact%d' % i, ''))
            if not any(impact_val):
                try:
                    impact_val = json.loads(performance.extra)
                except ValueError:
                    pass
            # begin rendering
            impact_form = [
                '社团活动反思总结', '与其他社团合作活动', '承办学校活动项目', '社团成果', '加分项申请'
            ]
            impact_placeholder = [
                '社团本学期的大致活动内容,例如日常开会、日常研讨等。'
                '若有固定时间也请进行补充说明',
                '合作活动的名称、时间以及合作社团的名称,外加合作社团社长的联系方式与姓名。'
                '需要上传可视化资料进行证明,例如照片视频等(在分享中上传)',
                '学校活动的名称、时间、50字简述。'
                '需要上传可视化资料进行证明,例如照片视频等(在分享中上传)',
                '本学期该社团具体都达成了什么成就,如果出杂志刊物的就列举出刊物和刊期',
                '根据评审方法上的加分项内容进行填写',
                '暂定是这些,谢谢',
            ]
            # 以上为 2015-2016 下学期的版本
            impact_form = [
                '举办过的社团内部活动', '参与或举办的校级活动', '举办的独立社团展示', '本学期社团活动总结与反思',
                '加分项申请'
            ]
            impact_placeholder = [
                '写明次数、时间地点、活动形式等',
                '活动名称和活动形式',
                '请参照核心评分标准填写',
                '字数大约为100字',
                '照片、视频、文档等证明资料为星级评价的重要标准,请在上方的分享栏中提交',
            ]
            dict_render['impact'] = []
            for i in range(5):
                dict_render['impact'].append(
                    (i, impact_form[i], impact_val[i], impact_placeholder[i]))
            semester_start = EventSnap.semester_start()
            dict_render['is_head'] = is_head
            dict_render['is_union'] = is_union
            dict_render['is_category_admin'] = is_category_admin
            head = ClubSnap.head_find_by_cid(cid)
            dict_render['head'] = head
            head_account = UserSnap.account_find_by_uid(head.id)
            dict_render['head_phone'] = head_account.phone
            dict_render['avatar'] = AvatarSnap.avatar_find('club', cid, 'raw')
            dict_render['head_grade'] = UserSnap.grade_translate \
                       (head_account.grade)
            dict_render['club'] = club
            # 评分表
            global_rubric = AuthSnap.get_rubric()
            category_rubric = AuthSnap.get_rubric(club.category)
            score = json.loads(performance.score or '[[], []]')
            dict_render['global_rubric'] = itertools.zip_longest \
                      (global_rubric, score[0])
            dict_render['category_rubric'] = itertools.zip_longest \
                      (category_rubric, score[1])
            dict_render['global_rubric_len'] = len(global_rubric)
            dict_render['category_rubric_len'] = len(category_rubric)
            if len(score[0]) == len(global_rubric):
                dict_render['global_score'] = ' - ' + str(sum(score[0]))
            if len(score[1]) == len(category_rubric):
                dict_render['category_score'] = ' - ' + str(sum(score[1]))
            #活动
            event_qry = EventSnap.event_semester_find_by_cid('club', cid).order_by \
             ('time_set')
            dict_render['event_list'] = []
            for i in event_qry:
                dict_render['event_list'].append({
                    'data':
                    i,
                    'join_num':
                    EventSnap.signup_total(i.id),
                    'datetime':
                    ChineseSnap.datetime_simp(i.time_set),
                })
            if not dict_render['event_location'] and event_qry:
                dict_render['event_location'] = event_qry.order_by \
                 ('-time_update')[0].location
            #分享
            sem_start = EventSnap.semester_start()
            share_qry = ShareSnap.share_find_by_aid('club', cid)
            share_qry = share_qry.filter(time_create__gte=sem_start, \
             category__in=('handout', 'knowledge', 'event', 'news', \
             'record-granted', 'record-denied', 'record-droped', \
             'record-broken', 'record-waiting'))
            dict_render['share_list'] = []
            for i in share_qry:
                dict_render['share_list'].append(ShareDicts.share_show \
                         (i.attach_uuid))
            #成员构成
            member_makeup = [0, 0, 0, 0, 0, 0, 0, 0]
            for i in ClubSnap.grade_list_by_cid(cid):
                member_makeup[i] += 1
            member_sum = sum(member_makeup)
            dict_render['member_makeup'] = []
            for i in range(7):
                name = UserSnap.grade_translate(i)
                style = ' progress-bar-'
                style += ('danger', 'warning', 'info', 'success', 'info',
                          'warning', 'danger', 'success')[i % 8]
                if i > 3:
                    style += ' progress-bar-striped'
                if member_makeup[i]:
                    dict_render['member_makeup'].append({
                        'id':
                        i,
                        'name':
                        name,
                        'value':
                        member_makeup[i],
                        'percent':
                        member_makeup[i] * 1000 // member_sum / 10,
                        'style':
                        style,
                    })
            #星级

            star_exchange = (0, 40, 50, 60, 70, 80)

            star = AuthSnap.star_calc(cid, event_qry, member_makeup, share_qry)
            if not event_qry or not share_qry:
                star = 0
            score = AuthSnap.star_calc \
             (cid, event_qry, member_makeup, share_qry, True)
            if performance.stars < star:
                dict_render['is_extended'] = 1
            elif performance.stars == star:
                dict_render['is_available'] = 1
            else:
                dict_render['is_failed'] = 1
                dict_render['requirement'] = \
                 (star_exchange[performance.stars] - score - 1) // 10 + 1
                dict_render['requirement_p1d2'] = \
                 (dict_render['requirement'] + 1) // 2
                if dict_render['requirement_p1d2'] <= 0:
                    dict_render['requirement_p1d2'] = 1
            dict_render['star_tend_list'] = [0] * performance.stars + [1] * \
             (5 - performance.stars)
            dict_render['star_list'] = [0] * star + [1] * (5 - star)
            dict_render['star_tend'] = performance.stars
            fname = dict_render['club'].full_name
            dict_render['title'] = t_(' - 申请星级 - %s') % fname
            return Snap.render('empty.html', dict_render)
        # 显示网页结束
        score = request.POST.get('score')
        if score:  # 进行评分
            if score == 'category':
                if not is_category_admin:
                    raise Http403('不是联盟长')
                index = 1
                rubric = AuthSnap.get_rubric(club.category)
            elif score == 'global':
                if not is_union:
                    raise Http403('不是社联成员')
                index = 0
                rubric = AuthSnap.get_rubric()
            else:
                raise Http404('参数错误')
            if not rubric:
                raise Snap.error('请先撰写评分表')
            score = json.loads(performance.score or '[[], []]')
            data = json.loads(request.POST.get('data', '[]'))
            if len(data) != len(rubric):
                raise Snap.error('数据错误: 长度不一致')
            number_data = []  # 将 data 中的数据类型转换为 int 或 float
            for i, j in zip(data, rubric):
                try:
                    number_data.append(j[1][j[1].index(float(i))])
                except ValueError:
                    raise Snap.error(t_('“%s”数据有误') % j[0])
            score[index] = number_data
            performance.score = json.dumps(score)
            performance.save()
            return Snap.success(request, '打分成功', {'reload': True})
        # 进行评分结束
        if not is_head:
            raise Snap.error('不是社长')
        elif request.POST.get('star', ''):  # 更改星级
            try:
                star = int(request.POST.get('star', ''))
            except ValueError:
                raise Snap.error('内容不合法')
            performance.stars = star
            performance.data = 'preparing'
            performance.save()
            return Snap.success(request, '成功更改星级')
        else:  # 提交数据
            impact = []
            for i in range(5):
                impact.append(request.POST.get('impact%d' % i, ''))
            if not all(impact):
                raise Snap.error('“影响力”没有填写全')
            star = AuthSnap.star_calc(cid)
            if performance.stars > star:
                raise Snap.error('星级太高')
            performance.extra = json.dumps(impact)
            performance.data = 'waiting'
            performance.save()
            PublicMessageAction.save(request, 'empty', 'new', cid, 'club',
                                     ClubSnap.cid_find_by_sname('club-union'),
                                     'club')
            return Snap.success(request, '成功提交', {'redirect': '/auth/apply/'})
Ejemplo n.º 14
0
    def thread_post(request, sname, tid=''):
        '''
			发表或编辑内容
			可能情况
				action	src			aid		reply
				new		group				-
				new		thread				group_sname
				new		response			(thread / response), aid
				edit	group		sname
				edit	thread		thid
				edit	response	rid
		'''
        from quan_news.views import NewsSnap
        dict_render = UserAgentSnap.record(request)
        # 处理参数
        action = request.POST.get('action') or request.GET.get('action')
        relation = request.POST.get('relation') or request.GET.get('relation')
        try:
            reply_aid = int(request.POST.get('reply_aid', '0'))
            aid = int(request.GET.get('aid') or request.POST.get('aid', '0'))
        except ValueError:
            raise Http404('参数错误')
        # 寻找数据
        if action == 'new':
            if relation == 'group':
                thid, gid = None, None  # 填表需要
                subject_required = True
                dict_render['page_title'] = '创建板块'
            elif relation == 'thread':
                group_qry = ForumSnap.group_find_by_sname(sname)
                if not group_qry:
                    raise Http404('找不到群组')
                thid, gid = None, group_qry.id
                subject_required = True
                dict_render['page_title'] = '发表帖子'
            elif relation == 'response':
                thid = reply_aid
                gid = ForumSnap.gid_find_by_thid(thid)
                if not gid or not thid:
                    raise Http404('参数错误')
                group_qry = ForumSnap.group_find_by_gid(gid)
                subject_required = False
                dict_render['page_title'] = '发表回复'
            else:
                raise Http404('参数错误')
            if not ForumSnap.creator_verify(relation, request, thid, gid):
                raise Snap.error('您没有权限')
            qry = None
        elif action == 'edit':
            if relation == 'group':
                qry = ForumSnap.group_find_by_sname(sname)
                subject_required = True
                aid = qry.id
                dict_render['page_title'] = '编辑板块信息'
                dict_render['data_account_sname'] = UserSnap.sname_find_by_uid \
                            (qry.account_id)
            elif relation == 'thread':
                raise Http404('功能已被禁用')
                qry = ForumSnap.thread_find_by_thid(aid)
                subject_required = True
                dict_render['page_title'] = '编辑帖子'
            elif relation == 'response':
                raise Http404('功能已被禁用')
                qry = ForumSnap.response_find_by_rid(aid)
                subject_required = False
                dict_render['page_title'] = '编辑回复'
            else:
                raise Http404('参数错误')
            if not qry:
                raise Http404('找不到对象')
            if not ForumSnap.edit_verify(relation, request, qry):
                if relation == 'group' and \
                 ForumSnap.forum_admin_verify(request) :
                    pass  # 允许特权用户
                else:
                    raise Snap.error('您没有权限')
        else:
            raise Http404('参数错误')
        # 如果不是提交,渲染模板
        if request.method != 'POST':
            dict_render['action'] = action
            dict_render['relation'] = relation
            dict_render['reply_aid'] = reply_aid
            dict_render['aid'] = aid
            dict_render['data'] = qry
            dict_render['subject_required'] = subject_required
            group_qry = ForumSnap.group_find_by_sname(sname)
            if action == 'new' and relation == 'group':
                dict_render['group_data'] = {
                    'subject': '创建',
                    'simp_name': '-',
                }
            elif not group_qry:
                raise Http404()
            else:
                dict_render['group_data'] = group_qry
            if action == 'new' and relation == 'thread':
                dict_render['title'] = ' - 发表帖子'
                dict_render['attach_allowed'] = True
            else:
                dict_render['title'] = ' - 创建板块'
            dict_render['thread_latest'] = ForumSnap.thread_latest_render()
            return Snap.render('forum_post.html', dict_render)
        # 标题和内容
        try:
            json_data = json.loads(request.POST.get('data', ''))
        except json.decoder.JSONDecodeError:
            raise Snap.error('数据已损坏')
        subject = json_data.get('subject', '')
        content = json_data.get('content', '')
        if (subject_required and not subject) or not content:
            raise Snap.error('标题或内容不全')
        if not NewsSnap.html_script_filter(content):
            raise Snap.error('内容中包含非法字符')
        # 创建 qry
        if action == 'new':
            if relation == 'group':
                qry = ForumGroup(relation='user',
                                 subject=subject,
                                 content=content)
            elif relation == 'thread':
                qry = ForumThread(send_id=request.user.id,
                                  send_relation='user',
                                  subject=subject,
                                  content=content,
                                  group_id=gid)
            else:  # relation == 'response'
                qry = ForumResponse(send_id=request.user.id,
                                    send_relation='user',
                                    reply_id=reply_aid,
                                    reply_relation='thread',
                                    content=content,
                                    thread_id=thid)
        else:  # action == 'edit'
            if relation == 'group':
                history = ForumHistory(relation='group',
                                       account_id=qry.id,
                                       subject=qry.subject,
                                       content=qry.content)
                qry.subject = subject
                qry.content = content
            elif relation == 'thread':
                history = ForumHistory(relation='thread',
                                       account_id=qry.id,
                                       subject=qry.subject,
                                       content=qry.content)
                qry.subject = subject
                qry.content = content
            else:  # relation == 'response'
                history = ForumHistory(relation='response',
                                       account_id=qry.id,
                                       content=qry.content)
                qry.content = content
        # 用户组控制的其他参数
        if relation == 'group':
            # Secret
            secret = json_data.get('secret')
            if secret not in ('0', '1'):
                raise Snap.error('请选择论坛是否私密')
            qry.secret = secret == '1'
            # Topic
            qry.topic = json_data.get('topic')
            if not qry.topic:
                raise Snap.error('请输入论坛所属群组')
            # Simp name
            simp_name = json_data.get('simp_name', '')
            if qry.simp_name != simp_name:
                ForumSnap.sname_validate(simp_name)
                qry.simp_name = simp_name
            # Account id
            uid = UserSnap.uid_find_by_sname(json_data.get('admin', ''))
            if not uid:
                raise Snap.error('请输入正确的用户链接')
            qry.account_id = uid
        # 附件
        attach_uuid = request.POST.get('attach_uuid')
        if attach_uuid:
            if action != 'new' or relation not in ('thread', 'response'):
                raise Snap.error('[附件] 不允许的操作')
            qry.attach_uuid = attach_uuid
            if not ShareSnap.attach_find_by_uuid(attach_uuid).exists():
                raise Snap.error('[附件] 无法找到这个AttachID')
            if ShareSnap.share_find_by_uuid(attach_uuid):
                raise Snap.error('附件已被分享')
            if subject:
                subj = subject + ' 的附件'
            else:
                subj = '论坛回复附件'
            share_qry = ShareInfo(subject=subj,
                                  account_id=request.user.id,
                                  relation='user',
                                  attach_uuid=attach_uuid)
        # 保存
        try:
            qry.save()
        except DataError:
            raise Snap.error('标题或内容过长')
        # 保存 history
        if action == 'edit':
            try:
                history.save()
            except DataError:
                logger.error('error in forum when saving history. ')
        # 保存 share
        if attach_uuid:
            try:
                share_qry.save()
                ShareSnap.archive_create(attach_uuid)
            except DataError:
                logger.error('error in forum when saving share_qry. ')
        # 维护数据库
        if action == 'new' and relation == 'response':
            thread = ForumSnap.thread_find_by_thid(thid)
            if thread:
                thread.response_number += 1
                thread.save()
        # 返回消息
        if relation == 'group':
            url = '/forum/%s/' % qry.simp_name
            if action == 'new':
                comment = '成功创建板块'
            else:
                comment = '成功编辑板块信息'
        elif relation == 'thread':
            url = '/forum/%s/%d/' % (sname, qry.id)
            if action == 'new':
                if not group_qry.secret:
                    PublicMessageAction.save(request, 'forum', 'thread',
                                             request.user.id, 'user', qry.id,
                                             'forum_thread')
                comment = '发帖成功'
            else:
                comment = '成功编辑帖子'
        else:  # relation == 'response'
            url = '/forum/%s/%d?response=%d#response-%d' % \
                 (sname, qry.thread_id, qry.id, qry.id)
            if action == 'new':
                if not group_qry.secret:
                    PublicMessageAction.save(request, 'forum', 'response',
                                             request.user.id, 'user', qry.id,
                                             'forum_response')
                comment = '回复成功'
            else:
                comment = '成功编辑回复'
        return Snap.success(request, comment, {'redirect': url})
Ejemplo n.º 15
0
	def single_event(request, evid) :
		event = EventSnap.event_find_by_evid(evid)
		if not event :
			return None
		evid = int(evid)
		event_dict = {'data':event,}
		date_string, time_end = ChineseSnap.datetime_comp(event.time_end)
		date_string, time_string = ChineseSnap.datetime_comp(event.time_set)
		event_dict['content'] = event.content.split('\n')
		event_dict['day_set'] = date_string
		event_dict['time_set'] = time_string
		event_dict['time_end'] = time_end
		event_dict['avatar'] = AvatarSnap.avatar_find(event.relation, event.account_id)
		event_dict['follower'] = EventSnap.follower_total(evid)
		event_dict['nice'] = EventSnap.nice_total(evid)
		event_dict['niced'] = EventSnap.niced_find_by_request(request, evid)
		event_dict['event_followed'] = EventSnap.followed_find_by_request(request, evid)
		if event.relation=='user':
			event_dict['sponsor_fname'] = '用户' + str(event.account_id)
		else:
			event_dict['sponsor_fname'] = ClubSnap.fname_find_by_cid \
															(event.account_id)
		event_dict['sponsor_sname'] = AccountSnap.sname_find_by_aid(event.relation, event.account_id)
		president = ClubSnap.cid_verify(request, event.account_id, True)
		event_dict.update(EventSnap.signed_get_by_event(event))
		event_dict['follower_list'] = EventSnap.follower_find_by_evid(event.id)
		event_dict['quest'] = EventSnap.quest_find_by_evid(event.id)
		time_status = EventSnap.time_status(event)

		# 计算需要显示的模块
		event_dict['president'] = president
		show = ()
		if president :
			if time_status == 0 and not event_dict['quest'] :
				show = ('signup_set', )
			elif time_status != -1 :
				show = ('join', 'signup_manual')
				if time_status == 0 :
					event_dict['signup_qrcode'] = \
									EventSnap.signup_qrcode_find_by_evid(evid)
		else :
			uid = UserSnap.uid_find_by_request(request)
			if time_status == 0 and event_dict['quest'] :
				if uid and not EventSnap.signed_find_by_uid(evid, uid) :
					show = ('signup', )
		for i in show :
			event_dict['show_%s' % i] = True
		
		# 为 share 和 event 关联渲染
		from quan_share.views import ShareSnap
		event_dict['share_list'] = [[]]
		event_dict['related_list'] = []
		related_list = []
		for i in ShareEventRelation.objects.filter(event_id=evid, status=0) :
			related_list.append(i.share_id)
		club_avatar = AvatarSnap.avatar_find \
			(event.relation, event.account_id, 'large')
		for i in ShareSnap.share_find_by_aid(event.relation, event.account_id) :
			thumbnail = ''
			if i.id in related_list :
				event_dict['relate_exist'] = True
				thumbnail = ShareSnap.thumbnail_find(i.attach_uuid, 'large')
			if not thumbnail :
				thumbnail = club_avatar
			append_object = {
				'data': i, 
				'related': i.id in related_list, 
				'date': ChineseSnap.datetime_simp(i.time_create), 
				'thumbnail': thumbnail, 
				'content': i.content.split('\n'), 
			}
			if len(event_dict['share_list'][-1]) < 10 :
				event_dict['share_list'][-1].append(append_object)
			else :
				event_dict['share_list'].append([append_object])
		return event_dict