Example #1
0
def submit(request):
    """Displays the UI for photo submissions as well as handling the
    resulting HTTP POST request. Uses django.forms for validation."""
    
    context = RequestContext(request)
    if request.method == 'GET':
        return render_to_response(
            'submit.html', { 'form': SubmitForm() }, context)

    form = SubmitForm(request.POST, request.FILES)
    if not form.is_valid():
        # Invalid form. Return to sender for fixing up.
        return render_to_response(
            'submit.html', { 'form': form }, context)

    # Form validated! Time to put data into database.
    photograph = form.cleaned_data['photo']
    caption = form.cleaned_data['caption']
    xpos, ypos = locate(photograph)
    ip = request.META['REMOTE_ADDR']

    photo = Photo(caption=caption,
                  location_x=xpos,
                  location_y=ypos,
                  approved=False,
                  dt_submitted=datetime.today(),
                  n_flagged=0,
                  n_flagged_offs=0,
                  n_flagged_cprv=0,
                  n_flagged_othr=0,
                  n_likes=0,
                  ip=ip)
    photo.save_with(photograph)
    return redirect('album.main.views.submit_update', id=photo.id)
Example #2
0
def report_image(request):
    if request.method != 'GET':
        raise Http404

    permalink = request.GET.get('id')
    if not permalink:
        raise Http404

    reason = request.GET.get('reason')
    if not reason:
        raise Http404

    photo = Photo.get_by_permalink(permalink)
    if not photo:
        raise Http404

    photo.n_flagged += 1
    if reason == 'offs':
        photo.n_flagged_offs = photo.n_flagged_offs + 1
    elif reason == 'cprv':
        photo.n_flagged_cprv = photo.n_flagged_cprv + 1
    elif reason == 'othr':
        photo.n_flagged_othr = photo.n_flagged_othr + 1
    photo.save()

    return HttpResponse(photo.n_flagged)
Example #3
0
def report_image(request):
    if request.method != 'GET':
        raise Http404

    permalink = request.GET.get('id')
    if not permalink:
        raise Http404

    reason = request.GET.get('reason')
    if not reason:
        raise Http404

    photo = Photo.get_by_permalink(permalink)
    if not photo:
        raise Http404

    photo.n_flagged += 1
    if reason == 'offs':
        photo.n_flagged_offs = photo.n_flagged_offs + 1
    elif reason == 'cprv':
        photo.n_flagged_cprv = photo.n_flagged_cprv + 1
    elif reason == 'othr':
        photo.n_flagged_othr = photo.n_flagged_othr + 1
    photo.save()

    return HttpResponse(photo.n_flagged)
Example #4
0
def comments(request):
    if request.method != 'GET':
        raise Http404

    permalink = request.GET.get('id')
    if not permalink:
        raise Http404

    photo = Photo.get_by_permalink(permalink)
    if not photo:
        raise Http404

    return render_to_response('api_comments.html',
                              {'comments': getcomments(photo) })
Example #5
0
def comments(request):
    if request.method != 'GET':
        raise Http404

    permalink = request.GET.get('id')
    if not permalink:
        raise Http404

    photo = Photo.get_by_permalink(permalink)
    if not photo:
        raise Http404

    return render_to_response('api_comments.html',
                              {'comments': getcomments(photo)})
Example #6
0
def like(request):
    if request.method != 'GET':
        raise Http404

    permalink = request.GET.get('id')
    if not permalink:
        raise Http404

    photo = Photo.get_by_permalink(permalink)
    if not photo:
        raise Http404

    photo.n_likes += 1
    photo.save()
    return HttpResponse(photo.n_likes)
Example #7
0
def like(request):
    if request.method != 'GET':
        raise Http404

    permalink = request.GET.get('id')
    if not permalink:
        raise Http404

    photo = Photo.get_by_permalink(permalink)
    if not photo:
        raise Http404

    photo.n_likes += 1
    photo.save()
    return HttpResponse(photo.n_likes)
Example #8
0
def search(request):
    """Returns search results for the given query."""

    if not 'q' in request.GET:
        return render_to_response('errors.html',
                                  { 'errors': ["Invalid query"] })

    query = request.GET['q']
    if len(query) < 3:
        return render_to_response('errors.html',
{ 'errors': ["Queries must be three characters or more"] })

    photos = Photo.search(query)
    photos = sorted(photos, reverse=True, key=lambda p: p.dt_submitted)
    return render_to_response('search.html',
                              { 'query': query, 'photos': photos })
