Ejemplo n.º 1
0
def sync(user=None):

    if user:
        conf = ModuleSetting.get('nuvius_profile', user=user, strict=True)
    else:
        conf = ModuleSetting.get('nuvius_profile')

    for item in conf:
        profile = item.loads()
        user = item.user
        if user:
            connector = Connector(profile_id=profile['id'])
            active_resources = ModuleSetting.get_for_module(
                'treeio.identities',
                'integration_resource',
                user=user,
                strict=True)
            for resource in active_resources:
                res = resource.loads()
                response = connector.get(
                    '/service/contact-book/contact/data.json/id' +
                    profile['id'] + '/app' + str(res.resource_id))
                data = DataBlock(response['data'])
                if data.result_name == 'success':
                    _do_sync(data, user)
Ejemplo n.º 2
0
def htdate(context, date, dateformat='DATE_FORMAT'):
    """ Render date in the current locale
    
    To render date in a custom format use Django format, details:
    http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
    
    """
    
    if not date:
        return ''
    
    lang = translation.get_language()
    
    localeformat = dateformat
    formatspath = getattr(settings, 'FORMAT_MODULE_PATH', 'treeio.formats')
    try:
        modulepath = formatspath + "." + lang + ".formats"
        module = __import__(modulepath, fromlist=[str(modulepath)])
        localeformat = getattr(module, dateformat, dateformat)
    except ImportError:
        pass
    
    request = context['request']
    
    user = None
    if request.user.username:
        try: 
            user = request.user.get_profile()
        except Exception:
            pass
        
    # timezone
    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except:
        pass
     
    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]
        
    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE', [(1, '(GMT-11:00) International Date Line West')])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10] # with sign e.g. +06:00
    sign = GMT[0:1] # + or -
    hours = int(GMT[1:3]) # e.g. 06
    mins = int(GMT[4:6])

    if sign == "-":
        date = date - timedelta(hours=hours, minutes=mins)
    else: 
        date = date + timedelta(hours=hours, minutes=mins)
    
    result = djangodate(date, localeformat)
    return Markup(result)
Ejemplo n.º 3
0
def htdate(context, date, dateformat='DATE_FORMAT'):
    """ Render date in the current locale
    
    To render date in a custom format use Django format, details:
    http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
    
    """
    
    if not date:
        return ''
    
    lang = translation.get_language()
    
    localeformat = dateformat
    formatspath = getattr(settings, 'FORMAT_MODULE_PATH', 'treeio.formats')
    try:
        modulepath = formatspath + "." + lang + ".formats"
        module = __import__(modulepath, fromlist=[str(modulepath)])
        localeformat = getattr(module, dateformat, dateformat)
    except ImportError:
        pass
    
    request = context['request']
    
    user = None
    if request.user.username:
        try: 
            user = request.user.get_profile()
        except Exception:
            pass
        
    # timezone
    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except:
        pass
     
    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]
        
    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE', [(1, '(GMT-11:00) International Date Line West')])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10] # with sign e.g. +06:00
    sign = GMT[0:1] # + or -
    hours = int(GMT[1:3]) # e.g. 06
    mins = int(GMT[4:6])

    if sign == "-":
        date = date - timedelta(hours=hours, minutes=mins)
    else: 
        date = date + timedelta(hours=hours, minutes=mins)
    
    result = djangodate(date, localeformat)
    return Markup(result)
