def post(self, idx, idx1):  # Apply a new activity
        applicant_id = idx
        activity_id = idx1

        # Search if the applicanttion has already existed in
        #  MongoDB collection 'Application'
        applications_exist = Application.objects(applicant_id=applicant_id)
        for application_exist in applications_exist:
            if application_exist.activity_id == activity_id:
                return jsonify("You already applied", 400)

        # Obtain applicant's information from collection 'User'
        user = User.objects(use_id=applicant_id).first()
        applicant_name = user.username

        # Obtain activity information from collection 'Activity'
        activity = Activity.objects(activity_id=activity_id).first()
        activity_name = activity.activity_name

        apply_id = Application.objects.count()
        apply_id += 1
        application = Application(apply_id=apply_id,
                                  applicant_id=applicant_id,
                                  applicant_name=applicant_name,
                                  activity_id=activity_id,
                                  activity_name=activity_name,
                                  status=0)
        application.save()
        return jsonify("Successfully apply", 200)
예제 #2
0
파일: views.py 프로젝트: phonelab/server
def create_or_update_application(request):
    # define default response
    response = {"err": "", "data": ""}
    # create new application
    if request.method == 'GET':
        response['err'] = {'no': 'err0', 'msg': 'sorry no GET'}
        return HttpResponseRedirect('/error/')
    else:

        # post
        params = request.POST
        ## First Save to database
        app = Application(
            user=request.user,
            name=params['name'],
            #package_name = params['package_name'],
            #intent_name  = params['intent_name'],
            description=params['description'],
            type=params['type'],
            active="E"
            #version      = params["version"],
        )

        app.save()
        # Verify Filename is coming in post
        if (request.POST):
            filename = os.path.join(RAW_APP_ROOT, str(app.id) + ".apk")
            filedir = os.path.dirname(filename)
            # create folder for user if it doesn`t exist
            try:
                os.mkdir(filedir)
            except OSError, e:
                if e.errno != errno.EEXIST:
                    print "some problem in creating dir"
                    response['err'] = {
                        'no': 'err1',
                        'msg': 'cannot create dir, failed upload'
                    }
                    raise
            # get file handle
            fileHandle = open(filename, 'wb+')
            # write it out
            for chunk in request.FILES['upload'].chunks():
                #        print chunk
                fileHandle.write(chunk)
            # close file handle
            fileHandle.close()
            #pulling package name from apk file
            #apktool extract apk file to a directory
            #      os.system('bin/apktool d ' + filename)
            #      with open(str(app.id) + '/AndroidManifest.xml', 'rt') as f:
            #        tree = ElementTree.parse(f)
            #      for node in tree.iter('manifest'):
            #        package = node.attrib.get('package')
            #      Application.objects.filter(id=app.id).update(package_name=package)
            #remove the directory
            #      os.system('rm -rf ' + str(app.id))
            # success msg
            response['data'] = "done"
        else:
예제 #3
0
    def handle(self, *args, **options):
        """
        Function that creates Users and Applications to make testing easier.
        To run use -- python manage.py shell < shared/seed.py
        WARNING - Will delete most of the Users and Applications when run.
        DO not use in production
        """
        self.stdout.write("Starting the seeding process.")
        num_users = options["num_users"]
        num_active = options["num_active"]
        num_apps = options["num_applications"]

        assert num_users >= num_active >= num_apps
        User.objects.filter(is_superuser=False).delete()
        Application.objects.filter(last_name=LAST_NAME).delete()
        Wave.objects.all().delete()

        wave_start = timezone.now()
        wave_end = wave_start + timedelta(days=10)
        wave = Wave(start=wave_start, end=wave_end, num_days_to_rsvp=5)
        wave.full_clean()
        wave.save()

        seeds = []
        for i in range(num_users):
            random_name = random.choice(COMMON_NAMES)
            email = random_name + str(i) + "@seed.com"
            is_active = True if i < num_active else False
            will_apply = True if i < num_apps else False
            user = User.objects.create_user(email, PASSWORD, is_active=is_active)
            seeds.append((user, will_apply, random_name))
        random.shuffle(seeds)

        for user, will_apply, random_name in seeds:
            if will_apply:
                application = Application(
                    first_name=random_name,
                    last_name=LAST_NAME,
                    notes="",
                    major="Major",
                    race=[random.choice(RACES[1:])[0]],
                    classification=random.choice(CLASSIFICATIONS[1:])[0],
                    gender=random.choice(GENDERS[1:])[0],
                    grad_year=random.choice(GRAD_YEARS[1:])[0],
                    num_hackathons_attended=random.choice(HACKATHON_TIMES[1:])[0],
                    extra_links="a",
                    question1="b",
                    question2="c",
                    question3="d",
                    status=random.choice([STATUS_PENDING, STATUS_ADMITTED]),
                    agree_to_coc=True,
                    is_adult=True,
                    additional_accommodations="",
                    resume="f.pdf",
                    wave_id=wave.pk,
                    user_id=user.pk,
                )
                application.save()
