Пример #1
0
    async def save_inspiration(self, ctx, name, url):
        '''Stores an inspiration for later retrieval.
        '''
        server = ctx.guild.name
        author = ctx.message.author.name
        member_id = ctx.message.author.id

        session = self.interface.database.Session()

        try:
            member = self.interface.find_member(session, member_id)
        except Exception as e:
            # Create member if they do not exist in our database
            member = Member(id=member_id, name=author, server=server)
            self.interface.database.add_object(session, member)

        try:
            inspo = Inspiration(name=name,
                                server=server,
                                url=url,
                                member_id=member_id)
            self.interface.database.add_object(session, inspo)
            session.commit()
            await ctx.send(f'Image saved as {name}')
        except Exception as e:
            await ctx.send('Could not complete your command')
            print(e)
        finally:
            session.close()
Пример #2
0
    async def attend(self, ctx, name: str):
        '''Allows a user to attend an upcoming event
            example: ?attend party
        '''
        author = ctx.message.author.name
        avatar = ctx.message.author.avatar_url
        id = ctx.message.author.id

        try:
            count = self.session.query(Member).filter(Member.id == id).count()
            event = self.session.query(Event).filter(Event.name == name).first()

            # Verify This event exists
            if not event:
                await self.bot.say('This event does not exist')
                return

            # Create member if they do not exist in our database
            if count < 1:
                member = Member(id=id, name=author, avatar=avatar, level = 1, experience = 0)
                self.session.add(member)

            attending = Attendance(member_id=id, event_id=event.id)
            self.session.add(attending)
            self.session.commit()
            await self.bot.say('Member {} is now attending event {}'.format(author, name))
        except Exception as e:
            await self.bot.say('Could not complete your command')
            self.logger.error(e)
Пример #3
0
def inscription(request):
    if request.method == 'POST':
        try:
            member = Member.objects.get(email=request.POST['email'])
        except:
            member = Member()
        member_form = MemberForm(request.POST, instance=member)
        inscription_form = InscriptionForm(request.POST)
        if any(insc.is_current()
               for insc in Inscription.objects.filter(member=member)):
            info(request, 'Already inscripted on the current session!')
        elif member_form.is_valid() and inscription_form.is_valid():
            member = member_form.save()
            inscription = inscription_form.save(commit=False)
            inscription.member = member
            inscription.session = Inscription.current_session()
            inscription.save()
            success(request, 'Inscription created!')
        else:
            error(request, 'Error when creating inscription!')
    else:
        member_form = MemberForm()
        inscription_form = InscriptionForm()

    return render(request, 'inscription/index.html', {
        'member_form': member_form,
        'inscription_form': inscription_form,
    })
Пример #4
0
def quiz(request,
         quiz_pk=None,
         quiz_title=None,
         member_pk=None,
         member_email=None):
    if quiz_pk:
        quiz = get_object_or_404(Quiz, pk=quiz_pk)
    else:
        quiz = get_object_or_404(Quiz, title=quiz_title)
    if (quiz.start and quiz.start > timezone.now()) or (
            quiz.end and quiz.end < timezone.now()):
        error(request, 'Oops! Quiz is closed.')
        return render(request, "quiz/inactive.html", {"quiz": quiz})

    if member_pk:
        member = get_object_or_404(Member, pk=member_pk)
    elif member_email:
        member = get_object_or_404(Member, email=member_email)
    elif request.method == 'POST':
        try:
            member = Member.objects.get(email=request.POST['email'])
        except:
            return HttpResponseForbidden()
    else:
        member = Member()

    score = 0
    try:
        instance = Submission.objects.get(quiz=quiz, member=member)
        if request.method == "GET":
            score = instance.score()
        submission_is_new = False
    except:
        instance = Submission(quiz=quiz, member=member)
        submission_is_new = True

    if request.method == 'POST':
        candidat_form = CandidatForm(request.POST, instance=member)
        form = QuizForm(request.POST,
                        instance=instance,
                        is_new=submission_is_new)
        if candidat_form.is_valid() and form.is_valid():
            candidat_form.save()
            instance.save()
            form.save()
            score = instance.score()
    else:
        candidat_form = CandidatForm(instance=member)
        form = QuizForm(instance=instance, is_new=submission_is_new)

    return render(request, 'quiz/quiz.html', {
        'candidat_form': candidat_form,
        'form': form,
        'score': score,
    })
