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')
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