예제 #1
0
 def post(self):
     post = self.request.POST
     if post['kind'] == 'badge':
         b = Badge(name=post['name'],
                   description=post['description'],
                   category=post['category'],
                   image=post['image'],
                   value=int(post['value']))
         b.save()
     elif post['kind'] == 'article':
         a = NewsArticle(title=post['title'],
                         author=post['author'],
                         body=post['body'],
                         date=datetime.date.today())
         a.save()
     elif post['kind'] == 'award':
         badge = Badge.gql('WHERE name = :1', post['badge']).get()
         for h in post.getall('hackers'):
             hacker = Hacker.gql('WHERE handle = :1', h).get()
             a = Award(hacker=hacker,
                       badge=badge,
                       date=datetime.date.today(),
                       proof=post['proof'])
             a.save()
             hacker.score_cache = hacker.score + badge.value
             hacker.save()
     self.get()
예제 #2
0
파일: handlers.py 프로젝트: hafeed/man-up
 def post(self):
     post = self.request.POST
     if post['kind'] == 'badge':
         badge = Badge(name=post['name'],
                       description=post['description'],
                       category=post['category'],
                       image=post['image'],
                       value=int(post['value']))
         badge.save()
     elif post['kind'] == 'article':
         date = datetime.datetime.strptime(post['date'], '%Y-%m-%d').date()
         article = NewsArticle(title=post['title'],
                               author=post['author'],
                               body=post['body'],
                               date=date)
         article.save()
     elif post['kind'] == 'award':
         badge = Badge.get_by_id(int(post['badge']))
         for member in post.getall('members'):
             member = Member.get_by_id(int(member))
             award = Award(member=member,
                           badge=badge,
                           date=datetime.date.today(),
                           proof=post['proof'])
             award.save()
     elif post['kind'] == 'talk':
         talk = Talk(title=post['title'],
                     date=datetime.datetime.strptime(
                         post['date'], '%Y-%m-%d').date(),
                     description=post['description'],
                     member=Member.get_by_id(int(post['member'])),
                     video=post['video'])
         talk.put()
     self.get()
예제 #3
0
파일: handlers.py 프로젝트: Ziyad/man-up
 def get(self):
     order = self.request.GET.get('order', 'value')
     if order == 'receivers':
         b = list(Badge.all())
         b.sort(key=lambda i:i.awards.count())
     else:
         b = Badge.gql('ORDER BY ' + order)
     self.render_template('badges', {'badges': b})
예제 #4
0
파일: handlers.py 프로젝트: hafeed/man-up
 def get(self):
     order = self.request.GET.get('order', 'value')
     if order == 'receivers':
         badges = list(Badge.all())
         badges.sort(key=lambda i: i.awards.count())
     else:
         badges = Badge.gql('ORDER BY ' + order)
     self.render_template('badges', {'badges': badges})
예제 #5
0
def update_ratings(chef, comment):
    score = analyzer.comment_analyzer(comment)
    total_entries = len(Foodlist.objects.filter(chef_id=chef))
    try:
        value = Badge.objects.get(user=chef)
    except ObjectDoesNotExist:
        value = Badge(user=chef, badge=0)

    new_val = float(
        float(value.badge * (total_entries - 1) + score) / total_entries)
    value.badge = new_val
    value.save()
예제 #6
0
파일: views.py 프로젝트: omque/fle-internal
def profile(request, id):
    person = TeamMember.objects.get(pk=id)
    if request.method == 'POST':
        form = BadgeForm(request.POST, request.FILES)
        if form.is_valid():
            b = Badge(badge_name=form.cleaned_data['name'], description=form.cleaned_data['description'], badge_image=form.cleaned_data['image'])
            b.save()
            person.badge.add(b)
            person.save()
    upload_form = BadgeForm()
    tasks = person.tasks_assigned.filter(status="open")
    return render(request,'profiles/profile_base.html', {'person': person,
                                                        'avg': person.feedback_averages(),
                                                        'form': upload_form,
                                                        'tasks': tasks})
