Beispiel #1
0
 def join_ratio(cid):
     event_list = EventSnap.event_month_find_by_cid('club', cid)
     active_rate = 0
     for event in event_list:
         active_rate += EventSnap.signup_total(event.id)
     if event_list.count():
         return active_rate / event_list.count()
     else:
         return 0
Beispiel #2
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
Beispiel #3
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
Beispiel #4
0
 def ratio_join(uid, cid):
     '获得用户在社团中一个月的参与率(0~1)'
     join, total = EventSnap.event_attendence_by_uid(uid, cid, True)
     try:
         return join / total
     except ZeroDivisionError:
         return 0
Beispiel #5
0
    def qrank_calc(cid):
        '计算社团星级(0.0-5.0)'
        '''
			分值			0	1	2	3	4	5
						========================
			每月活动次数	0	1	2	4	6	8
			活跃成员比例	15%	30%	45%	60%	75%	90%
			月底提交记录	False				True
			成员总数		0	4	8	12	16	20

			附加分*0.4:
			关注人数		0	8	16	24	32	36

			计算方法:
				记总和,除以总数4,向上取整。
				>5 => 5
		'''
        month_event = EventSnap.event_month_find_by_cid('club', cid).count()
        member_sum = ClubSnap.member_total(cid)
        active_ratio = AuthSnap.active_ratio(cid)
        submit_record = 1  # 暂时不考虑
        follower_total = ClubSnap.follower_total(cid)
        # 计算
        sum_score = 0.0
        sum_score += (0, 1, 2, 2.5, 3, 3.5, 4, 4.5, 5)[min(month_event, 8)]
        # 每月活动数量
        sum_score += min(max(active_ratio / 0.15 - 1, 0), 5)  # 活跃成员
        sum_score += 5 * int(submit_record)  # 是否提交
        sum_score += min(member_sum / 4, 5)  # 成员总数
        addition_score = min(follower_total / 8, 5)  # 附加分 关注人数
        # 求和
        sum_score /= 4
        sum_score += 0.4 * addition_score
        return min(sum_score, 5)
Beispiel #6
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
Beispiel #7
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),
                }
Beispiel #8
0
 def home_dict_get(request, special_passment=False):
     '得到“我参加的”、“最新”、“最火”,返回一个dict_render体'
     dict_render = {}
     if request.path in ['/square/', '/square/hotest/'] or special_passment:
         #最新,最火
         sliced_qry = AuthDicts.page_dict(request, EventInfo.objects.filter \
          (category__in=('history', '')).order_by("-time_set"), 10,
          dict_render)
         event_list = []
         for i in sliced_qry:
             event_list.append(
                 SquareDicts.square_event(i, 'latest', request))
         if request.path == '/square/hotest/' and not special_passment:
             a = event_list.sort(
                 key=lambda dictionary: -dictionary['follower'])
         dict_render['event_list'] = event_list
         return dict_render
     else:  #我参加的
         event_set = EventSnap.event_filter_by_request(request)
         sliced = AuthDicts.page_dict(request, event_set, 10, dict_render)
         dict_render['event_list'] = []
         for i in sliced:
             dict_render['event_list'].append \
              (SquareDicts.square_event(i, 'relative', request))
         return dict_render
Beispiel #9
0
 def get_rubric(category='global'):
     '得到某个联盟或总体 (global) 的 rubric ,失败返回 []'
     qry = AuthInfo.objects.filter(
         relation='performance-rubric',
         data=category,
         time_update__gte=EventSnap.semester_start())
     if qry:
         return json.loads(qry[0].extra)
     else:
         return []
Beispiel #10
0
 def square_event(data, belong, request):
     '复制每块的字典'
     item = {'data': data}
     # 渲染的模块名
     item['belong'] = belong
     # 开始时间
     time_set = data.time_set
     item['day_set'], item['time_set'] = ChineseSnap.datetime_comp(time_set)
     # 头相、赞、关注、发起者
     cid = data.account_id
     item['follower'] = EventSnap.follower_total(data.id)
     item['nice'] = EventSnap.nice_total(data.id)
     item['avatar'] = AvatarSnap.avatar_find(data.relation, cid, 'medium')
     item['sponsor'] = ClubSnap.sname_find_by_cid(cid)
     item['sponsor_fname'] = ClubSnap.fname_find_by_cid(cid)
     # 持续时间
     item['time_last'] = ChineseSnap.timedelta_comp(data.time_end -
                                                    time_set)
     # 是否已经关注/赞
     item['niced'] = EventSnap.niced_find_by_request(request, data.id)
     item['followed'] = EventSnap.followed_find_by_request(request, data.id)
     return item
