Пример #1
0
    def tag_asset(self, assetpath, tags):
        """
        Function is lowlevel and does not look up values from titles.

        assetpath: e.g. /my_robots/bernard.jpg
        tags: e.g. {name: ['bernard.jpg'], type: ['host']}
        """
        if assetpath.startswith("/content/dam"):
            assetpath = remove_prefix("/content/dam", assetpath)

        log("Fetching status for {}".format(assetpath))
        status, data = self.api.get(assetpath)
        if status != OK:
            error("Failed to get status for {}: {}".format(assetpath, data))
            return SERVER_ERROR, None
        props = data['properties']

        existing_tags = flatten_properties(props)
        tags = merge_tags(existing_tags, tags)
        if existing_tags == tags:
            log("Skipping {}, no updates to make".format(assetpath))
            return OK

        log("Tagging {}".format(assetpath))
        status, data = self.api.setprops(assetpath, tags)
        sys.stdout.write("{}\n".format(assetpath))
        if status != OK:
            error("Failed to update metadata of {}".format(assetpath))
            return status, None
        return OK, data
Пример #2
0
def list_pending_jobs(server):
    url = server.url(QUERYBUILDER_PATH)
    resp = requests.get(url, auth=server.auth, params=pending_params)
    if resp.status_code != 200:
        error("Failed to list pending jobs from {}".format(url))
    else:
        sys.stdout.write("{}\n".format(resp.content))
Пример #3
0
    def _list_assets(self, path):
        """ List assets under path
         
            :return (<status>, <list>)
            <status>: <OK|USER_ERROR|SERVER_ERROR>
            <list> [{name: <name>, title: <title>}...]
        """

        log("Fetching asset list for {}".format(path))
        req_path = "{root}{path}.json".format(root=API_ROOT, path=path)
        url = self.server.url(req_path)

        status, data = self._fetch_json(url)
        if status != OK:
            return SERVER_ERROR, None

        _add_path(data, path)

        next_url = _get_next_url(data)
        while next_url is not None:
            status, next_data = self._fetch_json(next_url)
            if status != OK:
                error("Failed to fetch next listing {}".format(next_url))
                next_url = None
            else:
                _add_path(next_data, path)
                data['entities'].extend(next_data['entities'])
                next_url = _get_next_url(next_data)
        return OK, data
Пример #4
0
def _post_file(server, filepath, dst_path, dry_run):
    """ POST single file to DAM
        curl -v -u admin:admin -X POST -i -F "file=@\"$FILENAME\"" $HOST$dampath.createasset.html &> $tempfile
    """
    assert os.path.isfile(filepath)

    if dry_run:
        return OK

    filename = os.path.basename(filepath)
    f = open(filepath, 'rb')
    mime, enc = mimetypes.guess_type(filepath)
    log("Uploading {} as {}, {}".format(f, mime, enc))
    form_data = dict(
        file=(filename, f, mime, dict()),
        fileName=filename
    )

    url = server.url("{path}.createasset.html".format(path=dst_path, filename=os.path.basename(filepath)))
    log("POSTing to {}".format(url))
    resp = requests.post(url, auth=server.auth, files=form_data)
    if not _ok(resp.status_code):
        error("Failed to upload file {}\n{}".format(filepath, resp.content))
        return SERVER_ERROR
    return OK
Пример #5
0
def promote_package(server, target_server, options, package_name):
    """ Download package from server, upload to target_server and install. """
    if not package_name:
        error("Missing package name argument")
        return USER_ERROR

    _, tmp_filepath = tempfile.mkstemp(".zip")
    log("Download package from source server {} to {}".format(
        server, tmp_filepath))
    status = download_package(server,
                              options,
                              package_name,
                              filename=tmp_filepath)
    if status != OK:
        return status

    log("Upload downloaded package file to target server {}".format(
        target_server))
    status = upload_package(target_server, options, tmp_filepath)
    os.remove(tmp_filepath)
    if status != OK:
        return status

    log("Install uploaded package on target server")
    install_package(target_server, options, package_name)
    return status
Пример #6
0
    def execute(self, server, argv):
        options, args = parser.parse_args(argv)

        action = get_action(args, default='list')
        actionarg = get_argument(args)

        if action == 'list' or action == 'ls':
            return list_packages(server, options)
        elif actionarg is None:
            parser.print_help()
            return USER_ERROR
        elif action == 'build':
            return build_package(server, options, actionarg)
        elif action == 'install':
            return install_package(server, options, actionarg)
        elif action == 'uninstall':
            return uninstall_package(server, options, actionarg)
        elif action == 'download':
            return download_package(server, options, actionarg)
        elif action == 'upload':
            return upload_package(server, options, actionarg)
        elif action == 'promote':
            target_server_name = options.target_server
            if target_server_name is None:
                error("Missing target server, use -t flag.")
                return USER_ERROR
            target_server = self.config.get_server(target_server_name)
            return promote_package(server, target_server, options, actionarg)
        else:
            sys.stderr.write(
                'error: Unknown package action {a}\n'.format(a=action))
            return USER_ERROR
Пример #7
0
def upload_package(server, options, filename):
    """ curl -u admin:admin -F file=@"name of zip file" -F name="name of package"
            -F strict=true -F install=false http://localhost:4505/crx/packmgr/service.jsp """
    form_data = dict(file=(filename, open(filename,
                                          'rb'), 'application/zip', dict()),
                     name=filename.rstrip('.zip'),
                     strict="true",
                     install=json_bool(options.install))
    log(form_data)
    url = server.url(SERVICE_PATH)
    log("POSTing to {}".format(url))
    resp = requests.post(url, auth=server.auth, files=form_data)
    log("Got status %s" % str(resp.content))

    if resp.status_code != 200:
        error('Failed to upload paackage: {}: {}'.format(
            resp.status_code, resp.content))
        if options.raw:
            sys.stdout.write("{}\n".format(resp.content))
        return SERVER_ERROR
    else:
        try:
            tree = ElementTree.fromstring(resp.content)
            pkg_elem = tree.find('response').find('data').find('package')
            pkg = parse_package(pkg_elem)
            sys.stdout.write("{}\n".format(format_package(pkg)))
        except Exception as e:
            sys.stderr.write('error: Failed to parse response: {}\n'.format(e))
            return SERVER_ERROR
    return OK
Пример #8
0
    def execute(server, argv):
        options, args = parser.parse_args(argv)

        action = get_command(args, default='list')
        argument = get_argument(args, i=2)
        argument2 = get_argument(args, i=3, default=argument)

        if action == 'list' or action == 'ls':
            return list_rcp_tasks(server, options)
        if action == 'create':
            src_path = argument
            dst_path = argument2
            return create_new_task(server, src_path, dst_path, options)
        elif action == 'start':
            return start_task(server, argument, options)
        elif action == 'stop':
            return stop_task(server, argument, options)
        elif action == 'remove' or action == 'rm':
            return remove_task(server, argument)
        elif action == 'clear':
            return clear_tasks(server)
        elif action == 'fetch':
            return fetch_tree_synchronous(server, options, argument)
        else:
            error("Unknown rcp action {a}".format(a=action))
            return USER_ERROR
Пример #9
0
def _create_task(server, task_id, src_path, dst_path, options):
    """ Create a new task, does not start it """
    log("Creating task {}".format(task_id))
    payload = {
        "cmd":
        "create",
        "id":
        task_id,
        "src":
        "http://{credentials}@{source_host}/crx/-/jcr:root{content_path}".
        format(credentials=options.source_credentials,
               source_host=options.source_host,
               content_path=src_path),
        "dst":
        dst_path,
        "batchsize":
        int(options.batch_size),
        "update":
        options.overwrite_existing,
        "onlyNewer":
        options.respect_modified_date,
        "throttle":
        int(options.throttle),
        "recursive":
        True,
    }
    url = server.url("/system/jackrabbit/filevault/rcp")
    resp = requests.post(url, auth=server.auth, json=payload)
    if resp.status_code != 201:
        error("Failed to create task, request returned {} and {}".format(
            resp.status_code, resp.content))
        return SERVER_ERROR, None

    return OK, resp.json()
Пример #10
0
    def execute(_, argv):
        (options, args) = parser.parse_args(argv)

        arg = get_command(args, '_tools')
        if arg == '_tools':
            print_tools(sys.stdout, options.compact)
        elif arg == '_servers':
            print_servers(sys.stdout)
        else:
            _tool = tool_repo.get_tool(arg)
            _module = tool_repo.get_module(arg)
            if _tool is None:
                error("No tool named {} found".format(arg))
                print_tools(sys.stderr, options.compact)
                return USER_ERROR
            if options.compact:
                for cmd in _tool.commands:
                    sys.stdout.write("{}\n".format(cmd))
            else:
                if hasattr(_module, 'parser'):
                    _module.parser.print_help()
                else:
                    sys.stdout.write("Available commands:\n")
                    for cmd in _tool.commands:
                        sys.stdout.write("\t{}\n".format(cmd))
        return OK
Пример #11
0
    def find(self, path):
        if path.startswith("/content/dam"):
            path = remove_prefix("/content/dam", path)

        status, root = self._list_assets(path)
        if status != OK:
            error("Failed to find in {}".format(path))
            return SERVER_ERROR, None

        assets = _filter_assets(root['entities'])
        folder_queue = _filter_folders(root['entities'])

        while len(folder_queue) > 0:
            entity = folder_queue.pop()
            path = join(entity['properties']['path'], entity['properties']['name'])
            status, data = self._list_assets(path)
            if status != OK:
                error("Failed to list contents of {}".format(path))
            else:
                for entity in data.get('entities', list()):
                    if _is_folder(entity):
                        folder_queue.insert(0, entity)
                    elif _is_asset(entity):
                        assets.append(entity)

        return OK, assets
Пример #12
0
    def execute(self, server, argv):
        options, args = parser.parse_args(argv)
        if len(argv) < 2:
            parser.print_help()
            return USER_ERROR

        filename = args[1]
        f = open(filename, 'r')
        status, data = backend.execute(server, f.read(), [], raw_output=options.raw)

        if status != OK:
            error("Failed to run script {filename}: {content}".format(
                filename=filename,
                content=data))
            return SERVER_ERROR

        if options.raw:
            sys.stdout.write("{}\n".format(json.dumps(data, indent=4)))
        else:
            # The stacktrace prop changed name with newer versions.
            if backend.STACKTRACE_FIELD in data:
                sys.stderr.write(data[backend.STACKTRACE_FIELD])
                return SERVER_ERROR
            elif backend.OUTPUT_FIELD in data:
                sys.stdout.write("{}".format(data[backend.OUTPUT_FIELD].encode('utf-8')))
            else:
                return INTERNAL_ERROR
        return OK
Пример #13
0
def parse_tag(tag_expr):
    """ Expects key=val """
    parts = re.split("(?<!\\\\)=", tag_expr)
    if len(parts) != 2:
        error("Failed to parse tag parameter string")
        return USER_ERROR, None, None
    return OK, decode(parts[0]), decode(parts[1])
Пример #14
0
    def execute(_, argv):
        (options, args) = parser.parse_args(argv)

        arg = get_command(args, '_tools')
        if arg == '_tools':
            print_tools(sys.stdout, options.compact)
        elif arg == '_servers':
            print_servers(sys.stdout)
        else:
            _tool = get_tool(arg)
            _module = get_module(arg)
            if _tool is None:
                error("No tool named {} found".format(arg))
                print_tools(sys.stderr, options.compact)
                return USER_ERROR
            if options.compact:
                for cmd in _tool.commands:
                    sys.stdout.write("{}\n".format(cmd))
            else:
                if hasattr(_module, 'parser'):
                    _module.parser.print_help()
                else:
                    sys.stdout.write("Available commands:\n")
                    for cmd in _tool.commands:
                        sys.stdout.write("\t{}\n".format(cmd))
        return OK
Пример #15
0
    def execute(server, argv):
        options, args = parser.parse_args(argv)
        action = get_action(args)
        actionarg = get_argument(args)

        api = WorkflowsApi(server)
        if action == 'models' or action == 'md':
            return list_workflow_models(server, options)
        elif action == 'instances' or action == 'in':
            return list_workflow_instances(api, 'COMPLETED')
        elif action == 'start':

            model = actionarg
            if len(args) >= 4:
                path = get_argument(args, i=3)
                status, output = api.start_workflow(model, path)
                sys.stdout.write("{}\n".format(output))
                return status
            else:
                ret = OK
                for path in sys.stdin:
                    status, output = api.start_workflow(model, path.strip())
                    if status == OK:
                        sys.stdout.write("{}\n".format(output))
                    ret = ret | status
                return ret
        else:
            error('Unknown workflows action {a}\n'.format(a=action))
            return USER_ERROR
Пример #16
0
    def execute(self, server, argv):
        options, args = parser.parse_args(argv)
        if len(argv) < 2:
            parser.print_help()
            return USER_ERROR

        filename = args[1]
        f = open(filename, 'r')
        status, data = backend.execute(server,
                                       f.read(), [],
                                       raw_output=options.raw)

        if status != OK:
            error("Failed to run script {filename}: {content}".format(
                filename=filename, content=data))
            return SERVER_ERROR

        if options.raw:
            sys.stdout.write("{}\n".format(json.dumps(data, indent=4)))
        else:
            # The stacktrace prop changed name with newer versions.
            if backend.STACKTRACE_FIELD in data:
                sys.stderr.write(data[backend.STACKTRACE_FIELD])
                return SERVER_ERROR
            elif backend.OUTPUT_FIELD in data:
                sys.stdout.write("{}".format(
                    data[backend.OUTPUT_FIELD].encode('utf-8')))
            else:
                return INTERNAL_ERROR
        return OK
Пример #17
0
    def start_workflow(self, model, path):
        """ curl -u admin:admin
                -d "model=/etc/workflow/models/request_for_activation/jcr:content/model&
                payload=/content/geometrixx/en/company&
                payloadType=JCR_PATH&
                workflowTitle=myWorkflowTitle" http://localhost:4502/etc/workflow/instances

        """
        task_id = create_task_id(model)

        form_data = dict(
            model='/etc/workflow/models/{}/jcr:content/model'.format(model),
            payload=path,
            payloadType='JCR_PATH',
            workflowTitle=task_id,
            startComment='')

        url = self.server.url(INSTANCES_PATH)
        resp = requests.post(url, auth=self.server.auth, data=form_data)
        if resp.status_code != 201:
            error("Unexpected error code {code}: {content}".format(
                code=resp.status_code, content=resp.content))
            return SERVER_ERROR

        output = resp.content if self.raw else task_id
        return OK, output
Пример #18
0
def list_workflow_instances(api, mode):
    status, data = api.get_instances(mode)
    if status != OK:
        error(data)
    else:
        for instance in data:
            sys.stdout.write("{}\n".format(instance['uri']))
    return status
Пример #19
0
def set_master_password():
    if not acmd.util.crypto.is_supported():
        error(
            "Crypto functions are not supported on this system. Install pycrypto or pycryptodome"
        )
        return USER_ERROR
    acmd.util.crypto.set_master_password()
    return OK
Пример #20
0
    def get_server(self, server_name):
        if server_name not in self.servers:
            error("Server {} not defined in {}; servers={}".format(
                server_name, get_rcfilename(), self.servers.keys()))
            sys.exit(acmd.USER_ERROR)


#            server_name = DEFAULT_SERVER_SETTING
        return self.servers.get(server_name)
Пример #21
0
def garbage_collect(server, options):
    url = server.url(GC_PATH)
    resp = requests.post(url, auth=server.auth)
    if resp.status_code != 200:
        error("Failed to trigger Tar Optimization because: {}".format(resp.content))
        return -1
    else:
        if options.raw:
            sys.stdout.write("{}".format(resp.content))
Пример #22
0
def garbage_collect(server, options):
    url = server.url(GC_PATH)
    resp = requests.post(url, auth=server.auth)
    if resp.status_code != 200:
        error("Failed to trigger Tar Optimization because: {}".format(
            resp.content))
        return -1
    else:
        if options.raw:
            sys.stdout.write("{}".format(resp.content))
Пример #23
0
    def execute(self, server, argv):
        options, args = parser.parse_args(argv)

        action = get_command(args)
        actionarg = get_argument(args)

        if action == 'import':
            return self.import_path(server, options, actionarg)
        else:
            error("Unknown action {}".format(action))
            return USER_ERROR
Пример #24
0
def get_bundle_list(server):
    url = server.url('/system/console/bundles.json')

    log("GETting service {}".format(url))
    response = requests.get(url, auth=server.auth)

    if response.status_code != 200:
        error("Failed to list bundles: {}".format(response.status_code))
        return []
    bundles = response.json()['data']
    return bundles
Пример #25
0
def delete_package(server, options, package_name):
    url = get_package_url(package_name, server, options)
    form_data = dict(cmd='delete')

    log("Deleting package with POST to {}".format(url))
    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 200:
        error("Failed to delete package: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    return OK
Пример #26
0
def _get_task_list(server):
    url = server.url("/system/jackrabbit/filevault/rcp")

    log("GETting service {}".format(url))
    resp = requests.get(url, auth=server.auth)

    if resp.status_code != 200:
        error("Failed to list rcp tasks, request returned {}".format(
            resp.status_code))
        return SERVER_ERROR, None

    return OK, resp.json()
Пример #27
0
def stop_bundle(server, bundlename, options):
    """ curl -u admin:admin http://localhost:4505/system/console/bundles/org.apache.sling.scripting.jsp
        -F action=stop."""
    form_data = {'action': 'stop'}
    url = server.url('/system/console/bundles/{bundle}'.format(bundle=bundlename))
    log("POSTing to service {}".format(url))
    resp = requests.post(url, auth=(server.username, server.password), data=form_data)
    if resp.status_code != 200:
        error("Failed to stop bundle {bundle}: {status}".format(bundle=bundlename, status=resp.status_code))
        return -1
    elif options.raw:
        sys.stdout.write("{}\n".format(resp.content))
Пример #28
0
def delete_package(server, options, package_name):
    url = get_package_url(package_name, server, options)
    form_data = dict(cmd='delete')

    log("Deleting package with POST to {}".format(url))
    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 200:
        error("Failed to delete package: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    return OK
Пример #29
0
    def execute(self, server, argv):
        self.api = AssetsApi(server)

        options, args = parser.parse_args(argv)

        action = get_action(args)
        actionarg = get_argument(args)

        if action == 'import':
            funnel = AssetsImportFunnel(server, dry_run=options.dry_run, destination_root=options.destination_root)
            return funnel.import_path(actionarg)
        elif action == 'touch':
            api = WorkflowsApi(server)
            if len(args) >= 3:
                self.touch_asset(api, actionarg, options.model)
            else:
                for line in sys.stdin:
                    self.touch_asset(api, line.strip(), options.model)
            return OK
        elif action == 'list' or action == 'ls':
            status, data = self.api._list_assets(actionarg)
            if status != OK:
                return status
            for item in data['entities']:
                sys.stdout.write("{}\n".format(item['properties']['name']))
            return OK
        elif action == 'find':
            status, data = self.api.find(actionarg)
            if status != OK:
                return status
            for item in data:
                props = item['properties']
                path = acmd.jcr.path.join(props['path'], props['name'])
                sys.stdout.write("{}\n".format(path))
            return OK
        elif action == 'tag':
            tag_str = get_argument(args)
            status, tags = parse_tags(tag_str)
            if status != OK:
                return status
            if len(args) <= 3:
                log("Reading files from input")
                for path in sys.stdin:
                    path = path.strip()
                    self.tag_asset(path, tags)
            else:
                path = get_argument(args, i=3)
                self.tag_asset(path, tags)
            return OK
        else:
            error("Unknown action {}".format(action))
            return USER_ERROR
Пример #30
0
def build_package(server, options, package_name):
    """ curl -u admin:admin -X POST
            http://localhost:4505:/crx/packmgr/service/.json/etc/packages/name_of_package.zip?cmd=build """
    url = get_package_url(package_name, server, options)
    form_data = dict(cmd='build')

    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 200:
        error("Failed to rebuild package: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    return OK
Пример #31
0
def build_package(server, options, package_name):
    """ curl -u admin:admin -X POST
            http://localhost:4505:/crx/packmgr/service/.json/etc/packages/name_of_package.zip?cmd=build """
    url = get_package_url(package_name, server, options)
    form_data = dict(cmd="build")

    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 200:
        error("Failed to rebuild package: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    return OK
Пример #32
0
    def get_instances(self, mode):
        if mode not in INSTANCE_MODES:
            return USER_ERROR, "Unknown instance mode {}".format(mode)

        path = "/etc/workflow/instances.{mode}.json".format(mode=mode)
        url = self.server.url(path)
        resp = requests.get(url, auth=self.server.auth)
        if resp.status_code != 200:
            error("Unexpected error code {code}: {content}".format(
                code=resp.status_code, content=resp.content))
            return SERVER_ERROR, []

        return OK, json.loads(resp.content)
Пример #33
0
def create_new_task(server, src_path, dst_path, options):
    if options.source_host is None:
        error("Missing argument source host (-s)")
        return USER_ERROR

    if not options.batch_size.isdigit():
        error("Batch size '{}' needs to be a number. (Default is 2048)".format(
            options.batch_size))
        return USER_ERROR

    if not options.throttle.isdigit():
        error("Throttling '{}' needs to be a number. (Default is 1)".format(
            options.throttle))
        return USER_ERROR

    task_id = create_task_id('rcp')

    status, data = _create_task(server, task_id, src_path, dst_path, options)
    if status != OK:
        error("Failed to fetch {} from {}".format(src_path,
                                                  options.source_host))
        return status

    if options.raw:
        sys.stdout.write("{}\n".format(json.dumps(data)))
    else:
        sys.stdout.write("{}\n".format(data['id']))
    return OK
Пример #34
0
def list_workflows(server, options):
    url = server.url(MODELS_PATH)
    resp = requests.get(url, auth=server.auth)
    if resp.status_code != 200:
        error("Unexpected error code {code}: {content}".format(
            code=resp.status_code, content=resp.content))
        return SERVER_ERROR
    data = resp.json()
    if options.raw:
        sys.stdout.write(json.dumps(data, indent=4))
    else:
        for model_item in data:
            model_name = _get_name(model_item['uri'])
            sys.stdout.write("{}\n".format(model_name))
    return OK
Пример #35
0
def _create_dir(server, path, dry_run):
    """ Create file in the DAM
        e.g. curl -s -u admin:admin -X POST -F "jcr:primaryType=sling:OrderedFolder" $HOST$dampath > /dev/null
    """
    if dry_run:
        return OK

    form_data = {'jcr:primaryType': 'sling:OrderedFolder'}
    url = server.url(path)
    log("POSTing to {}".format(url))
    resp = requests.post(url, auth=server.auth, data=form_data)
    if not _ok(resp.status_code):
        error("Failed to create directory {}\n{}".format(url, resp.content))
        return SERVER_ERROR
    return OK
Пример #36
0
def list_workflow_models(server, options):
    url = server.url(MODELS_PATH)
    resp = requests.get(url, auth=server.auth)
    if resp.status_code != 200:
        error("Unexpected error code {code}: {content}".format(
            code=resp.status_code, content=resp.content))
        return SERVER_ERROR
    data = json.loads(resp.content)
    if options.raw:
        sys.stdout.write(json.dumps(data, indent=4))
    else:
        for model_item in data:
            model_name = _get_name(model_item['uri'])
            sys.stdout.write("{}\n".format(model_name))
    return OK
Пример #37
0
def add_user(server, options, groupname, username):
    """ curl -u admin:admin -FaddMembers=testuser1
            http://localhost:4502/home/groups/t/testGroup.rw.html """
    group_path = get_group_path(groupname)
    path = "{}.rw.html".format(group_path)
    url = server.url(path)
    props = {'addMembers': username}
    resp = requests.post(url, auth=server.auth, data=props)
    if resp.status_code != 200:
        error("Failed to add user: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    else:
        path = html.parse_value(resp.text, 'div', 'Path')
        sys.stdout.write("{}\n".format(path))
    return OK
Пример #38
0
def install_package(server, options, package_name):
    """ curl -u admin:admin -X POST \
        http://localhost:4505/crx/packmgr/service/.json/etc/packages/export/name of package?cmd=install """
    url = get_package_url(package_name, server, options)
    form_data = dict(cmd="install")

    log("Installing package with POST to {}".format(url))
    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 200:
        error("Failed to install package: {}".format(resp.content))
        return SERVER_ERROR
    data = resp.json()
    assert data["success"] is True
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    else:
        sys.stdout.write("{}\n".format(data["msg"]))
    return OK
Пример #39
0
def add_user(server, options, groupname, username):
    """ curl -u admin:admin -FaddMembers=testuser1
            http://localhost:4502/home/groups/t/testGroup.rw.html """
    group_path = get_group_path(groupname)
    path = "{}.rw.html".format(group_path)
    url = server.url(path)
    props = {"addMembers": username}
    resp = requests.post(url, auth=server.auth, data=props)
    if resp.status_code != 200:
        error("Failed to add user: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    else:
        tree = html.fromstring(resp.text)
        path = tree.xpath('//div[@id="Path"]/text()')[0]
        sys.stdout.write("{}\n".format(path))
    return OK
Пример #40
0
def create_group(server, options, name):
    """ curl -u admin:admin -FcreateGroup=group1 -FauthorizableId=testGroup1
            http://localhost:4502/libs/granite/security/post/authorizables
    """
    assert len(name) > 0
    form_data = {"createGroup": "", "authorizableId": name}
    url = server.url("/libs/granite/security/post/authorizables")
    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 201:
        error("Failed to create group: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    else:
        tree = html.fromstring(resp.text)
        path = tree.xpath('//div[@id="Path"]/text()')[0]
        sys.stdout.write("{}\n".format(path))
    return OK
Пример #41
0
def list_groups(server, options):
    url = server.url("/home/groups.2.json")
    resp = requests.get(url, auth=server.auth)
    if resp.status_code != 200:
        error("Failed to get groups list:\n{}\n".format(resp.content))
        return SERVER_ERROR
    data = resp.json()
    if options.raw:
        sys.stdout.write("{}\n".format(json.dumps(data, indent=4)))
    elif options.compact:
        for initial, group in filter_system(data.items()):
            for groupname, userdata in filter_system(group.items()):
                sys.stdout.write("{}\n".format(groupname))
    else:
        sys.stdout.write("Available groups:\n")
        for initial, group in filter_system(data.items()):
            for username, userdata in filter_system(group.items()):
                sys.stdout.write("    {}\n".format(username))
    return OK
Пример #42
0
def create_user(server, options, username):
    """ curl -u admin:admin -FcreateUser= -FauthorizableId=testuser -Frep:password=abc123
            http://localhost:4502/libs/granite/security/post/authorizables """
    assert len(username) > 0
    form_data = {
        'createUser': '',
        'authorizableId': username,
        'rep:password': options.password
    }
    url = server.url('/libs/granite/security/post/authorizables')
    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 201:
        error("Failed to create user: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    else:
        path = html.parse_value(resp.text, 'div', 'Path')
        sys.stdout.write("{}\n".format(path))
    return OK
Пример #43
0
def create_group(server, options, name):
    """ curl -u admin:admin -FcreateGroup=group1 -FauthorizableId=testGroup1
            http://localhost:4502/libs/granite/security/post/authorizables
    """
    assert len(name) > 0
    form_data = {
        'createGroup': '',
        'authorizableId': name
    }
    url = server.url('/libs/granite/security/post/authorizables')
    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 201:
        error("Failed to create group: {}".format(resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    else:
        path = html.parse_value(resp.text, 'div', 'Path')
        sys.stdout.write("{}\n".format(path))
    return OK
Пример #44
0
    def execute(server, argv):
        options, args = parser.parse_args(argv)
        action = get_command(args)
        actionarg = get_argument(args)

        if action == 'list' or action == 'ls':
            return list_workflows(server, options)
        elif action == 'start':
            model = actionarg
            if len(args) >= 4:
                path = get_argument(args, i=3)
                return start_workflow(server, options, model, path)
            else:
                ret = OK
                for path in sys.stdin:
                    ret = ret | start_workflow(server, options, model, path.strip())

                return ret
        else:
            error('Unknown workflows action {a}\n'.format(a=action))
            return USER_ERROR
Пример #45
0
def start_workflow(server, options, model, path):
    task_id = create_task_id(model)

    form_data = dict(
        model='/etc/workflow/models/{}/jcr:content/model'.format(model),
        payload=_asset_path(path),
        payloadType='JCR_PATH',
        workflowTitle=task_id,
        startComment=''
    )
    log(_asset_path(path))
    
    url = server.url(INSTANCES_PATH)
    resp = requests.post(url, auth=server.auth, data=form_data)
    if resp.status_code != 201:
        error("Unexpected error code {code}: {content}".format(
            code=resp.status_code, content=resp.content))
        return SERVER_ERROR

    output = resp.content if options.raw else task_id
    sys.stdout.write("{}\n".format(output))
    return OK
Пример #46
0
def upload_package(server, options, filename):
    """ curl -u admin:admin -F file=@"name of zip file" -F name="name of package"
            -F force=true -F install=false http://localhost:4505/crx/packmgr/service.jsp """
    form_data = dict(
        file=(filename, open(filename, "rb"), "application/zip", dict()),
        name=filename.rstrip(".zip"),
        force=json_bool(options.install),
        install=json_bool(options.install),
    )
    log(form_data)
    url = server.url(SERVICE_PATH)
    resp = requests.post(url, auth=server.auth, files=form_data)

    if resp.status_code != 200:
        error("Failed to upload paackage: {}: {}".format(resp.status_code, resp.content))
        return SERVER_ERROR
    if options.raw:
        sys.stdout.write("{}\n".format(resp.content))
    else:
        tree = ElementTree.fromstring(resp.content)
        pkg_elem = tree.find("response").find("data").find("package")
        pkg = parse_package(pkg_elem)
        sys.stdout.write("{}\n".format(format_package(pkg)))
    return OK
Пример #47
0
def activate(server, options, path):
    """ curl -u admin:admin -X POST -F path="/content/path/to/page" -F cmd="activate" http://localhost:4502/bin/replicate.json
    """
    url = server.url(SERVICE_PATH)
    form_data = dict(cmd='activate',
                     path=path,
                     ignoredeactivated='false',
                     onlymodified='false')

    resp = requests.post(url, auth=server.auth, data=form_data)
    if not resp.status_code == 200:
        error("Failed to perform activation because {}: {}\n".format(resp.status_code, resp.content))
    else:
        if options.raw:
            sys.stdout.write("{}\n".format(resp.content))
        else:
            tree = html.fromstring(resp.text)
            paths = tree.xpath("//body/div/div[@class='path']/text()")
            paths = [path.split(' ')[0] for path in paths]
            paths = filter(lambda path: path.strip() != '', paths)
            msg = '\n'.join(paths)
            log("{}".format(msg))

            sys.stdout.write("{}\n".format(msg))
Пример #48
0
    def get_server(self, server_name):
        if server_name not in self.servers:
            error("Server {} not defined in {}; servers={}".format(server_name,get_rcfilename(),self.servers.keys()))
            sys.exit(acmd.USER_ERROR)
#            server_name = DEFAULT_SERVER_SETTING
        return self.servers.get(server_name)