예제 #4
0
def apply_for_job(request, pk):
    if request.method == 'POST':
        job = Job.objects.get(id=pk)
        if not Application.objects.filter(user=request.user.id, job=job).exists():
            application_object = Application(user=request.user, job=job, queue=job.applications_process.queue_set.get(position=1))
            application_object.save()
        return HttpResponseRedirect(reverse_lazy('user-job-list'))
    else:
        return HttpResponse(request)
예제 #5
0
    def test_admins_can_view_user_apps_in_context(self):
        self.client.force_login(self.admin)
        self.create_active_wave()
        application = Application(**self.application_fields, wave=self.wave1)
        application.save()
        self.user.application = application
        self.user.save()

        response: HttpResponse = self.client.get(
            reverse_lazy("application:update", args=(application.id, )), )
        self.assertEqual(response.status_code, 200)
예제 #6
0
    def test_accessible_after_login(self) -> None:
        self.client.force_login(self.user)
        self.create_active_wave()
        application = Application(**self.application_fields, wave=self.wave1)
        application.save()
        self.user.application = application
        self.user.save()

        response: HttpResponse = self.client.get(
            reverse_lazy("application:update", args=(application.id, )))

        self.assertEqual(response.status_code, 200)
예제 #7
0
파일: views.py 프로젝트: jay123/server
def create_or_update_application(request):
  # define default response
  response = { "err": "", "data": "" }
  # create new application
  if request.method == 'GET':
    response['err'] = {
      'no' : 'err0',
      'msg': 'sorry no GET'
    }
    return HttpResponseRedirect('/error/')
  else:
    # post 
    params = request.POST
    ## First Save to database
    app = Application(
        name          = params['name'], 
        package_name  = params['package_name'],
        intent_name   = params['intent_name'],
        description   = params['description'],
        type          = params['type'],
        version       = params["version"],
    )
    app.save()
    # Verify Filename is coming in post
    if (request.POST):
      filename = os.path.join(RAW_APP_ROOT, str(app.id) + ".apk")
      filedir = os.path.dirname(filename)
      print filename
      print filedir
      # create folder for user if it doesn`t exist
      try:
        os.mkdir(filedir)
      except OSError, e:
        if e.errno != errno.EEXIST:
          print "some problem in creating dir"
          response['err'] = {
            'no' : 'err1', 
            'msg': 'cannot create dir, failed upload'
          }
          raise
      # get file handle
      fileHandle = open(filename, 'wb+')
      # write it out
      for chunk in request.FILES['upload'].chunks():
#        print chunk
        fileHandle.write(chunk)
      # close file handle
      fileHandle.close()
      # success msg
      response['data'] = "done"
    else:
예제 #8
0
    def test_requires_login(self) -> None:
        self.create_active_wave()
        application = Application(**self.application_fields, wave=self.wave1)
        application.save()
        self.user.application = application
        self.user.save()

        response: HttpResponse = self.client.get(
            reverse_lazy("application:update", args=(application.id, )))

        self.assertRedirects(
            response,
            f"{reverse_lazy('customauth:login')}?next={reverse_lazy('application:update', args=(application.id,))}",
        )
예제 #9
0
파일: views.py 프로젝트: jay123/server
def create_or_update_application(request):
    # define default response
    response = {"err": "", "data": ""}
    # create new application
    if request.method == 'GET':
        response['err'] = {'no': 'err0', 'msg': 'sorry no GET'}
        return HttpResponseRedirect('/error/')
    else:
        # post
        params = request.POST
        ## First Save to database
        app = Application(
            name=params['name'],
            package_name=params['package_name'],
            intent_name=params['intent_name'],
            description=params['description'],
            type=params['type'],
            version=params["version"],
        )
        app.save()
        # Verify Filename is coming in post
        if (request.POST):
            filename = os.path.join(RAW_APP_ROOT, str(app.id) + ".apk")
            filedir = os.path.dirname(filename)
            print filename
            print filedir
            # create folder for user if it doesn`t exist
            try:
                os.mkdir(filedir)
            except OSError, e:
                if e.errno != errno.EEXIST:
                    print "some problem in creating dir"
                    response['err'] = {
                        'no': 'err1',
                        'msg': 'cannot create dir, failed upload'
                    }
                    raise
            # get file handle
            fileHandle = open(filename, 'wb+')
            # write it out
            for chunk in request.FILES['upload'].chunks():
                #        print chunk
                fileHandle.write(chunk)
            # close file handle
            fileHandle.close()
            # success msg
            response['data'] = "done"
        else:
