Example #1
0
 def _delete_cloud_service_files(self):
     today = datetime.date.today()
     buf = cache.get('cloud-service-clean-date')
     if buf and parse_date(buf) == today:
         # 今天已经运行过一次,不用再运行了
         return
     value = models.Setting.getvalue('desktop-preview-days-to-keep')
     try:
         days = int(value)
     except:
         return
     username = models.Setting.getvalue('desktop-preview-username')
     password = models.Setting.getvalue('desktop-preview-password')
     if not username or not password:
         return
     bucket = cloud_service.generate_bucket_name()
     up = upyun.UpYun(bucket, username, password, endpoint=upyun.ED_AUTO)
     res = up.getlist('/')
     for i in res:
         if i['type'] != 'F':
             continue
         folder_date = parse_date(i['name'])
         if folder_date is None:
             continue
         if (today - folder_date).days > days:
             _delete_upyun_folder(up, '/' + i['name'] + '/')
     cache.set('cloud-service-clean-date', str(today),
               get_timeout('cloud-service-clean-date', None))
Example #2
0
def _get_teacher_uuids(node_uuid, node_type, classes):
    k = 'teacher-uuids-for-node-%s' % node_uuid
    v = cache.get(k)
    if v:
        return cPickle.loads(v)
    else:
        teachers = models.Teacher.objects.all()
        teachers = teachers.filter(lessonteacher__class_uuid__in=classes,
                                   deleted=False).distinct()
        uuids = teachers.values_list('uuid', flat=True)
        v = cPickle.dumps(uuids, cPickle.HIGHEST_PROTOCOL)
        cache.set(k, v, get_timeout(k, 60 * 60))  # 缓存一小时应该可以吧
        return uuids
Example #3
0
def details(request, *args, **kwargs):
    timelog = []
    timelog.append({'start': str(datetime.datetime.now())})
    curruser = model_to_dict(request.current_user)
    timelog.append({'1': str(datetime.datetime.now())})
    k = 'permitted-groups-%s' % curruser['uuid']
    v = cache.get(k)
    if v:
        curruser['permitted_groups'] = cPickle.loads(v)
    else:
        q = models.Group.objects.filter(
            userpermittedgroup__user=curruser['uuid'])
        curruser['permitted_groups'] = model_list_to_dict(q)
        v = cPickle.dumps(curruser['permitted_groups'],
                          cPickle.HIGHEST_PROTOCOL)
        cache.set(k, v, get_timeout(k, None))
    timelog.append({'3': str(datetime.datetime.now())})
    curruser['role_name'] = ''
    curruser['privileges'] = []
    curruser['superuser'] = False
    timelog.append({'4': str(datetime.datetime.now())})

    if is_admin(request.current_user):
        curruser['role_name'] = '超级管理员'
        curruser['superuser'] = True
        timelog.append({'5-11': str(datetime.datetime.now())})
        server_type = models.Setting.getvalue('server_type')
        timelog.append({'5-12': str(datetime.datetime.now())})

        if server_type not in settings_privileges.PRIVILEGES:
            privileges = copy.deepcopy(
                settings_privileges.PRIVILEGES['school'])
        else:
            privileges = copy.deepcopy(
                settings_privileges.PRIVILEGES[server_type])
        timelog.append({'5-13': str(datetime.datetime.now())})
        curruser['privileges'] = get_all_privilege_keys(privileges)
        timelog.append({'5-14': str(datetime.datetime.now())})
    else:
        if request.current_user.role:
            curruser['role_name'] = request.current_user.role.name
            timelog.append({'5-21': str(datetime.datetime.now())})
            rp = request.current_user.role.roleprivilege_set.all()
            timelog.append({'5-22': str(datetime.datetime.now())})
            curruser['privileges'] = [i.privilege for i in rp]
            timelog.append({'5-23': str(datetime.datetime.now())})

    timelog.append({'end': str(datetime.datetime.now())})
    return create_success_dict(data=curruser, timelog=timelog)
Example #4
0
def set_active_status(request):
    '''下级服务器发送班级在线状态'''
    key = request.POST.get('key')
    data = request.POST.get('data', '{}')
    if not key:
        return create_failure_dict(msg=u'获取密钥失败!')
    try:
        models.Node.objects.get(communicate_key=key)
    except models.Node.DoesNotExist:
        return create_failure_dict(msg='错误的key')
    except Exception as e:
        return create_failure_dict(msg='错误的key', debug=str(e))
    res = json.loads(data)
    for k in res.keys():
        cache.set(k, res[k], get_timeout(k, 90))
    return create_success_dict()
