def predicate_info_object(): '''Returns our info object used for predicate comparisons''' info_object = {} machine = getMachineFacts() info_object.update(machine) info_object.update(get_conditions()) # use our start time for "current" date (if we have it) # and add the timezone offset to it so we can compare # UTC dates as though they were local dates. info_object['date'] = add_tzoffset_to_date( NSDate.dateWithString_( reports.report.get('StartTime', reports.format_time()))) # split os version into components for easier predicate comparison os_vers = machine['os_vers'] os_vers = os_vers + '.0.0' info_object['os_vers_major'] = int(os_vers.split('.')[0]) info_object['os_vers_minor'] = int(os_vers.split('.')[1]) info_object['os_vers_patch'] = int(os_vers.split('.')[2]) # get last build number component for easier predicate comparison build = machine['os_build_number'] info_object['os_build_last_component'] = pkgutils.MunkiLooseVersion( build).version[-1] if 'Book' in machine.get('machine_model', ''): info_object['machine_type'] = 'laptop' else: info_object['machine_type'] = 'desktop' return info_object
def appleSoftwareUpdatesAvailable(forcecheck=False, suppresscheck=False): '''Checks for available Apple Software Updates, trying not to hit the SUS more than needed''' if suppresscheck: # typically because we're doing a logout install; if # there are no waiting Apple Updates we shouldn't # trigger a check for them. pass elif forcecheck: # typically because user initiated the check from # Managed Software Update.app unused_retcode = checkForSoftwareUpdates(forcecheck=True) else: # have we checked recently? Don't want to check with # Apple Software Update server too frequently now = NSDate.new() nextSUcheck = now lastSUcheckString = munkicommon.pref('LastAppleSoftwareUpdateCheck') if lastSUcheckString: try: lastSUcheck = NSDate.dateWithString_(lastSUcheckString) interval = 24 * 60 * 60 nextSUcheck = lastSUcheck.dateByAddingTimeInterval_(interval) except (ValueError, TypeError): pass if now.timeIntervalSinceDate_(nextSUcheck) >= 0: unused_retcode = checkForSoftwareUpdates(forcecheck=True) else: unused_retcode = checkForSoftwareUpdates(forcecheck=False) if writeAppleUpdatesFile(): displayAppleUpdateInfo() return True else: return False
def software_updates_available( self, force_check=False, suppress_check=False): """Checks for available Apple Software Updates, trying not to hit the SUS more than needed. Args: force_check: Boolean. If True, forces a softwareupdate run. suppress_check: Boolean. If True, skips a softwareupdate run. Returns: Integer. Count of available Apple updates. """ success = True if suppress_check: # don't check at all -- # typically because we are doing a logout install # just return any AppleUpdates info we already have if not os.path.exists(self.apple_updates_plist): return 0 try: plist = FoundationPlist.readPlist(self.apple_updates_plist) except FoundationPlist.FoundationPlistException: plist = {} return len(plist.get('AppleUpdates', [])) if force_check: # typically because user initiated the check from # Managed Software Update.app success = self.check_for_software_updates(force_check=True) else: # have we checked recently? Don't want to check with # Apple Software Update server too frequently now = NSDate.new() next_su_check = now last_su_check_string = prefs.pref( 'LastAppleSoftwareUpdateCheck') if last_su_check_string: try: last_su_check = NSDate.dateWithString_( last_su_check_string) # dateWithString_ returns None if invalid date string. if not last_su_check: raise ValueError interval = 24 * 60 * 60 # only force check every 24 hours. next_su_check = last_su_check.dateByAddingTimeInterval_( interval) except (ValueError, TypeError): pass if now.timeIntervalSinceDate_(next_su_check) >= 0: success = self.check_for_software_updates(force_check=True) else: success = self.check_for_software_updates(force_check=False) display.display_debug1( 'CheckForSoftwareUpdates result: %s' % success) if success: count = self.write_appleupdates_file() else: self.clear_apple_update_info() return 0 return count
def software_updates_available(self, force_check=False, suppress_check=False): """Checks for available Apple Software Updates, trying not to hit the SUS more than needed. Args: force_check: Boolean. If True, forces a softwareupdate run. suppress_check: Boolean. If True, skips a softwareupdate run. Returns: Integer. Count of available Apple updates. """ if suppress_check: # don't check at all -- # typically because we are doing a logout install # just return any AppleUpdates info we already have return self.cached_update_count() if force_check: # typically because user initiated the check from # Managed Software Update.app updatecount = self.check_for_software_updates(force_check=True) else: # have we checked recently? Don't want to check with # Apple Software Update server too frequently now = NSDate.new() next_su_check = now last_su_check_string = prefs.pref('LastAppleSoftwareUpdateCheck') if last_su_check_string: try: last_su_check = NSDate.dateWithString_( last_su_check_string) # dateWithString_ returns None if invalid date string. if not last_su_check: raise ValueError interval = 24 * 60 * 60 # only force check every 24 hours. next_su_check = last_su_check.dateByAddingTimeInterval_( interval) except (ValueError, TypeError): pass if now.timeIntervalSinceDate_(next_su_check) >= 0: updatecount = self.check_for_software_updates(force_check=True) else: updatecount = self.check_for_software_updates( force_check=False) display.display_debug1('CheckForSoftwareUpdates result: %s' % updatecount) if updatecount == -1: # some (transient?) communications error with the su server; return # cached AppleInfo return self.cached_update_count() elif updatecount == 0: self.clear_apple_update_info() else: _ = self.write_appleupdates_file() return updatecount
def createEvent(title, start_time, stop_time, calendar_name=u"项目", note='', url='', location=''): """ createEvent("Python事件", "2018-10-28 10:00:00 +0800", "2018-10-28 12:00:00 +0800") """ store = CalCalendarStore.defaultCalendarStore() for cal in store.calendars(): if cal._.title == calendar_name: event = CalEvent.event() event._.calendar = cal event._.title = title event._.notes = textwrap.dedent(note) if url: event._.url = NSURL.URLWithString_(url) if location: event._.location = location event._.isAllDay = False start = NSDate.dateWithString_(start_time) stop = NSDate.dateWithString_(stop_time) event._.startDate = start event._.endDate = stop res, err = store.saveEvent_span_error_(event, 0, None) if not res: print("添加日历事件失败", err.localizedDescription()) break else: print("添加日历事件成功: %s" % res) break else: print("没有找到合适的日历") for cal in store.calendars(): print(cal._.title)
def _create_date(self, form_item, val, form_view): gregorian = NSCalendar.alloc().initWithCalendarIdentifier_(NSGregorianCalendar) control_label = NSTextField.createLabelWithText_font_(form_item.label, self._system_font) control = NSDatePicker.alloc().initWithFrame_(NSZeroRect) control.setCalendar_(gregorian) control.setDatePickerElements_(NSYearMonthDatePickerElementFlag) control.setDrawsBackground_(YES) control.setDateValue_(NSDate.date()) control.setMinDate_(NSDate.date()) control.setMaxDate_(NSDate.dateWithString_('2029-12-31 23:59:59 +0600')) control.sizeToFit() control.setAction_(self.datePickerAction_) self._form_y_offset -= NSHeight(control.frame()) control.setFrameOrigin_(NSPoint(self._center_point, self._form_y_offset)) control_label.placeRelativeToControl_(control) return (control, control_label)
def convert_date_string_to_nsdate(datetime_string): '''Converts a string in the "2013-04-25T20:00:00Z" format or "2013-04-25 20:00:00 +0000" format to an NSDate''' nsdate_format = '%Y-%m-%dT%H:%M:%SZ' iso_format = '%Y-%m-%d %H:%M:%S +0000' fallback_format = '%Y-%m-%d %H:%M:%S' try: tobj = time.strptime(datetime_string, nsdate_format) except ValueError: try: tobj = time.strptime(datetime_string, iso_format) except ValueError: try: tobj = time.strptime(datetime_string, fallback_format) except ValueError: return None iso_date_string = time.strftime(iso_format, tobj) return NSDate.dateWithString_(iso_date_string)
event = CalEvent.event() event._.calendar = cal event._.title = "WWDC 2009" event._.notes = textwrap.dedent( """\ This June, the center of the Mac universe will be at Moscone West in downtown San Francisco, as developers and IT professionals from around the globe come together for the Apple Worldwide Developers Conference. Don't miss this opportunity to connect with Apple engineers, get a firsthand look at the latest technology, and spend a week getting the kind of inspiration you won't find anywhere else. """ ) event._.url = NSURL.URLWithString_("http://www.apple.com/wwdc/") event._.location = "Moscone West, San Francisco, CA, USA" event._.isAllDay = True start = NSDate.dateWithString_("2009-06-8 00:00:00 +0600") stop = NSDate.dateWithString_("2009-06-12 23:59:59 +0600") event._.startDate = start event._.endDate = stop res, err = store.saveEvent_span_error_(event, 0, None) if not res: print("Adding WWDC failed", err.localizedDescription()) break else: print("Cannot find the right calendar")
for cal in store.calendars(): if cal._.title == "Work": event = CalEvent.event() event._.calendar = cal event._.title = "WWDC 2009" event._.notes = textwrap.dedent('''\ This June, the center of the Mac universe will be at Moscone West in downtown San Francisco, as developers and IT professionals from around the globe come together for the Apple Worldwide Developers Conference. Don't miss this opportunity to connect with Apple engineers, get a firsthand look at the latest technology, and spend a week getting the kind of inspiration you won't find anywhere else. ''') event._.url = NSURL.URLWithString_('http://www.apple.com/wwdc/') event._.location = "Moscone West, San Francisco, CA, USA" event._.isAllDay = True start = NSDate.dateWithString_("2009-06-8 00:00:00 +0600") stop = NSDate.dateWithString_("2009-06-12 23:59:59 +0600") event._.startDate = start event._.endDate = stop res, err = store.saveEvent_span_error_(event, 0, None) if not res: print("Adding WWDC failed", err.localizedDescription()) break else: print("Cannot find the right calendar")
""" from __future__ import print_function from CalendarStore import CalCalendarStore, CalEvent from Foundation import NSURL, NSDate import textwrap store = CalCalendarStore.defaultCalendarStore() for cal in store.calendars(): if cal._.title == "项目": event = CalEvent.event() event._.calendar = cal event._.title = "Python添加日历事件" event._.notes = textwrap.dedent(''' 这个是用Python添加的日历事件 ''') event._.url = NSURL.URLWithString_('http://www.google.com.hk') event._.location = "中国上海市安化路492号" event._.isAllDay = False start = NSDate.dateWithString_("2018-10-27 10:00:00 +0800") stop = NSDate.dateWithString_("2018-10-27 12:00:00 +0800") event._.startDate = start event._.endDate = stop res, err = store.saveEvent_span_error_(event, 0, None) if not res: print("添加日历事件失败", err.localizedDescription()) break else: print("没有找到合适的日历")