def handle_post(self, email, account_info):
     if self.request.get("project_entity_key"):
         project_key = ndb.Key(urlsafe=self.request.get("project_entity_key"))
         project = project_key.get()
     else:
         project = Project(parent=utils.get_parent_key_for_email(email))
         project_key = project.key
     
     #add all users we find to the project.users, likewise add the project to the User entity
     users = [ndb.Key(urlsafe=self.request.get("user_entity_key"))]    
     potential_users_list = self.request.get_all("project_collaborator")
     for potential_user in potential_users_list:
         if potential_user and potential_user != utils.get_profile_for_email(email).name:
             profile_query = Profile.query(Profile.name == potential_user)
             for profile in profile_query:
                 user_key = profile.key.parent()
                 users.append(user_key)
     
     administrators = [ndb.Key(urlsafe=self.request.get("user_entity_key"))]
     
     project.title = self.request.get("project_title")
     project.description = self.request.get("project_description")
     project.administrators = administrators
     project.users = users
     project.put()
     
     for user_key in users:
         user = user_key.get()
         if not user.projects:
             user.projects = [project.key]
         else:
             user.projects.append(project.key)
         user.put()
         
     self.redirect(self.request.referer)
Exemple #2
0
    def post(self, key):
        project = self.getProject(key)
        if project is None:
            project = Project()

        project.name = self.request.get('project[name]')
        project.description = self.request.get('project[description]')
        project.location = self.request.get('project[location]')
        project.type_of_work = self.request.get('project[type_of_work]')
        try:
            spots = int(self.request.get('project[max_volunteers]'))
            if spots <= 0:
                raise ValueError('Below zero')
            project.max_volunteers = spots
        except ValueError as e:
            raise ValidationError(errors={
                'project[max_volunteers]':
                'Must be an integer number above zero'
            })

        project.put()

        error_code = 1 if key == 'new' else 2
        self.redirect('/admin/projects/{}'.format(project.key()),
                      {'error': error_code})
def get_projects():
    projects = []
    list = {}
    use_short = False

    if request.args.get('slug'):
        list = client.entries({
            'content_type': 'project',
            'fields.slug': request.args.get('slug'),
        })
    else:
        list = client.entries({
            'content_type': 'project',
            'order': '-fields.year',
        })
        use_short = True

    for item in list:
        project = Project(id=item.id)
        project.cover = item.cover.url()
        project.description = item.description
        project.screens = item.screens
        project.short_description = item.short_description
        project.slug = item.slug
        project.thumbnail = item.thumbnail.url()
        project.title = item.title
        project.year = item.year

        projects.append(project)

    if len(projects) == 0:
        abort(404)

    return jsonify([project.serialize(use_short=use_short) for project in projects])
Exemple #4
0
def add_project(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)

        if form.is_valid():
            package = form.cleaned_data['package']
            username = form.cleaned_data['username']
            repository = form.cleaned_data['repository']
            branch = form.cleaned_data['branch']
            cargo_support = form.cleaned_data['cargo_support']
            categories = form.cleaned_data['categories']

            repo = travisclient.get_repo(username, repository)

            if not repo:
                error_message = 'Unable to get Travis CI repo: {}/{}'.\
                    format(username, repository)
                return index(request, error_message)

            project = Project(package=package,
                              username=username,
                              repository=repository,
                              branch=branch,
                              cargo_support=cargo_support)

            if ('description' in repo and repo['description']):
                project.description = repo['description']
            else:
                project.description = ''
            project.save()

            # Set categories
            project.categories = categories
            project.save()

            return authenticate_with_github(request, project.id, 'add_project')

    else:
        form = ProjectForm(initial={'branch': 'master'})

    context = {
        'title': private_settings.APP_TITLE,
        'form': form,
        'categories': ProjectCategory.objects.all()
    }
    return render(request, 'ppatrigger/project_form.html', context)
Exemple #5
0
def add_project(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)

        if form.is_valid():
            package = form.cleaned_data['package']
            username = form.cleaned_data['username']
            repository = form.cleaned_data['repository']
            branch = form.cleaned_data['branch']
            cargo_support = form.cleaned_data['cargo_support']
            categories = form.cleaned_data['categories']

            repo = travisclient.get_repo(username, repository)

            if not repo:
                error_message = 'Unable to get Travis CI repo: {}/{}'.\
                    format(username, repository)
                return index(request, error_message)

            project = Project(package = package, username = username,
                    repository = repository, branch = branch,
                    cargo_support = cargo_support)
           
            if('description' in repo and repo['description']):
                project.description = repo['description']
            else:
                project.description = ''
            project.save()

            # Set categories
            project.categories = categories
            project.save()

            return authenticate_with_github(request, project.id,
                    'add_project')

    else:
        form = ProjectForm(initial={'branch': 'master'})

    context = {
            'title': private_settings.APP_TITLE,
            'form': form,
            'categories': ProjectCategory.objects.all()
    }
    return render(request, 'ppatrigger/project_form.html', context)