Example #9
0
def submit_comment(request):
    if request.method != 'POST':
        raise Http404
    permalink = request.POST.get('id')
    if not permalink:
        raise Http404
    author = request.POST.get('author')
    if (not author) or (author.strip() == ""):
        author = 'Anonymous'
    if (author.strip().lower() == "moderator"):
        author = "Imposter"
    if (len(author) > 25):
        author = author[0:25]
    comment = request.POST.get('comment')
    if (not comment) or (comment.strip() == ""):
        return HttpResponse("")
    parent = request.POST.get('parent')
    if (not parent) or (parent.strip() == ""):
        parentobj = None
    else:
        parentobj = get_object_or_404(Comment, id=parent)
    if (len(comment) > 250):
        comment = comment[0:250]

    photo = Photo.get_by_permalink(permalink)
    if not photo:
        raise Http404

    ip = request.META['REMOTE_ADDR']
    #check if user is posting too many comments
    timediff = 0.5  # can only post 1 comment in this many minutes
    recent = Comment.objects.filter(
        ip=ip, dt_posted__gte=(datetime.today() - timedelta(minutes=timediff)))
    if (len(recent) > 0):
        return HttpResponse(
            "You are posting too frequently. Please wait a while before posting again"
        )
        #return
    new_comment = Comment(photo=photo,
                          parent=parentobj,
                          comment=comment,
                          author=author,
                          dt_posted=datetime.today(),
                          n_flagged=0,
                          ip=ip)
    new_comment.save()
    return HttpResponse("")
Example #10
0
def submit_comment(request):
    if request.method != 'POST':
        raise Http404
    permalink = request.POST.get('id')
    if not permalink:
        raise Http404
    author = request.POST.get('author')
    if (not author) or (author.strip() == ""):
        author = 'Anonymous'
    if (author.strip().lower() == "moderator"):
        author = "Imposter"
    if (len(author) > 25):
        author = author[0:25]
    comment = request.POST.get('comment')
    if (not comment) or (comment.strip() == ""):
        return HttpResponse("")
    parent = request.POST.get('parent')
    if (not parent) or (parent.strip() == ""):
        parentobj = None
    else:
        parentobj = get_object_or_404(Comment, id=parent)
    if (len(comment) > 250):
        comment = comment[0:250]

    photo = Photo.get_by_permalink(permalink)
    if not photo:
        raise Http404

    ip = request.META['REMOTE_ADDR']
    #check if user is posting too many comments
    timediff = 0.5 # can only post 1 comment in this many minutes
    recent = Comment.objects.filter(ip=ip,
dt_posted__gte=(datetime.today()-timedelta(minutes=timediff)))
    if (len(recent) > 0):
        return HttpResponse("You are posting too frequently. Please wait a while before posting again")
        #return
    new_comment = Comment(photo=photo, parent=parentobj, comment=comment,
                          author=author, dt_posted=datetime.today(),
                          n_flagged=0, ip=ip)
    new_comment.save()
    return HttpResponse("")
Example #11
0
def details(request):
    """Returns the details for a photo aka everything when a user
    clicks on it"""

    if request.method != 'GET':
        raise Http404

    request_get = request.GET
    permalink = request_get.get('id')
    if not permalink:
        raise Http404

    photo = Photo.get_by_permalink(permalink)
    if not photo.approved:
        raise Http404

    # find size of the image to display (fit into a maxsize by maxsize box)
    maxsize = 600
    height = 0
    width = 0
    if (photo.width < photo.height):
        height = maxsize
        width = round(photo.width / (photo.height/maxsize))
    else:
        width = maxsize
        height = round(photo.height / (photo.width/maxsize))

    data = {
        "photo": photo.photo,
        "permalink": permalink,
        "width": width ,
        "height": height,
        "caption": photo.caption,
        "dt_submitted": photo.dt_submitted.date(),
	"comments": getcomments(photo)
        }
    return render_to_response('details.html', data)
Example #12
0
def details(request):
    """Returns the details for a photo aka everything when a user
    clicks on it"""

    if request.method != 'GET':
        raise Http404

    request_get = request.GET
    permalink = request_get.get('id')
    if not permalink:
        raise Http404

    photo = Photo.get_by_permalink(permalink)
    if not photo.approved:
        raise Http404

    # find size of the image to display (fit into a maxsize by maxsize box)
    maxsize = 600
    height = 0
    width = 0
    if (photo.width < photo.height):
        height = maxsize
        width = round(photo.width / (photo.height / maxsize))
    else:
        width = maxsize
        height = round(photo.height / (photo.width / maxsize))

    data = {
        "photo": photo.photo,
        "permalink": permalink,
        "width": width,
        "height": height,
        "caption": photo.caption,
        "dt_submitted": photo.dt_submitted.date(),
        "comments": getcomments(photo)
    }
    return render_to_response('details.html', data)
Example #13
0
def photos(request):
    """Returns the most popular photos within a given geometrical
    bounds as JSON. Returns an error as JSON if something goes
    awry."""

    GET = request.GET

    def pleasegivemeafloat(key):
        """Returns the float value in the GET query dictionary that
        corresponds to the key. Raises a JSONError if something goes
        awry."""

        value = GET.get(key)
        if not value:
            raise JSONError('Missing %s parameter' % key)
        try:
            return float(value)
        except ValueError:
            raise JSONError('Expected float for %s parameter' % key)

    def pleasegivemeanint(key):
        """Returns the integer value in the GET query dictionary that
        corresponds to the key. Raises a JSONError if something goes
        awry."""

        value = GET.get(key)
        if not value:
            raise JSONError('Missing %s parameter' % key)
        try:
            return int(value)
        except ValueError:
            raise JSONError('Expected integer for %s parameter' % key)

    def pleasegivemeastring(key):
        """Returns the string value in the GET query dictionary that
        corresponds to the key. Raises a JSONError if something goes
        awry."""

        value = GET.get(key)
        if not value:
            raise JSONError('Missing %s parameter' % key)
        try:
            return str(value)
        except ValueError:
            raise JSONError('Expected float for %s parameter' % key)

    def to_dict(photo):
        """Returns a dictionary of keys and values representing a
        Photo model. This dictionary is suitable to be serialized into
        JSON."""

        return dict(id=photo.permalink,
                    location_x=photo.location_x,
                    location_y=photo.location_y,
                    photo=dict(name=photo.photo.name, height=photo.height,
                               width=photo.width),
                    thumbnail=photo.thumbnail.name,
                    popularity=photo.popularity)

    def filter_overlap(photo_list, zoom):
        """Removes photos from photo_list that overlap other photos preceding
        them"""

        new_list = []
        for photo1 in photo_list:
            overlaps = False
            for photo2 in new_list:
                if (photo1.overlaps(photo2, zoom)):
                    overlaps = True
            if (overlaps == False):
                new_list.append(photo1)
        return new_list

    def merge_lists(list1, list2, num):
        """Merges the 2 lists, and returns the num first elements."""
        i1 = 0
        i2 = 0
        combined = []

        while i1 < len(list1) and i2 < len(list2):
            if i1 < len(list1):
                for j in range(POPULAR_PRIORITY):
                    if (i1 >= len(list1)):
                        break
                    if ((list1[i1] in combined) == False):
                        combined.append(list1[i1])
                    i1 += 1
            if i2 < len(list2):
                if ((list2[i2] in combined) == False):
                    combined.append(list2[i2])
        
        return combined[:num]

    def stringtoage(time):
        """Converts the dropdown value from the age filter to a length of
        time."""
        if (time == 'week'):
            return 7*24
        elif (time == 'month'):
            return 30*24
        elif (time == 'year'):
            return 365*24
        else:
            raise ValueError
    try:
        xmin = pleasegivemeafloat('xmin')
        xmax = pleasegivemeafloat('xmax')
        ymin = pleasegivemeafloat('ymin')
        ymax = pleasegivemeafloat('ymax')
        num = pleasegivemeanint('num')
        zoom = pleasegivemeanint('zoom')
        time = pleasegivemeastring('time')

        if xmin >= xmax:
            raise JSONError('xmin must be less than xmax')
        if ymin >= ymax:
            raise JSONError('ymin must be less than ymax')
        if num > PHOTOS_LIMIT:
            raise JSONError('Cannot request more than %d photos' % PHOTOS_LIMIT)

        if (time == 'recent'):
            popular = Photo.popular(xmin, xmax, ymin, ymax, num)
            newest = Photo.newest(xmin, xmax, ymin, ymax, num)
            pics = merge_lists(popular, newest, num)
        elif (time == 'all'):
            pics = Photo.popular(xmin, xmax, ymin, ymax, num)
        else:
            threshold = stringtoage(time)
            pics = Photo.popular_by_age(xmin, xmax, ymin, ymax, num,
                                          threshold)

        pics = filter_overlap(pics, zoom)
        pics = map(to_dict, pics)
        return HttpResponse(json.dumps(dict(photos=pics), indent=2))

    except JSONError, err:
        return err.response()
Example #14
0
def photos(request):
    """Returns the most popular photos within a given geometrical
    bounds as JSON. Returns an error as JSON if something goes
    awry."""

    GET = request.GET

    def pleasegivemeafloat(key):
        """Returns the float value in the GET query dictionary that
        corresponds to the key. Raises a JSONError if something goes
        awry."""

        value = GET.get(key)
        if not value:
            raise JSONError('Missing %s parameter' % key)
        try:
            return float(value)
        except ValueError:
            raise JSONError('Expected float for %s parameter' % key)

    def pleasegivemeanint(key):
        """Returns the integer value in the GET query dictionary that
        corresponds to the key. Raises a JSONError if something goes
        awry."""

        value = GET.get(key)
        if not value:
            raise JSONError('Missing %s parameter' % key)
        try:
            return int(value)
        except ValueError:
            raise JSONError('Expected integer for %s parameter' % key)

    def pleasegivemeastring(key):
        """Returns the string value in the GET query dictionary that
        corresponds to the key. Raises a JSONError if something goes
        awry."""

        value = GET.get(key)
        if not value:
            raise JSONError('Missing %s parameter' % key)
        try:
            return str(value)
        except ValueError:
            raise JSONError('Expected float for %s parameter' % key)

    def to_dict(photo):
        """Returns a dictionary of keys and values representing a
        Photo model. This dictionary is suitable to be serialized into
        JSON."""

        return dict(id=photo.permalink,
                    location_x=photo.location_x,
                    location_y=photo.location_y,
                    photo=dict(name=photo.photo.name,
                               height=photo.height,
                               width=photo.width),
                    thumbnail=photo.thumbnail.name,
                    popularity=photo.popularity)

    def filter_overlap(photo_list, zoom):
        """Removes photos from photo_list that overlap other photos preceding
        them"""

        new_list = []
        for photo1 in photo_list:
            overlaps = False
            for photo2 in new_list:
                if (photo1.overlaps(photo2, zoom)):
                    overlaps = True
            if (overlaps == False):
                new_list.append(photo1)
        return new_list

    def merge_lists(list1, list2, num):
        """Merges the 2 lists, and returns the num first elements."""
        i1 = 0
        i2 = 0
        combined = []

        while i1 < len(list1) and i2 < len(list2):
            if i1 < len(list1):
                for j in range(POPULAR_PRIORITY):
                    if (i1 >= len(list1)):
                        break
                    if ((list1[i1] in combined) == False):
                        combined.append(list1[i1])
                    i1 += 1
            if i2 < len(list2):
                if ((list2[i2] in combined) == False):
                    combined.append(list2[i2])

        return combined[:num]

    def stringtoage(time):
        """Converts the dropdown value from the age filter to a length of
        time."""
        if (time == 'week'):
            return 7 * 24
        elif (time == 'month'):
            return 30 * 24
        elif (time == 'year'):
            return 365 * 24
        else:
            raise ValueError

    try:
        xmin = pleasegivemeafloat('xmin')
        xmax = pleasegivemeafloat('xmax')
        ymin = pleasegivemeafloat('ymin')
        ymax = pleasegivemeafloat('ymax')
        num = pleasegivemeanint('num')
        zoom = pleasegivemeanint('zoom')
        time = pleasegivemeastring('time')

        if xmin >= xmax:
            raise JSONError('xmin must be less than xmax')
        if ymin >= ymax:
            raise JSONError('ymin must be less than ymax')
        if num > PHOTOS_LIMIT:
            raise JSONError('Cannot request more than %d photos' %
                            PHOTOS_LIMIT)

        if (time == 'recent'):
            popular = Photo.popular(xmin, xmax, ymin, ymax, num)
            newest = Photo.newest(xmin, xmax, ymin, ymax, num)
            pics = merge_lists(popular, newest, num)
        elif (time == 'all'):
            pics = Photo.popular(xmin, xmax, ymin, ymax, num)
        else:
            threshold = stringtoage(time)
            pics = Photo.popular_by_age(xmin, xmax, ymin, ymax, num, threshold)

        pics = filter_overlap(pics, zoom)
        pics = map(to_dict, pics)
        return HttpResponse(json.dumps(dict(photos=pics), indent=2))

    except JSONError, err:
        return err.response()