Beispiel #11
0
 def detail(src, qry, category):
     'category in (sent, inbox, follow, event, share)'
     detail_list = []
     if category == 'share':
         for i in qry:
             date_time = ChineseSnap.datetime_simp(i.time_create)
             detail_list.append({
                 'link': '/share/%s/' % i.attach_uuid,
                 'date': date_time[0],
                 'data': i,
                 'time': date_time[1],
             })
     elif category == 'event':
         for i in qry:
             date_time = ChineseSnap.datetime_simp(i.time_set)
             detail_list.append({
                 'link': '/event/%s/' % i.id,
                 'date': date_time[0],
                 'data': i,
                 'time': date_time[1],
             })
     else:
         # There is an error, l gave up fixing it in 201510172138
         for i in qry:
             #				link = MessageSnap.link_find(i, category)
             #				if category == 'sent' :
             #					con = 0 #continue
             #					for j in detail_list :
             #						if j['link'] == link :
             #							con = 1
             #							break
             #					if con :
             #						continue
             link = '#'  # link 的生成函数已经实效
             date_time = ChineseSnap.datetime_simp(i.time_create)
             if category == 'event':
                 event = EventSnap.event_find_by_evid(i.id)
                 if event != None:
                     date_time = ChineseSnap.datetime_simp(event.time_set)
             detail_list.append({
                 'link': link,
                 'date': date_time[0],
                 'data': i,
                 'time': date_time[1],
             })
     return detail_list
Beispiel #12
0
    def mrank_calc(uid, cid):
        '计算社员等级(1.0-5.0)'
        '''
			分值								0	1	2	3	4	5
											========================
			参与率		ratio_join			15%	30%	45%	60%	75%	90%
			加入时间		month_join			0mo	1mo	2mo	3mo	4mo	6mo	
			参与小时数	attendence_hour		2	4	6	8	10	12
		'''
        #得到数据
        ratio_join = AuthSnap.ratio_join(uid, cid)
        month_join = ClubSnap.attendence_total(uid, cid)
        attendence = EventSnap.event_attendence_by_uid(uid, cid, True)[0]
        #计算
        return (min(ratio_join / 0.15, 5) +
                [0, 1, 2, 3, 4, 4.5, 5][min(int(month_join.days / 30), 6)] +
                min(max(attendence / timedelta(0, 3600) - 1, 0), 5)) / 3
Beispiel #13
0
 def member_manage(src, aid, render_list=('follower', 'member', 'wait')):
     '按照render_list中的要求选择性渲染'
     if src == 'user':
         return {}
     dict_render = {'member_wait': [], 'member': []}
     if 'wait' in render_list:  # 待审核社员
         mem_wait = ClubSnap.member_wait_find(aid)
         dict_render['member_wait_num'] = len(mem_wait)
         for i in mem_wait:
             time_create_tumple = ChineseSnap.datetime_simp(i.time_create)
             user = {
                 'name': UserSnap.fname_find_by_uid(i.account_id_A),
                 'grade': UserSnap.grade_find_by_uid(i.account_id_A, True),
                 'date': time_create_tumple[0],
                 'id': i.account_id_A,
             }
             dict_render['member_wait'].append(user)
     if 'member' in render_list:  # 通过社员
         for uid in ClubSnap.member_all(aid):
             join, total = EventSnap.event_attendence_by_uid(uid, aid)
             user = {
              'uid': uid,
              'name': UserSnap.fname_find_by_uid(uid),
              'grade': UserSnap.grade_find_by_uid(uid, True),
              'ratio': '%.1f' % \
                (100.0 * (total / timedelta(1) and join / total)),
              'score': '%.1f' % (0.2 * join / timedelta(0, 3600)),
              'identity': ClubSnap.club_position_by_uid(aid, uid),
              'avatar': AvatarSnap.avatar_find('user', uid, 'medium'),
             }
             dict_render['member'].append(user)
     if 'follower' in render_list:  # 跟随者
         qry = ClubSnap.follower_find(aid)
         follower_list = []
         for i in qry:
             follower_list.append({
                 'data':
                 UserSnap.user_find_by_uid(i.account_id_A),
                 'avatar':
                 AvatarSnap.avatar_find('user',
                                        i.account_id_A,
                                        size="medium"),
             })
         dict_render['follower_list'] = follower_list
     return dict_render
Beispiel #14
0
 def auth_apply(is_auth):
     'is_auth -> no preparing'
     dict_render = {'record_list': []}
     qry = AuthInfo.objects.filter(
         relation="performance",
         time_update__gte=EventSnap.semester_start()).order_by(
             '-time_update')
     label_dict = {
         'preparing': '填写中',
         'waiting': '等待中',
         'granted': '审核通过',
         'denied': '审核不通过',
         'droped': '材料不足',
         'broken': '附件损坏',
     }
     label_type_dict = {
         'preparing': 'default',
         'waiting': 'info',
         'granted': 'success',
         'denied': 'danger',
         'droped': 'warning',
         'broken': 'warning',
     }
     category_list = ClubSnap.category_list()
     dict_render['category_dict'] = category_list
     category_dict = dict(category_list)
     for i in qry:
         if i.data == 'preparing' and is_auth:
             continue
         club = ClubSnap.club_find_by_cid(i.account_id)
         if not club:
             continue  # 数据错误
         date, time = ChineseSnap.datetime_simp(i.time_update)
         data = {
             'data': i,
             'club': club,
             'date': date + time,
             'zhcn_label': label_dict[i.data],
             'zhcn_category': category_dict[club.category],
             'label_type': label_type_dict[i.data],
             'amercement': AuthSnap.amercement_num(i.account_id),
         }
         dict_render['record_list'].append(data)
     return dict_render