Ejemplo n.º 4
0
    def __init__(self, user, *args, **kwargs):
        "Sets choices and initial value"
        super(SettingsForm, self).__init__(*args, **kwargs)
        
        self.fields['default_perspective'].label = _("Default Perspective")
        self.fields['language'].label = _("Language")
        self.fields['default_timezone'].label = _("Time Zone")
        self.fields['email_notifications'].label = _("E-mail Notifications")
        
        self.user = user
    
        self.fields['default_perspective'].queryset = Object.filter_permitted(user, Perspective.objects)
        try:
            conf = ModuleSetting.get_for_module('treeio.core', 'default_perspective', user=self.user)[0]
            default_perspective = Perspective.objects.get(pk=long(conf.value))
            self.fields['default_perspective'].initial = default_perspective.id
        except:
            pass
        
        self.fields['default_timezone'].choices = getattr(settings, 'HARDTREE_SERVER_TIMEZONE')
        timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
        try:
            conf = ModuleSetting.get('default_timezone', user=user)[0]
            timezone = conf.value
        except:
            pass
        self.fields['default_timezone'].initial = timezone
        
        self.fields['language'].choices = getattr(settings, 'HARDTREE_LANGUAGES', [('en', 'English')])
        language = getattr(settings, 'HARDTREE_LANGUAGES_DEFAULT', '')
        try:
            conf = ModuleSetting.get('language', user=user)[0]
            language = conf.value
        except IndexError:
            pass
        self.fields['language'].initial = language
        
        try:
            conf = ModuleSetting.get('email_notifications', user=user)[0]
            self.fields['email_notifications'].initial = conf.value
        except:
            self.fields['email_notifications'].initial = settings.HARDTREE_ALLOW_EMAIL_NOTIFICATIONS

        perspective = user.get_perspective()

        modules = perspective.modules.filter(display=True).order_by('title')
        if not modules:
            modules = Module.objects.filter(display=True).order_by('title')
        self.fields['notifications_for_modules'].choices = [(module.pk, module.title) for module in modules]

        try:
            modules = NotificationSetting.objects.get(owner = self.user).modules.all()
            self.fields['notifications_for_modules'].initial = [m.pk for m in modules]
        except (NotificationSetting.DoesNotExist, NotificationSetting.MultipleObjectsReturned):
            pass
Ejemplo n.º 5
0
def httime(context, time, timeformat="TIME_FORMAT"):
    """ Render time in the current locale """

    if not time:
        return ""

    lang = translation.get_language()

    localeformat = timeformat
    formatspath = getattr(settings, "FORMAT_MODULE_PATH", "treeio.formats")
    try:
        modulepath = formatspath + "." + lang + ".formats"
        module = __import__(modulepath, fromlist=[str(modulepath)])
        localeformat = getattr(module, timeformat, timeformat)
    except ImportError:
        pass

    request = context["request"]

    user = None
    if request.user.username:
        try:
            user = request.user.get_profile()
        except Exception:
            pass

    # timezone
    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get("default_timezone")[0]
        default_timezone = conf.value
    except:
        pass

    try:
        conf = ModuleSetting.get("default_timezone", user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(settings, "HARDTREE_SERVER_TIMEZONE")[default_timezone][0]

    all_timezones = getattr(settings, "HARDTREE_SERVER_TIMEZONE", [(1, "(GMT-11:00) International Date Line West")])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10]  # with sign e.g. +06:00
    sign = GMT[0:1]  # + or -
    hours = int(GMT[1:3])  # e.g. 06
    mins = int(GMT[4:6])

    if sign == "-":
        time = time - timedelta(hours=hours, minutes=mins)
    else:
        time = time + timedelta(hours=hours, minutes=mins)

    result = djangotime(time, localeformat)

    return Markup(result)
Ejemplo n.º 6
0
def htform(context, form):
    "Set time zone"

    request = context['request']

    user = None
    if request.user.username:
        try:
            user = request.user.get_profile()
        except Exception:
            pass

    # timezone
    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except:
        pass

    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(
            settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]

    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE',
                            [(1, '(GMT-11:00) International Date Line West')])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10]  # with sign e.g. +06:00
    sign = GMT[0:1]  # + or -
    hours = int(GMT[1:3])  # e.g. 06
    mins = int(GMT[4:6])

    if not form.errors:
        for field in form:
            try:
                date = datetime.strptime(str(field.form.initial[field.name]),
                                         "%Y-%m-%d %H:%M:%S")
                if date:
                    if sign == "-":
                        field.form.initial[field.name] = date - timedelta(
                            hours=hours, minutes=mins)
                    else:
                        field.form.initial[field.name] = date + timedelta(
                            hours=hours, minutes=mins)
            except:
                pass

    return form
