Пример #1
0
	def get(self):
		if(not isUserAdmin(self)):
			self.session[LOGIN_NEXT_PAGE_KEY] = self.URL
			self.redirect("/")
			return
		pageText=self.request.get("page")
		pageSize=20
		actualPage=0
		if (pageText!=None and pageText!=""):
			actualPage=int(pageText)-1
		orderByText=self.request.get("order")
		if (orderByText==None or orderByText==""):
			orderByText='familyName'
		userCount=User.all().count()
		roles=Role.all().order("name")
		usersToDisplay=User.all().order(orderByText).run(offset=actualPage*pageSize, limit=pageSize)
		pages=[]
		corrector=1
		if (userCount/pageSize) * pageSize == userCount:
			corrector=0
		for i in range(0,userCount/pageSize + corrector):
			pages.append(i+1)
		template_values={
			'page':actualPage+1,
			'pages':pages,
			'userList':usersToDisplay,
			'order':orderByText,
			'roles':roles
		}
		if actualPage < userCount/ pageSize - 1 - corrector:
			template_values["nextPage"]=actualPage + 2
		if actualPage > 0:
			template_values["nextPage"]=actualPage
		template = jinja_environment.get_template('templates/userList.html')
		self.printPage("Felhasznalok", template.render(template_values), False, False)
Пример #2
0
    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)
        os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
        from model import g_blog, User

        self.blog = g_blog
        self.login_user = users.get_current_user()
        self.is_login = self.login_user != None
        self.loginurl = users.create_login_url(self.request.uri)
        self.logouturl = users.create_logout_url(self.request.uri)
        self.is_admin = users.is_current_user_admin()

        if self.is_admin:
            self.auth = "admin"
            self.author = User.all().filter("email =", self.login_user.email()).get()
            if not self.author:
                self.author = User(dispname=self.login_user.nickname(), email=self.login_user.email())
                self.author.isadmin = True
                self.author.user = self.login_user
                self.author.put()
        elif self.is_login:
            self.author = User.all().filter("email =", self.login_user.email()).get()
            if self.author:
                self.auth = "author"
            else:
                self.auth = "login"
        else:
            self.auth = "guest"

        try:
            self.referer = self.request.headers["referer"]
        except:
            self.referer = None

        self.template_vals = {"self": self, "blog": self.blog, "current": self.current}
Пример #3
0
    def initialize(self, request, response):
        self.current='home'
        webapp.RequestHandler.initialize(self, request, response)
        os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
        from model import User,Blog
        self.blog = Blog.getBlog()
        self.login_user = users.get_current_user()
        self.is_login = (self.login_user != None)
        self.loginurl=users.create_login_url(self.request.uri)
        self.logouturl=users.create_logout_url(self.request.uri)
        self.is_admin = users.is_current_user_admin()

        if self.is_admin:
            self.auth = 'admin'
            self.author=User.all().filter('email =',self.login_user.email()).get()
            if not self.author:
                self.author=User(dispname=self.login_user.nickname(),email=self.login_user.email())
                self.author.isadmin=True
                self.author.user=self.login_user
                self.author.put()
        elif self.is_login:
            self.author=User.all().filter('email =',self.login_user.email()).get()
            if self.author:
                self.auth='author'
            else:
                self.auth = 'login'
        else:
            self.auth = 'guest'

        try:
            self.referer = self.request.headers['referer']
        except:
            self.referer = None

        self.template_vals = {'self':self,'blog':self.blog,'current':self.current}
