def check_image(project_image): # check image is an image and has a proper dimension try: filename, file_extension = os.path.splitext(project_image.name) allowed_extensions = ['.jpg', '.jpeg', '.png'] if not (file_extension in allowed_extensions): raise ValueError('nonvalid') # limit to 1MB if project_image.size > 1048576: raise ValueError('sizelimit') project_image.name = str( datetime.now().microsecond) + '_' + str( project_image._size) + file_extension except ValueError as exc: if str(exc) == 'sizelimit': return bad_request('Image size must be less than 1MB') if str(exc) == 'nonvalid': return bad_request( 'The file you uploaded is not a supported image file ( you must upload a jpg or a png file' ) except KeyError as k: print(k) return bad_request("please fill all the fields") except Exception as e: print(e) return bad_request( 'Some error in the image upload process occour. Please try again.' ) else: return True
def get_interest_object_ids(request, model_object=None): if model_object is None: return bad_request('model missing') else: try: model = apps.get_model(app_label='dashboard', model_name=model_object.title()) return JsonResponse( [int(x.pk) for x in request.user.profile.get_interests(model)], safe=False) except ObjectDoesNotExist as e: print(e) error('model not found') except Exception as e: print(e) error()
def get_invitation_csv(request): import csv try: if request.user.is_superuser: response = HttpResponse(csv, content_type='application/csv') response['Content-Disposition'] = \ 'attachment; filename="invitation.csv"' response = HttpResponse(content_type='text/csv') response[ 'Content-Disposition'] = 'attachment; filename="OmExplorer_invitations.csv"' writer = csv.writer(response, delimiter=';', lineterminator='\n', quoting=csv.QUOTE_ALL, dialect='excel') invitations = Invitation.objects.all() writer.writerow([ 'sender email', 'sender first_name', 'sender last_name', 'receiver email', 'receiver first_name', 'receiver last_name' ]) for invitation in invitations: writer.writerow([ invitation.sender_email.encode('utf8'), invitation.sender_first_name.encode('utf8'), invitation.sender_last_name.encode('utf8'), invitation.receiver_email.encode('utf8'), invitation.receiver_first_name.encode('utf8'), invitation.receiver_last_name.encode('utf8'), ]) return response except: return bad_request("Error generating invitation csv")
def project(request, project_id=None): from dashboard.serializer import ProjectSerializer # DELETE PROJECT if request.method == 'DELETE' and project_id is not None: try: profile = request.user.profile projects = Project.objects.get(id=project_id, profile=profile) projects.delete() except ObjectDoesNotExist as e: print(e) print(not_authorized()) return success('ok', 'project deleted', {}) # GET ALL if request.method == 'GET' and project_id is None: try: profile = request.user.profile projects = Project.objects.filter(profile=profile) serialized = ProjectSerializer(projects, many=True) return success('ok', 'user projects', serialized.data) except Exception as e: print(e) return not_found() # GET SINGLE if request.method == 'GET' and project_id is not None: try: project = Project.objects.filter(id=project_id) serialized = ProjectSerializer(project, many=True) return success('ok', 'single project', serialized.data) except ObjectDoesNotExist as o: print(o) return not_found() except Exception as e: print(e) return error() # UPDATE if request.method == 'POST' and project_id is not None: data_to_update = {} data_to_update['name'] = request.POST.get('name', '') data_to_update['description'] = request.POST.get('description', '') data_to_update['start_date'] = request.POST.get('start_date', '') data_to_update['creator_role'] = request.POST.get( 'creator_role', '') data_to_update['project_url'] = request.POST.get('project_url', '') end_date = request.POST.get('end_date', '') # check if the image needs to be updated if request.POST.get('picture', None) != '': # image to be updated picture = request.FILES.get('picture') v13.check_image(picture) data_to_update['picture'] = picture # check if is or not an ongoing project try: if end_date != '': end_date = dt.strptime(end_date, '%Y-%m-%d') data_to_update['start_date'] = dt.strptime( data_to_update['start_date'], '%Y-%m-%d') # if end_date > dt.now(): # return bad_request('The project end_date cannot be in the future') if end_date < data_to_update['start_date']: return bad_request( 'The project end date cannot be before the project start date' ) data_to_update['end_date'] = end_date except Exception as e: print(e) return error() # get the model object and check the profile owns that project try: profile = request.user.profile project = Project.objects.filter(id=project_id, profile=profile).first() # clear and update tag project.set_tags(request.POST.get('tags', '')) # remove tag from data_to_update project.__dict__.update(data_to_update) project.save() except Project.DoesNotExist as e: print(e) return not_authorized() except Exception as e: print(e) return error() result = ProjectSerializer(project).data return success('ok', 'project updated', result) # CREATE if request.method == 'POST' and project_id is None: # check if fields are filled try: project_image = request.FILES.get('picture') project_name = request.POST['name'] project_description = request.POST['description'] project_start_date = dt.strptime(request.POST['start_date'], '%Y-%m-%d') project_creator_role = request.POST['creator_role'] project_url = request.POST['project_url'] project_tags = request.POST['tags'] # Check image is_image_ok = v13.check_image(project_image) if is_image_ok is not True: return is_image_ok except KeyError as k: print(k) return bad_request("Please fill all the fields") except Exception as e: return bad_request(e) # check if is or not an ongoing project try: project_end_date = dt.strptime(request.POST['end_date'], '%Y-%m-%d') except KeyError: project_end_date = None # if it is not an ongoing project check dates if project_end_date is not None: if project_end_date < project_start_date: return bad_request( 'The project END DATE cannot be before the project START DATE' ) try: # check user has not project with that name profile = request.user.profile projects = Project.objects.filter(profile=profile, name=project_name) if len(projects) > 0: return bad_request('Project name already exist') project = Project(profile=profile, name=project_name, picture=project_image, description=project_description, start_date=project_start_date, end_date=project_end_date, creator_role=project_creator_role, project_url=project_url) project.save() project.tags.clear() for tagName in [ x.lower().capitalize() for x in project_tags.split(",") ]: project.tags.add( Tag.objects.filter(name=tagName).first() or Tag.create(name=tagName)) project.save() result = ProjectSerializer(project).data except Exception as e: return bad_request(e) return success('ok', 'project created', result)
def project_invitation(request, status=None): # ToDo add token to avoid actions not allowed from dashboard.serializer import ProjectContributorSerializer if request.method == 'POST': try: body = json.loads(request.body) project_id = body['project_id'] profile_id = body['profile_id'] profile = Profile.objects.get(id=profile_id) project = Project.objects.get(id=project_id, profile=request.user.profile) # can not invite yourself if profile == request.user.profile: return bad_request('you are the owner of the project') contribution = ProjectContributor.objects.filter( project=project, contributor=profile) if len(contribution): if status is not None: # update the status of the invitation / collaboration contribution.update(status=status) serialized = ProjectContributorSerializer( contribution).data return success('ok', 'invitation updated', serialized) else: # ToDo send e-mail email_context = { 'FIRST_NAME': profile.user.first_name, 'LAST_NAME': profile.user.last_name, 'PROJECT_OWNER_FIRST_NAME': request.user.first_name, 'PROJECT_OWNER_LAST_NAME': request.user.last_name, 'PROJECT_NAME': project.name, 'CONFIRMATION_LINK': 'http://{}/profile/{}/invitation/{}/accepted/'. format( get_current_site(request), profile.id, project.id, ), 'DECLINE_LINK': 'http://{}/profile/{}/invitation/{}/declined/'. format( get_current_site(request), profile.id, project.id, ), } if contribution.first().status == 'pending': message = 'invitation re-sent' else: contribution.update(status='pending') message = 'invitation sent' EmailHelper.email( template_name='collaborator_invitation', title='Openmaker Explorer - Project nomination', vars=email_context, receiver_email=profile.user.email) serialized = ProjectContributorSerializer( contribution).data return success('ok', message, serialized) else: 'CREATING NEW INVITATION' # invitation not exist --> create and send e-mail contribution = ProjectContributor(project=project, contributor=profile) contribution.save() email_context = { 'FIRST_NAME': profile.user.first_name, 'LAST_NAME': profile.user.last_name, 'PROJECT_OWNER_FIRST_NAME': request.user.first_name, 'PROJECT_OWNER_LAST_NAME': request.user.last_name, 'PROJECT_NAME': project.name, 'CONFIRMATION_LINK': 'http://{}/profile/{}/invitation/{}/accepted/'.format( get_current_site(request), profile.id, project.id, ), 'DECLINE_LINK': 'http://{}/profile/{}/invitation/{}/declined/'.format( get_current_site(request), profile.id, project.id, ), } EmailHelper.email( template_name='collaborator_invitation', title='Openmaker Explorer - Project nomination', vars=email_context, receiver_email=profile.user.email) serialized = ProjectContributorSerializer( contribution).data return success('ok', 'invitation sent', serialized) except ObjectDoesNotExist as o: print('ERROR ObjectDoesNotExist') print(o) return error() except Exception as e: print('ERROR Exception') print(e) return error() else: bad_request('only post for now')
def post_om_invitation(request): if request.method != 'POST': return not_authorized() try: sender_first_name = request.POST['sender_first_name'].title() sender_last_name = request.POST['sender_last_name'].title() sender_email = request.POST['sender_email'].lower() receiver_first_name = request.POST['receiver_first_name'].title() receiver_last_name = request.POST['receiver_last_name'].title() receiver_email = request.POST['receiver_email'].lower() if sender_first_name.strip() == '' \ or sender_last_name.strip() == '' \ or sender_email.strip() == '' \ or receiver_first_name.strip() == '' \ or receiver_last_name.strip() == '' \ or receiver_email.strip() == '': return bad_request("Please fill al the fields") # Return to dsp error page if sender is already a DSP user? try: User.objects.get(email=sender_email) return HttpResponseRedirect('http://openmaker.eu/error_sender/') except User.DoesNotExist: pass Invitation.create(sender_email=sender_email, sender_first_name=sender_first_name, sender_last_name=sender_last_name, receiver_first_name=receiver_first_name, receiver_last_name=receiver_last_name, receiver_email=receiver_email, sender_verified=False) activation_link = 'http://{}/om_confirmation/{}/{}/{}/{}/{}/{}'.format( get_current_site(request), sender_first_name.encode('utf-8').encode('base64'), sender_last_name.encode('utf-8').encode('base64'), sender_email.encode('base64'), receiver_first_name.encode('utf-8').encode('base64'), receiver_last_name.encode('utf-8').encode('base64'), receiver_email.encode('base64')) EmailHelper.email(template_name='invitation_email_confirm', title='OpenMaker Nomination.. almost done!', vars={ 'SENDER_NAME': sender_first_name, 'CONFIRMATION_LINK': activation_link }, receiver_email=sender_email) except KeyError: return bad_request("Please fill al the fields") except EmailAlreadyUsed: return HttpResponseRedirect('http://openmaker.eu/error_receiver/') except UserAlreadyInvited: return HttpResponseRedirect('http://openmaker.eu/error_invitation/') except SelfInvitation: # @TODO : make appropriate page in openmaker return bad_request("Sender and receiver must be different") except Exception as e: #@TODO : make appropriate page in openmaker return bad_request("Some erro occour please try again") return HttpResponseRedirect('http://openmaker.eu/pending_invitation/')