예제 #10
0
    def test_attr_to_dict(self):
        application1 = Application(
            name='application1',
            description='testapp',
            client_type=Application.CLIENT_CONFIDENTIAL,
            authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
            redirect_uris='http://localhost:7000/',
            is_anonymous=True,
            required_scopes='send_mail picture',
        )
        result_dict = attr_to_dict(application1)
        self.assertDictContainsSubset({
            'name': 'application1',
            'description': 'testapp',
            'client_type': 'confidential',
            'authorization_grant_type': 'authorization-code',
            'redirect_uris': 'http://localhost:7000/',
            'is_anonymous': True,
            'required_scopes': 'send_mail picture',
        }, result_dict)

        dict_test = {'key': 'foo', 'value': 'bar'}
        self.assertDictEqual(dict_test, attr_to_dict(dict_test))

        self.assertDictEqual({'foo': 'bar'}, attr_to_dict('bar', key='foo'))
예제 #11
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = Application.query.filter_by(email=form.email.data).first()
        if user:
            blacklisted_user = ApplicationBlacklist.query.filter_by(
                application_id=user.id).first()
            if blacklisted_user:
                flash('The email entered has been blacklisted')
                return redirect(url_for('login'))

            if user.is_pending:
                flash(
                    'Your application still under review, Please try again later'
                )
                return redirect(url_for('login'))

        user2 = Application(name=form.name.data,
                            last_name=form.lastName.data,
                            email=form.email.data,
                            interest=form.interest.data,
                            credentials=form.credentials.data,
                            reference=form.reference.data)
        db.session.add(user2)
        db.session.commit()
        flash('Your application has been sent.', 'success')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
예제 #12
0
def application(request,pk):
    questions=QuestionAnswer.objects.filter(course__pk=pk)
    course=Course.objects.get(pk=pk)
    current_user=request.user

    # courses=Course.objects.all()
    if request.method == "POST":
        num_results = Application.objects.filter(course=course,user=current_user).count()
        if num_results >= 1:
            return redirect('application:already')
        else:
            answer=request.POST.getlist('answer')
            application=Application(course=course,user=current_user,answer=answer)
            application.save()

            return redirect('application:email_sent')

    return render(request, 'application.html', {'questions': questions})
예제 #13
0
    def put(self, idx):
        accept = request.form.get("accept")
        reject = request.form.get("reject")
        applicant_name = request.form.get("applicant")
        activity_name = request.form.get("project")
        activity_name = activity_name

        if accept:
            application = Application.objects(
                activity_name=activity_name).first()
            application.update(status=1)

            return jsonify("The applicant successfully attend your activity",
                           200)

        elif reject:
            activity = Application.objects(activity_name=activity_name).first()
            activity.update(status=-1)

            return jsonify("The applicant fails to attend your activity", 200)
예제 #14
0
 def test_default_scopes(self):
     application1 = Application(
         name='application1',
         description='testapp',
         client_type=Application.CLIENT_CONFIDENTIAL,
         authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
         redirect_uris='http://localhost:7000/',
         is_anonymous=True,
         required_scopes='send_mail picture',
     )
     six.assertCountEqual(self, ['send_mail', 'picture'], get_default_scopes(application1))
     application2 = Application(
         name='application2',
         description='testapp',
         client_type=Application.CLIENT_CONFIDENTIAL,
         authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
         redirect_uris='http://localhost:7000/',
         required_scopes='send_mail picture',
     )
     six.assertCountEqual(self, settings.OAUTH2_DEFAULT_SCOPES, get_default_scopes(application2))
예제 #15
0
    def test_doesnt_change_wave(self) -> None:
        self.create_active_wave()
        application = Application(**self.application_fields, wave=self.wave1)
        application.save()
        self.user.application = application
        self.user.save()
        self.application_fields["resume"] = SimpleUploadedFile(
            "resume2.pdf", b"dummy")

        self.client.post(
            reverse_lazy("application:update", args=(application.id, )),
            data=self.application_fields,
        )

        application.refresh_from_db()
        self.assertEqual(application.wave, self.wave1)
예제 #16
0
    def post(self, idx):
        # The activities the user attended
        user_id = idx  # idx = user_id
        applications = Application.objects(applicant_id=user_id)
        apply_activities = []

        if applications:
            for application in applications:
                activity_id = application.activity_id
                activity_id = activity_id
                status = application.status

                activity = Activity.objects(activity_id=activity_id).first()

                activity_name = activity.activity_name
                open_date = activity.open_date
                genre = activity.genre
                leader_name = activity.leader_name

                open_date_local = time.local(open_date)
                format_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                            open_date_local)

                apply_activity_dict = {
                    "Project_Name": activity_name,
                    "Deadline": open_date,
                    "Deadline": format_time,
                    "Major": genre,
                    "Leader": leader_name,
                    "Application Status": status
                }

                apply_activities.append(apply_activity_dict)

            return jsonify(apply_activities, 200)

        return jsonify("You don't have any applied acticities", 400)