Example #5
0
def classes1(request, *args, **kwargs):
    computerclass_need = request.GET.get('computerclass_need', False)
    only_computerclass = request.GET.get('only_computerclass', False)
    school_year = request.GET.get('school_year', None)
    term_type = request.GET.get('term_type', None)
    start_date = request.GET.get('start_date', None)
    end_date = request.GET.get('end_date', None)
    no_cache = request.GET.get('no_cache', False)
    c = cache.get('classes')
    if c and not no_cache:
        data = json.loads(c)
    elif start_date and end_date:
        t = get_term_from_date_range(request)
        if isinstance(t, (models.Term, models.NewTerm)):
            terms = [
                t,
            ]
        else:
            terms = models.Term.objects.none()
    else:
        school_uuid = request.GET.get('school')
        if school_uuid:
            school = models.Group.objects.get(uuid=school_uuid,
                                              group_type='school')
        else:
            school = models.Group.objects.filter(group_type='school')
        if school_year and term_type and school:
            terms = models.Term.objects.filter(school_year=school_year,
                                               term_type=term_type,
                                               school=school)
        else:
            terms = models.Term.get_current_term_list(school)
        q = models.Class.objects.filter(grade__term__in=terms)
        if only_computerclass == 'true':  # 仅需要电脑教室的联动信息
            q = q.filter(grade__number=13)
        elif computerclass_need != 'true':  # 仅需要普通年级班级的联动信息
            q = q.exclude(grade__number=13)
        q = q.order_by().values('name', 'grade__name').distinct()
        data = model_list_to_dict(q)
        cache.set('classes', json.dumps(data), get_timeout('classes', None))

    return create_success_dict(data=data)
Example #6
0
def resource_global(request):
    '''
        资源使用综合分析
        1. 选择区县,乡镇街道,其结点单位为学校
        2. 选择学校,其结点为年级
        3. 选择年级,其结点为班级
        4. 右侧上左饼图为资源来源的百分比图,右侧上右饼图为资源类型的百分比图
        5. 右侧下方柱状图为TOP10的学校或是年级或是班级的上课次数
    '''
    # TODO 2015-03-23
    # 添加查询条件
    # 查询条件:学年:(当前学年(默认)、动态获取学校所有的学年信息),
    # 学期:(当前学期(默认)、动态获取学校所选学年的所有学期);
    # 各分类数值统计将按序排列;当统计类型超过10种时,第10种及以上合并为其他;

    # 其他需求(前端修改?)
    # 右侧使用饼状图显示当前学校所查询学期的相关数据:资源来源分类统计,
    # 各分类总数与百分比;资源类型分类统计,各分类总数与百分比;右侧使用柱状图
    # 显示当前学校所查询学期的相关数据:各班级资源使用次数前十名。

    node_uuid = request.GET.get('uuid', '')
    node_type = request.GET.get('type', 'school')
    school_year = request.GET.get('school_year', '')
    term_type = request.GET.get('term_type', '')

    if not school_year and not term_type:
        terms = Term.get_current_term_list()
        if terms:
            school_year = terms[0].school_year
            term_type = terms[0].term_type

    if not node_type:
        node_type = 'school'

    if not node_uuid:
        # 只有type没有uuid,是默认界面的url
        if Setting.getvalue('server_type') != node_type:
            return create_failure_dict(msg=u'错误的node_type %s' % node_type)
        try:
            obj = Group.objects.get(group_type=node_type)
        except:
            return create_failure_dict(msg=u'查找服务器节点时出错')
        node_uuid = obj.uuid
    else:
        # 既有type又有uuid,需要验证数据合法性
        if node_type in ('province', 'city', 'country', 'town', 'school'):
            try:
                obj = Group.objects.get(group_type=node_type, uuid=node_uuid)
            except:
                return create_failure_dict(msg=u'错误的node_type和uuid')
        elif node_type == 'grade':
            try:
                obj = Grade.objects.get(uuid=node_uuid)
            except:
                return create_failure_dict(msg=u'错误的年级uuid')
        else:
            return create_failure_dict(msg=u'错误的node_type')

    k = u'resource-analysis-for-node-%s-%s-%s' % (node_uuid, school_year, term_type)

    v = cache.get(k)
    if v:
        data = pickle.loads(v)
    else:
        data = _get_data(node_uuid, node_type, school_year, term_type)
        cache.set(k, pickle.dumps(data), get_timeout(k, 60 * 10))

    return create_success_dict(data=data)
