Esempio n. 1
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()
     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()
Esempio n. 2
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()
Esempio n. 3
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()
Esempio n. 4
0
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})
Esempio n. 5
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()
Esempio n. 6
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()