Example #1
0
def main():
    args = parse_args()

    confluence = Confluence(api_url=args.api_url,
                            username=args.username,
                            password=args.password,
                            headers=args.headers,
                            dry_run=args.dry_run)

    if args.posts:
        changed_posts = [os.path.abspath(post) for post in args.posts]
        for post_path in changed_posts:
            if not os.path.exists(post_path) or not os.path.isfile(post_path):
                log.error('File doesn\'t exist: {}'.format(post_path))
                sys.exit(1)
    else:
        repo = git.Repo(args.git)
        changed_posts = [
            os.path.join(args.git, post) for post in get_last_modified(repo)
        ]
    if not changed_posts:
        log.info('No post created/modified in the latest commit')
        return

    for post in changed_posts:
        log.info('Attempting to deploy {}'.format(post))
        deploy_file(post, args, confluence)
Example #2
0
def form(form_id, label, title):
    trel = Trello()
    conf = Confluence()
    """
    makes form
    options is a dict?
    possible dec num of params?
    """
    # headers: is label neccesary?
    form = '<form id="{}">'.format(form_id)
    label = '<label for="{}">{}</label>'.format(label, title)

    # generalize below using "for options in options_list"
    resp = trel.get_a_on_b(a='lists', b='boards', b_id=board_id)
    lists = { l['name'] : l['id'] for l in resp }
    html += select('trello', 'trelloList', lists)

    spaces = conf.get_spaces()
    html += select('confluence', 'confSpace', spaces)
    html += button('submit', 'mod-primary', 'Create Page!')

    # close form
    html += '</form>'

    html += '<script src="{}"></script>'.format('./js/modal.js')
    
    pprint(html)
    return html
    def testHeaders(self):
        headers = ['Cookie: NAME=VALUE', 'X-CUSTOM-HEADER: VALUE']
        want = {'Cookie': 'NAME=VALUE', 'X-CUSTOM-HEADER': 'VALUE'}

        api = Confluence(api_url='https://wiki.example.com/rest/api',
                         headers=headers)
        self.assert_headers(api._session.headers, want)
    def testHeadersNoValue(self):
        # If no value is set, an empty string should be used.
        headers = ['X-CUSTOM-HEADER-1:', 'X-CUSTOM-HEADER-2']
        want = {'X-CUSTOM-HEADER-1': '', 'X-CUSTOM-HEADER-2': ''}

        api = Confluence(api_url='https://wiki.example.com/rest/api',
                         headers=headers)
        self.assert_headers(api._session.headers, want)
Example #5
0
 def connect(self, params={}):
     """
     Connect to Confluence
     """
     self.logger.info("Connecting to Confluence: %s", params.get('url'))
     self.client = Confluence(
         url=params.get('url'),
         username=params.get('credentials').get('username'),
         password=params.get('credentials').get('password'))
Example #6
0
 def connect(self, params={}):
     """
     Connect to Confluence
     """
     self.logger.info("Connecting to Confluence: %s", params.get("url"))
     self.client = Confluence(
         url=params.get("url"),
         username=params.get("credentials").get("username"),
         password=params.get("credentials").get("password"),
     )
Example #7
0
def confluenceConnector(conflConnector):
    options = {
        'server': conflConnector['url'],
        'verify': conflConnector['verify']
    }
    keyValue = pwdCaller('officeLdap')['data']
    confl = Confluence(profile='confluence',
                       username=keyValue['user'],
                       password=keyValue['password'])
    return confl
    def testHeadersDuplicates(self):
        # HTTP headers are case insensitive. If multiple headers with the same
        # name are passed, the last one should win.
        headers = [
            'X-CUSTOM-HEADER: foo', 'X-Custom-Header: bar',
            'x-custom-header: baz'
        ]
        want = {'x-custom-header': 'baz'}

        api = Confluence(api_url='https://wiki.example.com/rest/api',
                         headers=headers)
        self.assert_headers(api._session.headers, want)
 def _connect(self):
     try:
         self.confluence = Confluence(
             url=self.config.confluence_server_url,
             username=self.config.confluence_server_user,
             password=self.config.confluence_server_pass)
     except ImportError:
         raise ImportError(
             "Must install confluence PyPi package to publish")
     except Exception as ex:
         raise Exception(
             "Could not connect, check remote API is configured. %s" % ex)