Example #7
0
def status(request, *args, **kwargs):
    '''班级课程状态更新/获取'''
    now = datetime.datetime.now()
    mac = request.GET.get('mac', None)

    terms = models.Term.get_current_term_list()
    if not terms:
        return create_failure_dict(msg=u'无可用学年学期!', reported=False)

    if not terms[0].start_date <= now.date() <= terms[0].end_date:
        return create_failure_dict(msg=u'学期尚未开始', reported=False)

    try:
        c = models.Class.objects.get(classmacv2__mac=mac, grade__term=terms[0])
    except models.Class.DoesNotExist:
        return create_failure_dict(
            msg=u'教室尚未申报!',
            reported=False
        )
    except Exception as e:
        logger.exception('')
        return create_failure_dict(
            msg=u'教室尚未申报!',
            reported=False,
            debug=str(e)
        )

    # 1.缓存中标记班级客户端在线
    simplecache.set_class_active_time(c)

    # 2.判断是否异地登录
    # * 在另外一个班班通客户端登录上课(不会产生)
    # * 在电脑教室客户端登录上课
    started, log = c.get_status()
    if started:
        try:
            o = models.TeacherLoginLogTag.objects.get(bind_to=log)
            name = o.created_at.name  # class object(电脑教室)
            return create_failure_dict(msg=u'已在[%s]登录上课中.' % name)
        except models.TeacherLoginLogTag.DoesNotExist:
            pass
        except Exception as e:
            logger.exception('')
            return create_failure_dict(msg=u'未知错误.', debug=str(e))

    # 3.更新客户端使用时长
    # * 缓存中标记全局数据授课教师在线
    # * 缓存中标记登录状态的使用时长
    logintime_tmp_obj = update_time_used(c, now, log)
    if logintime_tmp_obj:
        simplecache.set_teacher_active_time(logintime_tmp_obj.teacherloginlog)
        key = 'class-%s-teacherlogintime' % c.uuid
        cache.set(key, logintime_tmp_obj.login_time, get_timeout(key, 90))

    # # 4.返回班级状态给客户端
    is_current, ls = simplecache.LessonSchedule.get_current(c)
    # V4.3.0
    # if not ls:
    #     return create_failure_dict(msg=u'本班级今天的课程已经上完')
    teacher_name = ''
    teacher_password = ''
    lesson_name = ''
    if ls:
        lesson_name = ls['lesson_name__name']
        q = models.LessonTeacher.objects.filter(
            class_uuid=c,
            lesson_name__name=ls['lesson_name__name']
        )
        if q.exists():
            teacher_name = q[0].teacher.name
            teacher_password = q[0].teacher.password

    lp = models.LessonPeriod.get_current_or_next_period()
    if not lp:
        return create_failure_dict(msg=u'今天的课程已经上完')
    is_current = bool(lp.start_time <= now.time() <= lp.end_time)
    key = is_current and 'current_lesson' or 'next_lesson'
    data = {key: {
        'grade_number': c.grade.name,
        'class_number': c.name,
        'start_datetime': lp.start_time,
        'end_datetime': lp.end_time,
        'lesson_name': lesson_name,  # 本节课程   科目:XXXX
        'teacher': teacher_name,
        'password': teacher_password,
    }}
    return create_success_dict(data=data, timestamp=now)