Пример #4
0
  def initialize(self, request, response):
    webapp.RequestHandler.initialize(self, request, response)
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
    
    self.login_user = users.get_current_user()
    self.is_login = (self.login_user != None)
    self.loginurl = users.create_login_url(self.request.uri)
    self.logouturl = users.create_logout_url(self.request.uri)
    self.is_admin = users.is_current_user_admin()

    if self.is_admin:
      self.auth = 'admin'
      self.user = User.all().filter('email =', self.login_user.email()).get()
      if not self.user:
        self.user = User(dispname = self.login_user.nickname(), email = self.login_user.email())
        self.user.isadmin = True
        self.user.user = self.login_user
        self.user.put()
    elif self.is_login:
      self.user = User.all().filter('email =', self.login_user.email()).get()
      if self.user:
        self.auth = 'user'
      else:
        self.auth = 'login'
    else:
      self.auth = 'guest'

    try:
      self.referer = self.request.headers['referer']
    except:
      self.referer = None

    self.template_vals = {'self':self, 'current':self.current}
Пример #5
0
	def get(self):
		lang = self.request.get('lang')
		if not lang:
			lang ='en'
		#********************** User Auth **************************#
		user = users.get_current_user()
		nickname = ''
		if user:
			nickname=user.nickname()
		if nickname:
			user_info = User.all().filter('user',nickname)
			if user_info.count(1)>0:
				user_info = user_info.get()
				user_info.lang = lang
				user_info.put()
			else:
				user_info =User();
				user_info.user = nickname
				user_info.lang = lang
				user_info.put()
			self.redirect('/link/'+nickname)
		uri = self.request.get('uri')
		if uri:
			self.redirect(unquote(uri).encode('utf-8'))
		else:
			self.redirect('/')
Пример #6
0
 def get(self):
     nowtime = datetime.datetime.now()
     users = User.all().filter("sync_time <=", nowtime)
     for user in users:
         fqueue = taskqueue.Queue(name='fetch')
         ftask = taskqueue.Task(url='/task/fetch/', params=dict(uid=user.key().name()))
         fqueue.add(ftask)
Пример #7
0
 def post(self, error_msg=None):
     email = self.request.get("email")
     username = self.request.get("username")
     users = User.all().filter('email', email)
     user = User()
     user.email = email
     user.username = username
     user.fullname = self.request.get("firstname")+" "+self.request.get("lastname")
     user.birthday = datetime.datetime.strptime(self.request.get("birthday"), '%Y-%m-%d')
     user.set_password(self.request.get("password")) #set password. need encrypt. 
     user.firstname = self.request.get("firstname")
     user.lastname = self.request.get("lastname")
     user.country = self.request.get("country")
     gender = self.request.get("gender")
     if gender:
         gender_ = str(gender)[0:1]
         user.gender = gender_
     if users.count() == 0:
         user.put()
         #init() the session
         sessions.Session().login_user(user)
         self.redirect("/")
         return
     else:
         error_msg = "That email address has already been registered."
     template_values = {
        "temp_user": user,
        "error": error_msg
     }
     self.generate('signup.html',template_values)
Пример #8
0
    def text_message(self, message):
        email = extract_email(message.sender)

        try:
            sender = users.User(email)
        except users.UserNotFoundError as e:
            message.reply("You don't seem to have an account that I can find.")

        appuser = User.all().filter("info = ", sender).get()

        if not appuser:
            appuser = User(info = sender)
            appuser.put()

        try:
            datum = parser.parse(message.body)
        except parser.ParseException as e:
            message.reply("I couldn't understand you. (Message was: {msg})".format(msg = e.message))

        variable = Variable.all().filter("name = ", datum["variable"]).get()
        if not variable:
            variable = Variable(name = datum["variable"], user = appuser)
            variable.put()

        value = Value(value = datum["value"], variable = variable)
        value.put()

        message.reply("I've logged variable {variable} as being {value}".format(sender = email,
                                                                                variable = datum["variable"],
                                                                                value = datum["value"]))
Пример #9
0
    def post(self):
        """ Changes the current users nickname """
        new_nickname = self.request.get('nickname')
        if not new_nickname:
            self.error(409)
            return
        new_nickname_lower = new_nickname.lower()

        user = utils.get_current_user()
        if not user:
            self.error(403)
            return

        if new_nickname != user.nickname:
            others = User.all().filter('nickname_lower =', new_nickname_lower).get()
            if others and others.key() != user.key():
                self.error(409)
                return
            user.nickname_lower = new_nickname_lower
            user.nickname = new_nickname
            user.save()

        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.out.write(json.dumps(user.to_struct()))
