Esempio n. 1
0
    def showHome(self):
        """
        Sets up template data and renders homepage template.

        """
        homepage = Config.get("homepage")
        features = Config.get("features")

        locationData = mLocation.getSimpleLocationDictionary(self.db)
        allIdeasData = mIdea.getMostRecentIdeas(self.db, homepage["num_recent_ideas"])

        locations = dict(data=locationData, json=json.dumps(locationData))
        allIdeas = dict(data=allIdeasData, json=json.dumps(allIdeasData))

        news = self.getNewsItems()

        if bool(features.get("is_display_leaderboard")):
            leaderboardProjects = mProject.getLeaderboardProjects(self.db, 6)
            self.template_data["leaderboard"] = leaderboardProjects

        if bool(features.get("is_display_featured_projects")):
            featuredProjects = mProject.getFeaturedProjects(self.db, 6)
            self.template_data["featured_projects"] = featuredProjects

        if bool(features.get("is_community_leaders_displayed")):
            community_leaders = self.orm.query(models.CommunityLeader).order_by("`order`").all()
            self.template_data["community_leaders"] = community_leaders

        self.template_data["locations"] = locations
        self.template_data["all_ideas"] = allIdeas
        self.template_data["news"] = news

        return self.render("home", {"locations": locations, "all_ideas": allIdeas})
Esempio n. 2
0
def emailAccountDeactivation(email):
    """
    Email deleted users.  Using template: account_deactivation
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    subject = "Your account has been deactivated"
    link = "%stou" % Config.get('default_host')
    template_values = {
        'link': link,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/account_deactivation', template_values, suffix = 'txt')

    # Send email.
    try:
        return Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])
    except Exception, e:
        log.info("*** couldn't send account deactivation email")
        log.error(e)
        return False
Esempio n. 3
0
    def showHome(self):
        """
        Sets up template data and renders homepage template.

        """
        homepage = Config.get('homepage')
        features = Config.get('features')

        locationData = mLocation.getSimpleLocationDictionary(self.db)
        allIdeasData = mIdea.getMostRecentIdeas(self.db, homepage['num_recent_ideas']);

        locations = dict(data = locationData, json = json.dumps(locationData))
        allIdeas = dict(data = allIdeasData, json = json.dumps(allIdeasData))

        news = self.getNewsItems()

        if (bool(features.get('is_display_leaderboard'))):
            leaderboardProjects = mProject.getLeaderboardProjects(self.db, 6)
            self.template_data['leaderboard'] = leaderboardProjects

        if (bool(features.get('is_display_featured_projects'))):
            featuredProjects = mProject.getFeaturedProjects(self.db, 6)
            self.template_data['featured_projects'] = featuredProjects

        if (bool(features.get('is_community_leaders_displayed'))):
            community_leaders = self.orm.query(models.CommunityLeader) \
                .order_by('`order`') \
                .all()
            self.template_data['community_leaders'] = community_leaders

        self.template_data['locations'] = locations
        self.template_data['all_ideas'] = allIdeas
        self.template_data['news'] = news

        return self.render('home', {'locations':locations, 'all_ideas':allIdeas})
Esempio n. 4
0
def emailTempPassword(email, password):
    """
    Email temporary password.  Using template: forgot_password
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    subject = "Your password has been reset"
    link = "%slogin" % Config.get('default_host')
    link = "%stou" % Config.get('default_host')
    template_values = {
        'password': password,
        'link': link,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/forgot_password', template_values, suffix = 'txt')

    # Send email.
    try:
        return Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])
    except Exception, e:
        log.info("*** couldn't send forgot password email")
        log.error(e)
        return False
Esempio n. 5
0
def emailProjectEndorsement(email, title, leaderName):
    """
    Email project admins about endorsements.  Using template: project_endorsement
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    subject = "%s liked your project!" % leaderName
    template_values = {
        'title': title,
        'leader_name': leaderName,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/project_endorsement', template_values, suffix = 'txt')
         
    # Send email.
    try:
        return Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])
    except Exception, e:
        log.info("*** couldn't send endorsement email")
        log.error(e)
        return False
Esempio n. 6
0
 def setUp(self):
     # HACK: We kept getting db.printing inexplicably set to True, so patch
     # it to be False here.
     _real_db_execute = web.db.DB._db_execute
     def _db_execute(self, cur, sql_query):
         self.printing = False
         return _real_db_execute(self, cur, sql_query)
     web.db.DB._db_execute = _db_execute
         
     # Set the dev flag in Config to False.
     Config.load()
     Config.data['dev'] = False
     
     # Set the debug flag to true, despite what is in the config file
     web.config.debug = False
     web.config.session_parameters['cookie_name'] = 'gam'
     
     # TODO: Clean up this initialization
     web.ctx.method = ''
     web.ctx.path = ''
     import StringIO
     web.ctx.env = {'wsgi.input': StringIO.StringIO(),
                    'REQUEST_METHOD': ''}
     
     # Set up the routes
     app = web.application(main.ROUTES, globals())
     
     # Grab a database connection
     self.db = main.sessionDB()
     
     # Initialize the session holder (I don't know what that is yet)
     #main.SessionHolder.set(web.session.Session(app, web.session.DBStore(db, 'web_session')))
     
     # Finally, create a test app
     self.app = TestApp(app.wsgifunc())
Esempio n. 7
0
def send(phone, message):
    
    log.info("Sending sms...")    
    
    message = clean(message)
    
    settings = Config.get('twilio')
    account = twilio.Account(settings['sid'], settings['token'])
    callback = Config.base_url()
    if not callback:
        callback = Config.get('default_host')
    
    data = {    'From': settings['phone'],
                'To': phone,
                'Body': message,
                'StatusCallback': "%stwilio/status" % callback
                }
    log.debug(data)
    try:
        response = account.request('/%s/Accounts/%s/SMS/Messages.json' % (settings['api'], settings['sid']), 'POST', data)
        log.info("--> %s" % response)        
        response = json.loads(response)        
        smsid = response['TwilioResponse']['SMSMessage']['Sid']
        status = "passed"
    except Exception, e:
        log.error(e)
        smsid = None
        status = "blocked"        
Esempio n. 8
0
def emailResourceApproval(email, title):
    """
    Email resource owner on approval.  Using template: resource_approval
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    subject = "Your resource has been approved"
    template_values = {
        'link': Config.get('default_host'),
        'title': title,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/resource_approval', template_values, suffix = 'txt')

    # Send email.
    try:
        return Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])  
    except Exception, e:
        log.info("*** couldn't send resource approval email")
        log.error(e)
        return False
Esempio n. 9
0
def emailUnauthenticatedUser(email, authGuid):
    """
    Send unauthenticated user a link to authenticate.  Using 
    template: auth_user
        
    @type   email: string
    @param  email: Email address to send to
    
    @rtype: *
    @returns: Emailer send response.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    subject = "Please authenticate your account"
    link = "%sjoin/auth/%s" % (Config.get('default_host'), authGuid)
    template_values = {
        'link': link,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/auth_user', template_values, suffix = 'txt')
            
    # Send email.            
    try:
        return Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])  
    except Exception, e:
        log.info("*** couldn't send authenticate user email")
        log.error(e)
        return False
Esempio n. 10
0
 def test_load(self):
     """
     Test `load` method and that a config has been loaded.
     
     """
     Config.load()
     self.assertIsNotNone(Config.data)
     self.assertIsInstance(Config.data, dict)
Esempio n. 11
0
 def test_load(self):
     """
     Test `load` method and that a config has been loaded.
     
     """
     Config.load()
     self.assertIsNotNone(Config.data)
     self.assertIsInstance(Config.data, dict)
Esempio n. 12
0
 def getHomepageQuestion(self):
     q = None
 
     if (Config.get('homepage').get('is_question_from_cms')):
         sql = "select question from homepage_question where is_active = 1 and is_featured = 1"
         data = list(self.db.query(sql))
         
         if (len(data) == 1):
             q = data[0].question
             
     if (not q):
         q = Config.get('homepage').get('question')
         
     return q
Esempio n. 13
0
    def getHomepageQuestion(self):
        q = None

        if (Config.get('homepage').get('is_question_from_cms')):
            sql = "select question from homepage_question where is_active = 1 and is_featured = 1"
            data = list(self.db.query(sql))

            if (len(data) == 1):
                q = data[0].question

        if (not q):
            q = Config.get('homepage').get('question')

        return q
Esempio n. 14
0
 def GET(self, action=None):
     """
     Get for Blitz.io route
     
     """
     response = Config.get('blitz_io').get('response')
     return response
Esempio n. 15
0
 def GET(self, action = None):
     """
     Get for Blitz.io route
     
     """
     response = Config.get('blitz_io').get('response')
     return response
    def __init__(self):
        super().__init__()

        self.router = Router()
        self.controller = self.router
        self.config = Config()
        self._session_repository = SessionRepository()

        login_controller = LoginController()
        login_controller.bind_routes("login", self.router)

        role_controller = RoleController()
        role_controller.bind_routes("role", self.router)

        account_form_controller = AccountFormController()
        account_form_controller.bind_routes("account", self.router)
        account_list_controller = AccountListController()
        account_list_controller.bind_routes("account", self.router)

        company_form_controller = CompanyFormController()
        company_form_controller.bind_routes("company", self.router)
        company_list_controller = CompanyListController()
        company_list_controller.bind_routes("company", self.router)

        def redirect_to_index(state):
            (request, response, session) = state.unfold()
            response.setRedirect("/index.html")
            return state

        self.router.addMapping(r"^/$", redirect_to_index)

        self.router.addStaticMapping(r"^/static/", "../client/dist")
        self.router.addStaticMapping(r"^/", "../client/dist")
Esempio n. 17
0
 def getS3Path(self, fileid):
     """
     Get the path to the file given by the fileid on the S3 server.
     
     """
     return "%(file_path)s/%(file_id)s" % {'file_path': Config.get('media').get('file_path'),
                                          'file_id': fileid}
Esempio n. 18
0
    def newProject(self):
        if (self.request('main_text')): return False

        supported_features = Config.get('features')

        if (self.user):
            owner_user_id = self.user.id
            title = self.request('title')
            description = self.request('text')
            organization = self.request('organization')
            locationId = util.try_f(int, self.request('location_id'), -1)
            imageId = self.request('image')
            keywords = [word.strip() for word in self.request('keywords').split(',')] if not util.strNullOrEmpty(self.request('keywords')) else []
            resourceIds = self.request('resources').split(',')
            isOfficial = self.user.isAdmin and supported_features.get('is_official_supported')

            projectId = mProject.createProject(self.db, owner_user_id, title, description, ' '.join(keywords), locationId, imageId, isOfficial, organization)

            for resourceId in resourceIds:
                log.info("*** insert resource id %s" % resourceId)
                mProject.addResourceToProject(self.db, projectId, resourceId)

            if (projectId):
                return projectId
            else:
                log.error("*** couldn't create project")
                return False
        else:
            log.error("*** only logged in users can create projects")
            return False
Esempio n. 19
0
    def GET(self, action=None, param0=None):
        project_user = dict(is_member=True, is_project_admin=True)
        self.template_data['project_user'] = dict(
            data=project_user, json=json.dumps(project_user))
        self.template_data['homepage_question'] = self.getHomepageQuestion()

        if (not action or action == 'home'):
            return self.showHome()
        elif (action == 'leaderboard'):
            return self.showLeaderboard()
        elif (action == 'mobile'):
            return self.showMobile()
        elif (action == 'bb'):
            return self.showMobile(isBlackBerry=True)

        # Main login page
        # TODO: This should be consolidated with the twitter & facebook actions
        elif (action == 'login'):
            return self.showLogin()

        # Twetter-related actions
        elif action == 'twitter':
            return self._twitter_action(action=param0)

        # The "correct" facebook URLs once we change them in the app(s)
        elif action == 'facebook':
            return self._facebook_action(action=param0)

        # Miscellaneous actions
        elif (action == 'nyc'):
            self.redirect('http://nyc.changeby.us/')
        elif (action == 'beta'):
            return self.showBeta()

        # About page can be city-specific
        elif (action == 'about'):
            for action in [
                    "%s_about" % Config.get("site").get("city_id"), "about"
            ]:
                template = os.path.dirname(
                    __file__) + '/../templates/%s.html' % action
                if os.path.exists(template):
                    return self.render(action)

            # If we got here, the template was not found
            return self.not_found()

        else:
            # This is the default for all pages.  We should check
            # if there is a matching template, and if not, throw
            # a 404.

            template = os.path.dirname(
                __file__) + '/../templates/' + action + '.html'
            print template
            if not os.path.exists(template):
                return self.not_found()
            else:
                return self.render(action)
Esempio n. 20
0
 def test_get_all(self):
     """
     Test `get_all` method
     
     """
     data = Config.get_all()
     self.assertIsNotNone(data)
     self.assertIsInstance(data, dict)
Esempio n. 21
0
def directMessageUser(db, toUserId, toName, toEmail, fromUserId, fromName, message):
    """
    Email user about direct message.  Using template: direct_message
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    #email = "%s <%s>" % (toName, toEmail)
    email = toEmail
    subject = "Change By Us message from %s" % fromName
    link = "%suseraccount/%s" % (Config.get('default_host'), fromUserId)
    template_values = {
        'name': fromName,
        'message': message,
        'link': link,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/direct_message', template_values, suffix = 'txt')

    # Send email.
    try:
        isSent = Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])
                                                       
        if (isSent):
            db.insert('direct_message', message = message, to_user_id = toUserId, from_user_id = fromUserId)
            return True
        else:
            log.info("*** couldn't log direct message")
            # Not sure if best to return False
            return False

    except Exception, e:
        log.info("*** couldn't send direct message email")
        log.error(e)
        return False
Esempio n. 22
0
 def test_get_all(self):
     """
     Test `get_all` method
     
     """
     data = Config.get_all()
     self.assertIsNotNone(data)
     self.assertIsInstance(data, dict)
Esempio n. 23
0
 def db_connect(cls):
     settings = Config.get('database')
     cls._db = web.database(dbn=settings['dbn'],
                            user=settings['user'],
                            pw=settings['password'],
                            db=settings['db'],
                            host=settings['host'])
     log.info("Connected to db: %s" % cls._db)
Esempio n. 24
0
 def getS3Path(self, fileid):
     """
     Get the path to the file given by the fileid on the S3 server.
     
     """
     return "%(file_path)s/%(file_id)s" % {
         'file_path': Config.get('media').get('file_path'),
         'file_id': fileid
     }
Esempio n. 25
0
def validate(request):    
    # this is just a cheap validate that depends on the attacker not knowing our AccountSid, it's not secure        
        
    settings = Config.get('twilio')        
    if request('AccountSid') != settings['sid']:
        log.error("Request from Twilio does not have correct sid! Possibly an attack! Blocking message.")
        log.error("--> was theirs [%s] vs ours [%s]" % (request('AccountSid'), settings['sid']))
        return False
    return True
Esempio n. 26
0
 def getLocalPath(self, fileid):
     """
     Get the path to the file given by the fileid on the local file system.
     This is used only to temporarily save the file before uploading it to
     the S3 server.
     
     """
     return "%(file_path)s/%(file_id)s" % {'file_path': Config.get('media').get('file_path'),
                                          'file_id': fileid}
Esempio n. 27
0
    def test_dev(self):
        """
        Test `dev` method with various manually values
        
        """
        dev = Config.dev()
        self.assertIsInstance(dev, bool)

        Config.data['dev'] = 'True'
        dev = Config.dev()
        self.assertFalse(dev)

        Config.data['dev'] = True
        dev = Config.dev()
        self.assertTrue(dev)

        Config.data['dev'] = 'Yes'
        dev = Config.dev()
        self.assertFalse(dev)
Esempio n. 28
0
 def test_dev(self):
     """
     Test `dev` method with various manually values
     
     """
     dev = Config.dev()
     self.assertIsInstance(dev, bool)
     
     Config.data['dev'] = 'True'
     dev = Config.dev()
     self.assertFalse(dev)
     
     Config.data['dev'] = True
     dev = Config.dev()
     self.assertTrue(dev)
     
     Config.data['dev'] = 'Yes'
     dev = Config.dev()
     self.assertFalse(dev)
Esempio n. 29
0
    def GET(self, action=None, param0=None):
        project_user = dict(is_member = True,
                              is_project_admin = True)
        self.template_data['project_user'] = dict(data = project_user, json = json.dumps(project_user))
        self.template_data['homepage_question'] = self.getHomepageQuestion()

        if (not action or action == 'home'):
            return self.showHome()
        elif (action == 'leaderboard'):
            return self.showLeaderboard()
        elif (action == 'mobile'):
            return self.showMobile()
        elif (action == 'bb'):
            return self.showMobile(isBlackBerry = True)

        # Main login page
        # TODO: This should be consolidated with the twitter & facebook actions
        elif (action == 'login'):
            return self.showLogin()
        
        # Twetter-related actions
        elif action == 'twitter':
            return self._twitter_action(action=param0)

        # The "correct" facebook URLs once we change them in the app(s)
        elif action == 'facebook':
            return self._facebook_action(action=param0)

        # Miscellaneous actions
        elif (action == 'nyc'):
            self.redirect('http://nyc.changeby.us/')
        elif (action == 'beta'):
            return self.showBeta()
        
        # About page can be city-specific
        elif (action == 'about'):
            for action in ["%s_about" % Config.get("site").get("city_id"), "about"]:
                template = os.path.dirname(__file__) + '/../templates/%s.html' % action
                if os.path.exists(template):
                    return self.render(action)
                
            # If we got here, the template was not found
            return self.not_found()
            
        else:
            # This is the default for all pages.  We should check
            # if there is a matching template, and if not, throw
            # a 404.
            
            template = os.path.dirname(__file__) + '/../templates/' + action + '.html'
            print template
            if not os.path.exists(template):
                return self.not_found()
            else:
                return self.render(action)
Esempio n. 30
0
 def getLocalPath(self, fileid):
     """
     Get the path to the file given by the fileid on the local file system.
     This is used only to temporarily save the file before uploading it to
     the S3 server.
     
     """
     return "%(file_path)s/%(file_id)s" % {
         'file_path': Config.get('media').get('file_path'),
         'file_id': fileid
     }
Esempio n. 31
0
def emailResourceNotification(email, projectId, title, description, resourceName):
    """
    Email resource contacts on resource add.  Using template: resource_notification
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    subject = "A project on Changeby.us has added %s as a resource" % resourceName
    link = "%sproject/%s" % (Config.get('default_host'), str(projectId))
    template_values = {
        'title': title,
        'description': description,
        'resource_name': resourceName,
        'link': link,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/resource_notification', template_values, suffix = 'txt')
    
    # If dev, don't email resources
    if (Config.get('dev')):
        log.info("*** body = %s" % body)
        return True

    # Send email.
    try:
        return Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])
    except Exception, e:
        log.info("*** couldn't send resource notification email")
        log.error(e)
        return False
Esempio n. 32
0
 def test_manualSetConfig(self):
     """
     Test manually setting a value.
     
     """
     # Assert that value is not there
     self.assertNotIn('testing', Config.data)
     
     # Set new value and assert it is there
     Config.data['testing'] = True
     data = Config.get_all()
     self.assertTrue(data['testing'])
Esempio n. 33
0
    def get_supported_languages(self):
        """
        Find the language files available in the translations directory. Returns
        a dictionary which has language codes as keys, and human-readable
        language names as values.

        """
        try:
            enabled_langs = Config.get('lang')
        except KeyError:
            enabled_langs = {}
        return enabled_langs
Esempio n. 34
0
    def test_manualSetConfig(self):
        """
        Test manually setting a value.
        
        """
        # Assert that value is not there
        self.assertNotIn('testing', Config.data)

        # Set new value and assert it is there
        Config.data['testing'] = True
        data = Config.get_all()
        self.assertTrue(data['testing'])
Esempio n. 35
0
    def get_supported_languages(self):
        """
        Find the language files available in the translations directory. Returns
        a dictionary which has language codes as keys, and human-readable
        language names as values.

        """
        try:
            enabled_langs = Config.get('lang')
        except KeyError:
            enabled_langs = {}
        return enabled_langs
Esempio n. 36
0
	def load_config(self):
		from framework.config import Config

		default_config = Config.default_config()
		app_config = Config.create(self.config_filepath)
		Config.install(self, default_config)
		Config.install(self, app_config)
Esempio n. 37
0
    def load_config(self):
        from framework.config import Config

        default_config = Config.default_config()
        app_config = Config.create(self.config_filepath)
        Config.install(self, default_config)
        Config.install(self, app_config)
Esempio n. 38
0
    def showHome(self):
        """
        Sets up template data and renders homepage template.

        """
        homepage = Config.get('homepage')
        features = Config.get('features')

        locationData = mLocation.getSimpleLocationDictionary(self.db)
        allIdeasData = mIdea.getMostRecentIdeas(self.db,
                                                homepage['num_recent_ideas'])

        locations = dict(data=locationData, json=json.dumps(locationData))
        allIdeas = dict(data=allIdeasData, json=json.dumps(allIdeasData))

        news = self.getNewsItems()

        if (bool(features.get('is_display_leaderboard'))):
            leaderboardProjects = mProject.getLeaderboardProjects(self.db, 6)
            self.template_data['leaderboard'] = leaderboardProjects

        if (bool(features.get('is_display_featured_projects'))):
            featuredProjects = mProject.getFeaturedProjects(self.db, 6)
            self.template_data['featured_projects'] = featuredProjects

        if (bool(features.get('is_community_leaders_displayed'))):
            community_leaders = self.orm.query(models.CommunityLeader) \
                .order_by('`order`') \
                .all()
            self.template_data['community_leaders'] = community_leaders

        self.template_data['locations'] = locations
        self.template_data['all_ideas'] = allIdeas
        self.template_data['news'] = news

        return self.render('home', {
            'locations': locations,
            'all_ideas': allIdeas
        })
Esempio n. 39
0
 def getNewsItems(self):
     data = []
     feedUrl = Config.get('blog_host_feed')
     if (feedUrl):
         try:
             # BUGFIX: couldn't parse json from production blog, hence the string conversion
             # eholda 2011-06-19
             raw = urllib2.urlopen(feedUrl, timeout = 1)
             data = json.loads(raw.read())
             raw.close()
         except Exception, e:
             log.info("*** couldn't get feed for news items at %s" % feedUrl)
             log.error(e)
Esempio n. 40
0
    def setUp(self):
        Config.load()

        # Use the test_db, so that you don't blow stuff away.
        db_config = Config.get('database')
        if 'test_db' in db_config and db_config['test_db']:
            db_config['db'] = db_config['test_db']

        # Grab a database connection
        self.db = main.sessionDB()
        self.install_db_structure(self.db)
        self.load_db_fixtures(self.db, *self.fixtures)

        # HACK: We kept getting db.printing inexplicably set to True, so patch
        # it to be False here.
        _real_db_execute = web.db.DB._db_execute
        def _db_execute(self, cur, sql_query):
            self.printing = False
            return _real_db_execute(self, cur, sql_query)
        web.db.DB._db_execute = _db_execute

        super(DbFixturesMixin, self).setUp()
Esempio n. 41
0
def emailProjectJoin(email, projectId, title, userId, userName):
    """
    Email project admins when new user joins.  Using template: project_join
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    defaultUrl = Config.get('default_host')
    subject = "A new member %s has joined your project %s" % (userName, title)
    userLink = "%suseraccount/%s" % (defaultUrl, str(userId))
    memberLink = "%sproject/%s#show,members" % (defaultUrl, str(projectId))
    template_values = {
        'title': title,
        'user_name': userName,
        'user_link': userLink,
        'member_link': memberLink,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/project_join', template_values, suffix = 'txt')
         
    # Send email.
    try:
        return Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])
    except Exception, e:
        log.info("*** couldn't send join email")
        log.error(e)
        return False
Esempio n. 42
0
 def getNewsItems(self):
     data = []
     feedUrl = Config.get('blog_host_feed')
     if (feedUrl):
         try:
             # BUGFIX: couldn't parse json from production blog, hence the string conversion
             # eholda 2011-06-19
             raw = urllib2.urlopen(feedUrl, timeout=1)
             data = json.loads(raw.read())
             raw.close()
         except Exception, e:
             log.info("*** couldn't get feed for news items at %s" %
                      feedUrl)
             log.error(e)
Esempio n. 43
0
def sendSMSInvite(db, phone, projectId):
    log.info("*** sending invite to %s" % phone)  
    
    try:
        if (not isPhoneStopped(db, phone)):
            link = "%sproject/%s" % (Config.get('default_host'), str(projectId))
            message = "You've been invited to a project on changeby.us. Visit %s to see the project. Reply 'STOP' to stop changeby.us messages." % link        
            return helpers.sms.send(phone, message)
        else:
            return False    
    except Exception, e:
        log.info("*** something failed in sending sms invite")
        log.error(e)
        return False    
Esempio n. 44
0
def emailInvite(email, inviterName, projectId, title, description, message = None):
    """
    Send invitation email.  Using template: project_invite
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    subject = "You've been invited by %s to join a project" % inviterName
    link = "%sproject/%s" % (Config.get('default_host'), str(projectId))
    template_values = {
        'inviter': inviterName,
        'title':title,
        'description':description,
        'link': link,
        'message': message,
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/project_invite', template_values, suffix = 'txt')     
    
    # Send email.
    try:
        return Emailer.send(email, subject,  body, from_name = emailAccount['from_name'], 
            from_address = emailAccount['from_email'])  
    except Exception, e:
        log.info("*** couldn't send invite email")
        log.error(e)
        return False
Esempio n. 45
0
def emailIdeaConfirmation(email, responseEmail, locationId):
    """
    Email upon idea submission.  Using template: idea_confirmation
        
    @type   email: string
    @param  email: Email address to send to
    ...
    
    @rtype: Boolean
    @returns: Whether emailer was successful or not.
    
    """
    
    # Create values for template.
    emailAccount = Config.get('email')
    host = Config.get('default_host')
    subject = "Thanks for submitting an idea to Change by Us!"
    searchLink = "%ssearch?location_id=%s" % (host, locationId)
    createLink = "%screate" % host
    template_values = {
        'search_link': searchLink,
        'create_link': createLink,
        'response_email': emailAccount['from_email'],
        'config': Config.get_all()
    }
    
    # Render email body.
    body = Emailer.render('email/idea_confirmation', template_values, suffix = 'txt')

    # Send email.
    try:
        return Emailer.send(email, subject, body, from_name = emailAccount['from_name'],
            from_address = emailAccount['from_email'])
    except Exception, e:
        log.info("*** couldn't send authenticate user email")
        log.error(e)
        return False
Esempio n. 46
0
    def setUp(self):
        # HACK: We kept getting db.printing inexplicably set to True, so patch
        # it to be False here.
        _real_db_execute = web.db.DB._db_execute

        def _db_execute(self, cur, sql_query):
            self.printing = False
            return _real_db_execute(self, cur, sql_query)

        web.db.DB._db_execute = _db_execute

        # Set the dev flag in Config to False.
        Config.load()
        Config.data['dev'] = False

        # Set the debug flag to true, despite what is in the config file
        web.config.debug = False
        web.config.session_parameters['cookie_name'] = 'gam'

        # TODO: Clean up this initialization
        web.ctx.method = ''
        web.ctx.path = ''
        import StringIO
        web.ctx.env = {'wsgi.input': StringIO.StringIO(), 'REQUEST_METHOD': ''}

        # Set up the routes
        app = web.application(main.ROUTES, globals())

        # Grab a database connection
        self.db = main.sessionDB()

        # Initialize the session holder (I don't know what that is yet)
        #main.SessionHolder.set(web.session.Session(app, web.session.DBStore(db, 'web_session')))

        # Finally, create a test app
        self.app = TestApp(app.wsgifunc())
Esempio n. 47
0
    def __init__(self, ui):
        self.ui = ui

        # Read in config information
        configdir = os.path.abspath(os.path.expanduser('~/.freeseer/'))
        self.config = Config(configdir)
        self.logger = Logger(configdir)

        # Start Freeseer Recording Backend
        self.freeseer = Freeseer_gstreamer(self)
        resolution = self.config.resolution.split('x')
        self.change_output_resolution(resolution[0], resolution[1])

        self.spaces = False
        self.logger.log.info(u"Core initialized")
Esempio n. 48
0
    def GET(self, action=None, param0=None, param1=None, param2=None):
        if (Config.get('features').get('is_calendar_enabled')):
            if (action == 'show' or action == 'get'):
                if (not param0 or not param1):
                    year, month = self.getCurrentYearMonth()
                else:
                    year, month = (param0, param1)

                d = datetime(int(year), int(month), 1)
                start = "%s-%s" % (year, month)
                end = (d + timedelta(days = 32)).strftime('%Y-%m')    
                events = self.getEvents(start, end)
                
                if (action == 'show'):
                    return self.showCalendar(events, start, end, d)
                elif (action == 'get'):
                    return self.getCalendar(events)
            
            else:
                return self.not_found()
        else:
            return self.not_found()
Esempio n. 49
0
#coding:utf-8

import logging, os, time
from configparser import ConfigParser
from framework.config import Config

config = Config.getConfig()


class Logger(object):
    def __init__(self, name):
        rootDir = os.path.dirname(os.path.abspath('.'))
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)
        #读取配置文件中日志路径
        self.logPath = config.get("log", "logPath")
        rq = time.strftime('%Y%d%m', time.localtime()) + '.log'
        self.logName = os.path.join(self.logPath, rq)

        #创建filehandler和streamhandler以及设置日志格式
        fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        self.formatter = logging.Formatter(fmt)
        self.streamHandler = logging.StreamHandler()
        self.streamHandler.setFormatter(self.formatter)
        self.streamHandler.setLevel(logging.INFO)
        self.fileHandler = logging.FileHandler(self.logName, 'a')
        self.fileHandler.setFormatter(self.formatter)
        self.fileHandler.setLevel(logging.INFO)
        self.logger.addHandler(self.fileHandler)
        self.logger.addHandler(self.streamHandler)
Esempio n. 50
0
 def get_db_config(self):
     """Pulls the database config information from the config.yaml file."""
     return Config.get('database')
Esempio n. 51
0
    def render(self,
               template_name,
               template_values=None,
               suffix="html",
               content_type="text/html",
               status="200 OK"):
        """
        Custom renderer for Change by Us templates.

        @type   template_name: string
        @param  template_name: Name of template (without extension)
        @type   template_values: dict
        @param  template_values: Values to include in the template.
        @type   suffix: string
        @param  suffix: Extension of template file.
        @type   content_type: string
        @param  content_type: HTTP header content type to output.

        @rtype: ?
        @returns: ?

        """
        if template_values is None:
            template_values = {}

        # Set the user object in case it's been created since we initialized.
        self.setUserObject()

        # Hand all config values to the template.  This method is deprecated
        # but around until all templates have been updated.
        config = Config.get_all()

        config['base_url'] = Config.base_url()
        for key in config:
            if type(config[key]) is dict:
                for param in config[key]:
                    template_values["%s_%s" %
                                    (key, param)] = config[key][param]
            else:
                template_values[key] = config[key]

        # Give all config values as a dict in a config space.
        template_values['config'] = config

        # Send user data to template
        if self.user:
            template_values['user'] = self.user
            template_values['sqla_user'] = self.sqla_user

        # Add template data object
        if self.template_data:
            template_values['template_data'] = self.template_data

        # Create full URL from web.py values
        template_values['full_url'] = web.ctx.home + web.ctx.fullpath

        # Check for "flash"?
        if hasattr(self.session, 'flash') and self.session.flash is not None:
            template_values['flash'] = self.session.flash
            log.info('showing flash message: "' + self.session.flash + '"')
            self.session.flash = None
            self.session.invalidate()

        template_values['session_id'] = self.session.session_id

        # Put session values into template ??
        keys = self.session.keys()
        for key in keys:
            template_values[key] = self.session[key]

        # Set up template and Jinja
        template_values['template_name'] = template_name
        renderer = render_jinja(os.path.dirname(__file__) + '/../templates/',
                                extensions=[
                                    'jinja2.ext.i18n',
                                    'jinja2.ext.with_',
                                ])
        renderer._lookup.filters.update(custom_filters.filters)

        # Install the translation
        translation = self.get_gettext_translation(self.get_language())
        renderer._lookup.install_gettext_translations(translation)

        # Insert HTML for the language chooser
        curr_lang = self.get_language()
        all_langs = self.get_supported_languages()

        template_values['language'] = {
            "current": curr_lang,
            "list": all_langs.iteritems()
        }

        template_values['language_selector'] = self.choice_list(
            all_langs, curr_lang)

        # Set HTTP header
        web.header("Content-Type", content_type)

        # Debug data.
        log.info("%s: %s (%s)" % (status, content_type, template_name))
        log.info("*** session  = %s" % self.session)

        # Set status
        web.ctx.status = status

        # Return template and data.
        return (renderer[template_name + "." + suffix](
            dict(d=template_values))).encode('utf-8')
Esempio n. 52
0
    def __init__(self):

        log.info(
            "---------- %s %s --------------------------------------------------------------------------"
            % (web.ctx.method, web.ctx.path))

        # database
        self.db = Controller.get_db()

        # memcache
        self.cache = memcache.Client([
            Config.get('memcache')['address'] + ":" +
            str(Config.get('memcache')['port'])
        ])

        # session
        self.session = SessionHolder.get_session()
        log.info("SESSION: %s " % self.session)

        # template data
        self.template_data = {}

        # set mode
        self.template_data['app_mode'] = self.appMode = Config.get('app_mode')

        self.template_data['app_env'] = self.appEnv = Config.get('app_env')

        #set media root
        self.template_data['media_root'] = Config.get('media')['root']

        #set city-specific map options
        self.template_data['map'] = Config.get('map')

        #set the supported features
        self.template_data['features'] = Config.get('features')

        # user
        self.setUserObject()

        # beta redirect
        if (self.appMode == 'beta' and not self.user):
            path = web.ctx.path.split('/')
            allowed = [
                'beta',
                'login',
                'join',
                'tou',
                'logout',
                # Twitter related paths
                'twitter',
                # 'twitter/login', 'twitter/create', 'twitter/callback', 'twitter/disconnect'

                # Facebook paths - not relevant until FB app is updated
                'facebook',
                # 'facebook/login', 'facebook/create', 'facebook/callback', 'facebook/disconnect'

                # Remove the following facebook paths once app is updated
                # 'login_facebook',
                # 'login_facebook_create',
                # 'disconnect_facebook',
            ]

            if (path[1] not in allowed):
                self.redirect('/beta')
Esempio n. 53
0
 def getConfigVar(self, var_name):
     return Config.get(var_name)
Esempio n. 54
0
import framework.util as util
import lib.web
#temp
from framework.image_server import *
import giveaminute.projectResource as mResource

import cgi
import oauth2 as oauth
import urllib
import urllib2
import json
import hashlib

import MySQLdb  # for exceptions

tw_settings = Config.get('twitter')
tw_consumer = oauth.Consumer(tw_settings['consumer_key'],
                             tw_settings['consumer_secret'])
tw_client = oauth.Client(tw_consumer)


class Home(Controller):
    def GET(self, action=None, param0=None):
        project_user = dict(is_member=True, is_project_admin=True)
        self.template_data['project_user'] = dict(
            data=project_user, json=json.dumps(project_user))
        self.template_data['homepage_question'] = self.getHomepageQuestion()

        if (not action or action == 'home'):
            return self.showHome()
        elif (action == 'leaderboard'):
Esempio n. 55
0
    def login_facebook(self):

        fb_settings = Config.get('facebook')

        #cookiename = "fbs_%s" % fb_settings['app_id']
        #fbcookie = web.cookies().get(cookiename)
        #entries = fbcookie.split("&")
        #dc = {}
        #for e in entries:
        #    es = e.split("=")
        #    dc[es[0]] = es[1]

        url = "https://graph.facebook.com/%s" % self.request('uid')
        # Facebook does not like POST requests, but when they do, we can
        # enable the following
        # params = {'access_token':self.request('access_token')}
        # resp = urllib2.urlopen(url, urllib.urlencode(dict(params)))
        resp = urllib2.urlopen("%s?access_token=%s" %
                               (url, self.request('access_token')))

        profile = json.loads(resp.read())
        resp.close()

        sql = "select * from facebook_user where facebook_id = $id"
        res = list(self.db.query(sql, {'id': profile['id']}))

        associated_user = -1

        created_user = False
        created_facebook_user = False
        # do we already have fb data for this user? -> log them in
        if len(res) == 1:
            facebook_user = res[0]
            self.session.user_id = facebook_user.user_id
            self.session.invalidate()

        else:
            email = profile["email"]
            check_if_email_exists = "select * from user where email = $email"
            users_with_this_email = list(
                self.db.query(check_if_email_exists, {'email': email}))
            email_exists = len(users_with_this_email)

            # see if we have a user with this email on a regular account
            if email_exists == 1:
                uid = users_with_this_email[0].user_id
            else:  # no regular account with this email

                # see if the user is logged in
                s = SessionHolder.get_session()

                make_new_user = True
                try:
                    uid = s.user_id
                    if uid is not None:
                        make_new_user = False  # user is logged in
                except AttributeError:
                    pass
                    #uid = mUser.createUser(self.db, profile["email"], passw, profile["first_name"], profile["last_name"])

                # not logged in, so make a new user
                if make_new_user:
                    created_user = True
                    self.session.profile = profile
                    self.session._changed = True
                    SessionHolder.set(self.session)

            if not created_user:  # we can associate an existing account with this data
                try:
                    self.db.insert('facebook_user',
                                   user_id=uid,
                                   facebook_id=profile['id'])
                except MySQLdb.IntegrityError:
                    # Means that we already have a record for this user
                    # Check if the facebook user id is the same as what's in the database
                    # If not, check if graph.facebook.com gives us the correct user for the existing id
                    # otherwise add the new facebook uid
                    log.info(
                        "Got IntegrityError inserting fbid %s for uid %s" %
                        (profile['id'], uid))
                    query = "select facebook_id from facebook_user where user_id = $uid"
                    res = self.db.query(query, {'uid': uid})
                    fbid = None
                    if len(res) > 0:
                        fbid = res[0].facebook_id
                    if fbid is not None and fbid != profile['id']:
                        log.info(
                            "Stored fbid (%s) does not match provided fbid (%s). Updating facebook_user for uid %s"
                            % (fbid, profile['id'], uid))
                        # Check if the existing id is correct or not
                        # If it's not correct, update the record
                        self.db.update('facebook_user',
                                       where='user_id=%s' % uid,
                                       facebook_id=profile['id'])

                associated_user = uid
                created_facebook_user = True

                self.session.user_id = associated_user
                self.session.invalidate()

        if created_user:
            return self.render('join', {
                'new_account_via_facebook': True,
                'facebook_data': profile
            })  # go to TOS
        else:
            raise self.redirect(
                '/')  # user had already signed up with us before