예제 #17
0
    def get(self, idx):  # idx = user_id
        user_id = idx
        activities = Activity.objects(leader_id=user_id).all()
        create_activities = []

        if activities:
            for activity in activities:

                activity_name = activity.activity_name
                applications = Application.objects(
                    activity_name=activity_name).all()
                application_list_zero = []
                application_list_one = []
                for application in applications:
                    if application.status == 0:
                        application_list_zero.append(application.applicant_id)
                    elif application.status == 1:
                        application_list_one.append(application.applicant_id)
                activity_id = activity.activity_id
                activity_name = activity.activity_name
                open_date = activity.open_date
                genre = activity.genre

                # '0': the application has not been decided by the leader
                # '1': the application is successful
                create_activity_dict = {
                    "Project_Name": activity_name,
                    "Deadline": open_date,
                    "Major": genre,
                    "0": application_list_zero,
                    "1": application_list_one
                }

                create_activities.append(create_activity_dict)
            return jsonify(create_activities, 200)

        return add_cors(jsonify("You do not have any created acticities", 400))
예제 #18
0
def addDefaultLog(request):
    if Application.authorize(request):

        try:
            appName = request.META['HTTP_APPNAME']
            logValue = request.POST['LOGVALUE']
            logType = request.POST['LOGTYPE']
        except KeyError:
            return JSONResponse(Response.BADREQUEST)

        try:
            app = Application.objects.get(appName=appName)
        except Application.DoesNotExist or Application.MultipleObjectsReturned:
            return JSONResponse(Response.BADREQUEST)

        if logValue and logType and appName:
            defaultLog = DefaultLog()
            if defaultLog.create(app, logValue, logType):
                return JSONResponse(Response.OK)
            else:
                return JSONResponse(Response.BADREQUEST)

    else:
        return JSONResponse(Response.UNAUTHORIZED)
예제 #19
0
    def test_actually_changes_application(self) -> None:
        self.client.force_login(self.user)
        self.create_active_wave()
        application = Application(**self.application_fields, wave=self.wave1)
        application.save()
        self.user.application = application
        self.user.save()
        new_first_name = "Mack"
        self.application_fields["first_name"] = new_first_name
        self.application_fields["resume"] = SimpleUploadedFile(
            "resume2.pdf", b"dummy")

        self.client.post(
            reverse_lazy("application:update", args=(application.id, )),
            data=self.application_fields,
        )

        application.refresh_from_db()
        self.assertEqual(application.first_name, new_first_name)
예제 #20
0
    def test_only_owner_can_view_application(self) -> None:
        self.client.force_login(self.user2)
        self.create_active_wave()
        application = Application(**self.application_fields, wave=self.wave1)
        application.save()
        self.user.application = application
        self.user.save()
        new_first_name = "Mack"
        self.application_fields["first_name"] = new_first_name
        self.application_fields["resume"] = SimpleUploadedFile(
            "resume2.pdf", b"dummy")

        response: HttpResponse = self.client.post(
            reverse_lazy("application:update", args=(application.id, )),
            data=self.application_fields,
        )
        self.assertEqual(response.status_code, 403)
        application.refresh_from_db()
        self.assertNotEqual(application.first_name, new_first_name)
예제 #21
0
def handle_application_csv(csv_file):
	csv_file_text_mode = codecs.iterdecode(csv_file, "utf-8")
	csv_reader = csv.reader(csv_file_text_mode, delimiter=',')
	for row in csv_reader:
		try:
			email = row[0]
			date_commitment = True if row[1] == "1" else False
			name = row[2]
			faculty = row[3]
			other_faculty = row[4]
			project_name = row[5]
			idea = row[6]
			fit_for_blue = row[7]
			media_link = row[8]
			country = row[9]
			year = row[10]
			valid = True
			application = Application(email=email, 
					date_commitment=date_commitment, 
					name=name, 
					faculty=faculty, 
					other_faculty=other_faculty, 
					project_name=project_name, 
					idea=idea, 
					fit_for_blue=fit_for_blue, 
					media_link=media_link, 
					country=country, 
					year=year, 
					valid=valid)
			application.full_clean()
		except ValidationError as e:
			"""Fields are not valid."""
			print('; '.join(e.messages))
			return True, "The csv fields are not valid."
		else:
			application.save()
	return False, "Uploaded applications"
