コード例 #1
0
ファイル: app.py プロジェクト: cjbvt/SpareME
def stats():
    """
    Get a list of all the given user's stats.
    """
    try:
        id_token = request.form['id_token']
        uid = verify_id_token(id_token)
    except KeyError:
        return "id_token required", status.HTTP_400_BAD_REQUEST
    except ValueError:
        return "id_token unrecognized", status.HTTP_400_BAD_REQUEST
    except auth.AuthError as exc:
        if exc.code == 'ID_TOKEN_REVOKED':
            return "id_token revoked", status.HTTP_400_BAD_REQUEST
        else:
            return "id_token invalid", status.HTTP_400_BAD_REQUEST
    session = Session()
    try:
        stats = dal.get_stats(session, uid)
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()
        Session.remove()
    return json.dumps(stats), status.HTTP_200_OK
コード例 #2
0
ファイル: apis.py プロジェクト: GetMeKnown/IdentiChip
	def get(self):

		# Get the Client for stats on a provider
		client_obj = False

		# Do the authentication
		if self.request.get('token'):

			# They did so now let's check the client
			client_obj = authenticate_client(str(self.request.get('token')))

			# Well was it valid ?
			if client_obj is False:
				# Inform them
				self.response.out.write(json.dumps({
						'error': 'No such client found. Invalid Token !'
					}))

				# Stop the request
				return

		# Build our params or errors
		(params, errors) = build_search_params(client_obj, self.request)

		# Check if there was any errors
		if len(errors) > 0:
			self.response.out.write(json.dumps({ 'errors': errors }))
		else:

			# Object to return
			stats = {}

			# Get the RAW responses from DB.
			responses = dal.get_stats(params)

			# Object to return
			stats = {}

			# Parse out Countries
			country_response = dal.parse_out_countries(responses)
			for country_code in country_response:

				# If found is there
				if 'found' in country_response[country_code]:
					stats[str(country_code)]  = int(country_response[country_code]["found"])
				else:
					stats[str(country_code)]  = 0
			
			# Output that list !
			self.response.out.write(json.dumps(stats))
コード例 #3
0
ファイル: apis.py プロジェクト: GetMeKnown/IdentiChip
	def get(self):

		# Get the Client for stats on a provider
		client_obj = False

		# Do the authentication
		if self.request.get('token'):

			# They did so now let's check the client
			client_obj = authenticate_client(str(self.request.get('token')))

			# Well was it valid ?
			if client_obj is False:
				# Inform them
				self.response.out.write(json.dumps({
						'error': 'No such client found. Invalid Token !'
					}))

				# Stop the request
				return

		# Build our params or errors
		(params, errors) = build_search_params(client_obj, self.request)

		# Create the output Object
		output = {}

		# Go through each month in the year
		for year in xrange(2012, int(time.strftime("%Y"))+1):

			# Set current year
			params.year = int(year)

			# Get the stats
			responses = dal.get_stats(params)

			# List of weeks
			weeks = []

			# Look each week in this month !
			for week in dal.parse_out_weeks(year, responses):
				weeks.append(int(week['found']))

			# Add Values to single looping value
			output[str(year)] = dal.parse_out_general_count(responses)
			output[str(year)]["weeks"] = weeks

		# Output to response
		self.response.out.write(json.dumps(output))
コード例 #4
0
ファイル: apis.py プロジェクト: GetMeKnown/IdentiChip
	def get(self):

		# Get the Client for stats on a provider
		client_obj = False

		# Do the authentication
		if self.request.get('token'):

			# They did so now let's check the client
			client_obj = authenticate_client(str(self.request.get('token')))

			# Well was it valid ?
			if client_obj is False:
				# Inform them
				self.response.out.write(json.dumps({
						'error': 'No such client found. Invalid Token !'
					}))

				# Stop the request
				return

		# Build our params or errors
		(params, errors) = build_search_params(client_obj, self.request)

		# Did we get any errors ?
		if len(errors) > 0:
			self.response.out.write(json.dumps({ 'errors': errors }))
		else:

			# Get our responses
			responses = dal.get_stats(params)

			# Our stat output object to return
			stats = {}

			# Parse the City out 
			city_response = dal.parse_out_cities(responses)
			for city_code in city_response:

				# Get Response
				if 'found' in city_response[city_code]:
					stats[str(city_code)] = int(city_response[city_code]["found"])
				else:
					stats[str(city_code)] = 0
			
			# Write our Output
			self.response.out.write(json.dumps(stats))
