Changeset - 042d38683d42
[Not reviewed]
beta
0 7 0
Marcin Kuzminski - 15 years ago 2010-12-29 10:39:46
marcin@python-works.com
implemented #89 google analytics code
7 files changed with 64 insertions and 6 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/admin/settings.py
Show inline comments
 
@@ -16,46 +16,51 @@
 
# of the License or (at your opinion) any later version of the license.
 
# 
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
# 
 
# You should have received a copy of the GNU General Public License
 
# along with this program; if not, write to the Free Software
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
# MA  02110-1301, USA.
 

	
 
import logging
 
import traceback
 
import formencode
 

	
 
from operator import itemgetter
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url, app_globals as g, \
 
    config
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
 
    HasPermissionAnyDecorator, NotAnonymous
 
from rhodecode.lib.base import BaseController, render
 
from rhodecode.lib.celerylib import tasks, run_task
 
from rhodecode.lib.utils import repo2db_mapper, invalidate_cache, \
 
    set_rhodecode_config
 
from rhodecode.model.db import RhodeCodeUi, Repository
 
from rhodecode.model.forms import UserForm, ApplicationSettingsForm, \
 
    ApplicationUiSettingsForm
 
from rhodecode.model.scm import ScmModel
 
from rhodecode.model.settings import SettingsModel
 
from rhodecode.model.user import UserModel
 

	
 
from sqlalchemy import func
 
import formencode
 
import logging
 