예제 #22
0
    return json.loads(file(json_path, 'r').read())

json_apps = get_apps_json(JSON_FILE)
print "len json_apps=", len(json_apps)

model = models.get_model('application', 'Application')

# TODO: Are (Null)Boolean fields saved properly?
# TODO: cm_resubmit_{date,time} fields to single DateTime

total_apps = len(json_apps)
logging.info("TOTAL APPS=%d" % total_apps)
num_apps = 0
for json_app in json_apps:
    num_apps += 1
    app = Application()
    app.save()                  # save for M2M
    logging.info("APP %d %d%%: %s %s" % (
            num_apps, int(100 * num_apps / total_apps),
            json_app['acronym'], json_app['release']))
    for k,v in json_app.items(): # Do we need to strip values?
        # Skip junk
        if k in UNUSED_FIELDS:
            continue
        if isinstance(v, list): # filter Nulls from M2M lists
            v = [vv for vv in v if not v in NULLISH_VALUES]
        if v in NULLISH_VALUES: # Don't bother storing empty data
            #logging.info("NULL k=%s v=%s" % (k,v))
            continue
        if not v:               # Don't bother storing empty data or list
            continue
예제 #23
0
파일: views.py 프로젝트: phonelab/server
def create_experiment(request):

    # define default response
    response = {"err": "", "data": ""}

    # initialize a counter for apps
    i = 0
    j = 0

    # initialize filename
    filenames = {}
    filedirs = {}

    if request.POST:

        period = request.POST["duration"]
        unit = request.POST["dur_unit"]

        if unit == "W":
            period = int(period) * 7
        elif unit == "M":
            period = int(period) * 30

            # Save Experiment
        exp = Experiment(
            name=request.POST["expname"], description=request.POST["expdesc"], tag=request.POST["exptag"], period=period
        )
        exp.save()

        # upload IRB Letter
        file_type = request.FILES["irbletter"].content_type.split("/")[1]

        # save IRB Letter
        irbname = os.path.join(RAW_IRB_ROOT, str(exp.irb) + "." + file_type)
        irbdir = os.path.dirname(irbname)

        try:
            os.mkdir(irbdir)
        except OSError, e:
            if e.errno != errno.EEXIST:
                response["err"] = {"no": "err1", "msg": "cannot create dir, failed upload"}
                raise

                # get file handle
        fileHandle = open(irbname, "wb+")
        for chunk in request.FILES["irbletter"].chunks():
            # write it out
            fileHandle.write(chunk)
            # close file handle
        fileHandle.close()

        response["data"] = "done"

        # add user to the experiment
        exp.user.add(request.user)

        devs = Device.objects.all()
        appnames = request.POST.getlist("appname")
        appdescs = request.POST.getlist("appdesc")
        apptypes = request.POST.getlist("apptype")

        # add the devices to the experiment
        for dev in devs:
            exp.dev.add(dev)

            # add the apps to the experiment
        for app in appnames:

            application = Application(
                user=request.user,
                name=app,
                # package_name = params['package_name'],
                # intent_name  = params['intent_name'],
                description=appdescs[i],
                type=apptypes[i],
                active="E",
            )

            # version      = params["version"],
            application.save()
            exp.app.add(application)
            i = i + 1

            # create dirs for Applications
            filename = os.path.join(RAW_APP_ROOT, str(application.id) + ".apk")
            filedir = os.path.dirname(filename)
            filenames[app] = filename
            filedirs[app] = filedir

        exp.save()

        exp_profile = ExperimentProfile(experiment=exp)
        exp_profile.starttime = datetime.now()
        exp_profile.endtime = datetime.now()
        exp_profile.save()

        # upload experiment
        for afile in request.FILES.getlist("upload"):
            # create folder for user if it doesn`t exist
            try:
                os.mkdir(filedirs[appnames[j]])
            except OSError, e:
                if e.errno != errno.EEXIST:
                    response["err"] = {"no": "err1", "msg": "cannot create dir, failed upload"}
                    raise

                    # get file handle
            fileHandle = open(filenames[appnames[j]], "wb+")
            # write it out
            for chunk in afile.chunks():
                fileHandle.write(chunk)
                # close file handle
            fileHandle.close()
            j = j + 1
            response["data"] = "done"
예제 #24
0
 def test_renames_file_to_uuid(self):
     self.create_active_wave()
     application = Application(**self.application_fields, wave=self.wave1)
     application.save()
     self.assertNotEqual(self.resume_file_name, application.resume.name)
예제 #25
0
파일: views.py 프로젝트: phonelab/server
def new(request):
    app = Application()
    # query the database for all applications
    return render_to_response('application/form.html', {'app': app},
                              context_instance=RequestContext(request))
