Beispiel #1
0
def todays_events(server,logtype,ids=[4648]):
    import datetime
    from vyperlogix import misc
    from vyperlogix.misc import _utils
    from vyperlogix.hash.lists import HashedLists
    from vyperlogix.classes.SmartObject import SmartObject
    
    import win32evtlog
    
    #logon_event_ids = [id for id in [int(e.id) for e in events_by_tokens.get('logon',[])] if (id > 999)]
    logon_event_ids = ids if (misc.isList(ids)) else [4648]
    
    hand = win32evtlog.OpenEventLog(server,logtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    
    now = _utils.today_localtime()
    
    seconds_in_day = 24*60*60
    
    __todays_events__ = []
    
    __running__ = True
    while (__running__):
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                if (event.EventID in logon_event_ids):
                    #print 'Event Category:', event.EventCategory
                    #print 'Time Generated:', event.TimeGenerated
                    dt = _utils.getFromDateTimeStr(event.TimeGenerated.Format(),format='%m/%d/%y %H:%M:%S')
                    delta = max(now,dt) - min(now,dt)
                    #print 'delta.total_seconds()=%s' % (delta.total_seconds())
                    if (delta.total_seconds() < seconds_in_day):
                        __todays_events__.append(event)
                    else:
                        __running__ = False
                        break
                    #print 'Source Name:', event.SourceName
                    #print 'Event ID:', event.EventID
                    #print 'Event Type:', event.EventType
                    #data = event.StringInserts
                    #if data:
                        #print 'Event Data:'
                        #for msg in data:
                            #print msg
                    #print '='*40
        else:
            break
    return __todays_events__
Beispiel #2
0
def today():
    from datetime import datetime,timedelta
    _today = datetime.today()
    _today = _utils.getFromDateTimeStr(_utils.getAsSimpleDateStr(_today,_utils.formatDate_MMDDYYYY_slashes()),_utils.formatDate_MMDDYYYY_slashes())
    return _today
Beispiel #3
0
    def validate_and_save(self,
                          request,
                          d_context,
                          callback=None,
                          callback_beforeSave=None,
                          callback_validation_failed=None,
                          callback_error=None):
        self.__last_error__ = ''
        for field_name in request.POST.keys():
            if (self.fields.has_key(field_name)):
                aField = self.fields[field_name]
                aField.value = request.POST[field_name]
                if (aField.required):
                    if (self.is_CharField(aField)):
                        if (len(aField.value.strip()) < aField.min_length if
                            (aField.min_length) else 1):
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    '&nbsp;%s requires at least %d chars.' %
                                    (aField.label, aField.min_length if
                                     (aField.min_length is not None) else 0),
                                    class_='error')
                    elif (self.is_EmailField(aField)):
                        valid_email = validateEmail(aField.value)
                        valid_email_domain = True  # Assume the domain is valid so long as the domain name appears to be valid in case there is no other filter.
                        email_domain = aField.value.split('@')[-1]
                        if (callable(
                                self.get_freehost_by_name)) and (valid_email):
                            hosts = self.get_freehost_by_name(email_domain)
                            valid_email_domain = (hosts is None) or (
                                (misc.isList(hosts)) and (len(hosts) == 0))
                        if (not valid_email) or (not valid_email_domain):
                            extra_msg = ' because "%s" is not an allowed domain' % (
                                email_domain) if (
                                    not valid_email_domain) else ''
                            d_context['ERROR_%s' % (field_name.upper(
                            ))] = oohtml.render_SPAN(
                                '&nbsp;Please enter a valid internet email address%s.'
                                % (extra_msg),
                                class_='error')
                    elif (self.is_ModelChoiceField(aField)):
                        can_consisder_validation = True
                        for validation_tuple in self.__field_validations__:
                            if (callable(validation_tuple[0])):
                                if (validation_tuple[-1].has_key(field_name)):
                                    can_consisder_validation = False
                        if (can_consisder_validation):
                            if (len(aField.value) == 0):
                                d_context[
                                    'ERROR_%s' %
                                    (field_name.upper())] = oohtml.render_SPAN(
                                        '&nbsp;Selection for %s is not valid.'
                                        % (aField.label),
                                        class_='error')
                        if (len(aField.value) > 0):
                            kw = {
                                self.get_choice_model_for_field_by_name(field_name).value_id:
                                aField.value
                            }
                            aField._value = aField.queryset.filter(**kw)[0]
                    elif (self.is_BooleanField(aField)):
                        isError = False
                        try:
                            aField.value = eval(aField.value)
                        except Exception as e:
                            isError = True
                            info_string = _utils.formattedException(details=e)
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    '<BR/>'.join(info_string.split('\n')),
                                    class_='error')
                            aField.value = False
                        if (not isError) and (not isinstance(
                                aField.value, bool)):
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    'Not a valid Boolean value.',
                                    class_='error')
                    elif (self.is_DateTimeField(aField)):
                        isError = False
                        try:
                            aField.value = _utils.getFromDateTimeStr(
                                aField.value,
                                format=_utils.formatDate_MMDDYYYY_slashes())
                        except Exception as e:
                            isError = True
                            info_string = _utils.formattedException(details=e)
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    '<BR/>'.join(info_string.split('\n')),
                                    class_='error')
                            aField.value = None
                        if (not isError) and (ObjectTypeName.typeClassName(
                                aField.value) != 'datetime.datetime'):
                            d_context[
                                'ERROR_%s' %
                                (field_name.upper())] = oohtml.render_SPAN(
                                    'Not a valid DateTime value.',
                                    class_='error')
            else:
                pass
        for validation_tuple in self.__field_validations__:
            if (callable(validation_tuple[0])):
                if (validation_tuple[0](self)):
                    for k, v in validation_tuple[-1].iteritems():
                        d_context['ERROR_%s' %
                                  (k.upper())] = oohtml.render_SPAN(
                                      '&nbsp;%s' % (v), class_='error')

        if (len(d_context) > 0):
            for field_name in request.POST.keys():
                if (self.fields.has_key(field_name)):
                    aField = self.fields[field_name]
                    aField.value = request.POST[field_name]
                    d_context['VALUE_%s' % (field_name.upper())] = aField.value
            if (callable(callback_validation_failed)):
                return callback_validation_failed(self, d_context)
        else:
            lable_from_field = lambda foo: f.label if (not misc.isString(f)
                                                       ) else f
            try:
                pk = self.model._meta.pk
                try:
                    kw = {
                        lable_from_field(pk.formfield()): [
                            f for f in self.fields if (lable_from_field(
                                f) == lable_from_field(pk.formfield()))
                        ][0]
                    }
                except:
                    url_toks = django_utils.parse_url_parms(request)
                    kw = {
                        pk.column:
                        int(url_toks[-1]) if
                        (str(url_toks[-1]).isdigit()) else -1
                    }
                anObj = self.model.objects.get(**kw)
            except Exception as details:
                anObj = self.model()

            for field_name, aField in self.fields.iteritems():
                try:
                    if self.is_ModelChoiceField(aField):
                        anObj.__setattr__(field_name, aField._value)
                    else:
                        anObj.__setattr__(field_name, aField.value)
                except Exception as e:  # ignore all the hidden fields or any other fields for which there is no data present.
                    info_string = _utils.formattedException(details=e)
            for k, v in self.__extra_fields__.iteritems():
                try:
                    anObj.__setattr__(k, v)
                except Exception as e:
                    info_string = _utils.formattedException(details=e)
            if (callable(callback_beforeSave)):
                callback_beforeSave(self, request, anObj)
            try:
                anObj.save()
            except Exception as details:
                self.__last_error__ = _utils.formattedException(
                    details=details)
                if (callable(callback_error)):
                    callback_error(self, request)
            finally:
                if (len(self.last_error) > 0):
                    if (callable(callback_validation_failed)):
                        return callback_validation_failed(self, d_context)
                else:
                    if (callable(callback)):
                        return callback(self, request)
        return None
Beispiel #4
0
def next_sunday():
    from datetime import datetime,timedelta
    today = datetime.today()
    today = _utils.getFromDateTimeStr(_utils.getAsSimpleDateStr(today,_utils.formatDate_MMDDYYYY_slashes()),_utils.formatDate_MMDDYYYY_slashes()) + timedelta(days = 1)
    _next_sunday = today + timedelta(days = 6 - today.weekday()) # next sunday is the next drawing...
    return _next_sunday