Пример #10
0
    def get(self):
        user = self.get_user()
        # Update enabled state if requested
        send_digest = self.request.get('send_digest')
        if send_digest == '1':
            user.send_digest = True
            user.put()
        elif send_digest == '0':
            user.send_digest = False
            user.put()

        send_reminder = self.request.get('send_reminder')
        if send_reminder == '1':
            user.send_reminder = True
            user.put()
        elif send_reminder == '0':
            user.send_reminder = False
            user.put()
            
        # Fetch user list and display
        raw_users = User.all().order('email').fetch(500)
        all_users = [(u, u.email) for u in raw_users]

        
        template_values = {
                           'current_user' : user,
                           'all_users': all_users,
                           'config': config,
                           }
        self.render('index', template_values)
Пример #11
0
 def get(self):
     user_lang = 'en'
     #********************** User Auth **************************#
     user = users.get_current_user()
     nickname = ''
     if user:
         nickname = user.nickname()
     if nickname:
         user_info = User.all().filter('user', nickname)
         if user_info.count(1) > 0:
             user_info = user_info.get()
             user_lang = user_info.lang
         auth_url = users.create_logout_url(self.request.uri)
         auth_text = 'signout'
     else:
         auth_url = users.create_login_url(self.request.uri)
         auth_text = 'signin'
     template_values = {
         'nickname': nickname,
         'auth_url': auth_url,
         'auth_text': auth_text
     }
     path = os.path.join(os.path.dirname(__file__),
                         'templates/' + user_lang + '/help.html')
     self.response.out.write(template.render(path, template_values))
Пример #12
0
	def get(self):
		if(not isUserAdmin(self)):
			self.session[LOGIN_NEXT_PAGE_KEY] = self.URL
			self.redirect("/")
			return
		today = datetime.datetime.now(timeZone)
		twoWeeksAgo = today + datetime.timedelta(days = - 14)
		unseenUsers = User.all().filter("lastOrder < ", twoWeeksAgo)
		unseenUsersOrdered = sorted(unseenUsers, key=getLastOrderDate)
		taskedUsers = User.all().filter("taskList >= ", None)
		
		template_values={
			'users': itertools.chain(taskedUsers, unseenUsersOrdered),
		}
		template = jinja_environment.get_template('templates/crm/crmTaskList.html')
		self.printPage("Felhaszn&aacute;l&oacute;k", template.render(template_values), False, False)
Пример #13
0
def login(login_name, login_password):
    if login_name == ANONYMOUS_ACCOUNT_NAME:
        usermodel = get_user(u_account=login_name)
    else:
        try:
            login_name = decrypt_password(login_name)
            login_password = decrypt_password(login_password)
        except:
            raise LoginFailedError()
        query = User.all()
        query.filter("u_account =", login_name, parenthesis="(")
        query.filter("u_email =", login_name, logic="or", parenthesis=")")
        password = encrypt_password(login_password)
        query.filter("u_password =", password)
        if query.count() > 0:
            usermodel = query.fetch(1)[0]
            _attach_userprops(usermodel)
        else:
            raise LoginFailedError()
    usermodel.logined_times += 1
    update_user_logined_info(usermodel.key(), usermodel.key())
    token = Token(usermodel.uid, anonymous=usermodel.u_account == ANONYMOUS_ACCOUNT_NAME)
    token.userName = usermodel.u_name
    token.accountName = usermodel.u_account
    return token
Пример #14
0
 def get(self):
     lang = self.request.get('lang')
     if not lang:
         lang = 'en'
     #********************** User Auth **************************#
     user = users.get_current_user()
     nickname = ''
     if user:
         nickname = user.nickname()
     if nickname:
         user_info = User.all().filter('user', nickname)
         if user_info.count(1) > 0:
             user_info = user_info.get()
             user_info.lang = lang
             user_info.put()
         else:
             user_info = User()
             user_info.user = nickname
             user_info.lang = lang
             user_info.put()
         self.redirect('/link/' + nickname)
     uri = self.request.get('uri')
     if uri:
         self.redirect(unquote(uri).encode('utf-8'))
     else:
         self.redirect('/')