Example #10
0
def process(html, title_format, space, parent_page_name):
    client = Confluence(profile='confluence')
    title = datetime.datetime.now().strftime(title_format)
    print(f'title:       {title}')
    print(f'space:       {space}')
    print(f'parent_page: {parent_page_name}')
    page = client.storePageContent(page=title,
                                   space=space,
                                   content=html,
                                   convert_wiki=False,
                                   parent_page=parent_page_name)

    return page
Example #11
0
def ConfluenceWritePage(space, title, content, parent):
   confl = Confluence(profile='confluence')
   token = confl._token
   server = confl._server
   parent_id = parent
   try:
      existing_page = confl.storePageContent(title, space, content)
      #print "Updated the page"
   except:
      write_page(server, token, space, title, content)
      #print "Created a page"

   return
Example #12
0
def excel():
    """
    Post an excel file and fetch it's configuration
    """
    excel_file = request.files['file']
    sheet = request.values.get('sheet')
    conditional_formatting = False if request.values.get(
        'conditional_formatting') == 'false' else True
    excel = Excel(get_config(),
                  excel_file._file,
                  conditional_formatting=conditional_formatting)
    confluence = Confluence(get_config())
    content = excel.parse(sheet=sheet)
    content['header'] = request.values.get('header')
    content['source'] = confluence.source_from_data(
        content.get('data', {}), header=content.get('header'))
    return json.dumps(content, default=json_serial)
Example #13
0
def main():
    args = parse_args()

    client = NotionClient(token_v2=os.environ.get("NOTION_TOKEN"))

    parent_page = client.get_block(args.notion_page)

    confluence = Confluence(
        args.confluence_url,
        HTTPBasicAuth(
            os.environ.get("CONFLUENCE_API_USERNAME"),
            os.environ.get("CONFLUENCE_API_TOKEN"),
        ),
    )

    exporter = Confluence2Notion(confluence, parent_page)
    with concurrent.futures.ThreadPoolExecutor(
            max_workers=args.concurrency) as executor:
        executor.map(exporter.write_space, confluence.get_spaces())
Example #14
0
 def __init__(self, base_url, username, password, page_id, verify_ssl=True):
     self.page_id = page_id
     self.c = Confluence(base_url,
                         username,
                         password,
                         verify_ssl=verify_ssl)
Example #15
0
def main(list_id, space_id):
    trel = Trello()
    conf = Confluence()
    page = trel.format_page(list_id) # html pageData
    conf.create_page(page, space_key) # creates page
    print('\n\n\n page.py script is done!!! \n\n\n') # TEST 
Example #16
0
def main() -> None:
    usage = (
        '\n{0} --baseurl BASEURL [--user USER] ([--space SPACE] --title TITLE | --pageid PAGEID) [--new-title NEW_TITLE] ([--file FILE] | --text TEXT)'
        '\n{0} --baseurl BASEURL [--user USER] ([--space SPACE] --new-title NEW_TITLE ([--file FILE] | --text TEXT)'
        '\n{0} (-h | --help)')
    parser = argparse.ArgumentParser(
        usage=usage.format(os.path.basename(sys.argv[0])))
    parser.add_argument(
        "--baseurl",
        required=True,
        help='Conflunce base URL. Format: https://example.com/confluence')
    parser.add_argument(
        "--user",
        default=None,
        help=
        "User name to log into Confluence. Default: from the environment or password database."
    )
    parser.add_argument("--pageid",
                        type=int,
                        help="Conflunce page id to edit page.")
    parser.add_argument(
        "--space",
        default=None,
        help=
        "Conflunce space key to create/edit page. Default: the user's home.")
    parser.add_argument("--title",
                        default=None,
                        help="Conflunce page title to edit page.")
    parser.add_argument(
        "--new-title",
        default=None,
        help=
        "New title to create/edit page. By default title is not changed on edit page."
    )
    group = parser.add_mutually_exclusive_group()
    group.add_argument(
        "--file",
        type=argparse.FileType('r'),
        default=sys.stdin,
        help="Write the content of FILE to the confluence page. Default: STDIN."
    )
    group.add_argument(
        "--text",
        help=
        "Write the TEXT in Confluence Storage Format (XHTML-like) to the confluence page."
    )
    args = parser.parse_args()
    if (args.pageid, args.title, args.new_title).count(None) == 3:
        parser.print_usage()
        exit()
    if args.space is None:
        args.space = '~' + args.user

    if args.text is not None:
        content = args.text
    else:
        content = args.file.read()

    confluence = Confluence(args.baseurl, args.user)
    confluence.post_page(args.pageid, args.space, args.title, args.new_title,
                         content)
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("file", type=str, help="Pandoc's Markdown file path.")
    args = parser.parse_args()

    file = pathlib.Path(args.file)

    # Read Pandoc markwdown file.
    with file.open('r', encoding='utf_8_sig') as fd:
        lines = fd.readlines()

    # Extract YAML metadata block from Pandoc markdown.
    # http://pandoc.org/README.html#extension-yaml_metadata_block
    metadata_content = ''
    if len(lines) > 0 and lines[0] == '---\n':
        lines.pop(0)
        while True:
            if len(lines) == 0:
                raise Exception('No YAML metadata block end')
            line = lines.pop(0)
            if line in ('...\n', '---\n'):
                metadata_end_line = line
                break
            metadata_content += line
    else:
        raise Exception('No YAML metadata block')
    yaml_preserve_order()
    metadata = yaml.safe_load(metadata_content)

    confluenceMetadata = metadata.get(CONFLUENCE)  # type: Optional[dict]
    if confluenceMetadata is None:
        raise Exception(
            'No `{0}` section in YAML metadata block'.format(CONFLUENCE))

    # Parse username, baseUrl, pageId, spaceKey, title from the metadata.
    if CONFLUENCE_PAGE_URL in confluenceMetadata:
        urlstr = confluenceMetadata[CONFLUENCE_PAGE_URL]
        url = urllib.parse.urlsplit(urlstr)  # type: urllib.parse.SplitResult
        path = pathlib.PurePosixPath(url.path)
        query = urllib.parse.parse_qs(url.query)
        plen = len(path.parts)

        username = url.username
        if plen >= 4 and path.parts[
                plen -
                3] == 'display':  # e.g. ['/', 'confluence', 'display', '~jsmith', 'Test+page']
            basePath = str(path.parents[2]).rstrip('/')
            pageId = None
            spaceKey = urllib.parse.unquote_plus(path.parts[plen - 2])
            title = urllib.parse.unquote_plus(path.parts[plen - 1])
        elif plen >= 3 and path.parts[plen - 2] == 'pages' and path.parts[
                plen -
                1] == 'viewpage.action':  # e.g. ['/', 'confluence', 'pages', 'viewpage.action']
            basePath = str(path.parents[1]).rstrip('/')
            pageId = int(query['pageId'][0])
            spaceKey = None
            title = None
        else:
            raise Exception(
                'Unknown Confluence page URL format: {0}'.format(urlstr))

    elif CONFLUENCE_BASE_URL in confluenceMetadata:
        urlstr = confluenceMetadata[CONFLUENCE_BASE_URL]
        url = urllib.parse.urlsplit(urlstr)  # type: urllib.parse.SplitResult

        username = url.username
        basePath = url.path.rstrip('/')
        pageId = None
        spaceKey = None
        title = None

    else:
        raise Exception(
            'No `{0}` or `{1}` in `{2}` section of YAML metadata block'.format(
                CONFLUENCE_PAGE_URL, CONFLUENCE_BASE_URL, CONFLUENCE))

    baseUrlWithUsername = urllib.parse.urlunsplit(
        (url.scheme, url.netloc, basePath, None, None))
    baseUrl = urllib.parse.urlunsplit(
        (url.scheme, url.netloc.rpartition("@")[2], basePath, None, None))

    newTitle = metadata.get('title')  # type: Optional[str]
    authors = metadata.get('author', [])  # type: List[str]

    # Set default user name.
    if username is None:
        if len(authors) > 0:
            author = authors[0]
            firstname, lastname = author.split()  # type: str
            username = firstname[0].lower() + lastname.lower()
        else:
            username = getpass.getuser()

    # Set default space key.
    if spaceKey is None:
        spaceKey = '~' + username

    # Convert Pandoc's Markdown file to Confluence Storage Format (CSF) using `pandoc` utility.
    cmd = [
        "pandoc",
        "--from=markdown+hard_line_breaks+lists_without_preceding_blankline+compact_definition_lists+smart+autolink_bare_uris",
        "--to",
        os.path.join(os.path.dirname(sys.argv[0]), "csf.lua"),
        str(file)
    ]
    res = subprocess.run(cmd, stdout=subprocess.PIPE)
    content = res.stdout.decode('utf-8')

    if confluenceMetadata.get(CONFLUENCE_NOTE_AUTOGEN, False):  # type: bool
        note = textwrap.dedent("""\
			<ac:structured-macro ac:name="info" ac:schema-version="1">
			  <ac:rich-text-body><p>This page is generated automatically from <ac:link><ri:attachment ri:filename="{filename}"/></ac:link> using <a href="{project_url}">{project_name}</a>.</p></ac:rich-text-body>
			</ac:structured-macro>
		""").format(filename=html.escape(file.name),
              project_name=html.escape(PROJECT_NAME),
              project_url=html.escape(PROJECT_URL))
        content = note + content

    # Ask username and password.
    confluence = Confluence(baseUrl, username)

    # Request Confluence API to edit or create a page.
    try:
        info = confluence.post_page(pageId, spaceKey, title, newTitle, content)
    except requests.exceptions.HTTPError as ex:
        response = ex.response  # type: requests.models.Response
        if response.status_code == 401:
            print('Authentication failed.')
        else:
            print(ex)
            print(response.text)
        return
    else:
        if info is None:
            return

    # Update metadata.
    confluenceMetadata.pop(CONFLUENCE_BASE_URL, None)
    confluenceMetadata[
        CONFLUENCE_PAGE_URL] = baseUrlWithUsername + info['_links']['webui']
    confluenceMetadata[CONFLUENCE_PAGE_VERSION] = info['version']['number']

    # Rewrite Pandoc markdown file with updated YAML metadata block.
    fd = tempfile.NamedTemporaryFile('w',
                                     encoding='utf_8',
                                     delete=False,
                                     dir=str(file.parent),
                                     suffix='.tmp')  # type: io.TextIOWrapper
    with fd:
        fd.write('---\n')
        yaml.dump(metadata, fd, default_flow_style=False, allow_unicode=True)
        fd.write(metadata_end_line)
        fd.writelines(lines)
    os.replace(fd.name, str(file))  # src and dst are on the same filesystem

    # Attach source file.
    try:
        confluence.attach_file(info,
                               file,
                               content_type="text/markdown",
                               comment="Source code of this page.")
    except requests.exceptions.HTTPError as ex:
        response = ex.response  # type: requests.models.Response
        print(ex)
        print(response.text)
Example #18
0
    def setUp(self):
        from confluence import Confluence

        self.conf = Confluence(profile="confluence-test")
Example #19
0
# main script to make Conf page from Trello list

from trello import Trello
from confluence import Confluence

if __name__ == "__main__":
    t = Trello()
    conf = Confluence()
    conf.create_page(t.mmain())
    print('main sript done!')
 def setUp(self):
     self.space = 'SPACE'
     self.slug = "example-page"
     self.api = Confluence(api_url='https://wiki.example.com/rest/api',
                           username='******',
                           password='******')
Example #21
0
    def distributed_confluence(self, output_ij_list):

        # 获取产流数据
        grid_runoff = self._distributed_runoff()

        # 汇流计算实例化
        confluence = Confluence(self.dt, self.dx, self.a3, self.b3, self.a4,
                                self.b4, self.CS, self.CI, self.CG)

        # 河道栅格汇流计算

        def river_flow(i, j):
            k, grid_input = find_input(i, j, fdr)  # 找到所有指向该河道栅格的栅格
            not_river_list = [
                item for item in grid_input if item not in river_mark_list
            ]
            river_list = [
                item for item in grid_input if item in river_mark_list
            ]
            # 线性叠加所有非河道栅格的坡地汇流之后的过程
            R_not_river = np.zeros(day_evap.size)
            for ij in not_river_list:
                grid_id = ij_toid(ij, ncols)
                RS, RI, RG = grid_runoff[grid_id]
                # 坡面汇流之后的结果线性叠加(序列值)
                RS_slope = confluence.surface_confluence(RS)
                RI_slope = confluence.interflow_confluence(RI)
                RG_slope = confluence.underground_confluence_1(RG)
                R_not_river += (RS_slope + RI_slope + RG_slope)
            if not river_list:  # 到了河道栅格的源头了
                # 该栅格本身所产生的净雨作为旁侧入流处理
                grid_id = ij_toid([i, j])
                RS, RI, RG = grid_runoff[grid_id]
                qlat = (RS + RI + RG) * self.U  # 旁侧入流
                # 此时所有上游栅格线性叠加作为计算栅格的入流过程
                R = np.zeros(day_evap.size)
                for dt_id in range(1, day_evap.size):
                    R[dt_id] = confluence.musking_cunge(
                        R_not_river[dt_id - 1], R_not_river[dt_id],
                        R[dt_id - 1], qlat[dt_id], fac[i, j])
                return R  # 返回该河道栅格出流过程
            else:
                # 如果不是源头河道栅格,即该栅格上游仍有河道栅格汇入
                # 上游河道栅格的出流过程线性叠加作为计算栅格的入流过程
                R_in = np.zeros(day_evap.size)
                for ij in river_list:
                    R = river_flow(ij[0], ij[1])  # 递归运算,算法精髓!!
                    R_in += R
                # 坡面栅格的出流过程与栅格本身净雨(产流)作为旁侧入流
                grid_id = ij_toid([i, j])
                RS, RI, RG = grid_runoff[grid_id]  # 本身产流
                qlat = R_not_river + (RS + RI + RG) * self.U  # 旁侧入流
                R = np.zeros(day_evap.size)
                for dt_id in range(1, day_evap.size):
                    R[dt_id] = confluence.musking_cunge(
                        R_in[dt_id - 1], R_in[dt_id], R[dt_id - 1],
                        qlat[dt_id], fac[i, j])
                return R

        q = np.zeros(day_evap.size)
        for ij_tuple in output_ij_list:
            q += river_flow(ij_tuple[0], ij_tuple[1])

        return q
Example #22
0
def connect():
    connection = Confluence(url=confluence_server,
                            username=confluence_user,
                            password=confluence_password)

    return connection
Example #23
0
 def test_Confluence(self):
     assert Confluence.Confluence() == "This is Main module for Confluence Project that do nothing.\nRead more about DevOpsHQ Community here: https://github.com/devopshq/ExampleProject"
Example #24
0
	def __init__(self, url, username, password):
		self.confluence = Confluence(url, username, password)