Exemple #6
0
def register(request):
    if request.method == 'POST':
        a = request.POST.get('action')
        if a == 'register':
            register_f = RegisterForm(request.POST)
            login_f = LoginForm()
            if register_f.is_valid():
                try:
                    User.objects.create_user(
                        register_f.cleaned_data['username'],
                        register_f.cleaned_data['email'],
                        register_f.cleaned_data['password'])
                except IntegrityError, e:
                    if 'username' in str(e):
                        register_f.add_error('username',
                                             'Username is taken')
                    elif 'email' in str(e):
                        register_f.add_error('email',
                                             'Email is already registered')
                    else:
                        raise e
                else:
                    user = authenticate(
                        username=register_f.cleaned_data['username'],
                        password=register_f.cleaned_data['password'])
                    login(request, user)
                    Timezone.objects.create(user=user)
                    project = Project()
                    project.user = user
                    project.name = 'default project'
                    project.description = 'default project description'
                    project.color = Project.DEFAULT_COLOR
                    project.save()
                    return redirect('dashboard')
        elif a == 'login':
            register_f = RegisterForm()
            login_f = LoginForm(request.POST)
            if login_f.is_valid():
                user = authenticate(
                    username=login_f.cleaned_data['username'],
                    password=login_f.cleaned_data['password'])
                if user is None:
                    login_f.add_error('username',
                                      'Wrong credentials')
                else:
                    login(request, user)
                    return redirect('dashboard')
        else:
            register_f = RegisterForm()
            login_f = LoginForm()
def get_project(project_id):
    project = None
    list = client.entries({'content_type': 'project', 'sys.id': project_id})

    for item in list:
        project = Project(id=item.id)
        project.cover = item.cover.url()
        project.description = item.description
        project.screens = item.screens
        project.title = item.title
        project.year = item.year

    if project is None:
        abort(404)

    return jsonify(project.serialize())
Exemple #8
0
    def add_project(payload):
        ''' Add/update a new/existing project based on user inputs '''
        to_create = request.method == 'POST'
        body = request.get_json()
        name = body.get('name', None)
        description = body.get('description', None)
        category = body.get('category', None)
        labels = body.get('labels', None)
        image_link = body.get('image_link', None)
        video_link = body.get('video_link', None)
        user_id = 1  # TODO get user_id from Auth info.

        if not name or not description or not category \
                or not labels or not image_link or not video_link:
            abort(
                400, 'invalid inputs of {} project'.format(
                    'new' if to_create else 'update'))

        try:
            if to_create:
                project = Project(name=name,
                                  description=description,
                                  category=category,
                                  labels=labels,
                                  image_link=image_link,
                                  video_link=video_link,
                                  user_id=user_id)
                project.insert()
            else:  # to update
                project = Project.query.filter_by(name=name).one_or_none()
                project.description = description
                project.category = category
                project.labels = labels
                project.image_link = image_link
                project.video_link = video_link
                project.update()
            return jsonify({
                'success': True,
            })
        except Exception:
            flash('An error occur when adding {} project'.format(
                'new' if to_create else 'update'))
            # print(sys.exc_info())
            abort(
                500, 'failed to add {} project'.format(
                    'new' if to_create else 'update'))
 def handle_post(self, email, account_info):
     if self.request.get("project_entity_key"):
         project_key = ndb.Key(urlsafe=self.request.get("project_entity_key"))
         project = project_key.get()
     else:
         project = Project(parent=utils.get_parent_key_for_email(email))
         project_key = project.key
     
     title = self.request.get("title")
     description = self.request.get("description")
     project.title = title
     project.description = description
     
     admin_key_list = []
     admin_list = self.request.get_all("admin_selected")   
     for admin_str in admin_list:
         admin_key = ndb.Key(urlsafe=admin_str)
         admin_key_list.append(admin_key.parent())
     project.administrators = admin_key_list
     
     if self.get_uploads() and len(self.get_uploads()) == 1:
         logging.info("Received an image blob with this profile update.")
         media_blob = self.get_uploads()[0]
         project.picture = media_blob.key()
     else:
         # There is a chance this is an edit in which case we should check for an existing blob key.
         original_blob_key = self.request.get("original_blob_key")
         if original_blob_key:
             logging.info("Attaching original blob key (this must have been an edit or duplicate)")
             project.picture = BlobKey(original_blob_key)
     
     potential_invitees = self.request.get_all("project_collaborator")
     for potential_user in potential_invitees:
         if potential_user and potential_user != utils.get_profile_for_email(email).name:
             profile_query = Profile.query(Profile.name == potential_user)
             for profile in profile_query:
                 user_key = profile.key.parent()
             user = user_key.get()
             if user_key not in project.users:
                 notification_count = Notification.query(Notification.project_key == project_key, 
                                                         ndb.OR(Notification.sender == user_key, 
                                                                Notification.receiver == user_key)).count()
                 if notification_count == 0:
                     notification = Notification(parent=user_key)
                     notification.sender = account_info.key
                     notification.receiver = user_key
                     notification.project_key = project_key
                     notification.message = utils.get_profile_for_email(email).name + " would like you to join " + project.title
                     notification.type = Notification.NotificationTypes.COLLABORATE
                     notification.put()
     
     project_status_str = self.request.get("status")
     if project_status_str == 'ACTIVE':   
         project.status = Project.ProjectStatus.ACTIVE
     elif project_status_str == 'ARCHIVED':
         project.status = Project.ProjectStatus.ARCHIVED
     elif project.status == 'COMPLETED':
         project.status = Project.ProjectStatus.COMPLETED
     
     project.put()
     
     self.redirect(self.request.referer)