コード例 #5
0
ファイル: about.py プロジェクト: wmv/supository
	def get(self):

		session = dal.return_and_global_session_update(self)

		year = int(time.strftime("%Y"))

		if self.request.get('year'):
			try:
				year = int(self.request.get('year'))
			except:
				pass

		search_count = memcache.get("search_count_" + str(year))
		if search_count is None:
			search_count = db.GqlQuery("SELECT * FROM UserSearch WHERE created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31)", year, year).count()

			if not memcache.add("search_count_" + str(year), search_count, 60*10):
				pass

		success_search_count = memcache.get("success_search_count_" + str(year))
		if success_search_count is None:
			success_search_count = db.GqlQuery("SELECT * FROM UserSearch WHERE success_status = True AND created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31)", year, year).count()

			if not memcache.add("success_search_count_" + str(year), success_search_count, 60*10):
				pass

		search_contact_count = memcache.get("search_contact_count_" + str(year))
		if search_contact_count is None:
			search_contact_count = db.GqlQuery("SELECT * FROM UserSearchDetail WHERE email_sent = True AND created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31)", year, year).count()

			if not memcache.add("search_contact_count_" + str(year), search_contact_count, 60*10):
				pass

		stats = memcache.get("stat_page_" + str(year))
		if stats is None:
			stats = []

			responses = dal.get_stats({
				'year': int(year)
			})
		
			stat = {
				'year': int(year),
				'countries': dal.parse_out_countries(responses),
				'cities': dal.parse_out_cities(responses)
			}
			stats.insert(0, stat)

			if not memcache.add("stat_page_" + str(year), stats, 60*10):
				pass

		locales = {
			'title': 'Statistics',
			'description': 'Some Statistics about Searches that were performed on our website and where they came from.',
			'user': users.get_current_user(),
			'stats': stats,
			'years': xrange(2012, int(time.strftime("%Y"))+1),
			'current_year': year,
			'search_count': search_count,
			'search_contact_count': search_contact_count,
			'success_search_count': success_search_count,
			'session': session,
			'is_current_user_admin': users.is_current_user_admin()
		}
		template = jinja_environment.get_template('stats.html')
		self.response.out.write(template.render(locales))