Пример #15
0
def get(handler, response):
  lat = handler.request.get('lat')
  lon = handler.request.get('lng')
  response.users = User.proximity_fetch(
    User.all(),
    geotypes.Point(float(lat),float(lon)),
  )
Пример #16
0
 def DeleteOpenID(self,request):
     openid = request.get("openid")
     users = User.all().filter('openids', openid)
     if users.count() != 0:
         user = users[0]
         user.openids.remove(db.Category(openid.strip().encode('utf8')))
         user.put()
     return True
Пример #17
0
 def get(self):
     all_users = User.all().filter("send_reminder =", True).fetch(500)
     for user in all_users:
         if not snippet_exists(user, date_for_new_snippet()):
             logging.info('reminding: '+ user.email)
             taskqueue.add(url='/onereminder', params={'email': user.email})
         else:
             logging.info('skipping: '+user.email)
Пример #18
0
	def get(self,req_user=''):
		user_lang = 'en'
		#********************** User Auth **************************#
		user = users.get_current_user()
		nickname = ''
		if user:
			nickname=user.nickname()
		if nickname:
			user_info = User.all().filter('user',nickname)
			if user_info.count(1)>0:
				user_info = user_info.get()
				user_lang = user_info.lang
			auth_url = users.create_logout_url(self.request.uri)
			auth_text= 'signout'
		else:
			auth_url = users.create_login_url(self.request.uri)
			auth_text= 'signin'
		
		entry_count =Entry.all().count(1000)
		if req_user:
			tag_user = req_user
			tags = Tag.all().filter("user",req_user)
		else:
			tag_user = '******'
			tags = Tag.all()
		tags_count = tags.count(1000)
		tag_list=[]
		for tag in tags:
			tag_count=tag.count_link + tag.count_note + tag.count_pic
			if tag.count_link >= tag.count_note:
				if tag.count_link >= tag.count_pic:
					max_type = 'link'
				else:
					max_type = 'pic'
			else:
				if tag.count_pic >= tag.count_note:
					max_type = 'pic'
				else:
					max_type = 'note'
			#logging.info(tag_count)
			#logging.info(entry_count)
			#logging.info(tags_count)
			tag_list.append({
				"info":tag,
				"type":max_type,
				"level":int(round(tag_count/(float(entry_count)/tags_count)))
				})
		template_values = {
			'nickname' : nickname,
			'req_user' : req_user,
			'auth_url' : auth_url,
			'auth_text': auth_text,
			'tag_user' : tag_user,
			'tags'     : tag_list,
			'uri'      : self.request.uri
			}
		path = os.path.join(os.path.dirname(__file__),'templates/'+user_lang+'/tag.html')
		self.response.out.write(template.render(path,template_values))
Пример #19
0
	def get(self):
		q = User.all()

		template_values = {
			'list_users':q.run(limit=10)
		}

		template = jinja_environment.get_template('/templates/user_list.html')
		self.response.out.write(template.render(template_values))
Пример #20
0
def get(handler, response):
  lat1 = handler.request.get('lat1')
  lon1 = handler.request.get('lng1')
  lat2 = handler.request.get('lat2')
  lon2 = handler.request.get('lng2')
  response.users = User.bounding_box_fetch(
    User.all(),
    geotypes.Box(float(lat1),float(lon2),float(lat2),float(lon1)),
  )
Пример #21
0
def getUsers():
	client = memcache.Client()
	users = client.get(USERS_KEY)
	if users == None:
		users = []
		usersDb = User.all()
		for userDb in usersDb:
			users.append(createUser(userDb))
		client.add(USERS_KEY, users)
	return users
