Exemplo n.º 1
0
def main():
    console.hud_alert('processing..', 'success')
    if not appex.is_running_extension():
        print('This script is intended to be run from the sharing extension.')
        return

    basepath = os.path.expanduser('~/Documents/')
    fpath = appex.get_file_path()
    if fpath:
        fname = os.path.split(fpath)[1]
        try:
            import_from_file(fname, fpath, basepath)
        except:
            fpath = appex.get_text()
            if os.path.isfile(fpath):
                fname = os.path.split(fpath)[1]
                import_from_text(fname, fpath, basepath)
    elif appex.get_text():
        fpath = appex.get_text()
        ask = 'Choose File Extension', 'py', 'txt', 'pyui'
        resp = console.alert('Import file as..', *ask,
                             hide_cancel_button=False)
        fname = 'imported.' + ask[resp]
        import_from_text(fname, fpath, basepath)
    elif appex.get_url():
        fpath = appex.get_url()
        fname = os.path.split(fpath)[1]
        import_from_url(fname, fpath, basepath)
    else:
        console.hud_alert('Not a file!', icon='error')
def main():
    url = appex.get_text()
    if url:
        url_info_plist = (re.search('(.+url=)(.+)', url))[2]
        url_info_plist = unquote(url_info_plist)
        info_plist_str = requests.get(url_info_plist).text

        with open("info.plist", "w") as handle:
            handle.write(info_plist_str)

        with open("info.plist", 'rb') as fp:
            info_plist = plistlib.load(fp)

        ipa_url = info_plist['items'][0]['assets'][0]['url']
        ipa_version = info_plist['items'][0]['metadata']['bundle-version']
        ipa_revision = info_plist['items'][0]['metadata']['subtitle']
        ipa_title = info_plist['items'][0]['metadata']['title']
        ipa_full_name = ipa_title + ' ' + ipa_version + '-' + ipa_revision + '.ipa'

        response = requests.get(ipa_url, stream=True)

        with open(ipa_full_name, "wb") as handle:
            handle.write(response.content)

    else:
        print(appex)
        print('No input URL found.')
Exemplo n.º 3
0
def main():
    if appex.is_running_extension():
        url = appex.get_url() or appex.get_text()
    else:
        import console

        try:
            url = console.input_alert('Enter URL').strip()
            if not url:
                return
        except KeyboardInterrupt:
            return

    print(f'Searching for <code> elements at {url}')
    try:
        elements = get_code_elements(url)

        if not elements:
            print(f'No <code> elements found')
            return

        result = '\n\n'.join([
            f'# <code> element no {idx+1}\n\n' + code
            for idx, code in enumerate(elements)
        ])

        clipboard.set(result)
        print(result)
        print(f'{len(elements)} <code> element(s) copied to the clipboard')

    except Exception as e:
        print(f'Failed to get <code> element values: {e}')
Exemplo n.º 4
0
def get_safe_text():
    url_ext = appex.get_url()
    url_clp = clipboard.get()
    txt_ext = appex.get_text()

    if url_ext:
        if check_anews(url_ext):
            url = redirect_anews(url_ext)
            return get_text(url)
        else:
            return get_text(url_ext)
    elif txt_ext:
        return txt_ext
    elif url_clp:
        if url_clp.startswith('http'):
            if check_anews(url_clp):
                url = redirect_anews(url_clp)
                return get_text(url)
            else:
                return get_text(url_clp)
        else:
            return url_clp
    else:
        raise ValueError(
            'no text or url received from app extension or clipboard')
Exemplo n.º 5
0
def main():
    curl = appex.get_text()
    if curl:
        url, body, headers, method = parse_curl(curl)
    else:
        path = appex.get_file_path()
        url, body, headers, method = parse(path)
Exemplo n.º 6
0
def main():
    if appex.is_running_extension():
        if appex.get_url():
            text = appex.get_url()
        else:
            text = appex.get_text()
    else:
        text = clipboard.get()
    if not text:
        text = console.input_alert('Jira ID')

    if text:
        ids = JIRA_PAT.findall(text)
        if len(ids) == 0:
            text = console.input_alert('Jira ID')
        ids = JIRA_PAT.findall(text)
        if len(ids) > 0:
            id = ids[0]
            base_url, username = get_conf_info()
            url = '%s/browse/%s' % (base_url, id)
            console.hud_alert('Jira ID: %s' % id)
            app=UIApplication.sharedApplication()
            url=nsurl(url)
            app.openURL_(url)
        else:
            console.hud_alert('No Jira ID found.')
    else:
        console.hud_alert('No input text found.')
    if appex.is_running_extension():
        appex.finish()
Exemplo n.º 7
0
def main():
    text = None
    if len(sys.argv) > 1:
        text = sys.argv[1]
    else:
        try:
            import appex
            import clipboard
            if appex.is_running_extension():
                if appex.get_url():
                    text = appex.get_url()
                else:
                    text = appex.get_text()
            else:
                text = clipboard.get()
        except ImportError:
            pass

    if text:
        keys = JIRA_PAT.findall(text)
        if len(keys) > 0:
            key = keys[0]
            print('Found Jira ID: %s' % key)
        else:
            key = raw_input('Jira ID:')

        base_url, username, jsessionid = get_conf_info()

        if check_jsessionid(base_url, jsessionid):
            get_issue_info(base_url, jsessionid, key)
        else:
            jsessionid = get_new_cookie(base_url, username)
            get_issue_info(base_url, jsessionid, key)
    else:
        print('No input text found.')
Exemplo n.º 8
0
def main():
    if not appex.is_running_extension():
        print 'This script is intended to be run from the sharing extension.'
        return

    app = UIApplication.sharedApplication()
    text = appex.get_text()
    url = appex.get_url()

    if text:
        openurl = nsurl('textastic://x-callback-url/new?name=foo.txt&text=' +
                        text)

    if url:
        url = urlsplit(url)
        openurl = nsurl('textastic://' + url.netloc + url.path + url.query +
                        url.fragment)

    if not openurl:
        print 'No input URL or text found.'
        return

    print openurl
    app.openURL_(openurl)
    appex.finish()
Exemplo n.º 9
0
def main():
    if appex.is_running_extension():
        if appex.get_url():
            text = appex.get_url()
        else:
            text = appex.get_text()
    else:
        text = clipboard.get()
    if not text:
        text = console.input_alert('Jira ID')

    if text:
        ids = JIRA_PAT.findall(text)
        if len(ids) == 0:
            text = console.input_alert('Jira ID')
        ids = JIRA_PAT.findall(text)
        if len(ids) > 0:
            id = ids[0]
            base_url, username = get_conf_info()
            url = '%s/browse/%s' % (base_url, id)
            console.hud_alert('Jira ID: %s' % id)
            app = UIApplication.sharedApplication()
            url = nsurl(url)
            app.openURL_(url)
        else:
            console.hud_alert('No Jira ID found.')
    else:
        console.hud_alert('No input text found.')
    if appex.is_running_extension():
        appex.finish()
def main():
    if not appex.is_running_extension():
        print('This script is intended to be run from the sharing extension.')
        return
    text = appex.get_text()
    if not text:
        print('No text input found.')
        return

    selection = console.alert('Transform Text',
                              'Select Transformation',
                              'Title Case',
                              'lower case',
                              'Sentance case',
                              hide_cancel_button=True)
    if selection == 1:
        text = text.title()
    elif selection == 2:
        text = text.lower()
    elif selection == 3:
        sentences = [x.capitalize() for x in re.split(r'([\.?!] |\n)', text)]
        print(sentences)
        text = ''.join(sentences)
    elif selection == 4:
        # console.alert() only supports 3 buttons,
        # so this option is superfluous for now.
        text = text.upper()
    else:
        pass
        
    try:
        clipboard.set(text)
        console.hud_alert('Copied to Clipboard')
    except KeyboardInterrupt:
        return
Exemplo n.º 11
0
def main():
    text = None
    if len(sys.argv) > 1:
        text = sys.argv[1]
    else:
        try:
            import appex
            import clipboard
            if appex.is_running_extension():
                if appex.get_url():
                    text = appex.get_url()
                else:
                    text = appex.get_text()
            else:
                text = clipboard.get()
        except ImportError:
            pass

    if text:
        keys = JIRA_PAT.findall(text)
        if len(keys) > 0:
            key = keys[0]
            print('Found Jira ID: %s' % key)
        else:
            key = raw_input('Jira ID:')

        base_url, username, jsessionid = get_conf_info()

        if check_jsessionid(base_url, jsessionid):
            get_issue_info(base_url, jsessionid, key)
        else:
            jsessionid = get_new_cookie(base_url, username)
            get_issue_info(base_url, jsessionid, key)
    else:
        print('No input text found.')
Exemplo n.º 12
0
def csv_reader(filename):
	if appex.is_running_extension():
		file_path = appex.get_text()
	else:
		file_path = filename
		
	stream = open(file_path, 'rb').read().decode('utf-8').split('\n')
	return iter(csv.reader(stream, delimiter=';'))
Exemplo n.º 13
0
def getUrl():
    if not appex.is_running_extension():
        raise RuntimeError(
            'This script is intended to be run from the sharing extension.')
    url = appex.get_text()
    if not url:
        raise TypeError('No input URL found.')

    return url
Exemplo n.º 14
0
def format_text():
    text = appex.get_text()
    if len(text.split(" ")) <= 1:
        definition = youdao.query_words(text)
        if definition:
            print(definition)
            text = text + '\n' + definition
    text = text + '\n ===========\n'
    return text
def real_text():
    hud_alert('Running ...', 'success', 1)
    
    # Some apps share the file path of the text (Ulysses) 
    # while others will send the text content (iA Writer)
    file_path = appex.get_file_path()
    if file_path is not None:
        return _read_file(file_path)
    else:
        return appex.get_text()
def main():
    if not appex.is_running_extension():
        print('Running in Pythonista app, using test data...\n')
        html_file = 'tests/files/sample-export-simple.html'
    else:
        html_file = appex.get_text()

    text = converter.convert_kindle_html_to_md(html_file)

    postToBear(text)
Exemplo n.º 17
0
def main():
	text = appex.get_text()
	if not text:
		print('No input text found. Use this script from the share sheet in an app like Notes.')
		return
	converted = markdown(text)
	html = TEMPLATE.replace('{{CONTENT}}', converted)
	webview = ui.WebView(name='Markdown Preview')
	webview.load_html(html)
	webview.present()
Exemplo n.º 18
0
def main():
    text = appex.get_text()
    if not text:
        print 'No input text found. Use this script from the share sheet in an app like Notes.'
        return
    converted = markdown(text)
    html = TEMPLATE.replace('{{CONTENT}}', converted)
    webview = ui.WebView(name='Markdown Preview')
    webview.load_html(html)
    webview.present()
Exemplo n.º 19
0
def main():
    text = appex.get_text()
    if text:
        list1 = list(text.lower())
        for i in range(len(list1)):
            if random.randint(0, 1):
                list1[i] = list1[i].upper()
        clipboard.set("".join(list1))
        print("".join(list1))
    else:
        print('No input text found.')
Exemplo n.º 20
0
def trns():
    if not appex.is_running_extension():
        raise RuntimeError(
            'This script is intended to be run from the sharing extension.')

    url = appex.get_text()
    if not url:
        raise ValueError('No input text found.')
    elif re.search(r'youtube', url):
        return url
    raise ValueError('Not YouTube')
Exemplo n.º 21
0
def origin_text():
    if appex.is_running_extension():
        view.origin_text.text = appex.get_text() or requests.get(
            appex.get_url()).text
    elif clipboard.get().startswith('http'):
        if requests.head(
                clipboard.get()).headers.get('content-type') == 'text/html':
            view.origin_text.text = requests.get(clipboard.get()).text
        else:
            view.origin_text.text = clipboard.get()
    else:
        view.origin_text.text = clipboard.get()
def main():
    if not appex.is_running_extension():
        print('Running in Pythonista app, using test data...\n')
        text = '東京'
    else:
        text = appex.get_text()
    if text:
        url = u"japanese://search/"
        text = quote(text)
        UIApplication.sharedApplication().openURL_(nsurl(url + text))
    else:
        print('No input text found.')
Exemplo n.º 23
0
def main():
	if not appex.is_running_extension():
		print('This script is intended to be run from the sharing extension.')
		return
	text = appex.get_text()
	if not text:
		print('No text input found.')
		return
	text = html2text(text)
	text = text.strip('* \n')
	words = text.split()
	sentences = [x for x in re.split(r'[\.?!]', text) if len(x) > 0]
	console.alert('Statistics', '%i words\n%i sentences\n%i characters' % (len(words), len(sentences), len(text)), 'OK', hide_cancel_button=True)
Exemplo n.º 24
0
def main():
    if not appex.is_running_extension():
        if len(sys.argv) == 2:
            url = sys.argv[1]
        else:
            url = clipboard.get()
    else:
        url = appex.get_url() or appex.get_text()
    if url:
        download(url)
        console.hud_alert('Done.')
    else:
        console.hud_alert('No input URL found.')
Exemplo n.º 25
0
def main():
    if not appex.is_running_extension():
        print('Running in Pythonista app, using test data...\n')
        text = 'https://maps.google.co.uk/maps?oe=UTF-8&hl=en-gb&client=safari&um=1&ie=UTF-8&fb=1&gl=uk&entry=s&sa=X&ll=48.390394,-4.486076&z=12&ftid=0x4816bbe1d9925b93:0xc6488358179c30ab&q=Brest,+France&gmm=CgIgAQ%3D%3D&ved=0ahUKEwiSvZfG6JfTAhUCPBoKHWRJAc4Q8gEILjAB'
    else:
        text = appex.get_text()
    try:
        x = geocoordinates.Geocoordinates.from_google_map_url(text)
        x.open_in('maps.me')
    except geocoordinates.NotAGoogleMapUrl as err:
        msg = ('\n'.join(err.url.split('\n')[:5])
               if err.url.find('\n') >= 0 else err.url)
        console.alert(str(err), msg, 'OK', hide_cancel_button=True)
    finally:
        appex.finish()
Exemplo n.º 26
0
def main():
  if not appex.is_running_extension():
    print('Running in Pythonista app, using test data...\n')
    text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
  else:
    text = appex.get_text()
  if text:
    # TODO:Heat up །༄~ཙ Pyhton
    print(('Input text: %s' % text))
    out = text.upper()
    print(('\nConverted to all-caps: %s' % out))
    clipboard.set(out)
    print('(Copied to clipboard)')
  else:
    print('No input text found.')
Exemplo n.º 27
0
def main():
    paletteFile = None
    paletteString = None

    parser = argparse.ArgumentParser(description='Procreate palette utility')
    commands = parser.add_mutually_exclusive_group()
    commands.add_argument(
        'create',
        nargs='?',
        help='Create Procreate palette (.swatches) files from hex colours')
    commands.add_argument(
        'view',
        nargs='?',
        help='Extract and view json from Procreate palette (.swatches) file')
    parser.add_argument('input',
                        nargs='?',
                        help='.swatches File path or hex values string')
    parser.add_argument('output',
                        nargs='?',
                        help='.json File or .swatches folder output path')
    args = parser.parse_args()

    is_running_extension = False
    if not appex is None and appex.is_running_extension():
        is_running_extension = True
        paletteFile = appex.get_file_path()
        paletteString = appex.get_text()
    else:
        paletteFile = args.input
        paletteString = args.input

    if not args.create is None and not paletteString is None:
        palettes = Palette.from_string(paletteString)
        for palette in palettes:
            path = os.path.join(args.output or tempfile.gettempdir(),
                                palette.name + '.swatches')
            palette.save(path)
            if is_running_extension:
                console.open_in(path)
    elif not args.view is None and not paletteFile is None:
        palette = paletteFile and Palette.from_file(paletteFile) or Palette()
        if args.output is None:
            print(palette)
        else:
            with open(args.output, 'w') as jsonFile:
                jsonFile.write(palette)
    else:
        parser.print_help()
Exemplo n.º 28
0
def main():
    text = appex.get_text()
    if not text:
        import editor
        text = editor.get_text()
        if not text:
            print(
                'No input text found. Use this script from the share sheet in an app like Notes.'
            )
            return
    converted = markdown(text, extras=["fenced-code-blocks"])

    html = TEMPLATE.replace('{{CONTENT}}', converted)
    webview = ui.WebView(name='Markdown Preview')
    webview.load_html(html)
    webview.present()
Exemplo n.º 29
0
def translate():
    if not appex.is_running_extension():
        print('Pythonista 앱에서 실행됐습니다. 테스트 데이터를 이용합니다.\n')
        text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
    else:
        # 드래그해서 선택했거나 복사한 문장(단어)이 사용된다.
        text = appex.get_text() or clipboard.get()

        if text:
            print(f'<입력된 텍스트>\n{text}')

            translation = Translator().translate(text, dest='ko')
            print('\n')
            print(f'<번역한 결과>\n{translation.text}')

        else:
            print('입력된 텍스트가 없습니다.\n번역할 문장을 드래그 선택하거나 복사한 후 이용하세요')
Exemplo n.º 30
0
def main():
    text = None
    if appex.is_running_extension():
        text = appex.get_text()
    if not text:
        text = console.input_alert('Jira Query')
    if text:
        base_url, username = get_conf_info()
        url = '%s/issues/?jql=%s' % (base_url, urllib.quote_plus(text))
        console.hud_alert('Launching Jira')
        app=UIApplication.sharedApplication()
        url=nsurl(url)
        app.openURL_(url)
    else:
        console.hud_alert('No input text found.')
    if appex.is_running_extension():
        appex.finish()
Exemplo n.º 31
0
def main():
    if not appex.is_running_extension():
        print 'This script is intended to be run from the sharing extension.'
        return

    # Input from extension/share sheet
    txt = appex.get_text()

    if not txt:
        print 'No text input found.'
        return
    else:
        txt = createToC(txt)
        txt = ref(txt)

        # Output to clipboard
        clipboard.set(txt)
Exemplo n.º 32
0
def main():
    if appex.is_running_extension():
        url = appex.get_url()
        if url == None:
            text = appex.get_text()
            url = [
                mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text)
            ][0]
    else:
        text = clipboard.get().strip()
        url = [mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text)][0]
        if not "http" in url:
            url = "http://"
        try:
            url = console.input_alert("URL", "", url)
        except:
            return True

    console.hud_alert('URL: %s' % url)

    h = html2text.HTML2Text()
    try:
        r = requests.get(url=url,
                         headers={
                             "User-agent":
                             "Mozilla/5.0{0:06}".format(
                                 random.randrange(999999))
                         })
    except Exception as e:
        raise (e.message)
        return True

    html_content = r.text.decode('utf-8')
    rendered_content = html2text.html2text(html_content)
    clipboard.set(rendered_content)

    launch_e = console.alert('Markdown copied to clipboard. Launch Evernote?',
                             button1='Yes',
                             button2='No',
                             hide_cancel_button=True)
    if launch_e == 1:
        _eurl = "evernote://x-callback-url/new-note?type=clipboard&title=DRAFT&text="
        app = UIApplication.sharedApplication()
        eurl = nsurl(_eurl)
        app.openURL_(eurl)
    appex.finish()
Exemplo n.º 33
0
def get_document(platform):
    """
    Get the document content based on the platform and context.

    If the script is run on iOS from the Share sheet, it captures the
    documents content. If it's run as a standalone script, it opens a
    File picker. If it's running on the Mac, it opens the filepath
    passed in as an argument.

    Parameters
    ----------
    platform : str, {ios, darwin}
        Platform on which the script is running.

    Returns
    -------
    text : str

    """
    if platform == 'ios':
        # If it's on iOS, get the text from the extension and get dates
        # from pop ups.
        import appex
        import dialogs

        if appex.is_running_extension():
            template = appex.get_text()
        else:
            # Running either from the Today widget or from Pythonista
            infile = dialogs.pick_document()
            if infile is None:
                # User cancelled
                sys.exit()
            with open(infile, encoding='utf-8') as f:
                template = f.read()
    else:
        import argparse
        parser = argparse.ArgumentParser(
            description=__doc__,
            formatter_class=argparse.RawTextHelpFormatter,
        )
        parser.add_argument('infile', help='path to taskpaper template')
        args = parser.parse_args()
        with open(args.infile, encoding='utf-8') as f:
            template = f.read()
    return template
Exemplo n.º 34
0
def main():
    text = None
    if appex.is_running_extension():
        text = appex.get_text()
    if not text:
        text = console.input_alert('Jira Query')
    if text:
        base_url, username = get_conf_info()
        url = '%s/issues/?jql=%s' % (base_url, urllib.quote_plus(text))
        console.hud_alert('Launching Jira')
        app = UIApplication.sharedApplication()
        url = nsurl(url)
        app.openURL_(url)
    else:
        console.hud_alert('No input text found.')
    if appex.is_running_extension():
        appex.finish()
Exemplo n.º 35
0
def origin_text():
    if appex.is_running_extension():
        view.origin_text.text = appex.get_text() or requests.get(
            appex.get_url()).text
    elif clipboard.get().startswith(
            'http') and not clipboard.get().endswith('.js'):
        if requests.head(clipboard.get()).headers.get(
                'Content-Type', '/').split('/')[0] == 'text':
            view.origin_text.text = '正在载入...'
            view.origin_text.text = requests.get(clipboard.get(),
                                                 timeout=10).text
        else:
            view.origin_text.text = clipboard.get()
    elif clipboard.get().startswith('http') and clipboard.get().endswith(
            '.js'):
        view.origin_text.text = '正在载入...'
        view.origin_text.text = requests.get(clipboard.get(), timeout=10).text
    else:
        view.origin_text.text = clipboard.get()
Exemplo n.º 36
0
def main():
    if not appex.is_running_extension():
        text = clipboard.get()
    else:
        text = appex.get_text()
    if text:
        ids = JIRA_PAT.findall(text)
        if len(ids) > 0:
            id = ids[0]
            base_url = get_base_url()
            url = '%s%s' % (base_url, id)
            console.hud_alert('Jira ID: %s' % id)
            app=UIApplication.sharedApplication()
            url=nsurl('http://'+url)
            app.openURL_(url)
        else:
            console.hud_alert('No Jira ID found.')
    else:
        console.hud_alert('No input text found.')
    if appex.is_running_extension():
        appex.finish()
Exemplo n.º 37
0
def main():
    if appex.is_running_extension():
        url = appex.get_url()
        if url == None:
            text = appex.get_text()
            url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0]
    else:
        text = clipboard.get().strip()
        url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0]
        if not "http" in url:
            url = "http://"
        try:
            url = console.input_alert("URL", "", url)
        except:
            return True

    console.hud_alert('URL: %s' % url)

    h = html2text.HTML2Text()
    try:
        r = requests.get(
            url=url,
            headers={"User-agent": "Mozilla/5.0{0:06}".format(random.randrange(999999))}
        )
    except Exception as e:
        console.alert(e.message)
        return True

    html_content = r.text.decode('utf-8')
    rendered_content = html2text.html2text(html_content)
    clipboard.set(rendered_content)

    launch_e = console.alert('Markdown copied to clipboard. Launch Evernote?', button1='Yes', button2='No', hide_cancel_button=True)
    if launch_e ==1:
        _eurl = "evernote://x-callback-url/new-note?type=clipboard&title=DRAFT&text="
        app=UIApplication.sharedApplication()
        eurl=nsurl(_eurl)
        app.openURL_(eurl)
    appex.finish()
Exemplo n.º 38
0
def main():
    text = None
    label = 'Shared text'
    if appex.is_running_extension():
        text = appex.get_text()
    if not text:
        try:
            import editor
            editor_file = editor.get_path()
            if editor_file:
                sel = console.alert('Editor or clipboard?', button1='Editor', button2='Clipboard')
                if sel == 1:
                    editor_text = editor.get_text()
                    sel_st, sel_end = editor.get_selection()
                    label = os.path.basename(editor_file)
                    if sel_end != sel_st:
                        text = editor_text[sel_st:sel_end]
                    elif editor_text:
                        text = editor_text
        except ImportError:
            pass
    if not text:
        label = 'Clipboard'
        text = clipboard.get().strip()
    if text:
        converted = markdown(text)
        html = TEMPLATE.replace('{{CONTENT}}', converted)

        clip = console.alert('Replace clipboard?', button1='Yes', button2='No', hide_cancel_button=True)
        if clip ==1:
            clipboard.set(html)
            console.hud_alert('HTML copied to clipboard.')
        wv = MyWebView(name='Markdown - %s' % label)
        wv.load_html(html)
        wv.present('full_screen')
    else:
        console.hud_alert('No text found.')
        appex.finish()
Exemplo n.º 39
0
def main():
    speech.stop()
    if not appex.is_running_extension():
        console.hud_alert('Reading clipboard')
        text = clipboard.get()
        url = None
    else:
        text = appex.get_text()
        url = appex.get_url()

    if url == None:
        try:
            url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0]
        except:
            pass

    if url != None:
        console.hud_alert('Reading: ' + url)
        h = html2text.HTML2Text()
        try:
            r = requests.get(
            url=url,
            headers={"User-agent": "Mozilla/5.0{0:06}".format(random.randrange(999999))})
        except Exception as e:
            console.alert(e.message)
            return True
        html_content = r.text.decode('utf-8')
        text = html2text.html2text(html_content)
    else:
        console.hud_alert('Reading text: ' + str(text))

    if text:
        speech.say(text)
        stop = console.alert('Done?', hide_cancel_button=True, button1='OK')
        speech.stop()
    else:
        console.hud_alert('No text found.')
# coding: utf-8

# https://forum.omz-software.com/topic/1988/launching-pythonista-from-1-6b-app-extension

# I'm trying to write a script for the 1.6 app extension that will:

# Take some text passed in from the share sheet
# Format the text in a specific way
# Place the formatted text on the pasteboard
# Launch Pythonista and run another script that will take the text on the pasteboard and do something with it.

# Is it possible to launch a pythonista:// URL from the app extension? If not, is it possible to do something with objc_util?

# Worst case, I can make it a two-step process but it would be great to have it in one place.

import appex
import clipboard
import webbrowser 

initial_text = appex.get_text()

# text processing stuff

clipboard.set(processed_text)
webbrowser.open('pythonista://NewFromClipboard.py')

# @omz
# As far as I'm aware, this is unfortunately impossible. The API that is supposed to open URLs from app extensions is [explicitly documented](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSExtensionContext_Class/#//apple_ref/occ/instm/NSExtensionContext/openURL:completionHandler:) as only being available for Today widgets, the regular one (via UIApplication) doesn't do anything either in an extension.

# In earlier versions of iOS 8, there was a workaround for this (essentially abusing a web view), but this has apparently been patched in 8.4.
Exemplo n.º 41
0
import re
import sys
import appex
import clipboard
import console
import webbrowser


# Find text to analyse

phases     = ''
draft_uuid = ''

if appex.is_running_extension():
  # 1. running as extension?
  phases = str(appex.get_text())
else:
  # 2. started with arguments?
  if len(sys.argv) > 1:
    draft = re.match('draft:(.*)', sys.argv[1])
    if draft:
      draft_uuid = draft.group(1)
      phases = ' '.join(sys.argv[2:])
    else:
      phases = ' '.join(sys.argv[1:])
  
# 3. text on clipboard?
if phases == '':
  phases = clipboard.get()

# 4. default sample text
Exemplo n.º 42
0
from sys import argv
from reminders import Reminder
from datetime import datetime
from webbrowser import open


def add_reminder(title: str):
  r = Reminder()
  r.title = title
  r.due_date = datetime.now()
  r.save()


if __name__ == '__main__':
  remind = ''

  if not appex.is_running_extension():
    # With argument
    remind = argv[1]

  else:
    # No argument
    remind = appex.get_text()
    if not remind:
      print('No input.')
      sys.exit()

  add_reminder(remind)
  open("x-apple-reminder:")

Exemplo n.º 43
0
def main():
    if not appex.is_running_extension():
        print 'Running in Pythonista app, using test data...\n'
        text = '''
'''
    else:
        text = appex.get_text()
    if text:
        author          = 'Taha Dhiaeddine Amdouni'

        github_repo     = 'tdamdouni.github.io'
        github_user     = '******'
        github_password = keychain.get_password('github', github_user) or ''

        (title, text)   = extract_title(text)
        filename        = '%s-%s.md' % (date.today(), slug(title))

        github_fields = (
            'Github Settings',
            [
                dict(title='Github Username', key='github_user', type='text', value=github_user, autocorrection=False, autocapitalization=False),
                dict(title='Github Password', key='github_password', type='password', value=github_password),
                dict(title='Repository', key='github_repo', type='text', value=github_repo, autocorrection=False, autocapitalization=False)
            ]
        )

        posting_fields = (
            'Post Settings',
            [
                dict(title='Title', key='title', type='text', value=title),
                dict(title='Author', key='author', type='text', value=author),
                dict(title='Layout', key='layout', type='text', value='post', autocorrection=False, autocapitalization=False),
                dict(title='Tags', key='tags', type='text', value=''),
                dict(title='Filename', key='filename', type='text', value=filename, autocorrection=False, autocapitalization=False)
            ],
            'Please seperate tags by spaces.'
        )

        results = dialogs.form_dialog(title='Publish new post', sections=[
            posting_fields,
            github_fields
        ])

        if results is None:
            console.hud_alert('Posting was cancelled', 'error')
            return

        metas = {
            'tags': results['tags'],
            'branch': 'master',
            'author': results['author'],
            'layout': results['layout'],
            'filename': results['filename']
        }

        if github_password != results['github_password']:
            keychain.set_password('github', results['github_user'], results['github_password'])

        console.show_activity()
        mb = MobileBlogger(results['github_user'], results['github_password'], results['github_repo'])
        mb.create_new_post(results['title'], text, metas)
        console.hud_alert('New post created!')
    else:
        print 'No input text found.'
Exemplo n.º 44
0
import appex
from sys import argv
from webbrowser import open
from urllib.parse import quote

if __name__ == '__main__':
  if not appex.is_running_extension():
    # With argument
    word = argv[1]

  else:
    # No argument
    word = appex.get_text()
    if not word:
      print('No input.')
      sys.exit()

  url = 'eureca://paste?go=true&str='
  url = url + quote(word)
  open(url)