Exemple #10
0
    def get(self):
        """ init the datastore with some test data.

        assumes the datastore is clear.
        """
        # a basic check to make sure the datastore is clear
        if Greek.all().count() > 0:
            return

        # Create a project
        kitten = Project()
        kitten.name = "Kitten Rescue"
        kitten.max_volunteers = 3
        kitten.location = "All around Atlanta."
        kitten.type_of_work = "Outdoor"
        kitten.description = "We will save kittens from trees all over Atlanta."
        kitten.put()

        soup = Project()
        soup.name = "Soup Making"
        soup.max_volunteers = 5
        soup.description = "You will make delicious soup."
        soup.put()

        huge = Project()
        huge.name = "Huge Project"
        huge.max_volunteers = 20
        huge.description = "This is a darn huge project. With 20 people what CAN'T we do?"
        huge.put()

        # Make a user with a pending PC app
        u = self.makeBasicUser("pending")
        pc_app = PCApplication(
            response="Here is the sample responses to the questions")
        pc_app.put()
        u.pc_application = pc_app
        u.put()

        # Put a user in the kitten project
        u = self.makeBasicUser("kitten")
        u.project = kitten
        u.put()

        # Create a PC for the soup project
        u = self.makeBasicUser("souppc")
        u.project = soup
        u.is_pc = True
        u.put()

        # Make a group for the HUGE project
        knights_group = Group(name="Knights who say Ni!",
                              password="******",
                              project=huge,
                              slots=5)
        knights_group.put()

        leader = self.makeBasicUser("leader")
        leader.joinGroup(knights_group)
        leader.is_group_leader = True
        leader.is_pc = True
        leader.put()

        knights = ["lancelot", "gawain", "gallahad", "mordred"]
        for knight in knights:
            k = self.makeBasicUser(knight)
            k.joinGroup(knights_group)
            k.put()

        # Make a full project
        full = Project(name="Full Project",
                       max_volunteers=5,
                       description="This was full so quickly...")
        full.put()

        alphabet = "abcdefghijklmnopqrstuvwxyz"
        for j in range(5):
            u = self.makeBasicUser(alphabet[j])
            u.project = full
            u.put()

        # Init the Greek Affliations
        for g_name in GREEK_AFFS:
            g = Greek(name=g_name)
            g.put()

        # Add the possible phases
        phases = [[
            "pc_apps",
            datetime.date(2014, 9, 5),
            datetime.date(2014, 10, 18)
        ],
                  [
                      "group_create",
                      datetime.date(2014, 9, 19),
                      datetime.date(2014, 10, 9)
                  ],
                  [
                      "group_join",
                      datetime.date(2014, 9, 26),
                      datetime.date(2014, 10, 9)
                  ],
                  [
                      "group_registration",
                      datetime.date(2014, 9, 19),
                      datetime.date(2014, 10, 9)
                  ],
                  [
                      "individual_registration",
                      datetime.date(2014, 10, 10),
                      datetime.date(2014, 10, 21)
                  ]]
        for phase_args in phases:
            phase = Phase(name=phase_args[0],
                          start_date=phase_args[1],
                          end_date=phase_args[2])
            phase.put()

        # Add a group that users can join
        nice_group = Group(name="A nice group for nice people",
                           password="******",
                           project=huge,
                           slots=5)
        nice_group.put()

        # Make a user that has no project
        lonely_user = self.makeBasicUser("lonely")
        lonely_user.put()

        return "done"