Пример #22
0
 def test_print_db(self):
     query = User.all()
     string = "database:\n"
     count = 0
     for result in query:
         if result.picture:
             string += str(count) + " "+ result.cubmail + ": (Pic found,"+str(result.registered)+")\n"
         else:
             string += str(count) + " "+ result.cubmail + ": (Pic not found,"+str(result.registered)+")\n"
         count = count+1
     print string
Пример #23
0
    def get(self):
        user_lang = 'en'
        #********************** User Auth **************************#
        user = users.get_current_user()
        nickname = ''
        if user:
            nickname = user.nickname()
        if nickname:
            user_info = User.all().filter('user', nickname)
            if user_info.count(1) > 0:
                user_info = user_info.get()
                user_lang = user_info.lang
            auth_url = users.create_logout_url(self.request.uri)
            auth_text = 'signout'

            key = self.request.get('key')
            if key:
                e = db.get(key)
                title = e.title
                url = e.url
                purl = ''
                content = e.content
                type = e.type
                tags = ' '.join(tag for tag in e.tags)
                tags += ' '
            else:
                title = unescape(self.request.get('title'))
                url = unescape(self.request.get('url'))
                purl = unescape(self.request.get('purl'))
                content = unescape(self.request.get('content'))
                type = self.request.get('type')
                if not type:
                    type = 'link'
                tags = ''

            template_values = {
                'nickname': nickname,
                'auth_url': auth_url,
                'auth_text': auth_text,
                'type': type,
                'key': key,
                'tag_list': Tag.all().filter("user",
                                             nickname).order('usetime'),
                'title': title,
                'url': url,
                'purl': purl,
                'content': content,
                'tags': tags
            }
            path = os.path.join(os.path.dirname(__file__),
                                'templates/' + user_lang + '/add.html')
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))
Пример #24
0
	def get(self):
		if not isUserAdmin(self):
			self.session[LOGIN_NEXT_PAGE_KEY] = self.URL
			self.redirect("/")
			return
		users = User.all()
		template_values = {
			'users' : users
		}
		template = jinja_environment.get_template('templates/csv/userList.download')
		self.response.out.write(template.render(template_values))
Пример #25
0
	def get(self):
		if(not isUserAdmin(self)):
			self.session[LOGIN_NEXT_PAGE_KEY] = self.URL
			self.redirect("/")
			return
		users=User.all().order("familyName")
		template_values={
			'userList':users
		}
		template = jinja_environment.get_template('templates/newsletter/newsletterEditor.html')
		self.printPage("H&iacute;rlev&eacute;l", template.render(template_values), False, False)
Пример #26
0
 def post(self):
     user = user_from_email(self.request.get('email'))
     d = date_for_retrieval()
     all_snippets = Snippet.all().filter("date =", d).fetch(500)
     all_users = User.all().fetch(500)
     following = compute_following(user, all_users)
     logging.info(all_snippets)
     body = '\n\n\n'.join([self.__snippet_to_text(s) for s in all_snippets if s.user.email in following])
     if body:
         self.__send_mail(user.email, 'https://snippetless.appspot.com\n\n' + body)
     else:
         logging.info(user.email + ' not following anybody.')
Пример #27
0
    def get_user(self):
        '''Returns the user object on authenticated requests'''
        user = users.get_current_user()
        assert user

        userObj = User.all().filter("email =", user.email()).fetch(1)
        if not userObj:
            userObj = User(email=user.email())
            userObj.put()
        else:
            userObj = userObj[0]
        return userObj
Пример #28
0
def get_user(user_id=None, u_account=None):
    user = None
    if user_id != None and user_id != model.EMPTY_UID and user_id != model.SYSTEM_UID:
        user = User.get_by_key(int(user_id))
    elif u_account != None:
        query = User.all()
        query.filter("u_account =", u_account)
        if query.count() > 0:
            user = query.get()
    if user != None:
        _attach_userprops(user)
    return user