예제 #26
0
class ApplicationAdminTestCase(test_case.SharedTestCase):
    def setUp(self):
        super().setUp()
        self.create_active_wave()
        self.app = Application(**self.application_fields, wave=self.wave1)
        self.app.full_clean()
        self.app.save()

    def test_approval_email_customizes_event_name(self):
        event_name = "BIGGEST HACKATHON EVER"
        with self.settings(EVENT_NAME=event_name):
            subject, *_ = build_approval_email(self.app, timezone.now())
            self.assertIn(event_name, subject)

    def test_approval_email_customizes_organizer_email(self):
        organizer_email = "*****@*****.**"
        with self.settings(ORGANIZER_EMAIL=organizer_email):
            _, message, *_ = build_approval_email(self.app, timezone.now())
            self.assertIn(organizer_email, message)

    def test_approval_email_customizes_user_first_name(self):
        _, message, *_ = build_approval_email(self.app, timezone.now())

        self.assertIn(self.app.first_name, message)

    def test_rejection_email_customizes_event_name(self):
        event_name = "BIGGEST HACKATHON EVER"
        with self.settings(EVENT_NAME=event_name):
            subject, *_ = build_rejection_email(self.app)
            self.assertIn(event_name, subject)

    def test_rejection_email_customizes_first_name(self):
        _, message, *_ = build_rejection_email(self.app)

        self.assertIn(self.app.first_name, message)

    def test_approval_action_approves_application(self):
        self.client.force_login(self.admin)
        change_url = reverse_lazy("admin:application_application_changelist")

        self.client.post(
            change_url,
            {
                "action": "approve",
                admin.ACTION_CHECKBOX_NAME: [self.app.pk]
            },
            follow=True,
        )

        self.app.refresh_from_db()
        self.assertEqual(self.app.status, STATUS_ADMITTED)

    def test_approval_action_sends_approval_email(self):
        self.client.force_login(self.admin)
        change_url = reverse_lazy("admin:application_application_changelist")

        self.client.post(change_url, {
            "action": "approve",
            admin.ACTION_CHECKBOX_NAME: [self.app.pk]
        })

        self.assertEqual(len(mail.outbox), 1)

    def test_reject_action_sends_rejection_email(self):
        self.client.force_login(self.admin)
        change_url = reverse_lazy("admin:application_application_changelist")

        self.client.post(
            change_url,
            {
                "action": "reject",
                admin.ACTION_CHECKBOX_NAME: [self.app.pk]
            },
            follow=True,
        )

        self.assertEqual(len(mail.outbox), 1)

    def test_reject_action_rejects_application(self):
        self.client.force_login(self.admin)
        change_url = reverse_lazy("admin:application_application_changelist")
        self.client.post(
            change_url,
            {
                "action": "reject",
                admin.ACTION_CHECKBOX_NAME: [self.app.pk]
            },
            follow=True,
        )
        self.app.refresh_from_db()
        self.assertEqual(self.app.status, STATUS_REJECTED)

    def test_export_application_emails(self):
        self.client.force_login(self.admin)
        change_url = reverse_lazy("admin:application_application_changelist")
        response = self.client.post(
            change_url,
            {
                "action": "export_application_emails",
                admin.ACTION_CHECKBOX_NAME: [self.app.pk],
            },
            follow=True,
        )
        self.assertEqual(response.status_code, 200)

    def test_resend_confirmation_email(self):
        self.client.force_login(self.admin)
        change_url = reverse_lazy("admin:application_application_changelist")
        response = self.client.post(
            change_url,
            {
                "action": "resend_confirmation",
                admin.ACTION_CHECKBOX_NAME: [self.app.pk],
            },
            follow=True,
        )
        self.assertEqual(response.status_code, 200)

        self.assertEqual(len(mail.outbox), 1)