コード例 #6
0
ファイル: provider.py プロジェクト: wmv/supository
	def get(self, provider_uid):

		provider_obj = schemas.Provider.get_by_id(int(provider_uid))
		user = users.get_current_user()

		if provider_obj is not None and provider_obj is not False:
			
			locales = {
				'title': provider_obj.name,
				'description': 'Dashboard for Provider',
				'user': user,
				'provider': provider_obj,
				'session': dal.return_and_global_session_update(self),
				'is_current_user_admin': users.is_current_user_admin()
			}

			# Ok so Provider exists.
			# Now check if this is a logged in user and if they are a member of this provider.
			# If so we rather so a dashboard and edit properties and controls.
			if user:
				
				# Ok so let's check if they are a member
				membership_obj = dal.membership_by_user(provider_obj, user)
				if membership_obj is not None and membership_obj is not False:

					# Assign post variables
					locales['post_params'] = self.request.POST

					# Provider Information
					form_test_error = False
					form_test_success = False

					# Testing Tool Response
					form_test_response = False

					# Provider response
					form_test_provide_response = False

					# Check if they want to do a form post
					if self.request.POST.get('form_test_tool'):

						# Check the API Url
						if not self.request.POST.get('form_test_api_url'):
							form_test_error = 'Url of the API Endpoint is Required.'
						elif 'http://' not in self.request.POST.get('form_test_api_url') and 'https://' not in self.request.POST.get('form_test_api_url'):
							# Url where we send the information
							form_test_error = 'Url of the API Endpoint is Required. This must include either http:// or https:// and of course we recommend https to keep it secure.'
						elif not self.request.POST.get('form_test_search_uid') or len(str(self.request.POST.get('form_test_search_uid')).lower().strip()) == 0:
							# Search UID is Required
							form_test_error = 'Please provide a valid Search UID to check the endpoint for'
						else:

							# Assign the test url
							provider_obj.api_url = str(self.request.POST.get('form_test_api_url')).strip()

							# Post Params
							search_uid = str(self.request.POST.get('form_test_search_uid')).lower().strip()

							# Ok so run the test
							search_response = runner.search(self.request, str(search_uid), [ provider_obj ])

							# Show the output
							form_test_response = search_response

							# Assign the provider response
							form_test_provide_response = search_response.responses[0]

							# Check if the result is true, if so we update them as tested
							if form_test_provide_response.status == runner.ProviderResponse.STATUS_FOUND:

								# Assign the Boolean
								provider_obj.tested = True
								provider_obj.put()

								# Success !
								form_test_success = 'We tested the new Url and we got a valid response from the server. After which we set the new url as the default one.'

							else:
								form_test_error = 'Response from Server was not a successfull response. Please check the response that was returned and verify that everthing is working and setup. We will not update the API url until this test is passed.'

					# Param Assignment
					locales['form_test_error'] = form_test_error
					locales['form_test_success'] = form_test_success
					locales['form_test_response'] = form_test_response
					locales['form_test_provide_response'] = form_test_provide_response

					if provider_obj.approved and provider_obj.tested:

						register_form_error = False
						register_form_success = False

						# Check if this is a form post
						if self.request.POST.get('form_provider_update'):

							# Assign Local cleaned parameters
							provider_name = str(self.request.POST.get('form_provider_name')).strip()
							provider_description = str(self.request.POST.get('form_provider_description')).strip()
							provider_website = str(self.request.POST.get('form_provider_website')).strip()

							# Valdidate
							if not self.request.POST.get('form_provider_name') or len(provider_name) == 0:
								# Name is Required
								register_form_error = 'Name of your Provider is Required'
							elif not self.request.POST.get('form_provider_website') or len(provider_website) == 0 or (not 'http://' in provider_website or 'https://' in provider_website):
								# Website is Required. # We check for http:// or https://
								register_form_error = 'Website of your Provider is Required. The Path must include http:// or https://'
							else:

								provider_obj.name = provider_name
								provider_obj.description = provider_description
								provider_obj.website = provider_website

								# Handle Logo Uploads
								if len(self.get_uploads()) > 0:
									try:
										logo = self.get_uploads()[0]
										# provider_obj.logo.delete()
										provider_obj.logo = logo
									except Exception as e:
										print e
										register_form_error = 'Error while uploading Logo'

								# Save that sucker
								provider_obj.put()

								self.redirect('/provider/' + str(provider_obj.key().id()) + "?section=profile")

								register_form_success = 'Provider was updated succesfully.'

						locales["register_form_error"] = register_form_error
						locales['register_form_success'] = register_form_success
						locales['upload_url'] = blobstore.create_upload_url('/provider/' + str(provider_obj.key().id()) + "?section=profile")

						# Statistics

						year = int(time.strftime("%Y"))

						if self.request.get('year'):
							try:
								year = int(self.request.get('year'))
							except:
								pass

						search_count = memcache.get("search_count_" + str(year))
						if search_count is None:
							search_count = db.GqlQuery("SELECT * FROM UserSearchDetail WHERE created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31) AND provider = :3", year, year, provider_obj).count()

							if not memcache.add("search_count_" + str(year), search_count, 60*10):
								pass

						success_search_count = memcache.get("success_search_count_" + str(year))
						if success_search_count is None:
							success_search_count = db.GqlQuery("SELECT * FROM UserSearchDetail WHERE success_status = True AND created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31) AND provider = :3", year, year, provider_obj).count()

							if not memcache.add("success_search_count_" + str(year), success_search_count, 60*10):
								pass

						search_contact_count = memcache.get("search_contact_count_" + str(year))
						if search_contact_count is None:
							search_contact_count = db.GqlQuery("SELECT * FROM UserSearchDetail WHERE email_sent = True AND created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31) AND provider = :3", year, year, provider_obj).count()

							if not memcache.add("search_contact_count_" + str(year), search_contact_count, 60*10):
								pass

						stats = memcache.get("stat_page_" + str(year))
						if stats is None:
							stats = []

							responses = dal.get_stats({
								'year': int(year),
								'provider': provider_obj
							})
						
							stat = {
								'year': int(year),
								'countries': dal.parse_out_countries(responses),
								'cities': dal.parse_out_cities(responses)
							}
							stats.insert(0, stat)

							if not memcache.add("stat_page_" + str(year), stats, 60*10):
								pass

						locales['stats' ] = stats
						locales['current_year' ] = year
						locales['search_count'] = search_count
						locales['search_contact_count'] = search_contact_count
						locales['success_search_count'] = success_search_count

						# Show the Dashboard
						section = 'dashboard'
						if self.request.get('section'):
							section = str(self.request.get('section')).strip().lower()

						user.organization = os.environ['USER_ORGANIZATION']

						session_store = sessions.get_store(request=self.request)
						session = session_store.get_session()

						locales['user'] = user
						locales['members'] = dal.memberships_by_provider(provider_obj)

						if 'members' in session:

							list_of_member_emails = []
							for cmember in locales['members']:
								list_of_member_emails.append(cmember.user.email())

							domain_members = []

							for dmember in json.loads(str(session['members'])):
								if dmember['email'] not in list_of_member_emails:
									domain_members.append(dmember)

							locales['domain_members'] = domain_members
						else:
							locales['domain_members'] = False

						locales['request'] = self.request
						locales['section'] = section
						locales['user_org'] = os.environ['USER_ORGANIZATION']
						locales['years'] = xrange(provider_obj.created.year, int(time.strftime("%Y"))+1)
						locales['current_year'] = year
						locales['membership'] = membership_obj

						clients = dal.get_clients_by_provider(provider_obj)
						locales['clients'] = clients
						locales['client_count'] = clients.count()

						template = jinja_environment.get_template('provider/dashboard.html')
						self.response.out.write(template.render(locales))

					elif not provider_obj.approved:

						# Show the Approval Waiting Page
						template = jinja_environment.get_template('provider/being_approved.html')
						self.response.out.write(template.render(locales))

					elif not provider_obj.tested:

						# Show the Approval Waiting Page
						template = jinja_environment.get_template('provider/not_tested.html')
						self.response.out.write(template.render(locales))

					else:
						self.redirect('/')

				else:
					template = jinja_environment.get_template('provider/detail.html')
					self.response.out.write(template.render(locales))

			else:
				# We used to show a Public Profile but decided against this.
				self.redirect('/providers')

		else:
			self.redirect('/providers')