def main(): parser = ArgumentParser( formatter_class=RawTextHelpFormatter, description="List or restore deleted events / collections from trash", epilog=""" Examples: * List deleted collections (and their resource IDs) for a given user by UID: calendarserver_trash -p 10000000-0000-0000-0000-000000000001 -c * Restore a deleted collection by resource ID (use -c / -e to find resource ID) for the same user: calendarserver_trash -p 10000000-0000-0000-0000-000000000001 -c -r <rid> """) parser.add_argument('-f', '--config', dest='configFileName', metavar='CONFIGFILE', help='caldavd.plist configuration file path') parser.add_argument('-d', '--debug', action='store_true', help='show debug logging') parser.add_argument('-p', '--principal', dest='principal', help='the principal to use (uid)') parser.add_argument('-e', '--events', action='store_true', help='list or restore trashed events') parser.add_argument('-c', '--collections', action='store_true', help='list or restore trashed collections for principal (uid)') parser.add_argument('-r', '--recover', dest='resourceID', type=int, help='recover trashed collection or event (by resource ID).\nWithout this option, items are listed but not recovered.') parser.add_argument('--empty', action='store_true', help='empty the principal\'s trash') parser.add_argument('--days', type=int, default=0, help='number of past days to retain') args = parser.parse_args() if not args.principal: print("--principal missing") return if args.empty: operation = emptyTrashForPrincipal operationArgs = [args.principal, args.days] elif args.collections: if args.resourceID: operation = restoreTrashedCollection operationArgs = [args.principal, args.resourceID] else: operation = listTrashedCollectionsForPrincipal operationArgs = [args.principal] elif args.events: if args.resourceID: operation = restoreTrashedEvent operationArgs = [args.principal, args.resourceID] else: operation = listTrashedEventsForPrincipal operationArgs = [args.principal] else: operation = listTrashedCollectionsForPrincipal operationArgs = [args.principal] TrashRestorationService.operation = operation TrashRestorationService.operationArgs = operationArgs utilityMain( args.configFileName, TrashRestorationService, verbose=args.debug, loadTimezones=True )
def main(argv=sys.argv, stderr=sys.stderr, reactor=None): """ Do the export. """ if reactor is None: from twisted.internet import reactor options = DBInspectOptions() options.parseOptions(argv[1:]) def makeService(store): return DBInspectService(store, options, reactor, config) utilityMain(options['config'], makeService, reactor, verbose=options['debug'])
def main(): parser = ArgumentParser(description="Display Apple Push Notification subscriptions") parser.add_argument( "-f", "--config", dest="configFileName", metavar="CONFIGFILE", help="caldavd.plist configuration file path" ) parser.add_argument("-d", "--debug", action="store_true", help="show debug logging") parser.add_argument("user", help="one or more users to display", nargs="+") # Required args = parser.parse_args() DisplayAPNSubscriptions.users = args.user utilityMain(args.configFileName, DisplayAPNSubscriptions, verbose=args.debug)
def main(): parser = ArgumentParser(description='Display Apple Push Notification subscriptions') parser.add_argument('-f', '--config', dest='configFileName', metavar='CONFIGFILE', help='caldavd.plist configuration file path') parser.add_argument('-d', '--debug', action='store_true', help='show debug logging') parser.add_argument('user', help='one or more users to display', nargs='+') # Required args = parser.parse_args() DisplayAPNSubscriptions.users = args.user utilityMain( args.configFileName, DisplayAPNSubscriptions, verbose=args.debug, )
def main(): parser = ArgumentParser(description='Restore events from trash') parser.add_argument('-f', '--config', dest='configFileName', metavar='CONFIGFILE', help='caldavd.plist configuration file path') parser.add_argument('-d', '--debug', action='store_true', help='show debug logging') parser.add_argument('-p', '--principal', dest='principal', help='the principal to use (uid)') parser.add_argument('-e', '--events', action='store_true', help='list trashed events') parser.add_argument('-c', '--collections', action='store_true', help='list trashed collections for principal (uid)') parser.add_argument('-r', '--recover', dest='resourceID', type=int, help='recover trashed collection or event (by resource ID)') parser.add_argument('--empty', action='store_true', help='empty the principal\'s trash') parser.add_argument('--days', type=int, default=0, help='number of past days to retain') args = parser.parse_args() if not args.principal: print("--principal missing") return if args.empty: operation = emptyTrashForPrincipal operationArgs = [args.principal, args.days] elif args.collections: if args.resourceID: operation = restoreTrashedCollection operationArgs = [args.principal, args.resourceID] else: operation = listTrashedCollectionsForPrincipal operationArgs = [args.principal] elif args.events: if args.resourceID: operation = restoreTrashedEvent operationArgs = [args.principal, args.resourceID] else: operation = listTrashedEventsForPrincipal operationArgs = [args.principal] else: operation = listTrashedCollectionsForPrincipal operationArgs = [args.principal] TrashRestorationService.operation = operation TrashRestorationService.operationArgs = operationArgs utilityMain( args.configFileName, TrashRestorationService, verbose=args.debug, loadTimezones=True )
lexer = shlex(line) lexer.whitespace_split = True tokens = [] while True: token = lexer.get_token() if not token: break tokens.append(token) return tokens def main(argv=sys.argv, stderr=sys.stderr, reactor=None): if reactor is None: from twisted.internet import reactor options = ShellOptions() try: options.parseOptions(argv[1:]) except UsageError, e: usage(e) def makeService(store): from twistedcaldav.config import config return ShellService(store, options, reactor, config) print("Initializing shell...") utilityMain(options["config"], makeService, reactor)
elif opt in ("-d", "--database"): database = arg elif opt in ("-t", "--dbtype"): dbtype = arg else: raise NotImplementedError(opt) DelegatesMigrationService.function = migrateDelegates DelegatesMigrationService.params = [ server, user, password, pod, database, dbtype ] utilityMain(configFileName, DelegatesMigrationService) @inlineCallbacks def getAssignments(db): """ Returns all the delegate assignments from the db. @return: a list of (delegator group, delegate) tuples """ print("Fetching delegate assignments...") rows = yield db.query("select GROUPNAME, MEMBER from GROUPS;") print("Fetched {} delegate assignments".format(len(rows))) returnValue(rows)
class PurgePrincipalService(WorkerService): root = None directory = None uids = None dryrun = False verbose = False proxies = True when = None @classmethod def usage(cls, e=None): name = os.path.basename(sys.argv[0]) print("usage: %s [options]" % (name,)) print("") print(" Remove a principal's events and contacts from the calendar server") print(" Future events are declined or cancelled") print("") print("options:") print(" -h --help: print this help and exit") print(" -f --config <path>: Specify caldavd.plist configuration path") print(" -n --dry-run: calculate how many events and contacts to purge, but do not purge data") print(" -v --verbose: print progress information") print(" -D --debug: debug logging") print("") if e: sys.stderr.write("%s\n" % (e,)) sys.exit(64) else: sys.exit(0) @classmethod def main(cls): try: (optargs, args) = getopt( sys.argv[1:], "Df:hnv", [ "dry-run", "config=", "help", "verbose", "debug", ], ) except GetoptError, e: cls.usage(e) # # Get configuration # configFileName = None dryrun = False verbose = False debug = False for opt, arg in optargs: if opt in ("-h", "--help"): cls.usage() elif opt in ("-v", "--verbose"): verbose = True elif opt in ("-D", "--debug"): debug = True elif opt in ("-n", "--dry-run"): dryrun = True elif opt in ("-f", "--config"): configFileName = arg else: raise NotImplementedError(opt) # args is a list of uids cls.uids = args cls.dryrun = dryrun cls.verbose = verbose utilityMain( configFileName, cls, verbose=debug, )
usage() elif opt in ("-f", "--config"): configFileName = arg else: raise NotImplementedError(opt) def _patchConfig(config): # Disable Wiki DirectoryService so when we look up uids we don't get # the synthesized ones. config.Authentication.Wiki.Enabled = False WikiMigrationService.principalID = principalID utilityMain(configFileName, WikiMigrationService, patchConfig=_patchConfig) @inlineCallbacks def migrateWiki(store, principalID): """ Iterate calendar homes looking for wiki principals; create resources for each. """ directory = store.directoryService() recordType = CalRecordType.resource prefix = WikiDirectoryService.uidPrefix ch = schema.CALENDAR_HOME if principalID is not None:
if args: cls.usage("Too many arguments: %s" % (args,)) if dryrun: verbose = True cutoff = PyCalendarDateTime.getToday() cutoff.setDateOnly(False) cutoff.offsetDay(-days) cls.cutoff = cutoff cls.batchSize = batchSize cls.dryrun = dryrun cls.verbose = verbose utilityMain( configFileName, cls, ) @classmethod @inlineCallbacks def purgeOldEvents(cls, store, cutoff, batchSize, verbose=False, dryrun=False): service = cls(store) service.cutoff = cutoff service.batchSize = batchSize service.dryrun = dryrun service.verbose = verbose result = (yield service.doWork()) returnValue(result)
elif opt in ("--debug"): debug = True else: raise NotImplementedError(opt) if not args: usage("Not enough arguments") MonitorAMPNotifications.ids = args MonitorAMPNotifications.hostname = hostname MonitorAMPNotifications.port = port utilityMain( configFileName, MonitorAMPNotifications, verbose=debug ) def notificationCallback(id, dataChangedTimestamp, priority): print("Received notification for:", id, "Priority", priority) return succeed(True) @inlineCallbacks def monitorAMPNotifications(hostname, port, ids): print("Subscribing to notifications...") yield subscribeToIDs(hostname, port, ids, notificationCallback)
elif searchTokens: function = runSearch searchTokens = [t.decode("utf-8") for t in searchTokens] params = (searchTokens, searchContext) else: if not args: usage("No principals specified.") unicodeArgs = [a.decode("utf-8") for a in args] function = runPrincipalActions params = (unicodeArgs, principalActions) PrincipalService.function = function PrincipalService.params = params utilityMain(configFileName, PrincipalService, verbose=verbose) def runListPrincipalTypes(service, store): directory = store.directoryService() for recordType in directory.recordTypes(): print(directory.recordTypeToOldName(recordType)) return succeed(None) @inlineCallbacks def runListPrincipals(service, store, listPrincipals): directory = store.directoryService() recordType = directory.oldNameToRecordType(listPrincipals) try: records = list((yield directory.recordsWithRecordType(recordType)))
""" Stop the service. Nothing to do; everything should be finished by this time. """ def main(argv=sys.argv, stderr=sys.stderr, reactor=None): """ Do the export. """ if reactor is None: from twisted.internet import reactor options = ObliterateOptions() options.parseOptions(argv[1:]) try: output = options.openOutput() except IOError, e: stderr.write("Unable to open output file for writing: %s\n" % (e)) sys.exit(1) def makeService(store): from twistedcaldav.config import config config.TransactionTimeoutSeconds = 0 return ObliterateService(store, options, output, reactor, config) utilityMain(options['config'], makeService, reactor) if __name__ == '__main__': main()
# if not args: usage("No principals specified.") for arg in args: try: principalForPrincipalID(arg, checkOnly=True) except ValueError, e: abort(e) function = runPrincipalActions params = (args, principalActions) PrincipalService.function = function PrincipalService.params = params utilityMain(configFileName, PrincipalService, verbose=verbose) def runListPrincipalTypes(service, rootResource, directory, store): for recordType in directory.recordTypes(): print(recordType) return succeed(None) def runListPrincipals(service, rootResource, directory, store, listPrincipals): try: records = list(directory.listRecords(listPrincipals)) if records: printRecordList(records)
rawInput = sys.stdin.read() try: plist = readPlistFromString(rawInput) except xml.parsers.expat.ExpatError, e: respondWithError(str(e)) return # If the plist is an array, each element of the array is a separate # command dictionary. if isinstance(plist, list): commands = plist else: commands = [plist] RunnerService.commands = commands utilityMain(configFileName, RunnerService, verbose=debug) class Runner(object): def __init__(self, store, commands, output=None): self.store = store self.dir = store.directoryService() self.commands = commands if output is None: output = sys.stdout self.output = output def validate(self): # Make sure commands are valid for command in self.commands: if 'command' not in command:
# Get configuration # configFileName = None verbose = False for opt, arg in optargs: if opt in ("-h", "--help"): usage() elif opt in ("-f", "--config"): configFileName = arg else: raise NotImplementedError(opt) utilityMain(configFileName, ResourceMigrationService, verbose=verbose) class DirectoryRecord(BaseDirectoryRecord, CalendarDirectoryRecordMixin): pass @inlineCallbacks def migrateResources(sourceService, destService, verbose=False): """ Fetch all the locations and resources from sourceService that are not already in destService and copy them into destService. """
def main(): parser = ArgumentParser(description='Restore events from trash') parser.add_argument('-f', '--config', dest='configFileName', metavar='CONFIGFILE', help='caldavd.plist configuration file path') parser.add_argument('-d', '--debug', action='store_true', help='show debug logging') parser.add_argument('-p', '--principal', dest='principal', help='the principal to use (uid)') parser.add_argument('-e', '--events', action='store_true', help='list trashed events') parser.add_argument('-c', '--collections', action='store_true', help='list trashed collections for principal (uid)') parser.add_argument( '-r', '--recover', dest='resourceID', type=int, help='recover trashed collection or event (by resource ID)') parser.add_argument('--empty', action='store_true', help='empty the principal\'s trash') parser.add_argument('--days', type=int, default=0, help='number of past days to retain') args = parser.parse_args() if not args.principal: print("--principal missing") return if args.empty: operation = emptyTrashForPrincipal operationArgs = [args.principal, args.days] elif args.collections: if args.resourceID: operation = restoreTrashedCollection operationArgs = [args.principal, args.resourceID] else: operation = listTrashedCollectionsForPrincipal operationArgs = [args.principal] elif args.events: if args.resourceID: operation = restoreTrashedEvent operationArgs = [args.principal, args.resourceID] else: operation = listTrashedEventsForPrincipal operationArgs = [args.principal] else: operation = listTrashedCollectionsForPrincipal operationArgs = [args.principal] TrashRestorationService.operation = operation TrashRestorationService.operationArgs = operationArgs utilityMain(args.configFileName, TrashRestorationService, verbose=args.debug, loadTimezones=True)
""" Stop the service. Nothing to do; everything should be finished by this time. """ # TODO: stopping this service mid-import should really stop the import # loop, but this is not implemented because nothing will actually do it # except hitting ^C (which also calls reactor.stop(), so that will exit # anyway). def main(argv=sys.argv, reactor=None): """ Do the import. """ if reactor is None: from twisted.internet import reactor options = ImportOptions() try: options.parseOptions(argv[1:]) except UsageError, e: usage(e) def makeService(store): from twistedcaldav.config import config return ImporterService(store, options, reactor, config) utilityMain(options["config"], makeService, reactor, verbose=options["debug"])
""" def main(argv=sys.argv, stderr=sys.stderr, reactor=None): """ Do the export. """ if reactor is None: from twisted.internet import reactor options = ObliterateOptions() options.parseOptions(argv[1:]) try: output = options.openOutput() except IOError, e: stderr.write("Unable to open output file for writing: %s\n" % (e)) sys.exit(1) def makeService(store): from twistedcaldav.config import config config.TransactionTimeoutSeconds = 0 return ObliterateService(store, options, output, reactor, config) utilityMain(options['config'], makeService, reactor, verbose=options["debug"]) if __name__ == '__main__': main()
debug = False for opt, arg in optargs: if opt in ("-h", "--help"): usage() if opt in ("-e", "--error"): debug = True elif opt in ("-f", "--config"): configFileName = arg else: raise NotImplementedError(opt) utilityMain(configFileName, WorkItemMonitorService, verbose=debug) class WorkItemMonitorService(WorkerService, object): def __init__(self, store): super(WorkItemMonitorService, self).__init__(store) from twisted.internet import reactor self.reactor = reactor def doWork(self): self.screen = curses.initscr() self.windows = [] self.updateScreenGeometry()
cls.usage("Too many arguments: %s" % (args,)) if dryrun: verbose = True cutoff = DateTime.getToday() cutoff.setDateOnly(False) cutoff.offsetDay(-days) cls.cutoff = cutoff cls.batchSize = batchSize cls.dryrun = dryrun cls.verbose = verbose utilityMain( configFileName, cls, verbose=debug, ) @classmethod @inlineCallbacks def purgeOldEvents(cls, store, cutoff, batchSize, verbose=False, dryrun=False): service = cls(store) service.cutoff = cutoff service.batchSize = batchSize service.dryrun = dryrun service.verbose = verbose result = (yield service.doWork()) returnValue(result)
tokens = [] while True: token = lexer.get_token() if not token: break tokens.append(token) return tokens def main(argv=sys.argv, stderr=sys.stderr, reactor=None): if reactor is None: from twisted.internet import reactor options = ShellOptions() try: options.parseOptions(argv[1:]) except UsageError, e: usage(e) def makeService(store): from twistedcaldav.config import config return ShellService(store, options, reactor, config) print("Initializing shell...") utilityMain(options["config"], makeService, reactor)
rawInput = sys.stdin.read() try: plist = readPlistFromString(rawInput) except xml.parsers.expat.ExpatError, e: respondWithError(str(e)) return # If the plist is an array, each element of the array is a separate # command dictionary. if isinstance(plist, list): commands = plist else: commands = [plist] RunnerService.commands = commands utilityMain(configFileName, RunnerService) attrMap = { 'GeneratedUID' : { 'attr' : 'guid', }, 'RealName' : { 'attr' : 'fullName', }, 'RecordName' : { 'attr' : 'shortNames', }, 'Comment' : { 'extras' : True, 'attr' : 'comment', }, 'Description' : { 'extras' : True, 'attr' : 'description', }, 'Type' : { 'extras' : True, 'attr' : 'type', }, 'Capacity' : { 'extras' : True, 'attr' : 'capacity', }, 'Building' : { 'extras' : True, 'attr' : 'building', }, 'Floor' : { 'extras' : True, 'attr' : 'floor', }, 'Street' : { 'extras' : True, 'attr' : 'street', }, 'City' : { 'extras' : True, 'attr' : 'city', }, 'State' : { 'extras' : True, 'attr' : 'state', },
])) def customServiceMaker(): customService = CalDAVServiceMaker() customService.doPostImport = options["postprocess"] return customService def _patchConfig(config): config.FailIfUpgradeNeeded = options["status"] or options["check"] config.CheckExistingSchema = options["check"] if options["prefix"]: config.UpgradeHomePrefix = options["prefix"] if not options["status"] and not options["check"]: config.DefaultLogLevel = "debug" def _onShutdown(): if not UpgraderService.started: print("Failed to start service.") utilityMain(options["config"], makeService, reactor, customServiceMaker, patchConfig=_patchConfig, onShutdown=_onShutdown, verbose=options["debug"]) if __name__ == '__main__': main()
customService = CalDAVServiceMaker() customService.doPostImport = options["postprocess"] return customService def _patchConfig(config): config.FailIfUpgradeNeeded = options["status"] if options["prefix"]: config.UpgradeHomePrefix = options["prefix"] def _onShutdown(): if not UpgraderService.started: print("Failed to start service.") utilityMain(options["config"], makeService, reactor, customServiceMaker, patchConfig=_patchConfig, onShutdown=_onShutdown, verbose=options["debug"]) def logDateString(): logtime = time.localtime() Y, M, D, h, m, s = logtime[:6] tz = computeTimezoneForLog(time.timezone) return '%02d-%02d-%02d %02d:%02d:%02d%s' % (Y, M, D, h, m, s, tz) def computeTimezoneForLog(tz): if tz > 0: neg = 1
usage() elif opt in ("-f", "--config"): configFileName = arg else: raise NotImplementedError(opt) if not args: usage("Not enough arguments") DisplayAPNSubscriptions.users = args utilityMain( configFileName, DisplayAPNSubscriptions, ) @inlineCallbacks def displayAPNSubscriptions(store, directory, root, users): for user in users: print record = directory.recordWithShortName("users", user) if record is not None: print "User %s (%s)..." % (user, record.uid) txn = store.newTransaction(label="Display APN Subscriptions") subscriptions = (yield txn.apnSubscriptionsBySubscriber(record.uid)) (yield txn.commit())
# Get configuration # configFileName = None verbose = False for opt, arg in optargs: if opt in ("-h", "--help"): usage() elif opt in ("-f", "--config"): configFileName = arg else: raise NotImplementedError(opt) utilityMain(configFileName, ResourceMigrationService, verbose=verbose) class DirectoryRecord(BaseDirectoryRecord, CalendarDirectoryRecordMixin): pass @inlineCallbacks def migrateResources(sourceService, destService, verbose=False): """ Fetch all the locations and resources from sourceService that are not already in destService and copy them into destService. """ destRecords = []
cls.uuid = uuid if dryrun: verbose = True cutoff = DateTime.getToday() cutoff.setDateOnly(False) cutoff.offsetDay(-days) cls.cutoff = cutoff cls.batchSize = batchSize cls.dryrun = dryrun cls.debug = debug utilityMain( configFileName, cls, verbose=verbose, ) @classmethod @inlineCallbacks def purgeOldEvents(cls, store, uuid, cutoff, batchSize, debug=False, dryrun=False): service = cls(store) service.uuid = uuid service.cutoff = cutoff service.batchSize = batchSize service.dryrun = dryrun service.debug = debug result = yield service.doWork() returnValue(result)
rawInput = sys.stdin.read() try: plist = readPlistFromString(rawInput) except xml.parsers.expat.ExpatError, e: respondWithError(str(e)) return # If the plist is an array, each element of the array is a separate # command dictionary. if isinstance(plist, list): commands = plist else: commands = [plist] RunnerService.commands = commands utilityMain(configFileName, RunnerService, verbose=debug) class Runner(object): def __init__(self, root, directory, store, commands, output=None): self.root = root self.dir = directory self.store = store self.commands = commands if output is None: output = sys.stdout self.output = output def validate(self):
password = arg elif opt in ("-d", "--database"): database = arg elif opt in ("-t", "--dbtype"): dbtype = arg else: raise NotImplementedError(opt) DelegatesMigrationService.function = migrateDelegates DelegatesMigrationService.params = [server, user, password, pod, database, dbtype] utilityMain(configFileName, DelegatesMigrationService) @inlineCallbacks def getAssignments(db): """ Returns all the delegate assignments from the db. @return: a list of (delegator group, delegate) tuples """ print("Fetching delegate assignments...") rows = yield db.query("select GROUPNAME, MEMBER from GROUPS;") print("Fetched {} delegate assignments".format(len(rows))) returnValue(rows)