Ejemplo n.º 7
0
def htform(context, form):
    "Set time zone"

    request = context['request']

    user = None
    if request.user.username:
        try:
            user = request.user.get_profile()
        except Exception:
            pass

    # timezone
    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except:
        pass

    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(
            settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]

    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE', [
                            (1, '(GMT-11:00) International Date Line West')])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10]  # with sign e.g. +06:00
    sign = GMT[0:1]  # + or -
    hours = int(GMT[1:3])  # e.g. 06
    mins = int(GMT[4:6])

    if not form.errors:
        for field in form:
            try:
                date = datetime.strptime(
                    str(field.form.initial[field.name]), "%Y-%m-%d %H:%M:%S")
                if date:
                    if sign == "-":
                        field.form.initial[
                            field.name] = date - timedelta(hours=hours, minutes=mins)
                    else:
                        field.form.initial[
                            field.name] = date + timedelta(hours=hours, minutes=mins)
            except:
                pass

    return form
Ejemplo n.º 8
0
def integration_view(request, conf_id, response_format='html'):
    "Integration view resource page"
    
    user = request.user.get_profile()
    
    resconf = get_object_or_404(ModuleSetting, pk=conf_id)
    res = resconf.loads()
    
    conf = ModuleSetting.get('nuvius_profile', user=user)
    try:
        profile = conf[0].loads()
    except IndexError:
        profile = None
    
    resource = None
    if profile:
        connector = Connector(request, profile_id=profile['id'])
        resource = DataBlock(connector.get_app(res.resource_id))
        if request.POST and 'delete' in request.POST:
            resconf.delete()
            return HttpResponseRedirect(reverse('events_integration_index'))
        
    context = {'conf_id': conf_id, 'resource': resource}
    
    return render_to_response('events/integration_view', context,
                              context_instance=RequestContext(request), response_format=response_format)
Ejemplo n.º 9
0
def integration_view(request, conf_id, response_format='html'):
    "Integration view resource page"

    user = request.user.get_profile()

    resconf = get_object_or_404(ModuleSetting, pk=conf_id)
    res = resconf.loads()

    conf = ModuleSetting.get('nuvius_profile', user=user)
    try:
        profile = conf[0].loads()
    except IndexError:
        profile = None

    resource = None
    if profile:
        connector = Connector(request, profile_id=profile['id'])
        resource = DataBlock(connector.get_app(res.resource_id))
        if request.POST and 'delete' in request.POST:
            resconf.delete()
            return HttpResponseRedirect(reverse('events_integration_index'))

    context = {'conf_id': conf_id, 'resource': resource}

    return render_to_response('events/integration_view',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Ejemplo n.º 10
0
def process_timezone_field(user, instance):
    "Processes date and datetime fields according to the selected time zone"
    from datetime import date, datetime, timedelta

    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except Exception:
        pass

    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(
            settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]

    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE',
                            [(1, '(GMT-11:00) International Date Line West')])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10]  # with sign e.g. +06:00
    sign = GMT[0:1]  # + or -
    hours = int(GMT[1:3])  # e.g. 06
    mins = int(GMT[4:6])

    for field in instance.get_fields():
        if field.name not in getattr(settings, 'HARDTREE_TIMEZONE_BLACKLIST',
                                     []):
            if isinstance(field, models.DateTimeField) or \
                    isinstance(field, models.DateField):
                if getattr(instance, field.name):
                    cur_date = getattr(instance, field.name)
                    if sign == "-":
                        new_date = cur_date + \
                            timedelta(hours=hours, minutes=mins)
                    else:
                        new_date = cur_date - \
                            timedelta(hours=hours, minutes=mins)
                    setattr(instance, field.name, new_date)
            elif isinstance(field, models.TimeField):
                if getattr(instance, field.name):
                    datetime.combine(date.today(), getattr(
                        instance, field.name)) + timedelta(hours=hours,
                                                           minutes=mins)