예제 #7
0
파일: views.py 프로젝트: ricree/Mafiastats
def badge(request, pk=""):
    choices = [(p.id, p.name + " - " + p.site.title) for p in request.user.players.all()]
    if request.method == "POST":
        form = BadgeForm(request.POST)
        form.fields["players"].choices = choices
        if form.is_valid():
            players = [get_object_or_404(Player, pk=int(p)) for p in form.cleaned_data["players"]]
            if pk:
                badge = get_object_or_404(Badge, pk=int(pk))
                badge.players.clear()
                badge.title = form.cleaned_data["title"]
                badge.format = form.cleaned_data["config"]
                badge.is_custom = form.custom_format
            else:
                config = form.cleaned_data["config"].replace(r"\n", "\n")
                badge = Badge(
                    user=request.user, is_custom=form.custom_format, format=config, title=form.cleaned_data["title"]
                )
                badge.save()
            for p in players:
                badge.players.add(p)
            badge.save()
            badge.url = "images/badges/badge_custom_%s_%s.png" % (request.user.pk, badge.pk)
            badge.save()
            try:
                build_badge.delay(badge)
            except Exception as e:
                logging.exception(e.args[0])
                raise e
            return HttpResponseRedirect(reverse("account_profile"))
    else:
        if pk:
            badge = get_object_or_404(Badge, pk=pk)
            if badge.is_custom:
                params = eval(badge.format)
                formData = {
                    "title": badge.title,
                    "players": [p.id for p in badge.players.all()],
                    "preset": params["template"],
                    "background": params["background"],
                    "top_color": params["color1"],
                    "bottom_color": params["color2"],
                    "text_color": params["text"],
                    "font_size": params["size"],
                }
            else:
                config = badge.format.replace("\n", "\\n")
                formData = {
                    "title": badge.title,
                    "config": config,
                    "players": [(p.id, p.name + " - " + p.site.title) for p in badge.players.all()],
                }
            form = BadgeForm(initial=formData)
        else:
            # form  = BadgeForm({'players':players})
            form = BadgeForm()
        form.fields["players"].choices = choices
    return render_to_response("badge.html", {"form": form, "pk": pk}, context_instance=RequestContext(request))
예제 #8
0
 def post(self):
     post = self.request.POST
     if post['kind'] == 'badge':
         badge = Badge(
             name=post['name'],
             description=post['description'],
             category=post['category'],
             image=post['image'],
             value=int(post['value'])
         )
         badge.save()
     elif post['kind'] == 'article':
         date = datetime.datetime.strptime(post['date'], '%Y-%m-%d').date()
         article = NewsArticle(
             title=post['title'],
             author=post['author'],
             body=post['body'],
             date=date
         )
         article.save()
     elif post['kind'] == 'award':
         badge = Badge.get_by_id(int(post['badge']))
         for member in post.getall('members'):
             member = Member.get_by_id(int(member))
             award = Award(
                 member=member,
                 badge=badge,
                 date=datetime.date.today(),
                 proof=post['proof']
             )
             award.save()
             member.score_cache = member.score + badge.value
             member.save()
     elif post['kind'] == 'talk':
         talk = Talk(
             title=post['title'],
             date=datetime.datetime.strptime(post['date'], '%Y-%m-%d').date(),
             description=post['description'],
             member=Member.get_by_id(int(post['member'])),
             video=post['video']
         )
         talk.put()
     self.get()
예제 #9
0
파일: handlers.py 프로젝트: Ziyad/man-up
 def get(self):
     selected_badge = self.request.GET.getall('badge')
     if selected_badge:
         selected_badge = selected_badge[0]
     else:
         selected_badge = None
     
     badges = Badge.gql('ORDER BY name')
     self.render_template('badge_application', template_dict={'badges':badges,
         'selected_badge': selected_badge})