Beispiel #15
0
 def auth_apply(request):
     dict_render = UserAgentSnap.record(request)
     is_auth = ClubSnap.club_union_check(request)
     if request.method == 'GET':
         dict_render.update(AuthDicts.auth_apply(is_auth))
         dict_render['is_auth'] = is_auth
         uid = UserSnap.uid_find_by_request(request)
         category_list = AuthSnap.category_list(uid)
         category_dict = dict(ClubSnap.category_list())
         dict_render['category_manage'] = \
           list(map(lambda x: (x, category_dict[x]), category_list))
         if is_auth:
             dict_render['category_manage'].insert(0, ('global', t_('综合')))
         dict_render['title'] = ' - 星级评价'
         return Snap.render('auth_apply.html', dict_render)
     else:
         if not is_auth:
             raise Http403("如果为社联成员,请检查登录情况。")
         try:
             pid = int(request.POST.get('pid', ''))  # performance id
         except Exception:
             raise Snap.error('表单信息有误')
         result = request.POST.get('result', '')
         qry = AuthInfo.objects.filter(id=pid, relation='performance')
         if qry.count() != 1 or not result in \
          ('granted', 'denied', 'droped', 'broken') :
             raise Snap.error('表单信息有误')
         if qry[0].time_update < EventSnap.semester_start():
             raise Snap.error('表单信息有误')
     #	if qry[0].category != 'record-waiting' :
     #		raise Snap.error('请求早已处理')
         qry.update(data=result)
         #fname = ClubSnap.fname_find_by_cid(qry[0].account_id)
         #hid = ClubSnap.head_id_find_by_cid(qry[0].account_id)
         #unid = ClubSnap.cid_find_by_sname('club-union')
         if result == 'granted':
             PublicMessageAction.save \
              (request, 'empty', 'granted', qry[0].account_id, 'club',
              ClubSnap.cid_find_by_sname('club-union'), 'club')
         else:
             PublicMessageAction.save \
              (request, 'empty', 'fine', qry[0].account_id, 'club',
              ClubSnap.cid_find_by_sname('club-union'), 'club')
         return Snap.success(request, '成功执行请求。')
Beispiel #16
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)
Beispiel #17
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
Beispiel #18
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
Beispiel #19
0
 def auth_apply_rubric(request, category):
     dict_render = UserAgentSnap.record(request)
     # 检测权限
     uid = UserSnap.uid_find_by_request(request)
     if category == 'global':
         if not ClubSnap.club_union_check(request):
             raise Http403('您没有社联管理权限')
     else:
         if category not in AuthSnap.category_list(uid):
             raise Http403('您没有联盟管理权限')
     # 查询是否已存在
     qry = AuthInfo.objects.filter(
         relation='performance-rubric',
         data=category,
         time_update__gte=EventSnap.semester_start())
     if qry:
         qry = qry[0]
     if request.method == "GET":
         dict_render['category'] = category
         if qry:
             data = json.loads(qry.extra)
             dict_render['form_data'] = '\n'.join(
                 map(lambda x: '\t'.join([x[0]] + list(map(str, x[1]))),
                     data))
             dict_render['best_score'] = sum(map(lambda x: x[1][-1], data))
         dict_render['title'] = ' - 编辑星级评分表'
         return Snap.render('auth_apply_rubric.html', dict_render)
     data = request.POST.get('data')
     if not data:
         raise Snap.error('表单内容不全')
     a = map(lambda x: x.split(), filter(bool, data.split('\n')))
     answer = []
     for index, i in enumerate(a):
         row = []
         for jndex, j in enumerate(i[1:]):
             try:
                 row.append(int(j))
             except ValueError:
                 try:
                     float_j = float(j)
                     if float_j * 2 % 1:
                         raise Snap.error(
                             t_('第%d行%d列:只能精确到0.5') %
                             (index + 1, jndex + 2))
                     int_j = int(float_j)
                     if int_j == float_j:
                         row.append(int_j)
                     else:
                         row.append(float_j)
                 except ValueError:
                     raise Snap.error(
                         t_('第%d行%d列数据有误') % (index + 1, jndex + 2))
         if not row:
             raise Snap.error(t_('第%d行没有数据') % (index + 1))
         if len(row) != len(set(map(float, row))):
             raise Snap.error(t_('第%d行有重复数据') % (index + 1))
         answer.append((i[0], sorted(row)))
     if qry:
         qry.extra = json.dumps(answer)
         qry.account_id = uid
         qry.save()
         return Snap.success(
             request, '更改成功',
             {'redirect': '/auth/apply/rubric/%s/' % category})
     else:
         AuthInfo(extra=json.dumps(answer),
                  relation='performance-rubric',
                  data=category,
                  account_id=uid).save()
         return Snap.success(
             request, '保存成功',
             {'redirect': '/auth/apply/rubric/%s/' % category})
Beispiel #20
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/'})