Ejemplo n.º 11
0
def sync(user=None):
    
    if user:
        conf = ModuleSetting.get('nuvius_profile', user=user, strict=True)
    else:
        conf = ModuleSetting.get('nuvius_profile')
    
    for item in conf:
        profile = item.loads()
        user = item.user
        if user:
            connector = Connector(profile_id=profile['id'])
            active_resources = ModuleSetting.get_for_module('treeio.events', 'integration_resource', user=user, strict=True)
            for resource in active_resources:
                res = resource.loads()
                response = connector.get('/service/calendar/event/data.json/id' + profile['id'] + '/app' + str(res.resource_id))
                data = DataBlock(response['data'])
                if data.result_name == 'success':
                    _do_sync(data, user)
Ejemplo n.º 12
0
def process_timezone_field(user, instance):
    "Processes date and datetime fields according to the selected time zone"
    from datetime import date, datetime, timedelta

    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except Exception:
        pass

    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(
            settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]

    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE', [
                            (1, '(GMT-11:00) International Date Line West')])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10]  # with sign e.g. +06:00
    sign = GMT[0:1]  # + or -
    hours = int(GMT[1:3])  # e.g. 06
    mins = int(GMT[4:6])

    for field in instance.get_fields():
        if field.name not in getattr(settings, 'HARDTREE_TIMEZONE_BLACKLIST', []):
            if isinstance(field, models.DateTimeField) or \
                    isinstance(field, models.DateField):
                if getattr(instance, field.name):
                    cur_date = getattr(instance, field.name)
                    if sign == "-":
                        new_date = cur_date + \
                            timedelta(hours=hours, minutes=mins)
                    else:
                        new_date = cur_date - \
                            timedelta(hours=hours, minutes=mins)
                    setattr(instance, field.name, new_date)
            elif isinstance(field, models.TimeField):
                if getattr(instance, field.name):
                    datetime.combine(date.today(), getattr(
                        instance, field.name)) + timedelta(hours=hours, minutes=mins)