Example #8
0
def get_grade_class(request, *args, **kwargs):
    """
    电脑教室登录上课前需要先选定年级班级,然后才能获取对应的课程表
    课表获取原则是:
    选定年级班级->获取选中班级的课表->筛选出能在电脑教室里面上的教室-课程信息
    """
    mac = request.GET.get('mac')
    if not mac:
        return create_failure_dict(msg=u'MAC地址获取失败')

    terms = models.Term.get_current_term_list()
    if not terms:
        return create_failure_dict(msg=u'当前时间不在任何学期内')

    objs = models.ClassMacV2.objects.filter(mac=mac,
                                            class_uuid__grade__term__in=terms)
    if objs.count() != 1:
        return create_failure_dict(msg=u'客户端尚未申报或数据异常', debug=objs.count())

    o = objs[0].class_uuid

    # Define
    _get_class = lambda grd: grd.class_set.all()
    _get_lesson = lambda cls, range: cls.lessonteacher_set.filter(
        lesson_name__in=range).values('lesson_name', 'lesson_name__name'
                                      ).distinct()
    _get_default = lambda cls_pk: get_defaultlesson(cls_pk)

    cache_key = 'grade_class_lesson_teacher::%s' % o.pk
    cached_value = cache.get(cache_key)
    if cached_value:
        data = cPickle.loads(cached_value)
        for ginfo in data:
            for cinfo in ginfo['class']:
                cinfo['default'] = _get_default(cinfo['key'])
        return create_success_dict(data=data, debug='from cache')

    if o.grade.number == 13:
        grade = models.Grade.objects.filter(term__in=terms).exclude(number=13)
        grade = grade.order_by('number')
        lsn = o.computerclass.computerclasslessonrange_set
        lst = lsn.values_list('lessonname', flat=True)
        data = map(
            lambda g: {
                'key':
                g.pk,
                'text':
                u'%s年级' % g.name,
                'class':
                map(
                    lambda c: {
                        'default':
                        _get_default(c.pk),
                        'key':
                        c.pk,
                        'text':
                        c.name,
                        'lesson':
                        map(
                            lambda lt: {
                                'key':
                                lt['lesson_name'],
                                'text':
                                lt['lesson_name__name'],
                                'teacher':
                                map(
                                    lambda ltt: {
                                        'key': ltt['teacher'],
                                        'text': ltt['teacher__name']
                                    }, get_lessonteacher(c, lt['lesson_name']))
                            }, _get_lesson(c, lst))
                    }, _get_class(g))
            }, grade)

    else:
        data = [{
            'key':
            o.grade.pk,
            'text':
            u'%s年级' % o.grade.name,
            'class': [{
                'default':
                _get_default(o.pk),
                'key':
                o.pk,
                'text':
                o.name,
                'lesson':
                map(
                    lambda lt: {
                        'key':
                        lt['lesson_name'],
                        'text':
                        lt['lesson_name__name'],
                        'teacher':
                        map(
                            lambda ltt: {
                                'key': ltt['teacher'],
                                'text': ltt['teacher__name']
                            }, get_lessonteacher(o, lt['lesson_name']))
                    },
                    o.lessonteacher_set.values('lesson_name',
                                               'lesson_name__name').distinct())
            }]
        }]
    if not DEBUG:
        cache.set(cache_key, cPickle.dumps(data, cPickle.HIGHEST_PROTOCOL),
                  get_timeout(cache_key, 60 * 45))
    return create_success_dict(data=data)
Example #9
0
def get_lessonstatus(request, *args, **kwargs):
    """
    客户端获取当前电脑教室的授课状态
    """
    mac = request.GET.get('mac')
    if models.Setting.getvalue('server_type') != 'school':
        return create_failure_dict()
    if not mac:
        return create_failure_dict(msg='获取客户端Mac地址失败')
    now = datetime.datetime.now()
    term = models.Term.get_current_term_list()
    if not term:
        return create_failure_dict(msg='当前时间不在任何学期内', reported=False)
    t = term[0]
    if not t.start_date <= now.date() <= t.end_date:
        return create_failure_dict(msg='学期尚未开始', reported=False)
    try:
        klass = models.Class.objects.get(classmacv2__mac=mac, grade__term=t)
        cc = models.ComputerClass.objects.get(class_bind_to=klass)
    except:
        return create_failure_dict(msg='当前电脑教室尚未申报', reported=False)

    # 1.标记电脑教室在线
    simplecache.set_class_active_time(klass)
    lp = models.LessonPeriod.get_current_or_next_period()
    if not lp:
        return create_failure_dict(msg='今天的课程已经上完')

    # 2.判断当前电脑教室状态
    # * 已经登录授课,则标记上课班级在线、标记教师在线、更新使用时长
    # * 未登录授课,则返回下一节课的时间(可多选,故不返回课程信息)
    started, log = cc.get_status()
    if started:
        c = log.class_uuid
        simplecache.set_class_active_time(c, True)  # in_computerclass=True
        tmp = update_time_used(c, now)
        if tmp:
            simplecache.set_teacher_active_time(tmp.teacherloginlog, klass)
            key = 'class-%s-teacherlogintime' % c.uuid
            cache.set(key, tmp.login_time, get_timeout(key, 90))

            data = {
                'status': True,
                'current_lesson': {
                    'lesson_name': log.lesson_name,
                    'start_datetime': log.lesson_period_start_time,
                    'end_datetime': log.lesson_period_end_time,
                    'grade_number': log.grade.number,
                    'class_number': log.class_uuid.number
                }
            }
            # 若教师在线时长更新失败,说明当前节次的课程已经结束
            return create_success_dict(data=data, timestamp=now)

    if lp.start_time < now.time() < lp.end_time:
        key = 'current_lesson'
    else:
        key = 'next_lesson'
    data = {
        'status': False,
        key: {
            'lesson_name': '',
            'start_datetime': lp.start_time,
            'end_datetime': lp.end_time,
            'class_number': '%s' % cc
        }
    }

    return create_success_dict(data=data, timestamp=now)
Example #10
0
def get_current_or_nextlesson(request, *args, **kwargs):
    """客户端获取电脑教室当前或下一节课的课程信息"""
    mac = request.GET.get('mac')
    # flag = request.GET.get('in_computerclass')
    if models.Setting.getvalue('server_type') != 'school':
        return create_failure_dict(msg='客户端应当连接校级服务器')
    if not mac:
        return create_failure_dict(msg='获取电脑教室Mac失败')
    lp = models.LessonPeriod.get_current_or_next_period()
    if not lp:
        return create_failure_dict(msg='今天的课程已经上完')

    t = models.Term.get_current_term_list()[0]
    u = models.Class.objects.get(classmacv2__mac=mac, grade__term=t).uuid
    cc = models.ComputerClass.objects.get(class_bind_to=u)
    ls = cc.get_curriculum()
    if not ls.exists():
        return create_failure_dict(msg='本教室授课范围内无可使用班级')

    rf = cache.get('resource_from_for_%s' % mac)
    rt = cache.get('resource_types_for_%s' % mac)
    if not rf:
        rf = models.ResourceFrom.objects.values_list('value', flat=True)
        rf = [{'key': i, 'text': i} for i in rf]
        key = 'resource_from_for_%s' % mac
        cache.set(key, rf, get_timeout(key, 60 * 45))
    if not rt:
        rt = models.ResourceType.objects.values_list('value', flat=True)
        rt = [{'key': i, 'text': i} for i in rt]
        key = 'resource_types_for_%s' % mac
        cache.set(key, rt, get_timeout(key, None))

    lr = cc.lesson_range.all().values_list('uuid', flat=True)
    cuus = list(set(ls.values_list('class_uuid', flat=True)))
    lt = models.LessonTeacher.objects.filter(lesson_name__in=lr,
                                             class_uuid__in=cuus)

    all_teachers = lt.values_list('teacher__uuid',
                                  'teacher__name',
                                  'lesson_name',
                                  'lesson_name__name',
                                  flat=False)

    now = datetime.datetime.now()
    wk = now.strftime('%a').lower()
    ls_name = ls.filter(lesson_period=lp.uuid, weekday=wk)
    ls_name = list(set(ls_name.values_list('lesson_name', flat=True)))
    current_teachers = lt.filter(lesson_name__in=ls_name)
    current_teachers = current_teachers.values_list('teacher__uuid',
                                                    'teacher__name',
                                                    'lesson_name',
                                                    'lesson_name__name',
                                                    flat=False)

    data = {'status': False}  # , 'lesson': [], 'teacher': []}
    data['resource_from'] = rf
    data['resource_types'] = rt
    data['all_teachers'] = _praser(all_teachers)
    data['lesson'] = _praser(current_teachers)

    started, log = cc.get_status()
    if started:
        data['status'] = True
        lesson = models.LessonName.objects.get(name=log.lesson_name)
        data['info'] = {
            'teacher_key': log.teacher.uuid,
            'password': log.teacher.password,
            'lesson_key': lesson.uuid,
            'resource_from': log.resource_from,
            'resource_types': log.resource_type,
            'server_time': now,
            'time': log.lesson_period_end_time,
            'class_uuid': log.class_uuid.uuid,
            'class_mac': log.class_uuid.mac()
        }
    return create_success_dict(data=data)