Exemplo n.º 1
0
    def post(self):
        delete = self.request.get("delete")
        if delete:
            g = Guild.get( delete )
            if users.is_current_user_admin() or g.owner == users.get_current_user():
                # the character fetcher deletes the characters once it notices that their
                # guild is gone - this makes the delete step here faster.
                g.delete()
            return
        
        if not users.get_current_user():
            return self.redirect("/")

        continent = self.request.get("continent")
        realm = self.request.get("realm")
        guildname = self.request.get("guild")

        guild = Guild.find_or_create( continent, realm, guildname )
        guild.owner = users.get_current_user()
        guild.put()
        if not guild:
            return self.error(404)
        taskqueue.add(url='/fetcher/guild/', params={'key': guild.key()})
        
        self.redirect( guild.url() )
Exemplo n.º 2
0
  def post(self):
    if users.get_current_user() is None:
      self.redirect('/')

    key = self.request.get('id', '')
    if key == '':
      self.error(400)
      return

    try:
      phone = Phone.all().filter('user ='******'__key__ =', db.Key(key)).get()

      phone.code = Phone.generate_code()
      phone.code_time = datetime.datetime.now()
      phone.put()

      v = Voice()
      v.login()
      v.send_sms(phone.number, phone.code)

    except db.BadKeyError:
      self.error(400)
      return;
      
    self.redirect('/phone/verify?id=%s' % key)    
Exemplo n.º 3
0
  def post(self):
    if users.get_current_user() is None:
      self.redirect('/')

    key = self.request.get('id', '')
    if key == '':
      self.error(400)
      return

    code = self.request.get('code', '')

    try:
      phone = Phone.all().filter('user ='******'__key__ =', db.Key(key)).get()

      now = datetime.datetime.now()
      delta = now - phone.code_time
      if phone.code == code and delta.seconds < (600) and delta.seconds >= 0:
        phone.verified = True
        phone.put()
      else:
        return self.redirect('/phone/verify?id=%s&message=%s' % (key, 'Code+incorrect'))

    except db.BadKeyError:
      self.error(400)
      return;
      
    self.redirect('/phone/')    
Exemplo n.º 4
0
 def post(self, id):
     if not users.get_current_user():
         self.response.set_status(401, "")
         return
     if len(id) > 0:
         entry = Package.get(id)
         if not entry:
             self.error(404)
             return
         entry.name = self.request.get('name'),
         entry.version = self.request.get("version"),
         entry.description = self.request.get("description"),
         entry.url = self.request.get("url"),
         entry.extractor = self.request.get("extractor"),
         entry.author = self.request.get("author"),
         entry.packer = users.get_current_user(),
         entry.requires = self.request.get("requires"),
         entry.installer = self.request.get("installer"),
         entry.installer_script = self.request.get("installer_script"),
     else:
         entry = Package(
             name=self.request.get('name'),
             version=self.request.get("version"),
             description=self.request.get("description"),
             url=self.request.get("url"),
             extractor=self.request.get("extractor"),
             author=self.request.get("author"),
             packer=users.get_current_user(),
             requires=self.request.get("requires"),
             installer=self.request.get("installer"),
             installer_script=self.request.get("installer_script"),
         )
     entry.put()
     memcache.delete("packages")
     self.redirect("/edit/%s" % (entry.key()))
Exemplo n.º 5
0
  def post(self):
    if users.get_current_user() is None:
      self.redirect('/')

    new_phone = Phone()
    new_phone.user = users.get_current_user()
    new_phone.name = self.request.get('phone_name', 'Phone')
    new_phone.verified = False

    number = self.request.get('phone_number', '')
    if not Phone.is_valid_number(number):
      template_data = {
        'logout_url': users.create_logout_url('/'),
        'phones': Phone.all().filter('user = '******'message': "Phone number invalid.",
        'nickname': new_phone.name,
        'number': number
      }

      self.response.headers['Content-Type'] = 'text/html'
      self.response.out.write(template.render(s.template_path('phone.html'), template_data))

    else:
      new_phone.number = Phone.normalize_number(number)
      new_phone.put()
      self.redirect('/phone/')
Exemplo n.º 6
0
Arquivo: lostab.py Projeto: lostab/log
	def get(self):
		site = memcache.get("site")
		if site is None:
			site = Site.all().get()
			memcache.add("site", site)
		if not site:
			self.redirect('/config')
		else:
			template_values = {
				'site': site,
				'page': 'about',
				'recentcomments': getrecentcomments(PAGESIZE)
			}

			user = users.get_current_user()
			if user:
				template_values['logout'] = users.create_logout_url(self.request.uri)
				template_values['user'] = users.get_current_user()
				if users.is_current_user_admin():
					template_values['admin'] = True
			else:
				template_values['login'] = users.create_login_url(self.request.uri)

			if ismobile(self):
				template_values['mobile'] = True

			path = os.path.join(os.path.dirname(__file__), 'template/about.html')
			self.response.out.write(template.render(path, template_values))
 def post(self):
     resource_name = self.request.get('resource_name')
     resource_date = self.request.get('resource_date')
     resource_UUID = self.request.get('resource_UUID')
     startHours = self.request.get('startHours')
     startMinutes = self.request.get('startMinutes')
     startSeconds = self.request.get('startSeconds')
     startMorEve = self.request.get('startMorEve')
     durHours = self.request.get('durHours')
     durMinutes = self.request.get('durMinutes')
     durSeconds = self.request.get('durSeconds')
     startTime = startHours+":"+startMinutes+":"+startSeconds+" "+startMorEve
     startDateTime24 = datetime.strptime(resource_date+" "+startTime,"%m/%d/%Y %I:%M:%S %p")
     reservation = Reservations()
     reservation.user = Owner(
         identity=users.get_current_user().user_id(),
         email=users.get_current_user().email())
     reservation.startTime=startDateTime24
     duration=durHours+":"+durMinutes+":"+durSeconds
     reservation.duration=duration
     reservation.UUID=str(uuid.uuid4())
     reservation.resource_UUID=resource_UUID
     reservation.resource_name=resource_name
     reservation.put()
     resource_query = Resources.query(Resources.UUID==resource_UUID)
     resource = resource_query.fetch()
     resource[0].lastReservedTime = datetime.now()
     resource[0].reservation_Num = resource[0].reservation_Num + 1
     resource[0].put()
     sleep(2)
     page="myres"
     query_params = {'page':page}
     self.redirect('/?'+urllib.urlencode(query_params))
Exemplo n.º 8
0
    def get(self):
        event_list = []
        event_name = "None"
        event_id = self.request.get('event_id');
        events=getEvents()
        for event in events:
             event_list.append(event)
#            event_list+='<option value=' + event[0] + '>' + event[1] + "</option>"
    
        if users.get_current_user():
            user = names[users.get_current_user().nickname()]
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            user = ""
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'event_list': event_list,
            'event_name': event_name,
            'title': "Events",
            'url': url,
            'url_linktext': url_linktext,
            'user': user,
        }
        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))
Exemplo n.º 9
0
  def post(self):
    # We set the same parent key on the 'Post' to ensure each
    # Post is in the same entity group. Queries across the
    # single entity group will be consistent. However, the write
    # rate to a single entity group should be limited to
    # ~1/second.
    wall_name = self.request.get('wall_name',DEFAULT_WALL)
    post = Post(parent=wall_key(wall_name))

    # When the person is making the post, check to see whether the person
    # is logged into Google
    if users.get_current_user():
      post.author = Author(
            identity=users.get_current_user().user_id(),
            name=users.get_current_user().nickname(),
            email=users.get_current_user().email())
    else:
      post.author = Author(
            name='*****@*****.**',
            email='*****@*****.**')


    # Get the content from our request parameters, in this case, the message
    # is in the parameter 'content'
    post.content = self.request.get('content')

    # Write to the Google Database
    post.put()

    # Do other things here such as a page redirect
    self.redirect('/?wall_name=' + wall_name)
Exemplo n.º 10
0
    def post(self):
        """

        """
        if users.get_current_user():
            try:
                organizer = users.get_current_user()
                ln = self.request.get('location_name')
                lat = self.request.get('lat')
                lon = self.request.get('lon')
                event_date = self.request.get('date')
                sd = event_date.split('/')
                db_date = date(int(sd[2]),int(sd[0]),int(sd[1]))
                days = int(self.request.get('duration'))
                num_days = days - 1
                end_event = db_date + timedelta(days=num_days)
                event_details = self.request.get('event_details')
                owner_locations = OwnerLocations.all().filter('owner', users.get_current_user()).filter('location_name',ln)
                if owner_locations.count() == 0:
                    owner_location = OwnerLocations(owner = organizer,location_name = ln,date = db_date,geolocation = db.GeoPt(lat,lon))
                    owner_location.put()
                location = Locations(owner = organizer,location_name = ln,date = db_date,end_date = end_event, event = event_details,geolocation = db.GeoPt(lat,lon))
                location.put()
            except db.Error, exStr:
                logging.error("Error while reading from db:% s"% exStr)
Exemplo n.º 11
0
    def get(self):

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'

        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
            return self.redirect(users.create_login_url(self.request.uri))

        locations = OwnerLocations.all().filter('owner = ', users.get_current_user())

        user=users.get_current_user()
        if locations.count() == 0:
            locations = {}

        message_body = """
          Welcome to the miingle app
        """
        mail.send_mail(
              sender='*****@*****.**',
              to='*****@*****.**',
              subject='welcome to miingle',
              body=message_body)

        template_values = {
            'locations': locations,
            'userdisplay' : user.nickname(),
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'searchlocations.html')
        self.response.out.write(template.render(path, template_values))
Exemplo n.º 12
0
    def get(self):

        greetings_query = Greeting.query(ancestor=guestbook_key()).order(-Greeting.date)
        greetings = greetings_query.fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'LOGOUT' #'Logooooout'
            #url_linktext1 = str(users.get_current_user()) + ', welcome to E4D! '   #'welcome'
            url_linktext1 = ''   
            user0 = users.get_current_user()
            user0id = user0.user_id()            
            
            
            url_linktext2 = 'welcome, ' + str(user0.nickname()) + '@e4d.in! ' 
            

        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'LOGIN to begin!'  #'Logiiiiin'
            url_linktext1 = 'E4D.start.'  
            url_linktext2 = ''   
			

        template = jinja_environment.get_template('index.html')
        
        self.response.out.write(template.render(greetings=greetings,
                                                url=url,
                                                url_linktext=url_linktext,
                                                url_linktext1=url_linktext1,
                                                url_linktext2=url_linktext2))
Exemplo n.º 13
0
  def get(self, resource=''):
    import pipeline  # Break circular dependency
    if pipeline._ENFORCE_AUTH:
      if users.get_current_user() is None:
        logging.debug('User is not logged in')
        self.redirect(users.create_login_url(self.request.url))
        return

      if not users.is_current_user_admin():
        logging.debug('User is not admin: %r', users.get_current_user())
        self.response.out.write('Forbidden')
        self.response.set_status(403)
        return

    if resource not in self._RESOURCE_MAP:
      logging.debug('Could not find: %s', resource)
      self.response.set_status(404)
      self.response.out.write("Resource not found.")
      self.response.headers['Content-Type'] = 'text/plain'
      return

    relative_path, content_type = self._RESOURCE_MAP[resource]
    path = os.path.join(os.path.dirname(__file__), relative_path)
    if not pipeline._DEBUG:
      self.response.headers["Cache-Control"] = "public, max-age=300"
    self.response.headers["Content-Type"] = content_type
    try:
      data = pkgutil.get_data(__name__, relative_path)
    except AttributeError:  # Python < 2.6.
      data = None
    self.response.out.write(data or open(path, 'rb').read())
Exemplo n.º 14
0
    def post(self):
        idTopic = self.request.get("idTopic")

        queryLastMessage = db.Query(Message)
        queryLastMessage.order("-idMessage")
        lastMessage = queryLastMessage.get()

        messagesQuery = db.GqlQuery("SELECT * FROM Message WHERE idTopic=%s" % idTopic)

        topicPage = int(messagesQuery.count() / 20)
        if messagesQuery.count() % 20:
            topicPage += 1

        if self.request.get("messageArea"):

            message = Message()
            message.idMessage = lastMessage.idMessage + 1

            if lastMessage.Row == 1:
                message.Row = 2
            else:
                message.Row = 1

            message.idTopic = int(idTopic)
            message.author = users.get_current_user().nickname()
            message.idAuthor = getIdUser(users.get_current_user().nickname())
            message.message = self.request.get("messageArea").replace("\n", "<br />")
            message.dateMessage = datetime.now().strftime("%d.%m.%y %H:%M")
            message.put()

            self.redirect("/topic?idTopic=%s&topicPage=%s" % (idTopic, topicPage))
        else:
            self.redirect("/errorAddMessage?idTopic=%s&topicPage=%s" % (idTopic, topicPage))
Exemplo n.º 15
0
    def sendXML(self, content, attrs=None):
        if attrs is None:
            attrs = {}
        if 'nowrap' not in attrs:
            if users.get_current_user():
                attrs['logout-uri'] = users.create_logout_url(self.request.uri)
            else:
                attrs['login-uri'] = users.create_login_url(self.request.uri)
            if users.is_current_user_admin():
                attrs['is-admin'] = 'yes'
            if users.get_current_user():
                attrs['user'] = users.get_current_user().nickname()
                attrs['email'] = users.get_current_user().email()
            attrs['class'] = type(self).__name__
            attrs['name'] = self.pageName
            attrs['theme'] = self.request.get('theme', 'default')
            attrs['tab'] = self.tabName
            attrs['host'] = self.request.host
            content = xml.em(u'page', attrs, content)

        result = u'<?xml version="1.0"?>'
        if 'xml' not in self.request.arguments() and 'nowrap' not in attrs:
            result += u"<?xml-stylesheet type=\"text/xsl\" href=\"/static/themes/" + attrs['theme'] + '/' + self.xsltName + u"\"?>\n"
        result += content
        self.response.headers['Content-Type'] = 'application/xml; charset=utf-8'
        self.response.out.write(result)
Exemplo n.º 16
0
def autorization(path):
    greetings = ""
    if users.get_current_user():
        greetings += "<a href='#'> %s</a>&nbsp;&nbsp;&nbsp;<a href=\"%s\">выйти</a>" % (
            users.get_current_user().nickname(),
            users.create_logout_url(path),
        )
        isLogin = True

        isUser = False
        usersForum = db.GqlQuery("SELECT * FROM UserForum")
        userForum = UserForum()

        for tmp_user in usersForum:
            if tmp_user.loginGoogle == users.get_current_user().nickname():
                isUser = True
        if isUser == False:
            if usersForum:
                userForum.idUser = usersForum.count() + 1
            else:
                userForum.idUser = 1
            userForum.loginGoogle = users.get_current_user().nickname()
            userForum.loginForum = None
            userForum.position = "user"
            userForum.name = None
            userForum.lastName = None
            userForum.put()

    else:
        greetings += '<a href="%s">Войти на сайт' % users.create_login_url(path)
        isLogin = False

    return greetings
Exemplo n.º 17
0
    def post(self):
        queryLastTopic = db.Query(Topic)
        queryLastTopic.order("-idTopic")
        lastTopic = queryLastTopic.get()

        if self.request.get("nameTopic"):
            topic = Topic()
            if lastTopic:
                topic.idTopic = lastTopic.idTopic + 1
            else:
                topic.idTopic = 1

            topic.author = users.get_current_user().nickname()
            topic.idAuthor = getIdUser(users.get_current_user().nickname())
            topic.nameTopic = self.request.get("nameTopic")
            topic.dateTopic = datetime.now().strftime("%d.%m.%y %H:%M")

            if self.request.get("message"):
                message = Message()
                message.idMessage = 1
                message.Row = 1
                message.idTopic = topic.idTopic
                message.author = users.get_current_user().nickname()
                message.idAuthor = getIdUser(users.get_current_user().nickname())
                message.message = self.request.get("message").replace("\n", "</br>")
                message.dateMessage = datetime.now().strftime("%d.%m.%y %H:%M")

                message.put()
                topic.put()

                self.redirect("/topic?idTopic=%s&topicPage=1" % topic.idTopic)
            else:
                self.redirect("/errorCreateTopic")
        else:
            self.redirect("/errorCreateTopic")
Exemplo n.º 18
0
    def get(self):
    			# Checks for active Google account session
        user = users.get_current_user()
    
    			# Redirect user after logging in
        if user:
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            
            # If user already submitted details, redirect to the main page
            if Patients.query(Patients.patient == user).fetch(10):
            		self.redirect('/main')
            		
            # If user hasn't filled in details yet, redirect to details registration'
            else:
            		self.redirect('/settings')
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
				
        template_values = {
        		'current_user': users.get_current_user(),
        		's_current_user': str(users.get_current_user()),
        		'url': url,
        		'url_linktext': url_linktext
        }
        
        template = JINJA_ENVIRONMENT.get_template("login.html")
        self.response.write(template.render(template_values))
Exemplo n.º 19
0
    def post(self):
    # We set the same parent key on the 'Comment' to ensure each
    # Comment is in the same entity group. Queries across the
    # single entity group will be consistent. 
    #
        guest_name = self.request.get('guest_name', GUEST_NAME)
        comment = Comment(parent=guest_key(guest_name))
         
        if users.get_current_user():
            comment.author = Author(
                identity=users.get_current_user().user_id(),
                email=users.get_current_user().email())

 # Get the description from our request parameters, 
 # "title" and "description".
        comment.title = self.request.get('title')
        comment.description = self.request.get('description')
        
        if comment.title.strip() and comment.description.strip():  
            # if title and description are valid 
            #  load data to Google Datastore
            time.sleep(num_of_secs)
            comment.put()
            query_params = {'guest_name': guest_name}
            self.redirect('/?' + urllib.urlencode(query_params))
        else:
            # Error, title or description not valid.
            time.sleep(num_of_secs)
            self.response.out.write(ERROR_HTML)
Exemplo n.º 20
0
 def post(self):
     if users.get_current_user():
         if self.request.get('avatar'):
             user = users.get_current_user()
             dbuser = UsersDB.gql("WHERE user = '******'" % user.nickname())
             usert = dbuser.get()
             avatar = images.resize(self.request.get("avatar"), 100, 100)
             avatar_mob = images.resize(self.request.get("avatar"), 50, 50)
             avatar_big = self.request.get("avatar")
             usert.avatar = db.Blob(avatar)
             usert.avatar_mob = db.Blob(avatar_mob)
             usert.avatar_big = db.Blob(avatar_big)
             usert.put()
             return True
         elif self.request.get('avatar_delete'):
             user = users.get_current_user()
             dbuser = UsersDB.gql("WHERE user = '******'" % user.nickname())
             usert = dbuser.get()
             usert.avatar = db.Blob(None)
             usert.avatar_mob = db.Blob(None)
             usert.avatar_big = db.Blob(None)
             usert.put()
             self.redirect("/mypage")
         else:
             self.redirect("/")
Exemplo n.º 21
0
	def get(self):
		if not users.get_current_user():
			self.redirect(users.create_login_url(self.request.uri))
		
		query = UrlItem.all()
		query.filter("owner =", users.get_current_user())
		query.order("-date")
		url_items = query.fetch(10)

		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'

		template_values = {
			'current_user': users.get_current_user(),
			'url_items': url_items,
			'url': url,
			'url_linktext': url_linktext,
		}

		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))
Exemplo n.º 22
0
    def post(self):
        user = users.get_current_user()
        if user:
         

         tagname = self.request.get('tags')
         raw_id = self.request.get('id')
         id = int(raw_id)
         lespace = EspaceModel.get_by_id(id)
         
         tag = TagModel(name =tagname , espace = lespace)
         tag.put();
         idlist = self.request.get_all('id[]')
         for idcompany in idlist:
             idc = int(idcompany)
             company = CompanyModel.get_by_id(idc)
             
             selection = SelectionModel(espace = lespace, company = company, tag = tag,
                                        selectedby =users.get_current_user()).put()

         
         values = {
             
            
	    'idlist': idlist,
	    
          }
Exemplo n.º 23
0
    def get(self):
        user = users.get_current_user()
        #if login already
        upload_url = blobstore.create_upload_url('/submit')

        if user:
            parent_key = ndb.Key('Persons', users.get_current_user().email())
            query = ndb.gql("SELECT * "
                            "FROM Images "
                            "ORDER BY date DESC "
                            )
            query2 = ndb.gql("SELECT *"
                             "from Liked_photos "
                             "WHERE ANCESTOR IS :1 "
                             "ORDER BY date DESC",
                             parent_key
            )

            template_values = {
                'user_mail' : users.get_current_user().email(),
                'user_name' : users.get_current_user().email().split("@")[0],
                'logout' : users.create_logout_url(self.request.host_url),
                'items' : query,
                'upload_url' :upload_url,
                'liked_photos' : query2,
                'liked_photos_count' : query2.count(),

            }

            template = jinja_env.get_template('home.html')
            self.response.out.write(template.render(template_values))
        else :
            template = jinja_env.get_template('welcome.html')
            self.response.out.write(template.render())
Exemplo n.º 24
0
	def post(self):
		context = {}
		if users.get_current_user():
			context['user'] = str(users.get_current_user()) + ': '
			context['login_url'] = users.create_logout_url(self.request.uri)
			context['login_text'] = "Log Out"
		else:
			context['user'] = "******"
			context['login_url'] = users.create_login_url(self.request.uri)
			context['login_text'] = "Log In"
		user = str(users.get_current_user())
		bname = cgi.escape(self.request.get('title'))
		context['bname'] = bname
		context['blink'] = urllib.quote(bname)
		context['owner'] = urllib.quote(user)
		query = Blog.query(Blog.owner == user, Blog.blogname == bname)
		if query.count(limit=1):
			self.response.write(template.render(
			os.path.join(os.path.dirname(__file__), 
			'dupe_blog.html'),
			context))
		else:
			b = Blog()
			b.owner = user
			b.blogname = bname
			b.put()
			self.response.write(template.render(
				os.path.join(os.path.dirname(__file__), 
				'create_blog_success.html'),
				context))
Exemplo n.º 25
0
    def show(self):
        user = users.get_current_user()
        if user:

            parent_key = ndb.Key('Persons', users.get_current_user().email())
            query = ndb.gql("SELECT * "
                            "FROM Images "
                            "WHERE ANCESTOR IS :1 "
                            "ORDER BY date DESC",
                            parent_key)
            upload_url = blobstore.create_upload_url('/submit')


            template_values = {
                'user_mail' : users.get_current_user().email(),
                'user_name' : users.get_current_user().email().split("@")[0],
                'logout' : users.create_logout_url(self.request.host_url),
                'items' : query,
                'items_num' : query.count(),
                'upload_url' : upload_url,

            }

            template = jinja_environment.get_template("upload.html")
            self.response.out.write(template.render(template_values))
        else :
            self.redirect(self.request.host_url)
Exemplo n.º 26
0
 def get(self):
     if not users.get_current_user():
         self.redirect(users.create_login_url(self.request.uri))
     else:
         key = self.request.get('key')
         datamodel.add_serie_4_user(users.get_current_user(), key)
         self.redirect('/mySeries')
Exemplo n.º 27
0
	def get(self):
		context = {	}
		if users.get_current_user():
			user = str(users.get_current_user())
			context['user'] =  user + ': '
			context['login_url'] = users.create_logout_url(self.request.uri)
			context['login_text'] = "Log Out"
			makeblog = '<a href = "/make-blog">make a new blog</a>. '
			context['view_text'] = "Welcome, " + str(users.get_current_user()) + '! Here are your blogs. Alternatively, ' + makeblog + 'Or, <a href = "/upload-img/">upload an image to use</a>.'
			#link to blogs
			query = Blog.query(Blog.owner == user)
			bloglist = """\
			<ul>
			"""
			for b in query:
				bname = b.blogname
				bloglist += '<li><a href="/b/' + urllib.quote(user) + '/'+ urllib.quote(bname) + '/?cursor='  + "00".encode('base64') + '">' + bname + '</a><br>'
			context['blog_list'] = bloglist + """\
			</ul>
			"""
		else:
			context['user'] = "******"
			context['login_url'] = users.create_login_url(self.request.uri)
			context['login_text'] = "Log In"
			context['view_text'] = "You will need to log in to access your blogs."
		self.response.write(template.render(
			os.path.join(os.path.dirname(__file__), 
			'index.html'),
			context))
Exemplo n.º 28
0
    def get(self):
        #Get the 10 most recent queries
        searches_query = Searches.all().filter('private', False).order('-timestamp')
        search_results = searches_query.fetch(limit=10)

        saved_searches = Searches.all().filter('user_id', users.get_current_user()).order('-timestamp')
        template_file = os.path.join(os.path.dirname(__file__), 'templates', 'shell.html')

        vars = {
            'server_software': os.environ['SERVER_SOFTWARE'],
            'application_version': LIVE_VERSION,
            'date_deployed': LIVE_DEPLOYED,
            'python_version': sys.version,
            'user': users.get_current_user(),
            'login_url': users.create_login_url('/'),
            'logout_url': users.create_logout_url('/'),
            'banner': banner(),
            'printer': self.request.get('printer').lower() or '',
            'submit': self.request.get('submit').lower() or '',
            'tabWidth': self.request.get('tabWidth').lower() or 'undefined',
            'searches': search_results,
            'has_searches': bool(search_results),
            'saved_searches': saved_searches,
            'has_saved_searches': saved_searches.count()
        }

        rendered = webapp.template.render(template_file, vars, debug=_DEBUG)
        self.response.out.write(rendered)
Exemplo n.º 29
0
def return_current_contact(self):
    if (users.get_current_user()):
        id = users.get_current_user().user_id();
        email = (users.get_current_user().email()).lower();
        if id:
            que = db.Query(Contact)
            que.filter('id =', id)
            contact_s = que.fetch(limit=1)
            if len(contact_s):
                contact = contact_s[0]
                if contact.email != email:
                    contact.email = email
                    contact.put();
                return contact
            elif email:
                que = db.Query(Contact)
                que.filter('email =', email)
                contact_s = que.fetch(limit=1)
                if len(contact_s):
                    contact = contact_s[0]
                    contact.id = id;
                    contact.put();
                    return contact
                new_contact = Contact(email=email, id=id)
                new_contact.put()
                return new_contact
Exemplo n.º 30
0
	def post(self):
		comment = Comment(parent=comments_key)

		if users.get_current_user():
			comment.author = Author(
				identity = users.get_current_user().user_id(),
				email = users.get_current_user().email())

		comment.content = self.request.get('content')
		comment.title = self.request.get('title')

		if comment.title and comment.content:
			if (check_profanity(comment.title) or check_profanity(comment.content)):
				msg = "No profanities please!!!"
				title = comment.title
				content = comment.content
				template_values = {
					'error': msg,
					'title': title,
					'content': content
				}
				self.render('comments.html', template_values = template_values)
			else:
				comment.put()
				self.redirect('/')
		else:
			template_values = { 'error': "Please enter title and comment!"}
			self.render('comments.html', template_values = template_values)
Exemplo n.º 31
0
 def __init__(self, request):
     user = users.get_current_user()
     game_key = request.get('g')
     if user and game_key:
         self.game = Game.get_by_key_name(game_key)
Exemplo n.º 32
0
def admin_edit_post(request, post_id):

    if users.is_current_user_admin():

        post = Post.get_by_id(int(post_id))
        if not post:
            raise Http404

        if request.method == 'GET':
            tp = Tag_Post.all().filter('post', post)

            tags = ''
            # Get all tags
            for tag in tp:
                tags += tag.tag.title + ','

            form = PostForm({
                'title': post.title,
                'category': post.category.key(),
                'content': post.content,
                'tags': tags
            })

        elif request.method == 'POST':

            form = PostForm(request.POST)

            if form.is_valid():

                # delete related tag_post
                for tp in post.tags:
                    tp.delete()

                p = form.save(commit=False)
                post.author = users.get_current_user()
                post.category = p.category
                post.content = p.content
                post.put()

                # add tag_post
                tagText = request.POST['tags']
                if tagText:
                    tags = tagText.split(',')
                    for tag in tags:
                        if tag:
                            tag = string.lower(string.strip(tag))

                            t = Tag.all().filter("title = ",
                                                 unicode(tag, "utf-8")).get()
                            if not t:

                                t = Tag(title=unicode(tag, "utf-8"))
                                t.put()
                            Tag_Post(tag=t, post=post).put()

            return HttpResponseRedirect('/admin')

        return render_to_response('admin/edit.html',
                                  dictionary={
                                      'form': form,
                                      'type': 'Edit Post',
                                  },
                                  context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/')
Exemplo n.º 33
0
def _get_current_student():
    user = users.get_current_user()
    if user is None:
        return None
    else:
        return models.Student.get_enrolled_student_by_email(user.email())
Exemplo n.º 34
0
    def get(self):
        template = jinja_environment.get_template('templates/saved_event.html')
        user = users.get_current_user()
        if user:
            base_url = "http://api.eventful.com/json/events/get?app_key=dTJDKdL9vWFkMrwQ&id="
            eventId = self.request.get("event_id")
            url = base_url + eventId
            specific_event_data_source = urllib2.urlopen(url)
            specific_event_json_content = specific_event_data_source.read()
            parsed_specific_event_dictionary = json.loads(
                specific_event_json_content)
            eventTitle = parsed_specific_event_dictionary["title"]
            eventCategory = parsed_specific_event_dictionary["categories"][
                "category"][0]["id"]
            if parsed_specific_event_dictionary["images"] is None:
                if eventCategory == 'outdoors_recreation':
                    eventImageURL = "/resources/outdoors_image.jpg"
                elif eventCategory == 'music':
                    eventImageURL = "/resources/concerts_image.gif"
                elif eventCategory == 'art':
                    eventImageURL = "/resources/art_image.png"
                elif eventCategory == 'animals':
                    eventImageURL = "/resources/pets_image.jpg"
                elif eventCategory == 'sports':
                    eventImageURL = "/resources/sports_image.png"
                elif eventCategory == 'comedy':
                    eventImageURL = "/resources/comedy_image.jpg"
                elif eventCategory == 'family_fun_kids':
                    eventImageURL = "/resources/family_image.jpg"
                elif eventCategory == 'singles_social':
                    eventImageURL = "/resources/nightlife_image.jpg"
                elif eventCategory == 'performing_arts':
                    eventImageURL = "/resources/performing_arts_image.jpg"
                elif eventCategory == 'learning_education':
                    eventImageURL = "/resources/educational_image.jpg"
                elif eventCategory == 'movies_film':
                    eventImageURL = "/resources/movies_image.jpg"
                elif eventCategory == 'food':
                    eventImageURL = "/resources/food_image.jpg"
                elif eventCategory == 'support':
                    eventImageURL = "/resources/health_image.jpg"
                elif eventCategory == 'attractions':
                    eventImageURL = "/resources/museums_image.jpg"
                elif eventCategory == 'politics_activism':
                    eventImageURL = "/resources/politics_image.jpg"
                elif eventCategory == 'science':
                    eventImageURL = "/resources/science_image.jpg"
                elif eventCategory == 'technology':
                    eventImageURL = "/resources/technology_image.jpg"
                elif eventCategory == 'conference':
                    eventImageURL = "/resources/conferences_image.jpg"
                elif eventCategory == 'fundraisers':
                    eventImageURL = "/resources/fundraiser_image.jpg"
                elif eventCategory == 'holiday':
                    eventImageURL = "/resources/holiday_image.jpg"
                elif eventCategory == 'community':
                    eventImageURL = "/resources/community_image.jpg"
                elif eventCategory == 'books':
                    eventImageURL = "/resources/books_image.jpg"
                elif eventCategory == 'business':
                    eventImageURL = "/resources/business_image.jpg"
                elif eventCategory == 'schools_alumni':
                    eventImageURL = "/resources/school_events.jpg"
                elif eventCategory == 'clubs_association':
                    eventImageURL = "/resources/organizations_image.jpg"
                elif eventCategory == 'sales':
                    eventImageURL = "/resources/sales_image.jpg"
                elif eventCategory == 'religion_spirituality':
                    eventImageURL = "/resources/religion_image.jpg"
                elif eventCategory == 'none':
                    eventImageURL = "/resources/none_image.jpg"
                elif eventCategory == 'other':
                    eventImageURL = "/resources/other_image.jpg"
                elif eventCategory == '':
                    eventImageURL = "/resources/other_image.jpg"
            else:
                if type(parsed_specific_event_dictionary["images"]) is list:
                    eventImageURL = parsed_specific_event_dictionary["images"][
                        0]["medium"]["url"]
                else:
                    eventImageURL = parsed_specific_event_dictionary["images"][
                        "image"]["medium"]["url"]

            event_obj = Event(event_id=eventId,
                              event_title=eventTitle,
                              event_image_url=eventImageURL,
                              event_category=eventCategory)
            event_key = event_obj.put()
            print "event_key = " + str(event_key)
            print "event_obj = " + str(event_obj)
            print "url = " + eventImageURL
            saved_events_dictionary = {
                "title": eventTitle,
                "URLimage": eventImageURL,
                "id": eventId
            }
            self.response.write(template.render(saved_events_dictionary))
        else:
            saved_events_dictionary = {
                "error": "Please sign in to save events"
            }
            self.response.write(template.render(saved_events_dictionary))
Exemplo n.º 35
0
    def get(self):
        template = jinja_environment.get_template(
            'templates/event_specifics.html')
        user = users.get_current_user()
        if user:
            nickname = user.nickname()
            greeting = ('<a href="%s">Sign Out</a>' %
                        (users.create_logout_url('/')))
        else:
            greeting = ('<a href="%s">Sign In</a>' %
                        users.create_login_url('/'))

        base_url = "http://api.eventful.com/json/events/get?app_key=dTJDKdL9vWFkMrwQ&id="
        url = base_url + self.request.get(
            "id") + '&category=' + self.request.get("category")
        specific_event_data_source = urllib2.urlopen(url)
        specific_event_json_content = specific_event_data_source.read()
        parsed_specific_event_dictionary = json.loads(
            specific_event_json_content)

        event_title = parsed_specific_event_dictionary["title"]
        event_category = parsed_specific_event_dictionary["categories"][
            "category"][0]["id"]

        event_venue_name = parsed_specific_event_dictionary["venue_name"]

        if "venue_address" in parsed_specific_event_dictionary:
            event_venue_address = parsed_specific_event_dictionary[
                "venue_address"]
        else:
            event_venue_address = "Sorry. No location address found"

        event_description = parsed_specific_event_dictionary["description"]
        if event_description is None:
            event_description = "No description found"

        if parsed_specific_event_dictionary['start_time'] is None:
            event_start_time = "No start time found"
        else:
            event_start_time = parsed_specific_event_dictionary["start_time"]

        if parsed_specific_event_dictionary['stop_time'] is None:
            event_stop_time = "No stop time found"
        else:
            event_stop_time = parsed_specific_event_dictionary["stop_time"]

        if parsed_specific_event_dictionary["images"] is None:
            if self.request.get('category') == 'outdoors_recreation':
                event_image_url_medium = "/resources/outdoors_image.jpg"
            elif self.request.get('category') == 'music':
                event_image_url_medium = "/resources/concerts_image.gif"
            elif self.request.get('category') == 'art':
                event_image_url_medium = "/resources/art_image.png"
            elif self.request.get('category') == 'animals':
                event_image_url_medium = "/resources/pets_image.jpg"
            elif self.request.get('category') == 'sports':
                event_image_url_medium = "/resources/sports_image.png"
            elif self.request.get('category') == 'comedy':
                event_image_url_medium = "/resources/comedy_image.jpg"
            elif self.request.get('category') == 'family_fun_kids':
                event_image_url_medium = "/resources/family_image.jpg"
            elif self.request.get('category') == 'singles_social':
                event_image_url_medium = "/resources/nightlife_image.jpg"
            elif self.request.get('category') == 'performing_arts':
                event_image_url_medium = "/resources/performing_arts_image.jpg"
            elif self.request.get('category') == 'learning_education':
                event_image_url_medium = "/resources/eduacational_image.jpg"
            elif self.request.get('category') == 'movies_film':
                event_image_url_medium = "/resources/movies_image.jpg"
            elif self.request.get('category') == 'food':
                event_image_url_medium = "/resources/food_image.jpg"
            elif self.request.get('category') == 'support':
                event_image_url_medium = "/resources/health_image.jpg"
            elif self.request.get('category') == 'attractions':
                event_image_url_medium = "/resources/museums_image.jpg"
            elif self.request.get('category') == 'politics_activism':
                event_image_url_medium = "/resources/politics_image.jpg"
            elif self.request.get('category') == 'science':
                event_image_url_medium = "/resources/science_image.jpg"
            elif self.request.get('category') == 'technology':
                event_image_url_medium = "/resources/technology_image.jpg"
            elif self.request.get('category') == 'conference':
                event_image_url_medium = "/resources/conferences_image.jpg"
            elif self.request.get('category') == 'fundraisers':
                event_image_url_medium = "/resources/fundraiser_image.jpg"
            elif self.request.get('category') == 'holiday':
                event_image_url_medium = "/resources/holiday_image.jpg"
            elif self.request.get('category') == 'community':
                event_image_url_medium = "/resources/community_image.jpg"
            elif self.request.get('category') == 'books':
                event_image_url_medium = "/resources/books_image.jpg"
            elif self.request.get('category') == 'business':
                event_image_url_medium = "/resources/business_image.jpg"
            elif self.request.get('category') == 'schools_alumni':
                event_image_url_medium = "/resources/school_events.jpg"
            elif self.request.get('category') == 'clubs_association':
                event_image_url_medium = "/resources/organizations_image.jpg"
            elif self.request.get('category') == 'sales':
                event_image_url_medium = "/resources/sales_image.jpg"
            elif self.request.get('category') == 'religion_spirituality':
                event_image_url_medium = "/resources/religion_image.jpg"
            elif self.request.get('category') == 'none':
                event_image_url_medium = "/resources/none_image.jpg"
            elif self.request.get('category') == 'other':
                event_image_url_medium = "/resources/other_image.jpg"
            elif self.request.get('category') == '':
                event_image_url_medium = "/resources/other_image.jpg"
        else:
            if type(parsed_specific_event_dictionary["images"]
                    ["image"]) is list:
                event_image_url_medium = (
                    parsed_specific_event_dictionary["images"]["image"][0]
                    ["medium"]["url"]).replace("medium", "large")
            else:
                event_image_url_medium = (
                    parsed_specific_event_dictionary["images"]["image"]
                    ["medium"]["url"]).replace("medium", "large")

        if event_start_time is not "No start time found":
            start_time_list = event_start_time.split(" ")
            start_time_date = start_time_list[0].split("-")
            start_time_time = start_time_list[1].split(":")

            year = start_time_date[0]
            month = start_time_date[1]
            day = start_time_date[2]
            finalDate = day + "/" + month + "/" + year + " "

            AMorPM = ""
            minute = start_time_time[1]
            if int(start_time_time[0]) >= 12:
                AMorPM = "PM"
            else:
                AMorPM = "AM"
            hour = int(start_time_time[0]) % 12
            if hour == 0:
                hour = 12
            finalTime = str(hour) + ":" + str(minute) + " " + AMorPM

            event_start_time = finalDate + finalTime

        if event_stop_time is not "No stop time found":
            stop_time_list = event_stop_time.split(" ")
            stop_time_date = stop_time_list[0].split("-")
            stop_time_time = stop_time_list[1].split(":")

            year = stop_time_date[0]
            month = stop_time_date[1]
            day = stop_time_date[2]
            finalDate = day + "/" + month + "/" + year + " "

            AMorPM = ""
            minute = stop_time_time[1]
            if int(stop_time_time[0]) >= 12:
                AMorPM = "PM"
            else:
                AMorPM = "AM"
            hour = int(stop_time_time[0]) % 12
            if hour == 0:
                hour = 12
            finalTime = str(hour) + ":" + str(minute) + " " + AMorPM

            event_stop_time = finalDate + finalTime

        event_dict = {
            "title": event_title,
            "venueName": event_venue_name,
            "description": event_description,
            "venueAddress": event_venue_address,
            "mediumPicURL": event_image_url_medium,
            "startTime": event_start_time,
            "stopTime": event_stop_time,
            "Signin": greeting
        }

        self.response.write(template.render(event_dict))
Exemplo n.º 36
0
    def get(self):
        if not self.request.get("location") and not self.request.get(
                "category"):
            self.response.write(
                'Error: Please go back and pick a location and category<form method="get" action="/"><button id=backbutton type="submit">Back</button></form>'
            )
        else:
            template = jinja_environment.get_template('templates/results.html')
            user = users.get_current_user()
            if user:
                nickname = user.nickname()
                greeting = ('<a href="%s">Sign Out</a>' %
                            (users.create_logout_url('/')))
            else:
                greeting = ('<a href="%s">Sign In</a>' %
                            users.create_login_url('/'))
            signin = (
                '<html><body><section id="WholeTopPart"><div class="top" id="SignIn">%s</div></section></body></html>'
                % greeting)

            base_url = "http://api.eventful.com/json/events/search?app_key=dTJDKdL9vWFkMrwQ"
            #remember to add code to make more than 10 events &page_size=100
            url = base_url + "&location=" + str(
                self.request.get("location")) + "&category=" + str(
                    self.request.get("category"))
            event_data_source = urllib2.urlopen(url)
            event_json_content = event_data_source.read()
            parsed_event_dictionary = json.loads(event_json_content)
            event_dictionary = {}
            print parsed_event_dictionary
            if parsed_event_dictionary['events'] is not None:
                listOfEvents = parsed_event_dictionary["events"]["event"]
                print "hola"
                i = 0
                event_title_list = []
                event_id_list = []
                event_title_id = {}
                event_title_venue = {}
                event_category = {}
                event_image_url_medium = {}
                event_start_time_id = {}
                event_stop_time_id = {}
                for event in listOfEvents:
                    if listOfEvents[i]["title"] not in event_title_list:
                        event_title_list.append(
                            listOfEvents[i]
                            ["title"])  #puts all the titles in a list
                    event_id_list.append(
                        listOfEvents[i]["id"])  #puts all the ids in a list
                    event_title_id[listOfEvents[i]["title"]] = listOfEvents[i][
                        "id"]  #conencts the title with its id
                    if listOfEvents[i]['start_time'] is None:
                        event_start_time = "No start time found"
                        event_start_time_id[listOfEvents[i]
                                            ["title"]] = "No start time found"
                    else:
                        event_start_time = listOfEvents[i]["start_time"]

                    if listOfEvents[i]['stop_time'] is None:
                        event_stop_time = "No stop time found"
                        event_stop_time_id[listOfEvents[i]
                                           ["title"]] = "No stop time found"
                    else:
                        event_stop_time = listOfEvents[i]["stop_time"]
                    if event_start_time is not "No start time found":
                        start_time_list = event_start_time.split(" ")
                        start_time_date = start_time_list[0].split("-")
                        start_time_time = start_time_list[1].split(":")

                        year = start_time_date[0]
                        month = start_time_date[1]
                        day = start_time_date[2]
                        finalDate = day + "/" + month + "/" + year + " "

                        AMorPM = ""
                        minute = start_time_time[1]
                        if int(start_time_time[0]) >= 12:
                            AMorPM = "PM"
                        else:
                            AMorPM = "AM"
                        hour = int(start_time_time[0]) % 12
                        if hour == 0:
                            hour = 12
                        finalTime = str(hour) + ":" + str(
                            minute) + " " + AMorPM

                        event_start_time = finalDate + finalTime
                        event_start_time_id[listOfEvents[i]
                                            ["title"]] = event_start_time

                    if event_stop_time is not "No stop time found":
                        stop_time_list = event_stop_time.split(" ")
                        stop_time_date = stop_time_list[0].split("-")
                        stop_time_time = stop_time_list[1].split(":")

                        year = stop_time_date[0]
                        month = stop_time_date[1]
                        day = stop_time_date[2]
                        finalDate = day + "/" + month + "/" + year + " "

                        AMorPM = ""
                        minute = stop_time_time[1]
                        if int(stop_time_time[0]) >= 12:
                            AMorPM = "PM"
                        else:
                            AMorPM = "AM"
                        hour = int(stop_time_time[0]) % 12
                        if hour == 0:
                            hour = 12
                        finalTime = str(hour) + ":" + str(
                            minute) + " " + AMorPM

                        event_stop_time = finalDate + finalTime
                        event_stop_time_id[listOfEvents[i]
                                           ["title"]] = event_stop_time
                    if listOfEvents[i]["image"] is None:
                        if self.request.get(
                                'category') == 'outdoors_recreation':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/outdoors_image.jpg"
                        elif self.request.get('category') == 'music':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/concerts_image.gif"
                        elif self.request.get('category') == 'art':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/art_image.png"
                        elif self.request.get('category') == 'animals':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/pets_image.jpg"
                        elif self.request.get('category') == 'sports':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/sports_image.png"
                        elif self.request.get('category') == 'comedy':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/comedy_image.jpg"
                        elif self.request.get('category') == 'family_fun_kids':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/family_image.jpg"
                        elif self.request.get('category') == 'singles_social':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/nightlife_image.jpg"
                        elif self.request.get('category') == 'performing_arts':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/performing_arts_image.jpg"
                        elif self.request.get(
                                'category') == 'learning_education':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/educational_image.jpg"
                        elif self.request.get('category') == 'movies_film':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/movies_image.jpg"
                        elif self.request.get('category') == 'food':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/food_image.jpg"
                        elif self.request.get('category') == 'support':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/health_image.jpg"
                        elif self.request.get('category') == 'attractions':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/museums_image.jpg"
                        elif self.request.get(
                                'category') == 'politics_activism':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/politics_image.jpg"
                        elif self.request.get('category') == 'science':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/science_image.jpg"
                        elif self.request.get('category') == 'technology':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/technology_image.jpg"
                        elif self.request.get('category') == 'conference':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/conferences_image.jpg"
                        elif self.request.get('category') == 'fundraisers':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/fundraiser_image.jpg"
                        elif self.request.get('category') == 'holiday':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/holiday_image.jpg"
                        elif self.request.get('category') == 'community':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/community_image.jpg"
                        elif self.request.get('category') == 'books':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/books_image.jpg"
                        elif self.request.get('category') == 'business':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/business_image.jpg"
                        elif self.request.get('category') == 'schools_alumni':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/school_events.jpg"
                        elif self.request.get(
                                'category') == 'clubs_association':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/organizations_image.jpg"
                        elif self.request.get('category') == 'sales':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/sales_image.jpg"
                        elif self.request.get(
                                'category') == 'religion_spirituality':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/religion_image.jpg"
                        elif self.request.get('category') == 'none':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/none_image.jpg"
                        elif self.request.get('category') == 'other':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/other_image.jpg"
                        elif self.request.get('category') == '':
                            event_image_url_medium[listOfEvents[i][
                                "title"]] = "/resources/other_image.jpg"
                    else:
                        if type(listOfEvents[i]["image"]) is list:
                            event_image_url_medium[
                                listOfEvents[i]["title"]] = (
                                    listOfEvents[i]["image"][0]["medium"]
                                    ["url"]).replace("medium", "large")
                        else:
                            event_image_url_medium[
                                listOfEvents[i]["title"]] = (
                                    listOfEvents[i]["image"]["medium"]["url"]
                                ).replace("medium", "large")
                    event_title_venue[listOfEvents[i]["title"]] = listOfEvents[
                        i]["venue_name"]
                    event_category[listOfEvents[i]["title"]] = str(
                        self.request.get("category"))
                    i += 1
                event_dictionary = {
                    "eventTitlePhotoUrl": event_image_url_medium,
                    "eventTitleVenue": event_title_venue,
                    "eventTitles": event_title_list,
                    "eventIds": event_id_list,
                    "eventTitleId": event_title_id,
                    "eventCategory": event_category,
                    "eventStartTimeId": event_start_time_id,
                    "eventStopTimeId": event_stop_time_id,
                    "Signin": signin
                }
            else:
                event_dictionary[
                    "error"] = "Sorry! There are no events for this category in this location"
            self.response.write(template.render(event_dictionary))
Exemplo n.º 37
0
 def post(self):
     game = GameFromRequest(self.request).get_game()
     user = users.get_current_user()
     if game and user:
         id = int(self.request.get('i'))
         GameUpdater(game).make_move(id, user)
Exemplo n.º 38
0
class BaseHandler(webapp.RequestHandler):
    # Handlers that don't need a repository name can set this to False.
    repo_required = True

    # Handlers that require HTTPS can set this to True.
    https_required = True

    # Set this to True to enable a handler even for deactivated repositories.
    ignore_deactivation = False

    # Handlers that require an admin permission must set this to True.
    admin_required = False

    # List all accepted query parameters here with their associated validators.
    auto_params = {
        'action': strip,
        'add_note': validate_yes,
        'age': validate_age,
        'alternate_family_names': strip,
        'alternate_given_names': strip,
        'author_email': strip,
        'author_made_contact': validate_yes,
        'author_name': strip,
        'author_phone': strip,
        'your_own_email': strip,
        'your_own_phone': strip,
        'believed_dead_permission': validate_checkbox_as_bool,
        'cache_seconds': validate_cache_seconds,
        'clone': validate_yes,
        'confirm': validate_yes,
        'contact_email': strip,
        'contact_name': strip,
        'content_id': strip,
        'context': strip,
        'cursor': strip,
        'date_of_birth': validate_approximate_date,
        'description': strip,
        'domain_write_permission': strip,
        'dupe_notes': validate_yes,
        'email_of_found_person': strip,
        'error': strip,
        'expiry_option': validate_expiry,
        'family_name': strip,
        'full_read_permission': validate_checkbox_as_bool,
        'given_name': strip,
        'home_city': strip,
        'home_country': strip,
        'home_neighborhood': strip,
        'home_postal_code': strip,
        'home_state': strip,
        'id': strip,
        'id1': strip,
        'id2': strip,
        'id3': strip,
        'is_valid': validate_checkbox_as_bool,
        'key': strip,
        'lang': validate_lang,
        'last_known_location': strip,
        'mark_notes_reviewed': validate_checkbox_as_bool,
        'max_results': validate_int,
        'min_entry_date': validate_datetime,
        'new_repo': validate_repo,
        'note_photo': validate_image,
        'note_photo_url': strip,
        'omit_notes': validate_yes,
        'operation': strip,
        'organization_name': strip,
        'person_record_id': strip,
        'phone_of_found_person': strip,
        'photo': validate_image,
        'photo_url': strip,
        'profile_url1': strip,
        'profile_url2': strip,
        'profile_url3': strip,
        'query': strip,
        'query_name': strip,
        'query_location': strip,
        'query_type': strip,
        'read_permission': validate_checkbox_as_bool,
        'referrer': strip,
        'resource_bundle': validate_resource_name,
        'resource_bundle_default': validate_resource_name,
        'resource_bundle_original': validate_resource_name,
        'resource_lang': validate_lang,
        'resource_name': validate_resource_name,
        'role': validate_role,
        'search_engine_id': validate_int,
        'search_permission': validate_checkbox_as_bool,
        'sex': validate_sex,
        'signature': strip,
        'skip': validate_int,
        'small': validate_yes,
        'source': strip,
        'source_date': strip,
        'source_name': strip,
        'source_url': strip,
        'stats_permission': validate_checkbox_as_bool,
        'status': validate_status,
        'style': strip,
        'subscribe': validate_checkbox,
        'subscribe_own_info': validate_checkbox,
        'subscribe_email': strip,
        'subscribe_permission': validate_checkbox_as_bool,
        'suppress_redirect': validate_yes,
        'target': strip,
        'text': strip,
        'thumb': validate_checkbox_as_bool,
        'timestamp': validate_timestamp,
        'ui': strip_and_lower,
        'utcnow': validate_timestamp,
        'version': validate_version,
        'own_info': validate_yes,
        'xsrf_token': strip,
    }

    def redirect(self, path, repo=None, permanent=False, **params):
        # This will prepend the repo to the path to create a working URL,
        # unless the path has a global prefix or is an absolute URL.
        if re.match('^[a-z]+:', path) or GLOBAL_PATH_RE.match(path):
            if params:
                path += '?' + urlencode(params, self.charset)
        else:
            path = self.get_url(path, repo, **params)
        return webapp.RequestHandler.redirect(self, path, permanent=permanent)

    def render(self,
               name,
               language_override=None,
               cache_seconds=0,
               get_vars=lambda: {},
               **vars):
        """Renders a template to the output stream, passing in the variables
        specified in **vars as well as any additional variables returned by
        get_vars().  Since this is intended for use by a dynamic page handler,
        caching is off by default; if cache_seconds is positive, then
        get_vars() will be called only when cached content is unavailable."""
        self.write(
            self.render_to_string(name, language_override, cache_seconds,
                                  get_vars, **vars))

    def render_to_string(self,
                         name,
                         language_override=None,
                         cache_seconds=0,
                         get_vars=lambda: {},
                         **vars):
        """Renders a template to a string, passing in the variables specified
        in **vars as well as any additional variables returned by get_vars().
        Since this is intended for use by a dynamic page handler, caching is
        off by default; if cache_seconds is positive, then get_vars() will be
        called only when cached content is unavailable."""
        # TODO(kpy): Make the contents of extra_key overridable by callers?
        lang = language_override or self.env.lang
        extra_key = (self.env.repo, self.env.charset,
                     self.request.query_string)

        def get_all_vars():
            vars.update(get_vars())
            for key in ('env', 'config', 'params'):
                if key in vars:
                    raise Exception(
                        'Cannot use "%s" as a key in vars. It is reserved.' %
                        key)
            vars['env'] = self.env  # pass along application-wide context
            vars['config'] = self.config  # pass along the configuration
            vars['params'] = self.params  # pass along the query parameters
            return vars

        return resources.get_rendered(name, lang, extra_key, get_all_vars,
                                      cache_seconds)

    def error(self, code, message='', message_html=''):
        self.info(code, message, message_html, style='error')

    def info(self, code, message='', message_html='', style='info'):
        """Renders a simple page with a message.

        Args:
          code: HTTP status code.
          message: A message in plain text.
          message_html: A message in HTML.
          style: 'info', 'error' or 'plain'. 'info' and 'error' differs in
              appearance. 'plain' just renders the message without extra
              HTML tags. Good for API response.
        """
        is_error = 400 <= code < 600
        if is_error:
            webapp.RequestHandler.error(self, code)
        else:
            self.response.set_status(code)
        if not message and not message_html:
            message = '%d: %s' % (code, httplib.responses.get(code))
        if style == 'plain':
            self.__render_plain_message(message, message_html)
        else:
            try:
                self.render('message.html',
                            cls=style,
                            message=message,
                            message_html=message_html)
            except:
                self.__render_plain_message(message, message_html)
        self.terminate_response()

    def __render_plain_message(self, message, message_html):
        self.response.out.write(
            django.utils.html.escape(message) +
            ('<p>' if message and message_html else '') + message_html)

    def terminate_response(self):
        """Prevents any further output from being written."""
        self.response.out.write = lambda *args: None
        self.get = lambda *args: None
        self.post = lambda *args: None

    def write(self, text):
        """Sends text to the client using the charset from select_charset()."""
        self.response.out.write(text.encode(self.env.charset, 'replace'))

    def get_url(self, action, repo=None, scheme=None, **params):
        """Constructs the absolute URL for a given action and query parameters,
        preserving the current repo and the parameters listed in
        PRESERVED_QUERY_PARAM_NAMES."""
        return get_url(self.request,
                       repo or self.env.repo,
                       action,
                       charset=self.env.charset,
                       scheme=scheme,
                       **params)

    def transitionary_get_url(self, path, repo, params=None):
        """Gets a URL to the given path, with the given params.

        We want to share some code between Django and webapp2 handlers (also,
        I'd like to get away from embedding so much code in the handlers), and a
        significant obstacle to that is that you can only create URLs from
        handlers. The solution seems to be passing a URL-building function into
        functions that need to build URLs.

        The Django app has a somewhat different URL builder for various reasons,
        and this function matches its signature so that functions don't have to
        know what web framework their URL-building function came from.
        """
        return self.get_url(path, repo=repo, **params)

    @staticmethod
    def add_task_for_repo(repo, name, action, **kwargs):
        """Queues up a task for an individual repository."""
        task_name = '%s-%s-%s' % (repo, name, int(time.time() * 1000))
        path = '/%s/%s' % (repo, action)
        taskqueue.add(name=task_name, method='GET', url=path, params=kwargs)

    def send_mail(self, to, subject, body):
        """Sends e-mail using a sender address that's allowed for this app."""
        app_id = get_app_name()
        sender = 'Do not reply <do-not-reply@%s.%s>' % (app_id, EMAIL_DOMAIN)
        logging.info('Add mail task: recipient %r, subject %r' % (to, subject))
        taskqueue.add(queue_name='send-mail',
                      url='/global/admin/send_mail',
                      params={
                          'sender': sender,
                          'to': to,
                          'subject': subject,
                          'body': body
                      })

    def get_captcha_html(self, error_code=None, use_ssl=False):
        """Generates the necessary HTML to display a CAPTCHA validation box."""

        # We use the 'custom_translations' parameter for UI messages, whereas
        # the 'lang' parameter controls the language of the challenge itself.
        # reCAPTCHA falls back to 'en' if this parameter isn't recognized.
        lang = self.env.lang.split('-')[0]

        return recaptcha.client.captcha.get_display_html(
            site_key=config.get('captcha_site_key'),
            use_ssl=use_ssl,
            error=error_code,
            lang=lang)

    def get_captcha_response(self):
        """Returns an object containing the CAPTCHA response information for the
        given request's CAPTCHA field information."""
        # Allows faking the CAPTCHA response by an HTTP request parameter, but
        # only locally, for testing purpose.
        faked_captcha_response = self.request.get('faked_captcha_response')
        if faked_captcha_response and self.request.remote_addr == '127.0.0.1':
            return recaptcha.client.captcha.RecaptchaResponse(
                is_valid=faked_captcha_response == 'success')

        captcha_response = self.request.get('g-recaptcha-response')
        return recaptcha.client.captcha.submit(captcha_response)

    def handle_exception(self, exception, debug_mode):
        logging.error(traceback.format_exc())
        self.error(
            500,
            _('There was an error processing your request.  Sorry for the '
              'inconvenience.  Our administrators will investigate the source '
              'of the problem, but please check that the format of your '
              'request is correct.'))

    def __get_env_language_for_babel(self):
        language_code = self.env.lang
        try:
            return babel.Locale.parse(language_code, sep='-')
        except babel.UnknownLocaleError as e:
            # fallback language
            return babel.Locale('en')

    def to_local_time(self, date):
        """Converts a datetime object to the local time configured for the
        current repository.  For convenience, returns None if date is None."""
        # TODO(kpy): This only works for repositories that have a single fixed
        # time zone offset and never use Daylight Saving Time.
        if date:
            if self.config.time_zone_offset:
                return date + timedelta(0, 3600 * self.config.time_zone_offset)
            return date

    def format_datetime_localized(self, dt):
        """Formats a datetime object to a localized human-readable string based
        on the current locale."""
        return format_datetime(dt, locale=self.__get_env_language_for_babel())

    def format_date_localized(self, dt):
        """Formats a datetime object to a localized human-readable string based
        on the current locale containing only the date."""
        return format_date(dt, locale=self.__get_env_language_for_babel())

    def format_time_localized(self, dt):
        """Formats a datetime object to a localized human-readable string based
        on the current locale containing only the time."""
        return format_time(dt, locale=self.__get_env_language_for_babel())

    def to_formatted_local_datetime(self, dt):
        """Converts a datetime object to the local datetime configured for the
        current repository and formats to a localized human-readable string
        based on the current locale."""
        dt = self.to_local_time(dt)
        return self.format_datetime_localized(dt)

    def to_formatted_local_date(self, dt):
        """Converts a datetime object to the local date configured for the
        current repository and formats to a localized human-readable string
        based on the current locale."""
        dt = self.to_local_time(dt)
        return self.format_date_localized(dt)

    def to_formatted_local_time(self, dt):
        """Converts a datetime object to the local time configured for the
        current repository and formats to a localized human-readable string
        based on the current locale."""
        dt = self.to_local_time(dt)
        return self.format_time_localized(dt)

    def maybe_redirect_for_repo_alias(self, request):
        """If the specified repository name is an alias, redirects to the URL
        with the canonical repository name and returns True. Otherwise returns
        False.
        """
        # Config repo_alias is a dictionary from a repository name alias to
        # its canonical.
        # e.g., {'yol': '2013-yolanda', 'jam': '2014-jammu-kashmir-floods'}
        #
        # A repository name alias can be used instead of the canonical
        # repository name in URLs. This is especially useful combined with
        # the short URL. e.g., You can access
        # https://www.google.org/personfinder/2014-jammu-kashmir-floods
        # by https://g.co/pf/jam .
        if not self.repo:
            return False
        repo_aliases = config.get('repo_aliases', default={})
        if self.repo in repo_aliases:
            canonical_repo = repo_aliases[self.repo]
            params = {}
            for name in request.arguments():
                params[name] = request.get(name)
            # Redirects to the same URL including the query parameters, except
            # for the repository name.
            self.redirect('/' + self.env.action, repo=canonical_repo, **params)
            self.terminate_response()
            return True
        else:
            return False

    def should_show_inline_photo(self, photo_url):
        """Returns True if we should show the photo in our site directly with
        <img> tag. Returns True only if the photo is served by our domain, to
        avoid loading resources in other domains in Person Finder.
        """
        if not photo_url:
            return False
        else:
            _, our_netloc, _, _, _ = urlparse.urlsplit(self.request.url)
            _, photo_netloc, _, _, _ = urlparse.urlsplit(photo_url)
            return photo_netloc == our_netloc

    URL_PARSE_QUERY_INDEX = 4

    def get_thumbnail_url(self, photo_url):
        """Get a thumbnail URL for an uploaded photo's URL.

        Args:
            photo_url: a photo URL for an uploaded photo
        """
        if not photo_url:
            return None
        parsed_url = list(urlparse.urlparse(photo_url))
        params_dict = dict(
            urlparse.parse_qsl(parsed_url[BaseHandler.URL_PARSE_QUERY_INDEX]))
        params_dict['thumb'] = 'true'
        parsed_url[BaseHandler.URL_PARSE_QUERY_INDEX] = urllib.urlencode(
            params_dict)
        return urlparse.urlunparse(parsed_url)

    def set_auth(self):
        self.auth = None
        if self.params.key:
            if self.repo:
                # check for domain specific one.
                self.auth = model.Authorization.get(self.repo, self.params.key)
            if not self.auth:
                # perhaps this is a global key ('*' for consistency with config).
                self.auth = model.Authorization.get('*', self.params.key)
        if self.auth and not self.auth.is_valid:
            self.auth = None

    def __return_unimplemented_method_error(self):
        return self.error(
            405, 'HTTP method %s is not allowed for this URL.' %
            self.request.method)

    def __init__(self, request, response, env):
        webapp.RequestHandler.__init__(self, request, response)
        self.params = Struct()
        self.env = env
        self.repo = env.repo
        self.config = env.config
        self.charset = env.charset

        # Set default Content-Type header.
        self.response.headers['Content-Type'] = ('text/html; charset=%s' %
                                                 self.charset)
        if self.admin_required:
            self.response.headers['X-Frame-Options'] = 'SAMEORIGIN'

        # Validate query parameters.
        for name, validator in self.auto_params.items():
            try:
                value = self.request.get(name, '')
                setattr(self.params, name, validator(value))
            except Exception, e:
                setattr(self.params, name, validator(None))
                return self.error(400, 'Invalid parameter %s: %s' % (name, e))

        # Ensure referrer is in whitelist, if it exists
        if self.params.referrer and (not self.params.referrer
                                     in self.config.referrer_whitelist):
            setattr(self.params, 'referrer', '')

        # Check for SSL (unless running local dev app server).
        if self.https_required and not is_dev_app_server():
            if self.env.scheme != 'https':
                url_parts = list(urlparse.urlparse(self.request.url))
                url_parts[0] = 'https'  # The 0th part is the scheme.
                webapp.RequestHandler.redirect(self,
                                               urlparse.urlunparse(url_parts))
                self.terminate_response()
                return

        # Handles repository alias.
        if self.maybe_redirect_for_repo_alias(request):
            return

        # Shows a custom error page here when the user is not an admin
        # instead of "login: admin" in app.yaml
        # If we use it, user can't sign out
        # because the error page of "login: admin" doesn't have sign-out link.
        if self.admin_required:
            self.env.user = users.get_current_user()
            if not self.env.user:
                login_url = users.create_login_url(self.request.url)
                webapp.RequestHandler.redirect(self, login_url)
                self.terminate_response()
                return
            if not users.is_current_user_admin():
                logout_url = users.create_logout_url(self.request.url)
                self.render('not_admin_error.html',
                            logout_url=logout_url,
                            user=self.env.user)
                self.terminate_response()
                return
            self.env.logout_url = users.create_logout_url(self.request.url)
            # This is different from env.repo_options because this contains all
            # repositories including deactivated ones.
            self.env.all_repo_options = [
                Struct(repo=repo,
                       url=get_repo_url(self.request, repo) + '/admin')
                for repo in sorted(model.Repo.list())
            ]

        # Handlers that don't need a repository configuration can skip it.
        if not self.repo:
            if self.repo_required:
                return self.error(400, 'No repository specified.')
            return
        # Everything after this requires a repo.

        # Reject requests for repositories that don't exist.
        if not model.Repo.get_by_key_name(self.repo):
            html = 'No such repository. '
            if self.env.repo_options:
                html += 'Select:<p>' + self.render_to_string('repo-menu.html')
            return self.error(404, message_html=html)

        # If this repository has been deactivated, terminate with a message.
        # The ignore_deactivation flag is for admin pages that bypass this.
        if (self.env.repo_entity.is_deactivated()
                and not self.ignore_deactivation):
            self.env.language_menu = []
            self.env.robots_ok = True
            self.render('message.html',
                        cls='deactivation',
                        message_html=self.config.deactivation_message_html)
            self.terminate_response()
Exemplo n.º 39
0
def _MakeUserStr():
    """Make a user string to use to represent the user.  'noauth' by default."""
    user = users.get_current_user()
    return user.nickname() if user else 'noauth'
Exemplo n.º 40
0
def get_student():
    user = users.get_current_user()
    return "{'userID':" + user.user_id() + "}"
Exemplo n.º 41
0
 def GetUser(self):
     return users.get_current_user()
Exemplo n.º 42
0
 def get_current_bird():
     user = users.get_current_user()
     bird = Bird.gql("WHERE account = :user", user=user).get()
     return bird
Exemplo n.º 43
0
  def store_media(self, upload_files, error_messages):
    """Store media information.

    Writes a MediaObject to the datastore for the uploaded file.

    Args:
      upload_files: List of BlobInfo records representing the uploads.
      error_messages: Empty list for storing error messages to report to user.
    """
    if not upload_files:
      error_messages.append('Form is missing upload file field')

    if len(upload_files) != 1:
      error_messages.append('Form has more than one image.')

    def get_param(name, error_message=None):
      """Convenience function to get a parameter from request.

      Returns:
        String value of field if it exists, else ''.  If the key does not exist
        at all, it will return None.
      """
      try:
        value = self.request.params[name]
        if isinstance(value, cgi.FieldStorage):
          value = value.value
        return value or ''
      except KeyError:
        #error_messages.append(error_message)
        return None

    # Check that title, description and share fields provided.  Do additional
    # constraint check on share to make sure it is valid.
    width = get_param('width')
    height = get_param('height')

    # title and description are only legit for single-page doc
    is_doc = get_param('is_doc')  # is a stand-alone single-page doc?
    title = get_param('title')
    description = get_param('description')
    tags = get_param('tags')  # comma-separated

    # Make sure user is logged in.
    user = users.get_current_user()
    user_email = ''
    if user is None:
      claimed_email = get_param("user_email")
      effective_user = lookup_and_authenticate_user(self, claimed_email, get_param('password'))
      if not effective_user:
        error_messages.append("No user or correct 'password' argument.")
      user_email = claimed_email
    else:
      user_email = user.email()

    if error_messages:
      return

    blob_info, = upload_files

    def store_media():
      """Store media object info in datastore.

      Also updates the user-info record to keep count of media objects.

      This function is run as a transaction.
      """
      user_info = UserInfo.get_by_key_name('user:%s' % user_email)
      if user_info is None:
        error_messages.append('User record has been deleted.  '
                              'Try uploading again')
        return

      media = MediaObject(
          parent=user_info,
          owner=user_info,
          blob=blob_info.key(),
          creation=blob_info.creation,
          content_type=blob_info.content_type,
          filename=blob_info.filename,
          size=int(blob_info.size),
          lacks_document=True)

      user_info.media_objects += 1
      db.put(user_info)
      db.put(media)

      if bool(is_doc) and is_doc != "0":
        tag_list = []
        if tags is not None:
          tag_list = [x for x in re.split('\s*,\s*', tags) if x]

        doc = Document(
            parent=user_info,
            owner=user_info,
            pages=[media.key()],
            title=title,
            description=description,
            no_tags=(len(tag_list)==0),
            tags=tag_list)
        db.put(doc)
        media.document = doc.key()
        media.lacks_document = False
        db.put(media)
    db.run_in_transaction(store_media)
Exemplo n.º 44
0
    def post(self):
        Guser = users.get_current_user()
        if Guser:
            vstrChoice = self.request.get('vstrChoice')

            if vstrChoice == "0":
                vstrListID = self.request.get('vstrListID')

                findRequest = Letters.query(Letters.strListID == vstrListID)
                thisArticlesList = findRequest.fetch()

                template = template_env.get_template('templates/newsletter/editor/articlelist.html')
                context = {'thisArticlesList':thisArticlesList}
                self.response.write(template.render(context))

            elif vstrChoice == "1":
                #'&vstrUserID=' + struid + '&vstrEmail=' + email + '&vstrAccessToken=' + accessToken;
                vstrUserID = self.request.get("vstrUserID")
                vstrEmail = self.request.get("vstrEmail")
                vstrAccessToken = self.request.get("vstrAccessToken")



                vstrArticleHeading = self.request.get('vstrArticleHeading')
                vstrURL = self.request.get('vstrURL')
                vstrArticleEditor = self.request.get('vstrArticleEditor')
                vstrListID = self.request.get('vstrListID')
                vstrArticleID = self.request.get('vstrArticleID')

                findRequest = Letters.query(Letters.strArticleID == vstrArticleID)
                thisLettersList = findRequest.fetch()

                if len(thisLettersList) > 0:
                    thisArticle = thisLettersList[0]

                    thisArticle.writeArticlesID(strinput=vstrArticleID)
                    thisArticle.writeLetterBody(strinput=vstrArticleEditor)
                    #TODO- check to see if URL is not already taken if yes then try and differentiate
                    thisArticle.writeHostedLink(strinput=vstrURL)

                    thisArticle.writeLetterHeading(strinput=vstrArticleHeading)
                    thisArticle.put()
                    self.response.write("Succesfully updated your article")
                else:
                    self.response.write("Error saving article")

            elif vstrChoice == "2":
                #'&vstrUserID=' + struid + '&vstrEmail=' + email + '&vstrAccessToken=' + accessToken;
                vstrUserID = self.request.get("vstrUserID")
                vstrEmail = self.request.get("vstrEmail")
                vstrAccessToken = self.request.get("vstrAccessToken")

                vstrArticleID = self.request.get('vstrArticleID')

                findRequest = Letters.query(Letters.strArticleID == vstrArticleID)
                thisArticleList = findRequest.fetch()
                isDel = False
                for thisArticle in thisArticleList:
                    thisArticle.key.delete()
                    isDel = True

                if isDel:
                    self.response.write("Successfully deleted Article")
                else:
                    self.response.write("Article Already deleted")


            elif vstrChoice == "3":
                #'&vstrUserID=' + struid + '&vstrEmail=' + email + '&vstrAccessToken=' + accessToken;
                vstrUserID = self.request.get("vstrUserID")
                vstrEmail = self.request.get("vstrEmail")
                vstrAccessToken = self.request.get("vstrAccessToken")

                vstrArticleHeading = self.request.get('vstrArticleHeading')
                vstrURL = self.request.get('vstrURL')
                vstrArticleEditor = self.request.get('vstrArticleEditor')
                vstrListID = self.request.get('vstrListID')
                vstrArticleID = self.request.get('vstrArticleID')

                findRequest = Letters.query(Letters.strArticleID == vstrArticleID)
                thisLettersList = findRequest.fetch()

                if len(thisLettersList) > 0:
                    thisArticle = thisLettersList[0]
                else:
                    thisArticle = Letters()

                vstrThisDate = datetime.datetime.now()
                strThisDate = datetime.date(year=vstrThisDate.year,month=vstrThisDate.month,day=vstrThisDate.day)
                strThisTime = datetime.time(hour=vstrThisDate.hour,minute=vstrThisDate.minute,second=vstrThisDate.second)

                thisArticle.writeLetterBody(strinput=vstrArticleEditor)
                thisArticle.writeLetterHeading(strinput=vstrArticleHeading)
                thisArticle.writeHostedLink(strinput=vstrURL)
                if thisArticle.writePublished(strinput=True):
                    thisArticle.writeDatePublished(strinput=strThisDate)
                    thisArticle.writeTimePublished(strinput=strThisTime)
                    thisArticle.put()
                    self.response.write("Article Published Successfully")
                else:
                    self.response.write("Error Publishing Article")
Exemplo n.º 45
0
 def get_logged_user(cls):
     user = users.get_current_user()
     user_key = ndb.Key('User', user.email())
     return user_key.get()
    def post(self):
        mobile = self.request.get('mobile')
        if mobile != "true":
            mobile = "false"
        #self.response.out.write('posted!')
        # Die Eingabe aus dem Formular holen
        verzeichnisname = self.request.get('verzeichnisname')
        # Den Bucketnamen aus dem Formular holen
        bucketname = self.request.get('bucket')
        # Das Verzeichnis aus dem Formular holen
        directory = self.request.get('dir')

        # Den Usernamen erfahren
        username = users.get_current_user()

        if verzeichnisname == "":
            # Testen ob ein Name für den neuen key angegeben wurde
            # Wenn kein Name angegeben wurde, kann kein Key angelegt werden
            #fehlermeldung = "Sie haben keine Namen angegeben"
            fehlermeldung = "113"
            if directory == "/":
                self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                              '&bucket=' + bucketname + '&message=' +
                              fehlermeldung)
            else:
                # Den Slash am Ende des Verzeichnisses entfernen
                directory = str(directory[:-1])
                self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                              '&bucket=' + bucketname + '&message=' +
                              fehlermeldung + '&dir=' + directory)
        elif re.search(r'[^\-_a-zA-Z0-9]', verzeichnisname) != None:
            # Testen ob der Name für den neuen key nicht erlaubte Zeichen enthält
            fehlermeldung = "114"
            if directory == "/":
                self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                              '&bucket=' + bucketname + '&message=' +
                              fehlermeldung)
            else:
                # Den Slash am Ende des Verzeichnisses entfernen
                directory = str(directory[:-1])
                self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                              '&bucket=' + bucketname + '&message=' +
                              fehlermeldung + '&dir=' + directory)
        else:
            # Mit S3 verbinden
            conn_s3 = logins3(username)
            # Mit dem Bucket verbinden
            bucket_instance = conn_s3.get_bucket(bucketname)
            # Liste der Keys im Bucket
            liste_keys = bucket_instance.get_all_keys()
            # Anzahl der Keys in der Liste
            laenge_liste_keys = len(liste_keys)

            verzeichnisname = verzeichnisname + '_$folder$'

            # Variable erzeugen zum Erfassen, ob das neue Verzeichnis schon existiert
            schon_vorhanden = 0
            for i in range(laenge_liste_keys):
                # Key-Namen in einen String umwandeln
                vergleich = str(liste_keys[i].name)
                # Vergleichen
                if vergleich == verzeichnisname:
                    # Verzeichnis-Name existiert schon!
                    schon_vorhanden = 1
                    fehlermeldung = "117"
                    if directory == "/":
                        self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                                      '&bucket=' + bucketname + '&message=' +
                                      fehlermeldung)
                    else:
                        # Den Slash am Ende des Verzeichnisses entfernen
                        directory = str(directory[:-1])
                        self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                                      '&bucket=' + bucketname + '&message=' +
                                      fehlermeldung + '&dir=' + directory)

            # Wenn man noch kein Verzeichnis mit dem eingegebenen Namen besitzt...
            if schon_vorhanden == 0:
                try:
                    # Versuch das Verzeichnis anzulegen
                    # Mit dem Bucket sind wir schon verbunden über die Zeile
                    # bucket_instance = conn_s3.get_bucket(bucketname)
                    if directory == '/':
                        key = bucket_instance.new_key(verzeichnisname)
                        key.set_contents_from_string('')
                    else:
                        verzeichnisname = directory + verzeichnisname
                        key = bucket_instance.new_key(verzeichnisname)
                        key.set_contents_from_string('')
                except:
                    # Wenn es nicht klappt...
                    fehlermeldung = "116"
                    if directory == "/":
                        self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                                      '&bucket=' + bucketname + '&message=' +
                                      fehlermeldung)
                    else:
                        # Den Slash am Ende des Verzeichnisses entfernen
                        directory = str(directory[:-1])
                        self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                                      '&bucket=' + bucketname + '&message=' +
                                      fehlermeldung + '&dir=' + directory)
                else:
                    # Wenn es geklappt hat...
                    fehlermeldung = "115"
                    if directory == "/":
                        self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                                      '&bucket=' + bucketname + '&message=' +
                                      fehlermeldung)
                    else:
                        # Den Slash am Ende des Verzeichnisses entfernen
                        directory = str(directory[:-1])
                        self.redirect('/bucket_inhalt?mobile=' + str(mobile) +
                                      '&bucket=' + bucketname + '&message=' +
                                      fehlermeldung + '&dir=' + directory)
Exemplo n.º 47
0
 def check_login(self, *args, **kwargs):
     user = users.get_current_user()
     if not user:
         self.redirect(users.create_login_url(self.request.uri))
     else:
         return handler(self, *args, **kwargs)
Exemplo n.º 48
0
    def get(self):
        print "Content-Type: text/html"
        JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
            extensions=['jinja2.ext.autoescape'],
            autoescape=False)
        template = JINJA_ENVIRONMENT.get_template('viewBlog.html')

        cur_url = self.request.url
        parsed_url = urlparse.urlparse(cur_url)
        bid = urlparse.parse_qs(parsed_url.query)['blogId']
        blogId = bid[0]

        query_type = 0
        query = ""

        try:
            qry = urlparse.parse_qs(parsed_url.query)['query']
            query = qry[0]
            query_type = 1
    #      self.response.write("found value for query")
        except Exception:
            query_type = 2
            query = ""

    #       self.response.write("query is null")

        page = 1
        try:
            pno = urlparse.parse_qs(parsed_url.query)['page']
            page = int(pno[0])
        except Exception:
            page = 1

#       sessionId = session_name[0]
        blogs = []
        parentId = []
        blog_owner = ''
        content = []
        blog_name = ""
        tags = []

        p = Pages.get_by_id(int(blogId))
        views = p.views
        views = views + 1
        p.views = views
        p.put()
        blogs = db.GqlQuery("SELECT * FROM Blogs WHERE ParentBlogId=" +
                            blogId + " ORDER BY create_time DESC")
        for b in blogs:
            if b.tag1 != "" and b.tag1 not in tags:
                tags.append(b.tag1)

            if b.tag2 != "" and b.tag2 not in tags:
                tags.append(b.tag2)

            if b.tag3 != "" and b.tag3 not in tags:
                tags.append(b.tag3)

            if b.tag4 != "" and b.tag4 not in tags:
                tags.append(b.tag4)

            if b.tag5 != "" and b.tag5 not in tags:
                tags.append(b.tag5)
        if query_type == 1:
            #     self.response.write(query_type)
            all_blogs = db.GqlQuery(
                'SELECT * from Blogs ORDER BY create_time DESC')
            blogs = []
            for b in all_blogs:
                if query in [b.tag1, b.tag2, b.tag3, b.tag4, b.tag5]:
                    blogs.append(b)

        blogpage = Pages.get_by_id(int(blogId))
        blog_name = blogpage.page_name

        likes = []
        comments = []

        more = 0
        count = -1
        selected = 0
        per_page = 10
        subset_blogs = []
        blogsnlikes = []
        login = 0
        user = ""
        username = ""

        user = users.get_current_user()

        #      try:
        #           user = UserLoggedIn.get_by_id(int(sessionId))
        #           username = user.blogger.nickname()
        #           login = 1
        #      except db.BadKeyError:
        #           login = 0

        if user:
            login = 1
            username = user.nickname()
        else:
            login = 0
            login_url = users.create_login_url(cur_url)
        following = 0

        dbquery = "Select * from Follow where item='" + blogId + "' AND user='******' AND type=" + str(
            query_type)
        follow_list = db.GqlQuery(dbquery)
        follow_count = 0

        for f in follow_list:
            follow_count = follow_count + 1

        if follow_count > 0:
            following = 1

#      count_blogs = count(blogs)

        for b in blogs:
            count = count + 1
            if (page - 1) * per_page > count:
                continue
            selected = selected + 1
            blogid = str(b.key().id())
            query_string = "SELECT * FROM Comments WHERE blogid ='" + blogid + "'"
            like_count = db.GqlQuery(query_string)
            #           lc = Likes.filter('blogid=',blogid).get().count()
            count_likes = 0
            for lc in like_count:
                count_likes = count_likes + 1
#           self.response.write(count_likes)
            likes.append(str(count_likes))
            subset_blogs.append(b)
            #           self.response.write(b.title)
            text_content = unicode(b.content, "utf8")
            #         self.response.write(text_content)

            #\bhttps?://\w*\b(?<!(png|jpg|gif))
            #r = re.compile(r"(https?://[^\s]+)")
            #c = Convert();
            link_content = re.sub(r'(https?://[^\s]+)', convert, text_content)
            #          self.response.write(link_content)
            content.append(link_content)
            if selected == per_page:
                #        if count != count_blogs:
                more = 1
                break


#       self.response.write(likes)
        blogsnlikes = zip(subset_blogs, likes, content)
        #       self.response.write(blogsnlikes)
        #      self.response.write(cur_url)
        nextpage = page + 1
        #   self.response.write(page)
        #   self.response.write(nextpage)
        template_values = {
            #                          'blogs': subset_blogs,
            'blogsnlikes': blogsnlikes,
            'blog_owner': blog_owner,
            'more': more,
            'nextpage': nextpage,
            'query': query,
            'query_type': query_type,
            'username': username,
            #                          'sessionId' :sessionId,
            'cur_url': cur_url,
            'following': following,
            'parentId': parentId,
            'login': login,
            'blogname': blog_name,
            'tags': tags,
            'blogId': blogId,
            'views': views
            #                          'likes':likes
        }

        self.response.write(template.render(template_values))
Exemplo n.º 49
0
 def post(self):
     """Save the user's preferences."""
     user = users.get_current_user()
     snipper_user = models.GetSnippetUser(user)
     logging.debug('Saving settings for %s', user)
     errors = []
     date_format = str(
         self.request.get('date_format', snipper_user.date_format))
     snippet_format = self.request.get('snippet_format',
                                       snipper_user.snippet_format)
     snipper_user.mail_snippets = bool(
         self.request.get('mail_snippets', False))
     snipper_user.send_confirm = bool(
         self.request.get('send_confirm', False))
     snipper_user.reset_day = int(
         self.request.get('reset_day', snipper_user.reset_day))
     snipper_user.reset_hour = int(
         self.request.get('reset_hour', snipper_user.reset_hour))
     timezone = self.request.get('timezone')
     try:
         assert pytz.timezone(timezone)
     except pytz.UnknownTimeZoneError:
         logging.exception('Invalid timezone: %s', timezone)
         errors.append('Invalid timezone: %s.' % timezone)
     else:
         snipper_user.timezone = timezone
         # Convert to UTC for storage.
         utc_reset = util.ResetDatetimeToUtc(snipper_user.reset_day,
                                             snipper_user.reset_hour,
                                             snipper_user.timezone)
         snipper_user.utc_reset_day = utc_reset.weekday()
         snipper_user.utc_reset_hour = utc_reset.hour
     try:
         assert datetime.datetime.now().strftime(date_format)
     except (ValueError, TypeError):
         errors.append('Invalid date format "%s".' % date_format)
         logging.exception('date_format "%s" failed validation.',
                           date_format)
     else:
         snipper_user.date_format = date_format
     try:
         assert snippet_format % 'test snippet'
     except (ValueError, TypeError):
         errors.append('Invalid snippet format "%s".' % snippet_format)
         logging.exception('snippet_format "%s" is invalid.',
                           snippet_format)
     else:
         snipper_user.snippet_format = snippet_format
     logging.debug(
         'date:%s, snip:%s, mail:%s, conf:%s, day:%s, hour:%s, tz:%s'
         'utc_day:%s, utc_hour:%s', snipper_user.date_format,
         snipper_user.snippet_format, snipper_user.mail_snippets,
         snipper_user.send_confirm, snipper_user.reset_day,
         snipper_user.reset_hour, snipper_user.timezone,
         snipper_user.utc_reset_day, snipper_user.utc_reset_hour)
     try:
         db.put(snipper_user)
     except (db.Timeout, db.InternalError):
         logging.exception('Could not save settings.')
         errors.append('Could not save settings.')
     else:
         memcache_key = 'SnippetUser-' + str(user)
         memcache.set(memcache_key, snipper_user)
     if errors:
         errors = urllib.quote_plus(','.join(errors))
         return self.redirect('/settings?errors=' + errors)
     # Drop the last two weeks from memcache.
     memcache.delete_multi(
         ['snippets_%s_%d' % (str(user), x) for x in (0, 1)])
     self.redirect('/?msg=Settings+saved.')
Exemplo n.º 50
0
 def get_current_user(cls):
     return users.get_current_user()
Exemplo n.º 51
0
def IsInternalUser():
  """Checks whether the user should be able to see internal-only data."""
  user = users.get_current_user()
  domain = stored_object.Get(INTERNAL_DOMAIN_KEY)
  return user and domain and user.email().endswith('@' + domain)
Exemplo n.º 52
0
 def get(self):
     self.response.headers['Content-Type'] = 'text/plain'
     self.response.write(
         'Hello, ' +
         str(ModelLoader.get_user(users.get_current_user().user_id())))
Exemplo n.º 53
0
def get_present_user():
    return ndbusers.get_current_user()
Exemplo n.º 54
0
def IsValidSheriffUser():
  """Checks whether the user should be allowed to triage alerts."""
  user = users.get_current_user()
  sheriff_domains = stored_object.Get(SHERIFF_DOMAINS_KEY)
  return user and sheriff_domains and any(
      user.email().endswith('@' + domain) for domain in sheriff_domains)
Exemplo n.º 55
0
    def post(self):
        answer = self.request.get('answer')
        intensityAnswer = int(self.request.get('intensityAnswer'))
        my_emotion = self.request.get('my_emotion')
        time = datetime.now()
		# time = datetime.strftime(time, '%H:%M')
        #time = self.timestamp.strftime('%Y-%m-%d %H:%M:%S')
        #self.response.write(answer)
        EmotionData = Feelings(chosen_reason =answer,chosen_intensity =intensityAnswer, chosen_emotion=my_emotion, chosen_time=time, user = users.get_current_user().user_id())
		#e = Feelings(chosen_emotion = "sad", chosen_intensity = 3)
		#e.put()
        EmotionData.put()
        #time.sleep(0.5)
        self.redirect('/dailylog')
Exemplo n.º 56
0
 def IsInternalUser():
   username = users.get_current_user()
   return bool(utils.GetCachedIsInternalUser(username))
Exemplo n.º 57
0
    def get(self, post_id):
        user = users.get_current_user().nickname()

        if user in ADMIN or user == Post.get_by_id(int(post_id)).name:
            return self.render_template("delete.html")
Exemplo n.º 58
0
def get_banners_for_current_user():
    banners = Banner.all()
    banners.order('-created')
    return banners.filter('author_id = ', users.get_current_user().nickname())
Exemplo n.º 59
0
    def get(self, topic_id):
        user = users.get_current_user()
        if user.nickname() in ADMIN:
            user.admin = True

        return self.render_template("delete.html")
    def post(self, community):
        #used to process post requests from /addalbums
        user = users.get_current_user()
        if user:
            email = user.email()
            if (os.getenv('SERVER_SOFTWARE') and os.getenv(
                    'SERVER_SOFTWARE').startswith('Google App Engine/')):
                db = MySQLdb.connect(
                    unix_socket='/cloudsql/hack-the-north-1:its-not-django',
                    db='musicsite',
                    user='******')
            else:
                db = MySQLdb.connect(host='localhost',
                                     user='******',
                                     passwd="htndjango",
                                     db="musicsite")

            cursor = db.cursor()
            cursor.execute(
                'SELECT * FROM users WHERE email = "%s" AND invite_accepted=1 AND community_id=%s'
                % (email, community))
            if (cursor.rowcount == 0):
                self.redirect('/communities')
            else:
                album_name = cgi.escape(self.request.get('album_name'))
                album_year = cgi.escape(self.request.get('album_year'))
                album_genre = cgi.escape(self.request.get('album_genre'))
                album_artist = cgi.escape(self.request.get('album_artist'))
                posted_by = cgi.escape(self.request.get('posted_by'))

                cursor.execute(
                    'INSERT INTO albums (album_name,album_year,album_genre,album_artist,posted_by,addition_date,community_id) VALUES ("%s",%s,"%s","%s","%s",NOW(),%s);'
                    % (album_name, album_year, album_genre, album_artist,
                       posted_by, community))
                db.commit()
                cursor.execute('SELECT name FROM communities WHERE id = %s' %
                               community)
                community_name = ""
                for row in cursor:
                    community_name = row[0]

                html_string = ""
                cursor.execute(
                    'SELECT id, album_name, album_artist FROM albums WHERE community_id = %s'
                    % community)
                for row in cursor:
                    album_name = row[1]
                    album_artist = row[2]
                    album_id = row[0]
                    album_string = """<div class="album">
                                          <a href="/albums/%s">
                                            <img class="album_art" src="http://placekitten.com/g/250/250" alt="%s">
                                          </a>
                                          <p><b>%s</b><br />%s</p>
                                        </div>""" % (album_id, album_name,
                                                     album_name, album_artist)
                    html_string = html_string + album_string

                template_messages = {
                    "community_id": community,
                    "community_name": community_name
                }
                self.render_response('community_albums.html',
                                     **template_messages)
                self.response.write(html_string)
                self.response.write('</div></div></body></html>')

        else:
            self.redirect('/communities')