Example #1
0
def new(request):
    if not request.user.payment.status['is_paid']:
        return render(request, 'central/fjelltreffen/payment_required.html')

    other_active_annonse_exists = Annonse.get_active().filter(user=request.user, hidden=False).exists()
    context = {
        'counties': County.typical_objects(),
        'annonse_retention_days': settings.FJELLTREFFEN_ANNONSE_RETENTION_DAYS,
        'obscured_age': Annonse.obscure_age(request.user.get_age()),
        'other_active_annonse_exists': other_active_annonse_exists
    }
    return render(request, 'central/fjelltreffen/edit.html', context)
Example #2
0
def edit(request, id):
    try:
        annonse = Annonse.objects.get(id=id)
        # checks if the user is the owner
        if annonse.user != request.user:
            raise PermissionDenied
    except Annonse.DoesNotExist:
        return render(request, 'central/fjelltreffen/edit_not_found.html')

    other_active_annonse_exists = Annonse.get_active().exclude(id=annonse.id).filter(user=request.user).exists()
    context = {
        'annonse': annonse,
        'counties': County.typical_objects(),
        'annonse_retention_days': settings.FJELLTREFFEN_ANNONSE_RETENTION_DAYS,
        'obscured_age': Annonse.obscure_age(request.user.get_age()),
        'other_active_annonse_exists': other_active_annonse_exists
    }
    return render(request, 'central/fjelltreffen/edit.html', context)
Example #3
0
def index(request):
    annonser, start_index, end = Annonse.get_by_filter(request.session.get('fjelltreffen.filter', {}))
    context = {
        'annonser': annonser,
        'start_index': start_index,
        'end': end,
        'counties': County.typical_objects(),
        'annonse_retention_days': settings.FJELLTREFFEN_ANNONSE_RETENTION_DAYS,
        'age_limits': settings.FJELLTREFFEN_AGE_LIMITS,
        'filter': request.session.get('fjelltreffen.filter')
    }
    return render(request, 'central/fjelltreffen/index.html', context)
Example #4
0
def show_mine(request, id):
    if not request.user.payment.status['is_paid']:
        messages.error(request, 'membership_not_paid')
        return redirect('fjelltreffen:mine')

    try:
        # Hide all other annonser that belongs to this user first
        hidden = Annonse.get_active().filter(user=request.user).update(hidden=True)
        if hidden > 0:
            messages.info(request, 'max_one_active_annonse')
        annonse = Annonse.objects.get(id=id, user=request.user)
        annonse.hidden = False
        annonse.save()
        return redirect('fjelltreffen:mine')
    except Annonse.DoesNotExist:
        # Unexpected case; maybe some asynchronous browsing. Ignore and return to the annonse-list
        return redirect('fjelltreffen:mine')
Example #5
0
def load(request):
    if not request.is_ajax() or request.method != 'POST' or 'filter' not in request.POST:
        raise PermissionDenied

    filter = json.loads(request.POST['filter'])
    start_index = request.POST['start_index']

    request.session['fjelltreffen.filter'] = {
        'minage': filter['minage'],
        'maxage': filter['maxage'],
        'gender': filter['gender'], # Empty gender means both genders
        'county': filter['county'],
        'text': filter['text']
    }

    annonser, start_index, end = Annonse.get_by_filter(request.session['fjelltreffen.filter'], int(start_index))

    context = {'annonser': annonser}
    string = render_to_string('central/fjelltreffen/annonselist.html', context, request=request)
    return HttpResponse(json.dumps({
        'html': string,
        'start_index': start_index,
        'end': end,
    }))
Example #6
0
def save(request):
    if request.method != 'POST':
        return redirect('fjelltreffen:mine')

    # If user hasn't paid, allow editing, but not creating new annonser
    if not request.user.payment.status['is_paid'] and request.POST['id'] == '':
        raise PermissionDenied

    # Pre-save validations
    errors = False

    if request.POST.get('id', '') == '':
        # New annonse (not editing an existing one), create it
        annonse = Annonse()
        annonse.user = request.user
    else:
        annonse = Annonse.objects.get(id=request.POST['id'])
        if annonse.user != request.user:
            # someone is trying to edit an annonse that dosent belong to them
            raise PermissionDenied

    if request.POST.get('title', '') == '':
        messages.error(request, 'missing_title')
        errors = True

    if not validator.email(request.POST['email']):
        messages.error(request, 'invalid_email')
        errors = True

    if request.POST.get('text', '') == '':
        messages.error(request, 'missing_text')
        errors = True

    if 'image' in request.FILES:
        try:
            # Uploading image
            file = request.FILES['image']
            data = file.read()
            extension = standardize_extension(file.name.split(".")[-1])

            # Create the thumbnail
            thumb = PIL.Image.open(BytesIO(data)).copy()
            fp = BytesIO()
            thumb.thumbnail(
                [settings.FJELLTREFFEN_IMAGE_THUMB_SIZE, settings.FJELLTREFFEN_IMAGE_THUMB_SIZE],
                PIL.Image.ANTIALIAS,
            )
            thumb.save(fp, extension)
            thumb_data = fp.getvalue()

            # Calculate sha1-hashes
            sha1 = hashlib.sha1()
            sha1.update(data)
            hash = sha1.hexdigest()
            sha1 = hashlib.sha1()
            sha1.update(thumb_data)
            thumb_hash = sha1.hexdigest()
        except Exception:
            logger.warning(
                "Kunne ikke laste opp Fjelltreffen-bilde",
                exc_info=sys.exc_info(),
                extra={'request': request}
            )
            messages.error(request, 'image_upload_error')
            errors = True

    if errors:
        if request.POST.get('id', '') == '':
            return redirect('fjelltreffen:new')
        else:
            return redirect('fjelltreffen:edit', request.POST['id'])

    hidden = request.POST.get('hidden', 'hide') == 'hide'

    # Don't allow showing an already hidden annonse when you haven't paid
    if request.POST['id'] != '':
        if annonse.hidden and not request.user.payment.status['is_paid']:
            hidden = True

    # Don't create new annonser if you already have an active annonse
    if request.POST.get('id', '') == '':
        annonser_to_check = Annonse.get_active()
    else:
        annonser_to_check = Annonse.get_active().exclude(id=request.POST['id'])
    if annonser_to_check.filter(user=request.user).exists():
        hidden = True

    if request.POST.get('county', '') == 'international':
        annonse.county = None
    else:
        annonse.county = County.typical_objects().get(id=request.POST.get('county', ''))
    # TODO: Validate and return form to user with error message
    annonse.title = request.POST.get('title', '')[:255]
    annonse.email = request.POST.get('email', '')[:255]
    if 'image' in request.FILES:
        # Delete any existing image
        annonse.delete_image()

        # Setup AWS connection
        conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
        bucket = conn.get_bucket(settings.AWS_S3_BUCKET)

        # Upload the original image to AWS
        key = bucket.new_key("%s/%s.%s" % (settings.AWS_S3_FOLDERS['fjelltreffen'], hash, extension))
        key.content_type = file.content_type
        key.set_contents_from_string(data, policy='public-read')

        # Upload the thumbnail to AWS
        key = bucket.new_key("%s/%s.%s" % (settings.AWS_S3_FOLDERS['fjelltreffen'], thumb_hash, extension))
        key.content_type = file.content_type
        key.set_contents_from_string(thumb_data, policy='public-read')

        # Update the DB fields with new images
        annonse.image = "%s.%s" % (hash, extension)
        annonse.image_thumb = "%s.%s" % (thumb_hash, extension)
    annonse.text = request.POST.get('text', '')
    annonse.hidden = hidden
    annonse.hideage = request.POST.get('hideage', '') == 'hide'
    annonse.save()
    return redirect('fjelltreffen:mine')
Example #7
0
def import_fjelltreffen_annonser(user):
    old_member = Member.objects.get(memberid=user.memberid)

    for link in Link.objects.filter(fromobject='Member', fromid=old_member.id, toobject='Classified'):
        try:
            # Check for any saved images, and see if we can determine a usable path
            imageid = Link.objects.get(fromobject='Classified', fromid=link.toid, toobject='ClassifiedImage').toid
            path = ClassifiedImage.objects.get(id=imageid).path
            if path.startswith('/var/www/hosts/turistforeningen.no/web/img/fjelltreff/'):
                # This one is served on the old site and still usable
                old_annonse_imageurl = path.split('/var/www/hosts/turistforeningen.no/web/')[1]
            elif path.startswith('/www/sherpa2/www/dnt/img/fjelltreff/'):
                # This one is served on the old site and still usable
                old_annonse_imageurl = path.split('/www/sherpa2/www/dnt/')[1]
            else:
                # Unknown path, or known unusable path - ignore this image.
                old_annonse_imageurl = ''
        except (Link.DoesNotExist, ClassifiedImage.DoesNotExist):
            old_annonse_imageurl = ''
        try:
            old_annonse = Classified.objects.get(id=link.toid)
        except Classified.DoesNotExist:
            continue

        annonse = Annonse()
        annonse.user = user
        annonse.title = old_annonse.title

        # Email is required, so make sure we find one for the old user
        if old_member.email is None or old_member.email == '':
            # Nope, it's not here. Try to get it from Focus
            focus_email = user.get_email()
            if focus_email == '':
                # Not in Focus either! We'll have to ignore this annonse.
                continue
            else:
                # Ok, use the focus email
                annonse.email = focus_email
        else:
            annonse.email = old_member.email

        try:
            annonse.county = County.objects.get(code=SHERPA2_COUNTIES[old_annonse.county])
        except KeyError:
            if old_annonse.county == 0:
                # The entire country is no longer applicable - set it to the Actor's county
                annonse.county = user.get_address().county
            elif old_annonse.county == 2:
                # Both Oslo and Akershus - set it to the Actor's county, which hopefully is one of those
                annonse.county = user.get_address().county
            elif old_annonse.county == 99:
                # International annonse - defined with 'NULL'
                annonse.county = None

        annonse.image = old_annonse_imageurl
        annonse.text = old_annonse.content
        annonse.is_image_old = True
        annonse.hidden = True
        annonse.hideage = True

        #hax to prevent autoadd now
        annonse.save()
        annonse.date_added = old_annonse.authorized
        annonse.date_renewed = old_annonse.authorized
        annonse.save()

    # After adding all of them, make sure the newest one (and only the newest one) is visible
    try:
        newest = Annonse.objects.filter(user=user).order_by('-date_added')[0]
        newest.hidden = False
        newest.save()
    except IndexError:
        pass