예제 #27
0
파일: views.py 프로젝트: phonelab/server
def create_experiment(request):

    # define default response
    response = {"err": "", "data": ""}

    #initialize a counter for apps
    i = 0
    j = 0

    #initialize filename
    filenames = {}
    filedirs = {}

    if request.POST:

        period = request.POST['duration']
        unit = request.POST['dur_unit']

        if unit == 'W':
            period = int(period) * 7
        elif unit == 'M':
            period = int(period) * 30

        # Save Experiment
        exp = Experiment(
            name=request.POST['expname'],
            description=request.POST['expdesc'],
            tag=request.POST['exptag'],
            period=period,
        )
        exp.save()

        #upload IRB Letter
        file_type = request.FILES['irbletter'].content_type.split('/')[1]

        #save IRB Letter
        irbname = os.path.join(RAW_IRB_ROOT, str(exp.irb) + '.' + file_type)
        irbdir = os.path.dirname(irbname)

        try:
            os.mkdir(irbdir)
        except OSError, e:
            if e.errno != errno.EEXIST:
                response['err'] = {
                    'no': 'err1',
                    'msg': 'cannot create dir, failed upload'
                }
                raise

        # get file handle
        fileHandle = open(irbname, 'wb+')
        for chunk in request.FILES['irbletter'].chunks():
            # write it out
            fileHandle.write(chunk)
        # close file handle
        fileHandle.close()

        response['data'] = "done"

        #add user to the experiment
        exp.user.add(request.user)

        devs = Device.objects.all()
        appnames = request.POST.getlist('appname')
        appdescs = request.POST.getlist('appdesc')
        apptypes = request.POST.getlist('apptype')

        #add the devices to the experiment
        for dev in devs:
            exp.dev.add(dev)

        #add the apps to the experiment
        for app in appnames:

            application = Application(
                user=request.user,
                name=app,
                #package_name = params['package_name'],
                #intent_name  = params['intent_name'],
                description=appdescs[i],
                type=apptypes[i],
                active="E")

            #version      = params["version"],
            application.save()
            exp.app.add(application)
            i = i + 1

            #create dirs for Applications
            filename = os.path.join(RAW_APP_ROOT, str(application.id) + ".apk")
            filedir = os.path.dirname(filename)
            filenames[app] = filename
            filedirs[app] = filedir

        exp.save()

        exp_profile = ExperimentProfile(experiment=exp)
        exp_profile.starttime = datetime.now()
        exp_profile.endtime = datetime.now()
        exp_profile.save()

        #upload experiment
        for afile in request.FILES.getlist('upload'):
            # create folder for user if it doesn`t exist
            try:
                os.mkdir(filedirs[appnames[j]])
            except OSError, e:
                if e.errno != errno.EEXIST:
                    response['err'] = {
                        'no': 'err1',
                        'msg': 'cannot create dir, failed upload'
                    }
                    raise

            # get file handle
            fileHandle = open(filenames[appnames[j]], 'wb+')
            # write it out
            for chunk in afile.chunks():
                fileHandle.write(chunk)
            # close file handle
            fileHandle.close()
            j = j + 1
            response['data'] = "done"
예제 #28
0
 def setUp(self):
     super().setUp()
     self.create_active_wave()
     self.app = Application(**self.application_fields, wave=self.wave1)
     self.app.full_clean()
     self.app.save()