예제 #10
0
def complete_task(request, pk, person_pk):
    response = {'result': False, 'reason': 'nope'}
    # import pdb
    # pdb.set_trace()
    user = is_logged_in(request)
    if user:
        task = Task.objects.filter(pk=pk)
        person = User.objects.filter(pk=person_pk)
        if task and person:
            task, person = task[0], person[0]
            if not (user in task.assigner.all() or user in task.group.first().admins.all()):
                response['reason'] = "You don't have permission to mark it complete"
                return HttpResponse(json.dumps(response), content_type="application/json")
            if person in task.assignedto.all():
                task.completedby.add(person)
                task.save()
                person.points += task.points
                person.save()
                response['result'] = True
                response['message'] = "Done"

                badge = Badge.get_well_begun_is_half_done_badge()
                if badge not in person.badges.all():
                    person.badges.add(badge)
                    person.points += badge.points
                    person.save()
                    badge.save()

                if person.completedtasks.count() > 10:
                    badge = Badge.get_dependable_badge()
                    if badge not in person.badges.all():
                        person.badges.add(badge)
                        person.points += badge.points
                        person.save()
                        badge.save()
            else:
                response['reason'] = "This person was never assigned this task"
        else:
            response['reason'] = "Task with this pk does not exist"
    else:
        response['reason'] = "not logged in"
    return HttpResponse(json.dumps(response), content_type="application/json")
예제 #11
0
파일: handlers.py 프로젝트: eldog/man-up
 def post(self):
     post = self.request.POST
     if post['kind'] == 'badge':
         badge = Badge(
             name=post['name'],
             description=post['description'],
             category=post['category'],
             image=post['image'],
             value=int(post['value'])
         )
         badge.save()
     elif post['kind'] == 'award':
         badge = Badge.get_by_id(int(post['badge']))
         for member in post.getall('members'):
             member = Member.get_by_id(int(member))
             award = Award(
                 member=member,
                 badge=badge,
                 date=datetime.date.today(),
                 proof=post['proof']
             )
             award.save()
             member.score += badge.value
             member.save()
     elif post['kind'] == 'talk':
         talk = Talk(
             title=post['title'],
             date=utils.parse_date(post['date']),
             description=post['description'],
             member=Member.get_by_id(int(post['member'])),
             video=post['video']
         )
         talk.put()
     elif post['kind'] == 'taglineform':
         properties = GeneralSiteProperties.all().get()
         if properties == None:
             properties = GeneralSiteProperties(tag_line=post['tagline'])
             properties.put()
         else:
             properties.tag_line = post['tagline']
             properties.put()
     self.get()
예제 #12
0
파일: handlers.py 프로젝트: hafeed/man-up
 def get(self):
     selected_badge = self.request.GET.getall('badge')
     if selected_badge:
         selected_badge = selected_badge[0]
     else:
         selected_badge = None
     badges = Badge.gql('ORDER BY name')
     self.render_template('badge_application', {
         'badges': badges,
         'selected_badge': selected_badge
     })
예제 #13
0
def join_group(request, pk):
    response = {'result': False, 'reason': 'nope'}
    # import pdb
    # pdb.set_trace()
    user = is_logged_in(request)
    if user:
        group = Group.objects.filter(pk=pk)
        if group:
            group = group[0]

            if not group.show_to(user):
                if not (group.joining_code == request.POST.get('joining_code', "Wohoo.!!")):
                    response['reason'] = "You don't have permission to be here or the joining code is incorrect."
                    return HttpResponse(json.dumps(response), content_type="application/json")

            group.members.add(user)
            group.save()
            response['result'] = True
            response['message'] = "Welcome to %s"%group.name

            badge = Badge.get_baby_steps_badge()
            if badge not in user.badges.all():
                user.badges.add(badge)
                user.points += badge.points
                user.save()
                badge.save()

            badge = Badge.get_social_climber_badge()
            if user.groups.count() >= 5:
                if badge not in user.badges.all():
                    user.badges.add(badge)
                    user.points += badge.points
                    user.save()
                    badge.save()


        else:
            response['reason'] = "No Group with this  PK found"
    else:
        response['reason'] = "not logged in"
    return HttpResponse(json.dumps(response), content_type="application/json")
예제 #14
0
파일: handlers.py 프로젝트: Ziyad/man-up
 def post(self):
     post =  self.request.POST
     if post['kind'] == 'badge':
         b = Badge(name=post['name'], description=post['description'], 
                   category=post['category'], image=post['image'],
                   value=int(post['value']))
         b.save()
     elif post['kind'] == 'article':
         a = NewsArticle(title=post['title'], author=post['author'],
                          body=post['body'], date=datetime.date.today())
         a.save()
     elif post['kind'] == 'award':
         badge = Badge.gql('WHERE name = :1', post['badge']).get()
         for h in post.getall('hackers'):
             hacker = Hacker.gql('WHERE handle = :1', h).get()
             a=Award(hacker=hacker, 
                     badge=badge,
                     date=datetime.date.today(),
                     proof=post['proof'])
             a.save()
             hacker.score_cache = hacker.score + badge.value
             hacker.save()
     self.get()
예제 #15
0
 def post(self):
     post = self.request.POST
     if post['kind'] == 'badge':
         badge = Badge(name=post['name'],
                       description=post['description'],
                       category=post['category'],
                       image=post['image'],
                       value=int(post['value']))
         badge.save()
     elif post['kind'] == 'award':
         badge = Badge.get_by_id(int(post['badge']))
         for member in post.getall('members'):
             member = Member.get_by_id(int(member))
             award = Award(member=member,
                           badge=badge,
                           date=datetime.date.today(),
                           proof=post['proof'])
             award.save()
             member.score += badge.value
             member.save()
     elif post['kind'] == 'talk':
         talk = Talk(title=post['title'],
                     date=utils.parse_date(post['date']),
                     description=post['description'],
                     member=Member.get_by_id(int(post['member'])),
                     video=post['video'])
         talk.put()
     elif post['kind'] == 'taglineform':
         properties = GeneralSiteProperties.all().get()
         if properties == None:
             properties = GeneralSiteProperties(tag_line=post['tagline'])
             properties.put()
         else:
             properties.tag_line = post['tagline']
             properties.put()
     self.get()
예제 #16
0
def assign_admin(request, group_pk, person_pk):
    response = {'result': False, 'reason': 'nope'}
    # import pdb
    # pdb.set_trace()
    user = is_logged_in(request)
    if user:
        group = Group.objects.filter(pk=group_pk)
        person = User.objects.filter(pk=person_pk)

        if group and person:
            group, person = group[0], person[0]

            if user not in group.admins.all():
                response['reason'] = "You don't have permission to perform this action"
                return HttpResponse(json.dumps(response), content_type="application/json")
            
            if not person in group.members.all():
                response['reason'] = "The person should be a member of this group"
                return HttpResponse(json.dumps(response), content_type="application/json")

            if person in group.admins.all():
                response['reason'] = "The person is already an admin of this group"
                return HttpResponse(json.dumps(response), content_type="application/json")

            person.adminOf.add(group)
            person.save()
            group.save()
            response['result'] = True
            response['message'] = "added as admin"

            badge = Badge.get_worth_following_badge()
            if badge not in person.badges.all():
                person.badges.add(badge)
                person.points += badge.points
                person.save()
                badge.save()
        else: 
            response['reason'] = "No group or person with this  PK found"
    else:
        response['reason'] = "not logged in"
    return HttpResponse(json.dumps(response), content_type="application/json")
예제 #17
0
def create_new_post(request, group_pk):
    response = {'result': False, 'reason': 'nope'}
    # import pdb
    # pdb.set_trace()
    user = is_logged_in(request)
    if user:
        group = Group.objects.filter(pk=group_pk)
        if group:
            group = group[0]
            if group in user.groups.all(): 
                try:
                    form = NewPostForm(request.POST)
                    if form.is_valid():
                        post = form.save()

                    post.OP.add(user)
                    post.save()
                    group.posts.add(post)
                    group.save()
                    response['result']=True
                    response['message'] = "Posted"
                    response['data'] = {"pk": post.pk}

                    badge = Badge.get_is_there_anybody_out_there_badge()
                    if badge not in user.badges.all():
                        user.badges.add(badge)
                        user.points += badge.points
                        user.save()
                        badge.save()

                except:
                    response['reason'] = "Incomplete Data"
            else:
                response['reason'] = "you are not a member of this group"
        else:
            response['reason'] = "No Group with this  PK found"
    else:
        response['reason'] = "not logged in"
    return HttpResponse(json.dumps(response), content_type="application/json")
예제 #18
0
 def get(self):
     self.render_template('admin', {
         'badges': Badge.all(),
         'hackers': Hacker.all()
     })
예제 #19
0
파일: handlers.py 프로젝트: hafeed/man-up
 def get(self, id):
     self.render_template('badge', {'badge': Badge.get_by_id(int(id))})
예제 #20
0
파일: handlers.py 프로젝트: hafeed/man-up
 def get(self):
     self.render_template('admin', {
         'badges': Badge.all(),
         'members': Member.all(),
     })
예제 #21
0
파일: handlers.py 프로젝트: Ziyad/man-up
 def get(self):
     self.render_template('admin', {'badges': Badge.all(),
                                    'hackers': Hacker.all()})
예제 #22
0
파일: handlers.py 프로젝트: eldog/man-up
 def get(self, id):
     self.render_template('badge', {
         'badge': Badge.get_by_id(int(id))
     })
예제 #23
0
파일: handlers.py 프로젝트: eldog/man-up
 def get(self):
     self.render_template('admin', {
         'badges': Badge.all(),
         'members': Member.all(),
     })
예제 #24
0
 def get(self, name):
     query = Badge.gql('WHERE name = :1', urllib.unquote(name))
     badge = iter(query).next() if query.count() else None
     self.render_template('badge', {'badge': badge})
예제 #25
0
def report():
    """Add a base64 image"""

    import base64
    import uuid
    import PIL
    from PIL import Image, ExifTags
    import tweepy
    import json
    from boto.s3.connection import S3Connection
    from boto.s3.connection import OrdinaryCallingFormat
    from boto.s3.key import Key
    import datetime
    import requests

    img_data = request.values.get('img_data')

    # try:
    decoded = base64.b64decode(img_data)

    filename = ("%s" % uuid.uuid4())[0:8]

    with open("tmp/%s.png" % filename, 'wb') as f:
        f.write(decoded)

    im = Image.open("tmp/%s.png" % filename)

    try:
        for orientation in ExifTags.TAGS.keys():
            if ExifTags.TAGS[orientation] == 'Orientation':
                break
        exif = dict(im._getexif().items())

        if exif[orientation] == 3:
            im = im.rotate(180, expand=True)
        elif exif[orientation] == 6:
            im = im.rotate(270, expand=True)
        elif exif[orientation] == 8:
            im = im.rotate(90, expand=True)

    except (AttributeError, KeyError, IndexError):
        # cases: image don't have getexif
        pass

    maxsize = (float(620), float(620))
    size = (float(im.size[0]), float(im.size[1]))
    scale = "down"

    if size[0] < maxsize[0] or size[1] < maxsize[1]:
        scale = "up"

    if size[0] < size[1]:
        newsize = (maxsize[0], maxsize[1] * (size[1] / size[0]))
    else:
        newsize = (maxsize[0] * (size[0] / size[1]), maxsize[1])

    crop = (int(
        (newsize[0] - maxsize[0]) / 2), int(
            (newsize[1] - maxsize[1]) / 2), int((newsize[0] + maxsize[0]) / 2),
            int((newsize[1] + maxsize[1]) / 2))

    newsize = (int(newsize[0]), int(newsize[1]))

    im = im.resize(newsize, PIL.Image.ANTIALIAS)
    im = im.crop(crop)

    page_type = get_page_type_from_request()

    if page_type == 'VOTED':
        img_overlay_file = "images/frame_badge_confetti.png"
        tweet_string = '#IVOTED'
    else:
        img_overlay_file = "images/frame_badge_voter.png"
        tweet_string = 'Voting!'

    foreground = Image.open(img_overlay_file)
    im.paste(foreground, (0, 0), foreground)

    im.save("tmp/%s.png" % filename)

    auth = tweepy.OAuthHandler(os.environ.get('TWITTER_API_KEY'),
                               os.environ.get('TWITTER_API_SECRET'))
    auth.set_access_token(os.environ.get('TWITTER_TOKEN'),
                          os.environ.get('TWITTER_TOKEN_SECRET'))

    api = tweepy.API(auth)
    r = api.update_with_media(
        "tmp/%s.png" % filename,
        (u"%s Your "
         u"turn\u2014txt VOTE to 384-387 or visit hello.vote for your "
         u"voting location & selfie!") % tweet_string)

    item = r._json

    conn = S3Connection(os.environ.get('AWS_ACCESS_KEY'),
                        os.environ.get('AWS_SECRET_KEY'),
                        calling_format=OrdinaryCallingFormat())
    bucket = conn.get_bucket(os.environ.get('AWS_S3_BUCKET'))
    bucket_url = "https://%s.s3.amazonaws.com" % os.environ.get(
        'AWS_S3_BUCKET')

    username = item.get('user').get('screen_name')
    user_id = item.get('user').get('id')
    user_avatar = item.get('user').get('profile_image_url')
    photo_id = str(item.get('id'))
    photo_url = item.get('entities').get('media')[0].get('media_url')
    display_url = item.get('entities').get('media')[0].get('display_url')
    user_avatar_s3 = "%s/avatars/%s.jpg" % (bucket_url, user_id)
    photo_url_s3 = "%s/photos/%s.png" % (bucket_url, photo_id)

    photo = Badge(source='twitter',
                  source_id=photo_id,
                  username=username,
                  user_avatar=user_avatar,
                  user_avatar_s3=user_avatar_s3,
                  photo_url=photo_url,
                  photo_url_s3=photo_url_s3,
                  photo_display_url=display_url,
                  original_url='https://twitter.com/%s/status/%s' %
                  (username, photo_id),
                  caption=item.get('text'),
                  visible=False,
                  priority=0,
                  random_index=random.randint(0, 2147483647),
                  permalink_slug=filename,
                  created=datetime.datetime.now())
    photo.save()

    # save avatar to s3
    avatar = requests.get(user_avatar).content
    k = Key(bucket)
    k.key = "avatars/%s.jpg" % user_id
    k.delete()
    k.set_metadata('Content-Type', 'image/jpeg')
    k.set_contents_from_string(avatar)
    k.set_acl('public-read')

    # save photo to s3
    k = Key(bucket)
    k.key = "photos/%s.png" % photo_id
    k.delete()
    k.set_metadata('Content-Type', 'image/png')
    k.set_contents_from_filename("tmp/%s.png" % filename)
    k.set_acl('public-read')
    # except:
    #     return '{"error": true}'

    return photo.to_json()
예제 #26
0
파일: handlers.py 프로젝트: Ziyad/man-up
 def get(self, name):
     query = Badge.gql('WHERE name = :1', urllib.unquote(name))
     badge = iter(query).next() if query.count() else None
     self.render_template('badge', {'badge': badge})
예제 #27
0
    # connect to solr
    print('Connecting to solr...')
    solr = Solr(settings.SOLR_URL)
    # pysolr doesn't try to connect until a request is made, so we'll make a ping request
    try:
        solr._send_request('GET', 'admin/ping')
    except socket.error, e:
        print('Failed to connect to solr - error was: %s' % str(e))
        print('Aborting.')
        sys.exit(2)
    print('Connected.\n')

    # ensure required tables exist
    print("Creating tables if they don't exist...")
    Site.createTable(ifNotExists=True)
    Badge.createTable(ifNotExists=True)
    User.createTable(ifNotExists=True)
    print('Created.\n')

    # SITE INFO
    # only look if they were not specified at the command line; also only if
    # readme.txt exists (they don't in dumps after Aug 2012)
    readme_path = get_file_path(xml_root, 'readme.txt')
    if not (site_name and dump_date) and readme_path:
        # get the site name from the first line of readme.txt. This could be fragile.
        with open(readme_path, 'r') as f:
            site_readme_desc = f.readline().strip()

        # assume if there's a colon in the name, the name part is before, and the date
        # part is after.
        if ':' in site_readme_desc: