Ejemplo n.º 1
0
def run(event, context):
    load_dependency('pydot')
    channel = event.get('channel')
    data = event.get('dot')

    #slack_message("in dot to svg: {0}".format(event), [], channel)
    log_to_elk("in dot to svg: {0}".format(event))

    import dot_parser

    try:
        (fd, tmp_file) = tempfile.mkstemp('dot)')
        dot_static = '/tmp/lambdas-dependencies/pydot/dot_static'
        Process.run("chmod", ['+x', dot_static])
        data = data.replace('&lt;', '<').replace(
            '&gt;', '>'
        )  # this solved a really nasty bug caused by the fact that Slack will html encode the < and >

        # graph          = pydot.graph_from_dot_data(data).pop()
        # <from pydot>  use code below (instead of above) to get a better error message from dot parser
        graphparser = dot_parser.graph_definition()
        graphparser.parseWithTabs()
        tokens = graphparser.parseString(data)
        graph = list(tokens).pop()
        # </from pydot>
        graph.write_svg(tmp_file, prog=dot_static)
        svg_raw = Files.contents(tmp_file)
        return base64.b64encode(svg_raw.encode()).decode()
    except Exception as error:
        slack_message("[dot_to_svg] Error: {0} ".format(error), [], channel)
        return None
Ejemplo n.º 2
0
    def elk(team_id=None, channel=None, params=None):
        load_dependency('syncer')
        from osbot_browser.browser.sites.Site_ELK import ELK_Commands
        from osbot_browser.browser.sites.Site_ELK import Site_ELK

        if len(params) == 0:
            Slack_Commands_Helper(ELK_Commands).invoke(team_id, channel,
                                                       params)
            return None

        browser_helper = Browser_Lamdba_Helper().setup()
        elk = Site_ELK(browser_helper.api_browser, team_id, channel)

        elk.sync__connect_and_login()

        params.append(browser_helper)
        params.append(elk)

        result = Slack_Commands_Helper(ELK_Commands).invoke(
            team_id, channel, params)

        if team_id:
            return None
        else:
            return result
Ejemplo n.º 3
0
def run(event, context):
    load_dependency('plantuml')
    dot_static = '/tmp/lambdas-dependencies/plantuml/dot_static'
    plantuml_jar = '/tmp/lambdas-dependencies/plantuml/plantuml.jar'

    Process.run("chmod", ['+x', dot_static])
    Process.run("chmod", ['+x', plantuml_jar])

    os.environ['PLANTUML_LIMIT_SIZE'] = str(
        4096 * 4)  # set max with to 4 times the default (16,384)
    os.environ['GRAPHVIZ_DOT'] = dot_static
    (fd, puml_file) = tempfile.mkstemp('.puml')
    png_file = puml_file.replace(".puml", ".png")
    code = event.get('puml')
    Files.write(puml_file, code)

    subprocess.run([
        'java', '-jar', plantuml_jar, '-Xmx2512m', '-tpng', '-o', '/tmp',
        puml_file
    ],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)

    if os.path.exists(png_file):
        with open(png_file, "rb") as image_file:
            png = base64.b64encode(image_file.read()).decode()
    else:
        png = None

    return {"png_base64": png}
Ejemplo n.º 4
0
def run(event, context):
    load_dependency('jira')
    data = event.get('data')
    channel = event.get('channel')
    team_id = event.get('team_id')
    from osbot_jira.api.slack.Slack_Dialog_Submissions import Slack_Dialog_Submissions
    return Slack_Dialog_Submissions(data, channel, team_id).handle()
Ejemplo n.º 5
0
def run(event, context):
    load_dependency("slack")                                                # this will download the dependencies the first time the lambda function is executed

    from pbx_gs_python_utils.utils.slack.API_Slack import API_Slack
    API_Slack(channel='...').send_message("this was sent from an lambda function")

    #load_dependency("requests")                                             # the Slack dependency already includes this dependency
    import requests
    return len(requests.get("https://www.google.com").text)
Ejemplo n.º 6
0
def run(event, context):
    load_dependency('requests')

    issue_id = event.get('issue_id')

    from osbot_jira.api.jira_server.API_Jira_Rest import API_Jira_Rest
    api_jira_rest = API_Jira_Rest()

    return api_jira_rest.issue(issue_id)
Ejemplo n.º 7
0
def run(event, context):
    load_dependency('jupyter')
    #result = Process.run('jupyter')

    from runipy.notebook_runner import NotebookRunner
    from IPython.nbformat.current import read

    notebook = read(open("MyNotebook.ipynb"), 'json')
    return notebook
Ejemplo n.º 8
0
def run(event, context):

    load_dependency(
        "pyppeteer"
    )  # (on first run downloads a zip file from S3 to /tmp/lambdas-dependencies/pyppeteer/ which contains
    #   the contents of `pip3 install pyppeteer - t pyppeteer` and the headless_shell file created by
    #   https://github.com/sambaiz/puppeteer-lambda-starter-kit
    #   This command also sets the add the /tmp/lambdas-dependencies/pyppeteer/ to sys.path

    path_headless_shell = '/tmp/lambdas-dependencies/pyppeteer/headless_shell'  # path to headless_shell AWS Linux executable
    path_page_screenshot = '/tmp/screenshot.png'  # path to store screenshot of url loaded
    os.environ[
        'PYPPETEER_HOME'] = '/tmp'  # tell pyppeteer to use this read-write path in Lambda aws
    target_url = event.get('url')  # get url to load from lambda params
    doc_type = event.get('doc_type')

    async def get_screenshot():  # async method to run request

        from pyppeteer import launch  # import pyppeteer dependency
        Process.run("chmod",
                    ['+x', path_headless_shell
                     ])  # set the privs of path_headless_shell to execute
        browser = await launch(
            executablePath=
            path_headless_shell,  # lauch chrome (i.e. headless_shell)
            args=['--no-sandbox', '--single-process'
                  ])  # two key settings or the requests will not work

        page = await browser.newPage(
        )  # typical pyppeteer code, where we create a new Page object
        await page.goto(target_url)  #   - open an url

        await page.waitFor(2 * 1000)
        # To Remove
        #await page.waitForNavigation(); not working

        if doc_type and doc_type == 'pdf':
            await page.pdf({'path': path_page_screenshot})
        else:
            await page.screenshot({
                'path': path_page_screenshot
            })  #   - take a screenshot of the page loaded and save it

        await browser.close()  #   - close the browser

    asyncio.get_event_loop().run_until_complete(get_screenshot(
    ))  # event loop to start the run async method which will open the
    #   url provided in the lambda params and save it as an png
    with open(path_page_screenshot,
              "rb") as image_file:  # open path_page_screenshot file
        encoded_png = base64.b64encode(image_file.read()).decode(
        )  # save it as a png string (base64 encoded to make it easier to return)

    return {"base64_data": encoded_png}  # return value to Lambda caller
Ejemplo n.º 9
0
def run(event, context):
    load_dependency('requests')
    from osbot_jupyter.api.Live_Notebook import Live_Notebook

    short_id = event.get('short_id')
    code = event.get('code')
    target = event.get('target')
    keep_contents = event.get('keep_contents')
    notebook = Live_Notebook(short_id)
    notebook.login()
    return notebook.execute_python(python_code=code,
                                   target=target,
                                   keep_contents=keep_contents)
    return notebook.jupyter_web().screenshot_base64()
Ejemplo n.º 10
0
    def cmd_create(self, params, team_id=None, channel=None):
        try:
            if len(params) < 3:
                text = ":exclamation: To create an issue you need to provide the `issue type` and `summary`. For example `jira create task abc"
                return {"text": text, "attachments": []}
            else:
                params.pop(0)  # the create command
                issue_type = params.pop(
                    0)  #.title() # todo: find a better solution for this
                project = issue_type.upper(
                )  # todo: and to address the mapping of issue types to projects
                summary = ' '.join(params)
                slack_message(
                    ':point_right: Going to create an `{0}` issue, in project `{1}` with summary `{2}`'
                    .format(issue_type, project,
                            summary), [], channel, team_id)

                #to do, move this feature to a separate lambda (which can be called to create issues
                from osbot_aws.Dependencies import load_dependency
                load_dependency('jira')
                from osbot_jira.api.jira_server.API_Jira import API_Jira

                # create issue
                result = API_Jira().issue_create(project, summary, '',
                                                 issue_type)
                issue_id = "{0}".format(result)

                # show issue screenshot
                # payload = {'issue_id': issue_id,'channel': channel,'team_id': team_id, }
                # Lambda('osbot_browser.lambdas.jira_web').invoke_async(payload)

                # show issue UI
                payload = {'params': ['issue', issue_id], "channel": channel}
                Lambda('osbot_jira.lambdas.jira').invoke_async(payload)

                # show link of new issue to user
                jira_link = "https://glasswall.atlassian.net/browse/{0}".format(
                    issue_id)
                text = ':point_right: New issue created with id <{0}|{1}>'.format(
                    jira_link, issue_id)
            return {"text": text, "attachments": []}
        except Exception as error:
            log_to_elk('jira create error', f'{error}')
            return {
                'text':
                f':red_circle: Issue could not be created, please make sure that: \n - issue type exists\n - issue type = project type\n - Issue type CamelCase is correctly entered (you want `Task` and not `task`)',
                "attachments": []
            }
Ejemplo n.º 11
0
 def maps(team_id=None, channel=None, params=None):
     load_dependency('syncer')
     load_dependency('requests')
     load_dependency('pyppeteer')
     load_dependency('websocket-client')
     from osbot_browser.view_helpers.Maps_Views import Maps_Views
     (text, attachments) = Slack_Commands_Helper(Maps_Views).invoke(
         'not-used', channel, params)
     if team_id is None:
         return text
Ejemplo n.º 12
0
 def sow(team_id=None, channel=None, params=None):
     load_dependency('syncer')
     load_dependency('requests')
     load_dependency('pyppeteer')
     load_dependency('websocket-client')
     try:
         from osbot_browser.view_helpers.Sow_Views import Sow_Views
         (text, attachments) = Slack_Commands_Helper(Sow_Views).invoke(
             'not-used', channel, params)
         if channel is None:
             return text
     except Exception as error:
         return f'[sow error] {error}'
Ejemplo n.º 13
0
    def handle_request(self, event, response_handler=None):
        load_dependency('requests')
        import requests
        path = event.get('path', '')
        method = event.get('httpMethod', '')
        headers = event.get('headers', {})
        domain_prefix = event.get('requestContext', {}).get('domainPrefix')
        try:
            self.log_request(path, method, headers, domain_prefix, self.url)

            request_headers = {
                'accept': headers.get('headers'),
                'User-Agent': headers.get('User-Agent'),
                'accept-encoding': headers.get('accept-encoding'),
            }
            response = requests.get(self.url, headers=request_headers)

            # The original value of result.headers is not serializable:
            response_headers = {}
            for key, value in response.headers.items():
                if key != 'Content-Encoding':
                    response_headers[key] = str(value)

            response_body = self.get_response_body(response)
            if response_handler:
                response_body = response_handler.process(response_body)
            return self.response(
                self.is_binary_content_type(response), HTTPStatus.OK.value,
                response_headers, response_body
            )
        except Exception as error:
            message = f'Proxy error: {error}'
            log_to_elk('proxy message', message, level='error')
            return self.response(
                False, HTTPStatus.INTERNAL_SERVER_ERROR.value, headers, message
            )
Ejemplo n.º 14
0
def run(event, context):
    load_dependency('gmail')
    from _from_pydot.gmail.API_GMail import API_GMail
    gmail = API_GMail().setup()
    return gmail.labels()
Ejemplo n.º 15
0
 def test_nbconvert(self):
     payload     = { }
     from osbot_aws.Dependencies import load_dependency
     load_dependency('jupyter')
     #self.png_data = self.aws_lambda.invoke(payload)
     self.result =  self.aws_lambda.invoke(payload)