Пример #5
0
async def find_member_by_open_id(open_id):
    try:
        member = RedisCache.get(open_id)
        if member:
            member = Member().result_2_obj(
                from_msgpack(msgpack.unpackb(member, raw=False)))
            return member
    except Exception:
        pass
    member = await Member.find_one(dict(open_id=open_id,
                                        status=STATUS_USER_ACTIVE),
                                   read_preference=ReadPreference.PRIMARY)
    if member:
        RedisCache.set(open_id, msgpack.packb(to_msgpack(member)),
                       60 * 60 * 24)
        RedisCache.set('mid_%s' % str(member.oid), open_id, 60 * 60 * 24)
        return member
Пример #6
0
def init_members(member_dict):
    """
    初始化会员信息
    :return:
    """
    logger.info("init member")
    logger.info(member_dict)
    member = Member()
    member.address = member_dict._userOwner
    member.id_number = member_dict._ID_Number.decode().strip(b'\x00'.decode())
    member.id_url = member_dict._ID_url
    member.username = member_dict._username
    member.phone = member_dict._phone
    member.driver_license = member_dict._driver_license
    member.driver_license_url = member_dict._driver_license_url
    member.status = 1
    member.sync_save()
    logger.info(member)
Пример #7
0
def register(request, event_id):
    event = get_object_or_404(Event, pk=event_id)
    if event.end and event.end < timezone.now():
        return render(request, 'event/ended.html', {'event': event})
    if request.method == 'POST':
        try:
            member = Member.objects.get(email=request.POST['email'])
        except:
            member = Member()
        member_form = MemberForm(request.POST, instance=member)
        inscription_form = InscriptionForm(request.POST)
        insc = [insc for insc in Inscription.objects.filter(member=member)
                if insc.is_current()]
        insc = insc[0] if len(insc) == 1 else None
        if not insc and member_form.is_valid() and inscription_form.is_valid():
            member = member_form.save()
            insc = inscription_form.save(commit=False)
            insc.member = member
            insc.session = Inscription.current_session()
            insc.save()
        if insc:
            try:
                Register.objects.create(member=member, event=event)
                success(request, 'You have successfully registered')
            except:
                info(request, 'You has already registred!')
        else:
            error(request, 'Error when registering!')
    else:
        member_form = MemberForm()
        inscription_form = InscriptionForm()

    return render(request, 'event/register.html', {
        'member_form': member_form,
        'inscription_form': inscription_form,
        'forms': [member_form, inscription_form],
        'event': event,
    })