Пример #29
0
    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)
        from model import g_blog, User
        self.blog = g_blog
        self.login_user = users.get_current_user()
        self.is_login = (self.login_user != None)
        self.loginurl = users.create_login_url(self.request.uri)
        self.logouturl = users.create_logout_url(self.request.uri)
        self.is_admin = users.is_current_user_admin()

        if self.is_admin:
            self.auth = 'admin'
            self.author = User.all().filter('email =',
                                            self.login_user.email()).get()
            if not self.author:
                self.author = User(dispname=self.login_user.nickname(),
                                   email=self.login_user.email())
                self.author.isadmin = True
                self.author.user = self.login_user
                self.author.put()
        elif self.is_login:
            self.author = User.all().filter('email =',
                                            self.login_user.email()).get()
            if self.author:
                self.auth = 'author'
            else:
                self.auth = 'login'
        else:
            self.auth = 'guest'

        try:
            self.referer = self.request.headers['referer']
        except:
            self.referer = None

        self.template_vals = {
            'self': self,
            'blog': self.blog,
            'current': self.current
        }
Пример #30
0
	def get(self):
		user_lang = 'en'
		#********************** User Auth **************************#
		user = users.get_current_user()
		nickname = ''
		if user:
			nickname=user.nickname()
		if nickname:
			user_info = User.all().filter('user',nickname)
			if user_info.count(1)>0:
				user_info = user_info.get()
				user_lang = user_info.lang
			auth_url = users.create_logout_url(self.request.uri)
			auth_text= 'signout'

			key = self.request.get('key')
			if key:
				e = db.get(key)
				title = e.title
				url   = e.url
				purl  = ''
				content = e.content
				type  = e.type
				tags  = ' '.join(tag for tag in e.tags)
				tags +=' '
			else:
				title = unescape(self.request.get('title'))
				url   = unescape(self.request.get('url'))
				purl  = unescape(self.request.get('purl'))
				content = unescape(self.request.get('content'))
				type= self.request.get('type')
				if not type:
					type = 'link'
				tags  = ''
			
			template_values = {
				'nickname' : nickname,
				'auth_url' : auth_url,
				'auth_text': auth_text,
				'type'    : type,
				'key'     : key,
				'tag_list': Tag.all().filter("user",nickname).order('usetime'),
				'title'   : title,
				'url'     : url,
				'purl'    : purl,
				'content' : content,
				'tags'    : tags
				}
			path = os.path.join(os.path.dirname(__file__),'templates/'+user_lang+'/add.html')
			self.response.out.write(template.render(path,template_values))
		else:
			self.redirect(users.create_login_url(self.request.uri))
Пример #31
0
 def post(self, error_msg=None):
     email = self.request.get("email")
     password = self.request.get("password")
     if(email.find('@')!=-1):
         users = User.all().filter('email', email)
     else:
         users = User.all().filter('username', email)
     if users.count() == 0:
         error_msg = "You have entered an incorrect e-mail address or username."
     else:
         user = users.get()
         if not user.check_password(password):
             error_msg = "You have entered an incorrect password."
         else:
             sessions.Session().login_user(user)
             self.redirect("/")
             return
     template_values = {
        "email": email,
        "error": error_msg
     }
     self.generate('login.html',template_values)
Пример #32
0
class Base:
  def __init__(self, database):
    self.model = User(database, bcrypt)

  def on_get(self, req, resp):
    if authorize_as(req.auth, 'developer'):
      resp.body = dumps(self.model.all())
    else:
      raise HTTPUnauthorized('unautharized', 'unautharized')

  def on_post(self, req, resp):
    body = authorize_body(req)
    new_user = self.model.create(body)
    resp.status = HTTP_201
    resp.body = dumps(new_user)
Пример #33
0
    def dispatch(self):
        """Overridden"""

        user_list = memcache.get('app_users')
        if not user_list:
            user_list = []
            for user in User.all().fetch(100):
                user_list.append(str(user.email))
            memcache.set('app_users', user_list)

        user = users.get_current_user()
        if not user or not user.email() in user_list:
            self.redirect('/static/nofly.html')
            return
        super(AuthHandler, self).dispatch()
Пример #34
0
  def __error(self):
    email_or_nickname = self.request.get('name')
    if re.match('^[-.\w]+@(?:[a-z\d][-a-z\d]+\.)+[a-z]{2,6}$', email_or_nickname) is not None:
      self.user = User.all().filter('email =', email_or_nickname).get()
    elif re.match('^\w*$', email_or_nickname) is not None:
      self.user = User.all().filter('nickname =', email_or_nickname).get()
    else:
      return 'incorrectEmailOrNickname'

    if self.user is None:
      return 'wrongEmailOrNickname'

    salt = self.user.salt
    password = self.request.get('password')

    # temp: allow login without password
    if password == 'password':
      return
    if re.match('^\w+$', password) is None:
      password = ''
    passwordHash = hashlib.sha1(password + salt).hexdigest()

    if self.user.password != passwordHash:
      return 'wrongPassword'
Пример #35
0
    def get(self):
        start = datetime.now().strftime("%s")
        users = User.all().fetch(1000)

        for user in users:
            queries = Query.get_by_user(user)
            for query in queries:
                if query.is_stale() and query.is_time_to_send():
                    send_query(query)
                    break  # only send one query per user every interval

        end = datetime.now().strftime("%s")

        logging.info("SendQueries started at " + start)
        logging.info("SendQueries finished at " + end)
Пример #36
0
    def get(self):
        google_user = users.get_current_user()

        # will have already been authorized by appengine. Look up in our
        # user database
        appuser = User.all().filter("info =", google_user).get()
        if not appuser:
            # no records for this person yet, so tell them to send a message to
            # our bot.
            templ = env.get_template("fail.template.html")
            self.response.write(templ.render(dict(user=google_user)))
        else:
            # look up variables
            templ = env.get_template("view.template.html")
            self.response.write(templ.render(dict(user=appuser)))
Пример #37
0
    def dispatch(self):
        """Overridden"""

        user_list = memcache.get('app_users')
        if not user_list:
            user_list = []
            for user in User.all().fetch(100):
                user_list.append(str(user.email))
            memcache.set('app_users', user_list)

        user = users.get_current_user()
        if not user or not user.email() in user_list:
            self.redirect('/static/nofly.html')
            return
        super(AuthHandler, self).dispatch()
Пример #38
0
 def _handle_locations_notification(self, data, userid):
     """Handle locations notification."""
     location = self.mirror_service.locations().get(
         id=data['itemId']).execute()
     text = 'New location is %s, %s' % (location.get('latitude'),
                                        location.get('longitude'))
     user = User.all().filter('userid =', userid).get()
     logging.info(
         "user %s, latitude %s, longitude %s" %
         (userid, location.get('latitude'), location.get('longitude')))
     Location(
         longitude=location.get('longitude'),
         latitude=location.get('latitude'),
         created_at=datetime.now(),
         userid=user.userid,
         email=user.email,
     ).put()
     GlassApp(self.mirror_service).insert_products()
Пример #39
0
    def get(self, req_user=''):
        user_lang = 'en'
        #********************** User Auth **************************#
        user = users.get_current_user()
        nickname = ''
        if user:
            nickname = user.nickname()
        if nickname:
            user_info = User.all().filter('user', nickname)
            if user_info.count(1) > 0:
                user_info = user_info.get()
                user_lang = user_info.lang
            auth_url = users.create_logout_url(self.request.uri)
            auth_text = 'signout'
        else:
            auth_url = users.create_login_url(self.request.uri)
            auth_text = 'signin'

        entry_count = Entry.all().count(1000)
        if req_user:
            tag_user = req_user
            tags = Tag.all().filter("user", req_user)
        else:
            tag_user = '******'
            tags = Tag.all()
        tags_count = tags.count(1000)
        tag_list = []
        for tag in tags:
            tag_count = tag.count_link + tag.count_note + tag.count_pic
            if tag.count_link >= tag.count_note:
                if tag.count_link >= tag.count_pic:
                    max_type = 'link'
                else:
                    max_type = 'pic'
            else:
                if tag.count_pic >= tag.count_note:
                    max_type = 'pic'
                else:
                    max_type = 'note'
            #logging.info(tag_count)
            #logging.info(entry_count)
            #logging.info(tags_count)
            tag_list.append({
                "info":
                tag,
                "type":
                max_type,
                "level":
                int(round(tag_count / (float(entry_count) / tags_count)))
            })
        template_values = {
            'nickname': nickname,
            'req_user': req_user,
            'auth_url': auth_url,
            'auth_text': auth_text,
            'tag_user': tag_user,
            'tags': tag_list,
            'uri': self.request.uri
        }
        path = os.path.join(os.path.dirname(__file__),
                            'templates/' + user_lang + '/tag.html')
        self.response.out.write(template.render(path, template_values))