Ejemplo n.º 13
0
def integration_add(request, resource_id, response_format='html'):
    "Integration add new resource page"

    user = request.user.get_profile()

    conf = ModuleSetting.get('nuvius_profile', user=user)
    try:
        profile = conf[0].loads()
    except IndexError:
        profile = None

    resource = None
    data = None
    if profile:
        connector = Connector(request, profile_id=profile['id'])
        resource = DataBlock(connector.get_app(resource_id))
        if request.POST and 'add' in request.POST:
            resource = IntegrationResource(profile['id'], resource_id,
                                           resource.application.name.raw,
                                           '9rw')
            conf = ModuleSetting.add_for_module('integration_resource',
                                                '',
                                                'treeio.identities',
                                                user=user)
            conf.dumps(resource).save()
            return HttpResponseRedirect(
                reverse('identities_integration_index'))
        else:
            data = connector.get('/service/contact-book/contact/data.json/id' +
                                 profile['id'] + '/app' + unicode(resource_id),
                                 no_cache=True)
            data = DataBlock(data)
            if data.result_name == 'success':
                pass
            elif data.result_name == 'redirect':
                next = request.build_absolute_uri(
                    reverse('identities_integration_add', args=[resource_id]))
                data = connector.get(
                    '/service/contact-book/contact/data.json/id' +
                    profile['id'] + '/app' + unicode(resource_id),
                    parameters={'next': next},
                    no_cache=True)
            data = DataBlock(data)

    context = _get_default_context(request)
    context.update({
        'resource_id': resource_id,
        'resource': resource,
        'data': data
    })

    return render_to_response('identities/integration_add',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Ejemplo n.º 14
0
 def process_request(self, request):
     "Set language for the current user"
     
     lang = getattr(settings, 'HARDTREE_LANGUAGES_DEFAULT', 'en')
     
     if request.user.username:
         try:
             user = request.user.get_profile()
             conf = ModuleSetting.get('language', user=user)[0]
             lang = conf.value
         except IndexError:
             pass
         except AttributeError:
             pass
     else:
         try:
             conf = ModuleSetting.get('language', user__isnull=True, strict=True)[0]
             lang = conf.value
         except IndexError:
             pass
     translation.activate(lang)
Ejemplo n.º 15
0
def profile_reset(request, response_format='html'):
    "Resets Nuvius_profile for the current account"
    
    next = '/'
    if 'next' in request.GET:
        next = request.GET.get('next')
    
    user = request.user.get_profile()
    conf = ModuleSetting.get('nuvius_profile', user=user)
    if conf:
        conf.delete()
    
    return HttpResponseRedirect(next)
Ejemplo n.º 16
0
def profile_reset(request, response_format='html'):
    "Resets Nuvius_profile for the current account"

    next = '/'
    if 'next' in request.GET:
        next = request.GET.get('next')

    user = request.user.get_profile()
    conf = ModuleSetting.get('nuvius_profile', user=user)
    if conf:
        conf.delete()

    return HttpResponseRedirect(next)
Ejemplo n.º 17
0
def sync(user=None):

    if user:
        conf = ModuleSetting.get("nuvius_profile", user=user, strict=True)
    else:
        conf = ModuleSetting.get("nuvius_profile")

    for item in conf:
        profile = item.loads()
        user = item.user
        if user:
            connector = Connector(profile_id=profile["id"])
            active_resources = ModuleSetting.get_for_module(
                "treeio.identities", "integration_resource", user=user, strict=True
            )
            for resource in active_resources:
                res = resource.loads()
                response = connector.get(
                    "/service/contact-book/contact/data.json/id" + profile["id"] + "/app" + str(res.resource_id)
                )
                data = DataBlock(response["data"])
                if data.result_name == "success":
                    _do_sync(data, user)
Ejemplo n.º 18
0
def integration_index(request, response_format='html'):
    "Integration index page"

    user = request.user.get_profile()
    active_resources = ModuleSetting.get_for_module('treeio.identities',
                                                    'integration_resource',
                                                    user=user,
                                                    strict=True)

    conf = ModuleSetting.get('nuvius_profile', user=user, strict=True)
    try:
        profile = conf[0].loads()
    except IndexError:
        profile = None

    available_resources = []
    response = None
    if profile:
        connector = Connector(request, profile_id=profile['id'])
        response = connector.collect('/service/contact-book/contact/',
                                     no_cache=True)

        resources = getattr(response.data.info, 'applications', [])
        for resource in resources:
            active = [int(res.loads().resource_id) for res in active_resources]
            if not resource.id.raw in active:
                available_resources.append(resource)

    message = None
    if 'message' in request.session:
        message = request.session.get('message')
        del request.session['message']

    context = _get_default_context(request)
    context.update({
        'active_resources': active_resources,
        'available_resources': available_resources,
        'message': message,
        'response': response,
        'profile': profile
    })

    return render_to_response('identities/integration_index',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Ejemplo n.º 19
0
def integration_index(request, response_format='html'):
    "Integration index page"
    
    user = request.user.get_profile()
    active_resources = ModuleSetting.get_for_module('treeio.events', 'integration_resource', user=user, strict=True)
    
    conf = ModuleSetting.get('nuvius_profile', user=user, strict=True)
    try:
        profile = conf[0].loads()
    except IndexError:
        profile = None
    
    available_resources = []
    response = None
    if profile:
        connector = Connector(request, profile_id=profile['id'])
        response = connector.collect('/service/calendar/event/', no_cache=True)
        
        resources = getattr(response.data.info, 'applications', [])
        for resource in resources:
            active = [int(res.loads().resource_id) for res in active_resources]
            if not resource.id.raw in active:
                available_resources.append(resource)
    
    message = None
    if 'message' in request.session:
        message = request.session.get('message')
        del request.session['message']
        
    context = {'active_resources': active_resources,
               'available_resources': available_resources,
               'message': message,
               'response': response,
               'profile': profile}
    
    return render_to_response('events/integration_index', context,
                              context_instance=RequestContext(request), response_format=response_format)
Ejemplo n.º 20
0
def integration_add(request, resource_id, response_format='html'):
    "Integration add new resource page"
    
    user = request.user.get_profile()
    
    conf = ModuleSetting.get('nuvius_profile', user=user)
    try:
        profile = conf[0].loads()
    except IndexError:
        profile = None
    
    resource = None
    data = None
    if profile:
        connector = Connector(request, profile_id=profile['id'])
        resource = DataBlock(connector.get_app(resource_id))
        if request.POST and 'add' in request.POST:
            resource = IntegrationResource(profile['id'], resource_id, resource.application.name.raw, '9rw')
            conf = ModuleSetting.add_for_module('integration_resource', '', 'treeio.events', user=user)
            conf.dumps(resource).save()
            return HttpResponseRedirect(reverse('events_integration_index'))
        else:
            data = connector.get('/service/calendar/event/data.json/id' + profile['id'] + '/app' + unicode(resource_id),
                                 no_cache=True)
            data = DataBlock(data)
            if data.result_name == 'success':
                pass
            elif data.result_name == 'redirect':
                next = request.build_absolute_uri(reverse('events_integration_add', args=[resource_id]))
                data = connector.get('/service/calendar/event/data.json/id' + profile['id'] + '/app' + unicode(resource_id),
                                     parameters={'next': next},  no_cache=True)
            data = DataBlock(data)
        
    context = {'resource_id': resource_id, 'resource': resource, 'data': data}
    
    return render_to_response('events/integration_add', context,
                              context_instance=RequestContext(request), response_format=response_format)
Ejemplo n.º 21
0
def settings_view(request, response_format='html'):
    "Settings view"
    user = request.user.get_profile()

    # default permissions
    try:
        conf = ModuleSetting.get_for_module(
            'treeio.core', 'default_permissions', user=user)[0]
        default_permissions = conf.value
    except:
        default_permissions = settings.HARDTREE_DEFAULT_PERMISSIONS

    # default perspective
    try:
        conf = ModuleSetting.get_for_module(
            'treeio.core', 'default_perspective', user=user)[0]
        default_perspective = Perspective.objects.get(pk=long(conf.value))
    except:
        default_perspective = None

    # language
    language = getattr(settings, 'HARDTREE_LANGUAGES_DEFAULT', '')
    try:
        conf = ModuleSetting.get('language', user=user)[0]
        language = conf.value
    except IndexError:
        pass
    all_languages = getattr(
        settings, 'HARDTREE_LANGUAGES', [('en', 'English')])

    # time zone
    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except:
        pass

    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except:
        default_timezone = getattr(
            settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]

    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE')

    # email notifications e.g. new task assigned to you
    email_notifications = getattr(
        settings, 'HARDTREE_ALLOW_EMAIL_NOTIFICATIONS', False)
    try:
        conf = ModuleSetting.get('email_notifications', user=user)[0]
        email_notifications = conf.value
    except:
        pass

    try:
        ns = NotificationSetting.objects.get(owner=user, enabled=True)
        notifications_for_modules = [m.title for m in ns.modules.all()]
    except NotificationSetting.DoesNotExist:
        notifications_for_modules = []

    return render_to_response('account/settings_view',
                              {
                                  'default_permissions': default_permissions,
                                  'default_perspective': default_perspective,
                                  'language': language,
                                  'all_languages': all_languages,
                                  'default_timezone': default_timezone,
                                  'all_timezones': all_timezones,
                                  'email_notifications': email_notifications,
                                  'notifications_for_modules': notifications_for_modules,
                              },
                              context_instance=RequestContext(request), response_format=response_format)
Ejemplo n.º 22
0
def humanize_datetime(context, value):
    """
    Finds the difference between the datetime value given and now()
    and returns appropriate humanize form
    """
 
    request = context['request']
    
    user = None
    if request.user.username:
        try: 
            user = request.user.get_profile()
        except:
            pass
        
    # timezone
    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except:
        pass
     
    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]
        
    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE', [(1, '(GMT-11:00) International Date Line West')])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10] # with sign e.g. +06:00
    sign = GMT[0:1] # + or -
    hours = int(GMT[1:3]) # e.g. 06
    mins = int(GMT[4:6])

    now = datetime.now()

    if value:
        if sign == "-":
            value = value - timedelta(hours=hours, minutes=mins)
            now = now - timedelta(hours=hours, minutes=mins)
        else: 
            value = value + timedelta(hours=hours, minutes=mins)
            now = now + timedelta(hours=hours, minutes=mins)
    
    if isinstance(value, timedelta):
        delta = value
    elif isinstance(value, datetime):
        delta = now - value
    else:
        delta = None
        
    if delta:
        if delta.days > 6:                                      # May 15, 17:55               
            month = None
            if value.strftime("%b") == 'Jan':
                month = _("Jan")
            elif value.strftime("%b") == 'Feb':
                month = _("Feb")
            elif value.strftime("%b") == 'Mar':
                month = _("Mar")
            elif value.strftime("%b") == 'Apr':
                month = _("Apr")
            elif value.strftime("%b") == 'May':
                month = _("May")
            elif value.strftime("%b") == 'Jun':
                month = _("Jun")
            elif value.strftime("%b") == 'Jul':
                month = _("Jul")
            elif value.strftime("%b") == 'Aug':
                month = _("Aug")
            elif value.strftime("%b") == 'Sep':
                month = _("Sep")
            elif value.strftime("%b") == 'Oct':
                month = _("Oct")
            elif value.strftime("%b") == 'Nov':
                month = _("Nov")
            elif value.strftime("%b") == 'Dec':
                month = _("Dec")
            return month + value.strftime(" %d, %H:%M")
        
        if delta.days > 1:                                      # Wednesday
            if value.strftime("%A") == 'Monday':                      
                return _("Monday")
            elif value.strftime("%A") == 'Tuesday':                      
                return _("Tuesday")
            elif value.strftime("%A") == 'Wednesday':                      
                return _("Wednesday")
            elif value.strftime("%A") == 'Thursday':                      
                return _("Thursday")
            elif value.strftime("%A") == 'Friday':                      
                return _("Friday")
            elif value.strftime("%A") == 'Saturday':                      
                return _("Saturday")
            elif value.strftime("%A") == 'Sunday':                      
                return _("Sunday")
        
        elif delta.days == 1:
            return _("yesterday")                               # yesterday
        elif delta.seconds >= 7200:
            return str(delta.seconds / 3600 ) + _(" hours ago") # 3 hours ago
        elif delta.seconds >= 3600:
            return _("1 hour ago")                              # 1 hour ago
        elif delta.seconds > MOMENT:
            return str(delta.seconds/60) + _(" minutes ago")    # 29 minutes ago
        else:
            return _("a moment ago")                            # a moment ago
        return djangodate(value)
    else:
        return str(value)
Ejemplo n.º 23
0
def humanize_datetime(context, value):
    """
    Finds the difference between the datetime value given and now()
    and returns appropriate humanize form
    """

    request = context['request']

    user = None
    if request.user.username:
        try:
            user = request.user.get_profile()
        except:
            pass

    # timezone
    default_timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
    try:
        conf = ModuleSetting.get('default_timezone')[0]
        default_timezone = conf.value
    except:
        pass

    try:
        conf = ModuleSetting.get('default_timezone', user=user)[0]
        default_timezone = conf.value
    except Exception:
        default_timezone = getattr(
            settings, 'HARDTREE_SERVER_TIMEZONE')[default_timezone][0]

    all_timezones = getattr(settings, 'HARDTREE_SERVER_TIMEZONE',
                            [(1, '(GMT-11:00) International Date Line West')])
    title = all_timezones[int(default_timezone)][1]
    GMT = title[4:10]  # with sign e.g. +06:00
    sign = GMT[0:1]  # + or -
    hours = int(GMT[1:3])  # e.g. 06
    mins = int(GMT[4:6])

    now = datetime.now()

    if value:
        if sign == "-":
            value = value - timedelta(hours=hours, minutes=mins)
            now = now - timedelta(hours=hours, minutes=mins)
        else:
            value = value + timedelta(hours=hours, minutes=mins)
            now = now + timedelta(hours=hours, minutes=mins)

    if isinstance(value, timedelta):
        delta = value
    elif isinstance(value, datetime):
        delta = now - value
    else:
        delta = None

    if delta:
        if delta.days > 6:  # May 15, 17:55
            month = None
            if value.strftime("%b") == 'Jan':
                month = _("Jan")
            elif value.strftime("%b") == 'Feb':
                month = _("Feb")
            elif value.strftime("%b") == 'Mar':
                month = _("Mar")
            elif value.strftime("%b") == 'Apr':
                month = _("Apr")
            elif value.strftime("%b") == 'May':
                month = _("May")
            elif value.strftime("%b") == 'Jun':
                month = _("Jun")
            elif value.strftime("%b") == 'Jul':
                month = _("Jul")
            elif value.strftime("%b") == 'Aug':
                month = _("Aug")
            elif value.strftime("%b") == 'Sep':
                month = _("Sep")
            elif value.strftime("%b") == 'Oct':
                month = _("Oct")
            elif value.strftime("%b") == 'Nov':
                month = _("Nov")
            elif value.strftime("%b") == 'Dec':
                month = _("Dec")
            return month + value.strftime(" %d, %H:%M")

        if delta.days > 1:  # Wednesday
            if value.strftime("%A") == 'Monday':
                return _("Monday")
            elif value.strftime("%A") == 'Tuesday':
                return _("Tuesday")
            elif value.strftime("%A") == 'Wednesday':
                return _("Wednesday")
            elif value.strftime("%A") == 'Thursday':
                return _("Thursday")
            elif value.strftime("%A") == 'Friday':
                return _("Friday")
            elif value.strftime("%A") == 'Saturday':
                return _("Saturday")
            elif value.strftime("%A") == 'Sunday':
                return _("Sunday")

        elif delta.days == 1:
            return _("yesterday")  # yesterday
        elif delta.seconds >= 7200:
            return str(delta.seconds / 3600) + _(" hours ago")  # 3 hours ago
        elif delta.seconds >= 3600:
            return _("1 hour ago")  # 1 hour ago
        elif delta.seconds > MOMENT:
            return str(delta.seconds / 60) + _(
                " minutes ago")  # 29 minutes ago
        else:
            return _("a moment ago")  # a moment ago
        return djangodate(value)
    else:
        return str(value)
Ejemplo n.º 24
0
    def __init__(self, user, *args, **kwargs):
        "Sets choices and initial value"
        super(SettingsForm, self).__init__(*args, **kwargs)

        self.fields['default_perspective'].label = _("Default Perspective")
        self.fields['language'].label = _("Language")
        self.fields['default_timezone'].label = _("Time Zone")
        self.fields['email_notifications'].label = _("E-mail Notifications")

        self.user = user

        self.fields['default_perspective'].queryset = Object.filter_permitted(
            user, Perspective.objects)
        try:
            conf = ModuleSetting.get_for_module('treeio.core',
                                                'default_perspective',
                                                user=self.user)[0]
            default_perspective = Perspective.objects.get(pk=long(conf.value))
            self.fields['default_perspective'].initial = default_perspective.id
        except:
            pass

        self.fields['default_timezone'].choices = getattr(
            settings, 'HARDTREE_SERVER_TIMEZONE')
        timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE
        try:
            conf = ModuleSetting.get('default_timezone', user=user)[0]
            timezone = conf.value
        except:
            pass
        self.fields['default_timezone'].initial = timezone

        self.fields['language'].choices = getattr(settings,
                                                  'HARDTREE_LANGUAGES',
                                                  [('en', 'English')])
        language = getattr(settings, 'HARDTREE_LANGUAGES_DEFAULT', '')
        try:
            conf = ModuleSetting.get('language', user=user)[0]
            language = conf.value
        except IndexError:
            pass
        self.fields['language'].initial = language

        try:
            conf = ModuleSetting.get('email_notifications', user=user)[0]
            self.fields['email_notifications'].initial = conf.value
        except:
            self.fields[
                'email_notifications'].initial = settings.HARDTREE_ALLOW_EMAIL_NOTIFICATIONS

        perspective = user.get_perspective()

        modules = perspective.modules.filter(display=True).order_by('title')
        if not modules:
            modules = Module.objects.filter(display=True).order_by('title')
        self.fields['notifications_for_modules'].choices = [
            (module.pk, module.title) for module in modules
        ]

        try:
            modules = NotificationSetting.objects.get(
                owner=self.user).modules.all()
            self.fields['notifications_for_modules'].initial = [
                m.pk for m in modules
            ]
        except (NotificationSetting.DoesNotExist,
                NotificationSetting.MultipleObjectsReturned):
            pass