Пример #8
0
    async def post(self):
        res = dict(code=0)

        name = self.get_argument('name')
        sex = int(self.get_argument('sex', 1))
        email = self.get_argument('email')
        mobile = self.get_argument('mobile')
        birthday = self.get_argument('birthday')
        province_code = self.get_argument('province_code')  # 省份编码
        city_code = self.get_argument('city_code')  # 城市编码
        vehicle_code = self.get_argument('vehicle_code')  # 车型编号
        purchase_datetime = self.get_argument('purchase_datetime')  # 车辆购买时间
        content = self.get_argument('content')  # 备注
        status = int(self.get_argument('status', STATUS_USER_ACTIVE))

        if name and mobile and email:
            # 校验用户名
            if mobile:
                exist_count = await Member.count(dict(mobile=mobile))
                if exist_count:
                    res['code'] = -2
                    return res
            if email:
                email_valid = re.match(
                    r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", email)
                exist_count = await Member.count(dict(email=email))
                if exist_count:
                    res['code'] = -3
                    return res
                if not email_valid:
                    res['code'] = -4
                    return res
            if mobile:
                member = Member()
                member.mobile = mobile
                member.code = get_increase_code(KEY_INCREASE_MEMBER_CODE)
                if email:
                    member.email = email
            else:
                member = Member()
                member.email = email
                member.code = get_increase_code(KEY_INCREASE_MEMBER_CODE)

            if name:
                member.name = name
            member.sex = sex
            if birthday:
                member.birthday = str2datetime(birthday, '%Y-%m-%d')

            if vehicle_code:
                vehicle = await Vehicle.find_one(
                    dict(code=vehicle_code, record_flag=1))
                if vehicle:
                    member.needless['vehicle_title'] = vehicle.title
                    member.needless['vehicle_brand'] = vehicle.needless.get(
                        'brand')
                    member.needless['vehicle_category'] = vehicle.needless.get(
                        'category')
                    member.needless['vehicle_series'] = vehicle.needless.get(
                        'series')
                    member.needless['vehicle_config'] = vehicle.needless.get(
                        'config')
                    member.needless['vehicle_colour'] = vehicle.needless.get(
                        'colour')
                    member.needless['vehicle_displace'] = vehicle.needless.get(
                        'displace')
            else:
                for attr in [
                        'vehicle_brand', 'vehicle_category', 'vehicle_series',
                        'vehicle_config', 'vehicle_colour', 'vehicle_displace',
                        'vehicle_title'
                ]:
                    try:
                        member.needless.pop(attr)
                    except KeyError:
                        pass

            member.content = content
            member.status = status

            # 冗余信息
            if province_code:
                province = await AdministrativeDivision.find_one(
                    dict(parent_code=None, code=province_code))
                if province:
                    member.needless['province'] = province.title
                    city = await AdministrativeDivision.find_one(
                        dict(parent_code=province_code, code=city_code))
                    if city:
                        member.needless['city'] = city.title

            member.province_code = province_code
            member.city_code = city_code
            member.source = SOURCE_TYPE_MEMBER_SYSTEM

            if vehicle_code:
                if vehicle_code:
                    vehicle = await Vehicle.find_one(
                        dict(code=vehicle_code, record_flag=1))
                    if vehicle:
                        member.needless['vehicle_title'] = vehicle.title
                        member.needless[
                            'vehicle_brand'] = vehicle.needless.get('brand')
                        member.needless[
                            'vehicle_category'] = vehicle.needless.get(
                                'category')
                        member.needless[
                            'vehicle_series'] = vehicle.needless.get('series')
                        member.needless[
                            'vehicle_config'] = vehicle.needless.get('config')
                        member.needless[
                            'vehicle_colour'] = vehicle.needless.get('colour')
                        member.needless[
                            'vehicle_displace'] = vehicle.needless.get(
                                'displace')
                member.vehicle_code = vehicle_code

            if purchase_datetime:
                member.purchase_datetime = str2datetime(
                    purchase_datetime, '%Y-%m')

            member.status = status
            member_id = await member.save()

            res['code'] = 1
            res['member_id'] = member_id
        else:
            res['code'] = -1
        return res
Пример #9
0
    async def post(self):
        r_dict = {'code': 0}
        try:
            args_dict = json.loads(self.request.body)
            auth_code = args_dict.get('auth_code', None)
            user_info = args_dict.get('userInfo', {})
            if not user_info:
                user_info = {}

            source = args_dict.get('source', None)
            if auth_code:
                params_dict = {
                    'app_id': MINI_APP_ID,
                    'app_secret': MINI_APP_SECRET,
                    'code': auth_code
                }
                exchange_url = API_CODE_EXCHANGE_SESSION_URL.format(
                    **params_dict)
                http_client = AsyncHTTPClient()
                response = await http_client.fetch(exchange_url,
                                                   validate_cert=False)
                if response.code == 200:
                    rep_dict = json.loads(response.body)
                    open_id = rep_dict.get('openid')
                    friend_open_id = args_dict.get('friend_open_id', None)
                    session_key = rep_dict.get('session_key')
                    if open_id:
                        member = await find_member_by_open_id(open_id)
                        if not member:
                            if source is not None:
                                source_type = str(source)
                            else:
                                source_type = str(SOURCE_TYPE_MEMBER_SYSTEM)
                            # 创建用户
                            member = Member(id=ObjectId(),
                                            code=get_increase_code(
                                                KEY_INCREASE_MEMBER_CODE),
                                            open_id=open_id,
                                            source=source_type,
                                            status=STATUS_USER_ACTIVE)
                            wechat_info = await parse_wechat_info(user_info)
                            member.sex = int(
                                user_info.get('gender')) if user_info.get(
                                    'gender') else SEX_NONE

                            member.avatar = wechat_info.get(
                                'avatar'
                            ) if wechat_info.get('avatar') else '%s://%s%s' % (
                                SERVER_PROTOCOL, SERVER_HOST,
                                self.static_url('images/default/visitor.png'))
                            member.nick_name = wechat_info.get(
                                'nick_name') if wechat_info.get(
                                    'nick_name') else '游客'

                            if wechat_info:
                                member.province_code = wechat_info.get(
                                    'province_code')
                                member.city_code = wechat_info.get('city_code')
                                member.district_code = wechat_info.get(
                                    'district_code')

                                member.needless['province'] = wechat_info.get(
                                    'province_name')
                                member.needless['city'] = wechat_info.get(
                                    'city_name')
                                member.needless['district'] = wechat_info.get(
                                    'district_name')

                                member.wechat_info = user_info

                            member.register_datetime = datetime.datetime.now()
                            member.login_datetime = datetime.datetime.now()
                            member.login_times += 1

                            await member.save()

                            # 会员属性统计
                            await start_task_member_property_statistics(member)

                            r_dict['open_id'] = open_id
                            r_dict['session_key'] = session_key
                            r_dict['code'] = 1000
                        else:
                            if member.status == STATUS_USER_INACTIVE:
                                r_dict['code'] = 1002
                            else:
                                member.login_datetime = datetime.datetime.now()
                                member.login_times += 1
                                await member.save()

                                r_dict['open_id'] = open_id
                                r_dict['session_key'] = session_key
                                r_dict['code'] = 1000
                        if friend_open_id:
                            friend = await find_member_by_open_id(
                                friend_open_id)
                            if friend:
                                friend_member = MemberFriend(
                                    member_cid=member.cid,
                                    friend_cid=friend.cid)
                                await friend_member.save()
                                member_friend = MemberFriend(
                                    member_cid=friend.cid,
                                    friend_cid=member.cid)
                                await member_friend.save()
                else:
                    r_dict['code'] = 1003
            else:
                r_dict['code'] = 1001
        except Exception:
            logger.error(traceback.format_exc())
        return r_dict
Пример #10
0
 def test_add_member(self):
     member = Member(id=2, name='test', avatar='2', level=0, experience=5)
     self.session.add(member)
     self.session.commit()
     self.assertEqual(
         self.session.query(Member).filter(Member.id == 2).count(), 1)
Пример #11
0
def attend():
    team = current_user
    event = get_empty_event_or_fail()
    attending = AttendingTeam.query.filter_by(event=event, team=team).first()

    form = AttendForm()
    if form.validate_on_submit():

        if datetime.now() > event.registration_end:
            flash("Registration time is over")
            return flask.redirect(flask.url_for('attend'))

        members_to_add = []

        def verify_member_form(tpl):
            if any(tpl):
                if not all(tpl):
                    return False
                return True
            return None

        def check_3_tuple(tpl):
            tpl = tuple(t.strip() for t in tpl)
            if verify_member_form(tpl) is False:
                flash("Fill all 3 fields for each member")
                return False
            # return flask.render_template('attend.html', form=form, members=team.members, attending=attending)
            elif verify_member_form(tpl) is True:
                if not tpl[0].endswith("@hs-albsig.de"):  # FIXME
                    flash("Please use only university email addresses")
                    return False
                # return flask.render_template('attend.html', form=form, members=team.members, attending=attending)
                members_to_add.append(tpl)
            else:
                print("Empty 3-tuple")
            return True

        # Check form

        _ = check_3_tuple((form.email1.data, form.surname1.data, form.forename1.data))
        if not _:
            return flask.render_template('attend.html', form=form, members=team.members, attending=attending)
        _ = check_3_tuple((form.email2.data, form.surname2.data, form.forename2.data))
        if not _:
            return flask.render_template('attend.html', form=form, members=team.members, attending=attending)
        _ = check_3_tuple((form.email3.data, form.surname3.data, form.forename3.data))
        if not _:
            return flask.render_template('attend.html', form=form, members=team.members, attending=attending)
        _ = check_3_tuple((form.email4.data, form.surname4.data, form.forename4.data))
        if not _:
            return flask.render_template('attend.html', form=form, members=team.members, attending=attending)
        _ = check_3_tuple((form.email5.data, form.surname5.data, form.forename5.data))
        if not _:
            return flask.render_template('attend.html', form=form, members=team.members, attending=attending)

        # delete AttendingTeam
        if attending is not None:
            db_session.delete(attending)
            db_session.commit()

        # delete all users
        for m in team.members:
            db_session.delete(m.user)
            db_session.delete(m)
        db_session.commit()

        for email, surname, forename in members_to_add:
            test_u = User.query.filter_by(email=email).first()
            if test_u is not None:
                flash("User with this email found in database. Please unregister first.")
                return flask.render_template('attend.html', form=form, members=team.members, attending=attending)
            else:
                u = User()
                u.email = email
                u.surname = surname
                u.forename = forename
                u.ensure_token()
                db_session.add(u)

                m = Member()
                m.team = team
                m.user = u
                db_session.add(m)
                db_session.commit()

                send_validation_email(u, team)

        # add AttendingTeam if member count is > 0
        if len(members_to_add) > 0:
            at = AttendingTeam()
            at.event = event
            at.team = team
            at.subnet = first_empty_subnet()
            db_session.add(at)
            db_session.commit()
            flash("Emails were sent to your email addresses. Please follow the instructions in this email.")

        db_session.commit()

        return flask.redirect(flask.url_for('attend'))

    # Send verification links TODO

    return flask.render_template('attend.html', form=form, members=team.members, attending=attending)