Пример #40
0
    def get(self, req_type='link', req_user='', req_tag=''):

        user_lang = 'en'
        #********************** User Auth **************************#

        user = users.get_current_user()
        nickname = ''
        if user:
            nickname = user.nickname()
        if nickname:
            user_info = User.all().filter('user', nickname)
            if user_info.count(1) > 0:
                user_info = user_info.get()
                user_lang = user_info.lang
            auth_url = users.create_logout_url(self.request.uri)
            auth_text = 'signout'
        else:
            auth_url = users.create_login_url(self.request.uri)
            auth_text = 'signin'

        #********************** Pagenator init**************************#
        limit = 20
        p = self.request.get('p')
        if not p:
            p = 1
        else:
            p = int(p)
        offset = (p - 1) * limit

        #********************** Query **************************#
        e = Entry.all().filter('type', req_type).order("-addtime")
        if req_user == 'all':
            req_user = ''
        if req_user:
            e = e.filter("user", req_user)
        if req_tag:
            e = e.filter("tags", unquote(req_tag).decode('utf-8'))
        if not nickname:
            e = e.filter("private", False)

        if e and e.count() > 0:
            cur_pageid = e.get().pageid
        else:
            cur_pageid = 0
        item_count = 0
        while cur_pageid >= 0:
            entry = Entry.all().filter('type', req_type)
            if req_user:
                entry = entry.filter("user", req_user)
            if req_tag:
                entry = entry.filter('tags', unquote(req_tag).decode('utf-8'))
            if not nickname:
                entry = entry.filter("private", False)

            item_count += entry.filter('pageid', cur_pageid).count()
            cur_pageid -= 1

        e = e.fetch(limit, offset)

        #********************** Pagenator **************************#
        page_count = int(math.ceil(item_count / float(limit)))  #总页数
        if page_count <= 7:
            page_numbers = range(1, page_count + 1)
        else:
            if p <= 6:
                page_numbers = range(1, max(1, p - 3))
            else:
                page_numbers = [1, 2] + ['...']
            page_numbers += range(max(1, p - 3), min(p + 4, page_count + 1))
            if p >= page_count - 5:
                page_numbers += range(min(p + 4, page_count + 1),
                                      page_count + 1)
            else:
                page_numbers += (['...'] +
                                 range(page_count - 1, page_count + 1))

        if req_user:
            tag_list = Tag.all().filter("user", req_user).order("usetime")
        else:
            tag_list = Tag.all().order("-count_" + req_type)

        template_values = {
            'nickname': nickname,
            'req_type': req_type,
            'req_user': req_user,
            'auth_url': auth_url,
            'auth_text': auth_text,
            'entry_list': e,
            'tag_list': tag_list,
            'is_paginated': page_count > 1,
            'has_next': p * limit < item_count,
            'has_previous': p > 1,
            'current_page': p,
            'next_page': p + 1,
            'previous_page': p - 1,
            'pages': page_count,
            'page_numbers': page_numbers,
            'count': item_count,
            'uri': self.request.uri
        }
        path = os.path.join(
            os.path.dirname(__file__),
            'templates/' + user_lang + '/' + req_type + '.html')
        self.response.out.write(template.render(path, template_values))