import traceback
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class SettingsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('setting', 'settings', controller='admin/settings', 
 
    #         path_prefix='/admin', name_prefix='admin_')
 

	
 

	
 
@@ -114,34 +119,40 @@ class SettingsController(BaseController)
 
        if setting_id == 'whoosh':
 
            repo_location = self.get_hg_ui_settings()['paths_root_path']
 
            full_index = request.POST.get('full_index', False)
 
            task = run_task(tasks.whoosh_index, repo_location, full_index)
 

	
 
            h.flash(_('Whoosh reindex task scheduled'), category='success')
 
        if setting_id == 'global':
 

	
 
            application_form = ApplicationSettingsForm()()
 
            try:
 
                form_result = application_form.to_python(dict(request.POST))
 
                settings_model = SettingsModel()
 

	
 
                try:
 
                    hgsettings1 = settings_model.get('title')
 
                    hgsettings1.app_settings_value = form_result['rhodecode_title']
 

	
 
                    hgsettings2 = settings_model.get('realm')
 
                    hgsettings2.app_settings_value = form_result['rhodecode_realm']
 

	
 
                    hgsettings3 = settings_model.get('ga_code')
 
                    hgsettings3.app_settings_value = form_result['ga_code']
 

	
 

	
 

	
 
                    self.sa.add(hgsettings1)
 
                    self.sa.add(hgsettings2)
 
                    self.sa.add(hgsettings3)
 
                    self.sa.commit()
 
                    set_rhodecode_config(config)
 
                    h.flash(_('Updated application settings'),
 
                            category='success')
 

	
 
                except:
 
                    log.error(traceback.format_exc())
 
                    h.flash(_('error occurred during updating application settings'),
 
                            category='error')
 

	
 
                    self.sa.rollback()
 

	
rhodecode/lib/base.py
Show inline comments
 
@@ -7,29 +7,30 @@ from pylons.controllers import WSGIContr
 
from pylons.templating import render_mako as render
 
from rhodecode import __version__
 
from rhodecode.lib import auth
 
from rhodecode.lib.utils import get_repo_slug
 
from rhodecode.model import meta
 
from rhodecode.model.scm import ScmModel
 
from rhodecode import BACKENDS
 

	
 
class BaseController(WSGIController):
 

	
 
    def __before__(self):
 
        c.rhodecode_version = __version__
 
        c.rhodecode_name = config['rhodecode_title']
 
        c.rhodecode_name = config.get('rhodecode_title')
 
        c.ga_code = config.get('rhodeocode_ga_code')
 
        c.repo_name = get_repo_slug(request)
 
        c.cached_repo_list = ScmModel().get_repos()
 
        c.backends = BACKENDS.keys()
 
        self.cut_off_limit = int(config['cut_off_limit'])
 
        self.cut_off_limit = int(config.get('cut_off_limit'))
 
        self.sa = meta.Session()
 
        scm_model = ScmModel(self.sa)
 
        #c.unread_journal = scm_model.get_unread_journal()
 

	
 
        if c.repo_name:
 
            cached_repo = scm_model.get(c.repo_name)
 
            if cached_repo:
 
                c.repository_tags = cached_repo.tags
 
                c.repository_branches = cached_repo.branches
 
                c.repository_followers = scm_model.get_followers(cached_repo.dbrepo.repo_id)
 
                c.repository_forks = scm_model.get_forks(cached_repo.dbrepo.repo_id)
 
            else:
rhodecode/lib/db_manage.py
Show inline comments
 
@@ -157,24 +157,27 @@ class DbManage(object):
 
                pass
 

	
 
            def step_2(self):
 
                print ('Patching repo paths for newer version of RhodeCode')
 
                self.klass.fix_repo_paths()
 

	
 
                print ('Patching default user of RhodeCode')
 
                self.klass.fix_default_user()
 

	
 
                log.info('Changing ui settings')
 
                self.klass.create_ui_settings()
 

	
 
            def step_3(self):
 
                print ('Adding additional settings into RhodeCode db')
 
                self.klass.fix_settings()
 

	
 
        upgrade_steps = [0] + range(curr_version + 1, __dbversion__ + 1)
 

	
 
        #CALL THE PROPER ORDER OF STEPS TO PERFORM FULL UPGRADE
 
        for step in upgrade_steps:
 
            print ('performing upgrade step %s' % step)
 
            callable = getattr(UpgradeSteps(self), 'step_%s' % step)()
 

	
 

	
 

	
 
    def fix_repo_paths(self):
 
        """Fixes a old rhodecode version path into new one without a '*'
 
@@ -203,25 +206,35 @@ class DbManage(object):
 

	
 
        def_user.name = 'Anonymous'
 
        def_user.lastname = 'User'
 
        def_user.email = 'anonymous@rhodecode.org'
 

	
 
        try:
 
            self.sa.add(def_user)
 
            self.sa.commit()
 
        except:
 
            self.sa.rollback()
 
            raise
 

	
 
    def fix_settings(self):
 
        """Fixes rhodecode settings adds ga_code key for google analytics
 
        """
 

	
 
        hgsettings3 = RhodeCodeSettings('ga_code', '')
 
        try:
 
            self.sa.add(hgsettings3)
 
            self.sa.commit()
 
        except:
 
            self.sa.rollback()
 
            raise
 

	
 
    def admin_prompt(self, second=False):
 
        if not self.tests:
 
            import getpass
 

	
 

	
 
            def get_password():
 
                password = getpass.getpass('Specify admin password (min 6 chars):')
 
                confirm = getpass.getpass('Confirm password:')
 

	
 
                if password != confirm:
 
                    log.error('passwords mismatch')
 
@@ -351,34 +364,36 @@ class DbManage(object):
 
        web4.ui_section = 'web'
 
        web4.ui_key = 'baseurl'
 
        web4.ui_value = '/'
 

	
 
        paths = RhodeCodeUi()
 
        paths.ui_section = 'paths'
 
        paths.ui_key = '/'
 
        paths.ui_value = path
 

	
 

	
 
        hgsettings1 = RhodeCodeSettings('realm', 'RhodeCode authentication')
 
        hgsettings2 = RhodeCodeSettings('title', 'RhodeCode')
 
        hgsettings3 = RhodeCodeSettings('ga_code', '')
 

	
 

	
 
        try:
 
            self.sa.add(web1)
 
            self.sa.add(web2)
 
            self.sa.add(web3)
 
            self.sa.add(web4)
 
            self.sa.add(paths)
 
            self.sa.add(hgsettings1)
 
            self.sa.add(hgsettings2)
 
            self.sa.add(hgsettings3)
 

	
 
            self.sa.commit()
 
        except:
 
            self.sa.rollback()
 
            raise
 

	
 
        self.create_ldap_options()
 

	
 
        log.info('created ui config')
 

	
 
    def create_user(self, username, password, email='', admin=False):
 
        log.info('creating administrator user %s', username)
rhodecode/model/forms.py
Show inline comments
 
@@ -429,24 +429,25 @@ def RepoSettingsForm(edit=False, old_dat
 
        private = StringBoolean(if_missing=False)
 

	
 
        chained_validators = [ValidPerms, ValidSettings]
 
    return _RepoForm
 

	
 

	
 
def ApplicationSettingsForm():
 
    class _ApplicationSettingsForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        rhodecode_title = UnicodeString(strip=True, min=1, not_empty=True)
 
        rhodecode_realm = UnicodeString(strip=True, min=1, not_empty=True)
 
        ga_code = UnicodeString(strip=True, min=1, not_empty=False)
 

	
 
    return _ApplicationSettingsForm
 

	
 
def ApplicationUiSettingsForm():
 
    class _ApplicationUiSettingsForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        web_push_ssl = OneOf(['true', 'false'], if_missing='false')
 
        paths_root_path = All(ValidPath(), UnicodeString(strip=True, min=1, not_empty=True))
 
        hooks_changegroup_update = OneOf(['True', 'False'], if_missing=False)
 
        hooks_changegroup_repo_size = OneOf(['True', 'False'], if_missing=False)
 
        hooks_pretxnchangegroup_push_logger = OneOf(['True', 'False'], if_missing=False)
rhodecode/model/settings.py
Show inline comments
 
@@ -37,24 +37,29 @@ class SettingsModel(BaseModel):
 
    Settings model
 
    """
 

	
 
    def get(self, settings_key, cache=False):
 
        r = self.sa.query(RhodeCodeSettings)\
 
            .filter(RhodeCodeSettings.app_settings_name == settings_key).scalar()
 
        if cache:
 
            r = r.options(FromCache("sql_cache_short",
 
                                          "get_setting_%s" % settings_key))
 
        return r
 

	
 
    def get_app_settings(self):
 
        """Get's config from database, each config key is prefixed with 
 
        'rhodecode_' prefix, than global pylons config is updated with such 
 
        keys
 
        """
 

	
 
        ret = self.sa.query(RhodeCodeSettings)\
 
            .options(FromCache("sql_cache_short",
 
                           "get_hg_settings")).all()
 

	
 
        if not ret:
 
            raise Exception('Could not get application settings !')
 
        settings = {}
 
        for each in ret:
 
            settings['rhodecode_' + each.app_settings_name] = each.app_settings_value
 

	
 
        return settings
 

	
rhodecode/templates/admin/settings/settings.html
Show inline comments
 
@@ -88,25 +88,34 @@
 
                    ${h.text('rhodecode_title',size=30)}
 
                </div>
 
             </div>
 
                          
 
            <div class="field">
 
                <div class="label">
 
                    <label for="rhodecode_realm">${_('Realm text')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('rhodecode_realm',size=30)}
 
                </div>
 
            </div>
 
                                     
 
            
 
            <div class="field">
 
                <div class="label">
 
                    <label for="ga_code">${_('Google analytics code')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('ga_code',size=30)}
 
                </div>
 
            </div>
 
                                                 
 
            <div class="buttons">
 
                ${h.submit('save','Save settings',class_="ui-button")}
 
                ${h.reset('reset','Reset',class_="ui-button")}
 
           </div>                                                          
 
        </div>
 
    </div>      
 
    ${h.end_form()}
 

	
 
    <h3>${_('Mercurial settings')}</h3> 
 
    ${h.form(url('admin_setting', setting_id='mercurial'),method='put')}
 
    <div class="form">
 
        <!-- fields -->
rhodecode/templates/base/base.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" id="mainhtml">
 
<head>
 
    <title>${next.title()}</title>
 
    <link rel="icon" href="/images/icons/database_gear.png" type="image/png" />
 
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
 
    <meta name="robots" content="index, nofollow"/>
 
    <!-- stylesheets -->
 
    ${self.css()}
 
    <!-- scripts -->
 
    ${self.js()}
 
%if c.ga_code:
 
<script type="text/javascript">
 

	
 
  var _gaq = _gaq || [];
 
  _gaq.push(['_setAccount', '${c.ga_code}']);
 
  _gaq.push(['_trackPageview']);
 

	
 
  (function() {
 
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
 
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 
  })();
 

	
 

	
 
</script>
 
%endif
 
</head>
 
<body>
 
    <!-- header -->
 
    <div id="header">
 
        <!-- user -->
 
        <ul id="logged-user">
 
	            <li class="first">
 
	                <div class="gravatar">
 
	                    <img alt="gravatar" src="${h.gravatar_url(c.rhodecode_user.email,20)}" />
 
	                </div>
 
		            <div class="account">
 
		            %if c.rhodecode_user.username == 'default':
0 comments (0 inline, 0 general)