예제 #29
0
def home(request):
    # create_team_view(request)
    context = {}
    no_teams_found = False
    try:
        profile = ParticipantProfile.objects.get(user=request.user)
    except ParticipantProfile.DoesNotExist:
        return redirect('profile-update')
    # print(application)
    # print(len(application))
    if request.user.is_authenticated:
        application = Application.objects.filter(members__id=request.user.id)
        if not (len(application) == 0):
            application = application[0]
            context['application'] = application
            team = application.team
            print("team ind")
            user_has_team = True
            context['users_team'] = team
        else:
            team = Team(admin=request.user)
            print("team indaakki")
            # team.save()
            user_has_team = False

            # try:
            #     application = application[0]
            #     team = application.team
            #     print("team ind")
            #     user_has_team = True
            #     context['users_team'] = team
            # except Team.DoesNotExist:
            #     team = Team(admin = request.user)
            #     print("team indaakki")
            #     # team.save()
            #     user_has_team = False

        # try:
        #     application = Application.objects.get(team=team)
        #     print("has team")
        #     print(team.application_team.team.name)
        # except Application.DoesNotExist:
        #     application = Application(team = team)
        #     application.save()
        #     application.members.add(request.user)
        #     # application.save()
        #     print("created Team")

        team_form = TeamCreateForm()
        context['team_form'] = team_form
        search_form = TeamSearchForm()
        context['search_form'] = search_form
        context['user_has_team'] = user_has_team
        # context['application'] = application
        if request.POST:
            # team_form = TeamCreateForm(request.POST)
            # search_form = TeamSearchForm(request.POST)
            if "create_team" in request.POST:
                team_form = TeamCreateForm(request.POST)
                if team_form.is_valid():  #TODO searching for teams to join
                    if user_has_team:
                        context['message'] = 'You already have a team!!'
                        return render(request, 'messages.html', context)
                    else:
                        team = team_form.save(commit=False)
                        team.admin = request.user
                        # request.user.team.add(team)
                        # team.strength = 1
                        # team.application_status = 'Not Submitted'
                        team.save()

                        try:
                            application = Application.objects.get(team=team)
                            print("has team")
                            context['application'] = application
                            print(team.application_team.team.name)
                        except Application.DoesNotExist:
                            application = Application(team=team)
                            application.save()
                            application.members.add(request.user)
                            ctx = {
                                'user': request.user,
                                'team_name': application.team.name,
                                "team_id": application.team.id
                            }
                            message = get_template(
                                'emails/team_created.html').render(ctx)
                            # msg = EmailMessage(
                            #     "Team Created",
                            #     message,
                            #     '*****@*****.**',
                            #     [request.user.email],
                            #     )
                            # msg.content_subtype = "html"
                            # msg.send()
                            subject = "Team Created"
                            recepient_list = [request.user.email]
                            EmailThread(subject, message,
                                        recepient_list).start()

                            print("Team Created message sent")
                            # application.save()
                            print("created Team")
                            context['application'] = application

                        # application = Application(team = team)
                        # # application.save()
                        # application.save()
                        # application.members.add(request.user)
                        # context['application'] = application

                        # team = team_form.save()
                        # request.user.team.add(team)
                        # user_obj = team_form.save()
                        # user_obj.team.add(team)
                        # context['message'] = 'Team Created Successfully'
                        # return render(request, 'home.html', context )
                        return redirect('home')
                else:
                    context['team_form'] = team_form

            elif "search_team" in request.POST:
                # conext['search_performed'] = True
                search_form = TeamSearchForm(request.POST)
                if search_form.is_valid():
                    team_id = search_form.cleaned_data.get('team_id')
                    try:
                        searched_team = Team.objects.get(id=team_id)
                        context['searched_team'] = searched_team
                    except Team.DoesNotExist:
                        no_teams_found = True
                        context['no_teams_found'] = no_teams_found
                else:
                    context['search_form'] = search_form
            # elif "accept_request" in request.POST:
            #     try:
            #         application = Application.objects.get(team=team)
            #         # print("has team")
            #         context['application'] = application
            #         application.members.add(request.user)
            #         application.save()
            #         # request.user.request_team.request_status = "Accepted"
            #         # request.user.join_request.request_status = "Accepted"
            #         print(team.application_team.team.name)
            #     except Application.DoesNotExist:
            #         pass
            # elif "decline_request" in request.POST:
            #     pass
        else:
            team_form = TeamCreateForm(initial={
                # 'name': team.name,
            })
            context['team_form'] = team_form
            search_form = TeamSearchForm(initial={})
            context['search_form'] = search_form

        # try:
        #     application = Application.objects.get(team=team)
        #     # context['user_has_team'] = True
        #     print("has team")
        #     context['application'] = application
        #     print(team.application_team.team.name)
        # except Application.DoesNotExist:
        #     print("except of appli in end executed")

        # if team.admin == request.user:
        #     join_requests = JoinRequest.objects.filter(team=team, request_status="Submitted")
        #     context['join_requests'] = join_requests
    return render(request, 'home.html', context)
예제 #30
0
파일: views.py 프로젝트: phonelab/server
def create_or_update_application(request):
  # define default response
  response = { "err": "", "data": "" }
  # create new application
  if request.method == 'GET':
    response['err'] = {
      'no' : 'err0',
      'msg': 'sorry no GET'
    }
    return HttpResponseRedirect('/error/')
  else:
 
    # post 
    params = request.POST
    ## First Save to database
    app = Application(
        user          = request.user,
        name          = params['name'], 
        #package_name = params['package_name'],
        #intent_name  = params['intent_name'],
        description   = params['description'],
        type          = params['type'],
        active        = "E"
        #version      = params["version"],
    )
    
    app.save()
    # Verify Filename is coming in post
    if (request.POST):
      filename = os.path.join(RAW_APP_ROOT, str(app.id) + ".apk")
      filedir = os.path.dirname(filename)
      # create folder for user if it doesn`t exist
      try:
        os.mkdir(filedir)
      except OSError, e:
        if e.errno != errno.EEXIST:
          print "some problem in creating dir"
          response['err'] = {
            'no' : 'err1', 
            'msg': 'cannot create dir, failed upload'
          }
          raise
      # get file handle
      fileHandle = open(filename, 'wb+')
      # write it out
      for chunk in request.FILES['upload'].chunks():
#        print chunk
        fileHandle.write(chunk)
      # close file handle
      fileHandle.close()
      #pulling package name from apk file
      #apktool extract apk file to a directory
#      os.system('bin/apktool d ' + filename)
#      with open(str(app.id) + '/AndroidManifest.xml', 'rt') as f:
#        tree = ElementTree.parse(f)
#      for node in tree.iter('manifest'):
#        package = node.attrib.get('package')
#      Application.objects.filter(id=app.id).update(package_name=package)
      #remove the directory 
#      os.system('rm -rf ' + str(app.id))
      # success msg
      response['data'] = "done"
    else: