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 appex.is_running_extension(): get_path = appex.get_file_path() file_name = path.basename(get_path) file_ext = path.splitext(file_name)[-1] if file_ext == '.ipa': dstpath = path.join(save_dir, 'app.ipa') try: shutil.copy(get_path, dstpath) except Exception as eer: print(eer) console.hud_alert('导入失败!','error',1) start(port_number) if httpd: webbrowser.open(plist_url) try: finish = console.alert(file_name, '\n正在安装…请返回桌面查看进度…\n\n安装完成后请返回点击已完成','已完成', hide_cancel_button=False) if finish == 1: os.remove(dstpath) stop() print("Server stopped") except: print("Cancelled") os.remove(dstpath) stop() appex.finish() else: console.hud_alert('非 ipa 文件无法导入安装', 'error', 2) appex.finish() else: console.hud_alert('请在分享扩展中打开本脚本','error',2)
def get_src_path(): src_path = appex.get_file_path() if src_path == None: console.alert('No input file provided', 'error') appex.finish() sys.exit(1) return src_path
def main(): if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return file_path = appex.get_file_path() if not file_path: print('No file found.') return console.hud_alert('Encrypting PDF...', duration=1) file_name = os.path.basename(file_path) with open(file_path, 'rb') as source_file: source_pdf = PdfFileReader(source_file) dest_pdf = get_pdf_file_writer(source_pdf) dest_pdf.encrypt(get_encryption_password()) with open(file_name, 'wb') as dest_file: dest_pdf.write(dest_file) console.open_in(dest_file.name) os.unlink(dest_file.name) appex.finish()
def import_from_working_copy(): src_path = get_src_path() dest_path = get_dest_path(src_path) shutil.copy2(src_path, dest_path) process_imported_file(dest_path) console.hud_alert('Imported', 'success', 1) appex.finish()
def main_app_extension() -> int: import appex import webbrowser import console result_cmd = None console.show_activity() last_url = None last_title = None try: url_list = appex.get_urls() result_list = [] for url in url_list: last_url = url markdown_template, last_title = safari_url(url) result_list.append(markdown_template) all_docs = "\n---\n".join(result_list) docs_url = quote(all_docs, safe='') last_url_encoded = quote(last_url, safe='') last_title_encoded = quote(last_title, safe='') # Open IA Writer to handle the new document # result_cmd = f'ia-writer://new?&text={docs_url}&edit=true' #result_cmd = f'x-devonthink://clip?text={docs_url}&location={last_url_encoded}&title={last_title_encoded}' result_cmd = f'x-devonthink://createMarkdown?text={docs_url}&title={last_title_encoded}&tags=Safari%20Gold' finally: console.hide_activity() appex.finish() if result_cmd is not None: webbrowser.open(result_cmd) return 0
def main(): if not is_running_extension(): print('This script is intended to be run from the sharing extension.') return files = get_file_paths() if not files: alert('No files were specified') return for file in files: filename = path.basename(file) if not filename.endswith('.pdf'): showAlert('Only PDF are allowed', filename) continue pdf = ObjCClass('PDFDocument').alloc().initWithURL(nsurl(file)) if pdf.isEncrypted(): pwd = input_alert('Password', filename) if pdf.unlockWithPassword_(pwd): pdf.writeToFile_(file) else: showAlert("Wrong Password", filename) else: showAlert("This PDF is not encrypted", filename) finish()
def file_picker_dialog(import_file_path=None, title=None, root_dir=None, multiple=False, select_dirs=False, file_pattern=None, show_icloud=False, show_info=True): if root_dir is None: root_dir = os.path.expanduser('~/Documents') if title is None: title = os.path.split(root_dir)[1] root_node = FileTreeNode(root_dir, show_info, select_dirs, file_pattern) root_node.title = title or '' icloud_node = None if show_icloud: icloud_dir = os.path.expanduser( '/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents' ) icloud_node = FileTreeNode(icloud_dir, show_info, select_dirs, file_pattern) icloud_node.title = 'iCloud' picker = TreeDialogController(root_node, icloud_node, import_file_path=import_file_path, allow_multi=multiple, async_mode=True) picker.view.present('sheet') picker.view.wait_modal() appex.finish() return
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()
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(): # Sharing: receive file fil = appex.get_file_path() if fil == None: print('no file passed') return server = 'Your ip' user = '******' pwd = 'your password' server_file = os.path.basename(fil) try: ftp = FTP(server) #connect ftp.encoding = 'utf-8' ftp.login(user,pwd) ipad_file = open(fil,'rb') ftp.storbinary('STOR '+server_file,ipad_file,blocksize=8192) ipad_file.close() ftp.close() except Exception as e: print(str(e)) appex.finish()
def will_close(self): global back, sheet if self == sheet: if appex.is_running_extension(): # back ui.view does not exist appex.finish() else: back.close() # close back ui.view
def main(): # get text from app share or clipboard if appex.is_running_extension(): text = appex.get_url() else: text = clipboard.get().strip() # get url url = '' try: url = [mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text)][0] except: url = console.input_alert("URL", "", url) if url: if not 'http' in url: url = 'http://' + url else: console.hud_alert('No URL found.') sys.exit() sel = console.alert('Save: %s ?' % url, button1='File', button2='Clipboard') # get url info url_items = url.split("?")[0].split("/") # if url ends with /, last item is an empty string file_name = url_items[-1] if url_items[-1] else url_items[-2] try: content = urllib2.urlopen(url).read() except Exception as e: console.alert(e.message) sys.exit() if sel == 1: # get file save info save_dir_name = get_save_dir() save_dir = os.path.join(BASE_DIR, save_dir_name) file_path = os.path.join(save_dir, file_name) try: # check dirs and save if not os.path.exists(save_dir): os.makedirs(save_dir) with open(file_path, 'w') as f: f.write(content) f.close() # wrapup console.alert('Saved to: %s' % file_path, hide_cancel_button=True, button1='OK') except Exception as e: console.alert(str(e), button1='OK', hide_cancel_button=True) elif sel == 2: clipboard.set(content) if appex.is_running_extension(): appex.finish()
def main(): # get text from app share or clipboard if appex.is_running_extension(): text = appex.get_url() else: text = clipboard.get().strip() # get url url = '' try: url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0] except: url = console.input_alert("URL", "", url) if url: if not 'http' in url: url = 'http://' + url else: console.hud_alert('No URL found.') sys.exit() sel = console.alert('Save: %s ?' % url, button1='File', button2='Clipboard') # get url info url_items = url.split("?")[0].split("/") # if url ends with /, last item is an empty string file_name = url_items[-1] if url_items[-1] else url_items[-2] try: content = urllib2.urlopen(url).read() except Exception as e: console.alert(e.message) sys.exit() if sel == 1: # get file save info save_dir_name = get_save_dir() save_dir = os.path.join(BASE_DIR, save_dir_name) file_path = os.path.join(save_dir, file_name) try: # check dirs and save if not os.path.exists(save_dir): os.makedirs(save_dir) with open(file_path, 'w') as f: f.write(content) f.close() # wrapup console.alert('Saved to: %s' % file_path, hide_cancel_button=True, button1='OK') except Exception as e: console.alert(str(e), button1='OK',hide_cancel_button=True) elif sel == 2: clipboard.set(content) if appex.is_running_extension(): appex.finish()
def main(): # Sharing: receive file input_file = appex.get_file_path() if input_file == None: print('no file passed') return # SFTP Configuration host = '192.168.1.x' port = 22 password = '******' username = '******' remoteFilePath = '/media/sda/' server_file = os.path.basename(input_file) filesize = os.path.getsize(input_file) # print("server_file:" + server_file) print("Starting to upload the file:" + input_file + "(Size: ", end='') print(filesize, end='') print(")... ") try: transport = paramiko.Transport((host, port)) transport.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(transport, max_packet_size=8 * 1024 * 1024) ''' sftp.open() while with open(input_file, 'rb') as ipad_file: read(ipad_file, ) ''' #sftp.putfo(ipad_file, remoteFilePath + server_file, callback=UploadCallBack(int, int )) ipad_file = open(input_file, 'rb') sftp.putfo(ipad_file, remoteFilePath + server_file) ipad_file.close() sftp.close() transport.close() print('Upload done!') except Exception as e: print(str(e)) appex.finish()
def main(): '''App extension logic, with unit tests if run within Pythonista''' if appex.is_running_extension(): if appex.get_url(): copy_url(appex.get_url()) appex.finish() else: console.hud_alert('No input URL found', 'error') else: console.hud_alert('This script must be run from the sharing extension', 'error') import doctest doctest.testmod()
def main(): try: url = appex.get_url() except NameError: url = sys.argv[1] html_file = get_html_from_url(url) send_html_page_to_kindle(url, html_file) try: appex.finish() except NameError: sys.exit(0)
def save(): """Save an attachment""" if appex.is_running_extension(): sFp = appex.get_file_path() if sFp: dialogs.hud_alert('Saving...') comps = __file__.split(os.sep) doc_path = os.sep.join(comps[:comps.index('Documents') + 1]) with open(sFp, 'rb') as f1: with open(doc_path + '/' + os.path.basename(sFp), 'wb') as f2: shutil.copyfileobj(f1, f2, length=512 * 1024) dialogs.hud_alert('Saved') appex.finish()
def main(): '''App extension logic, with unit tests if run within Pythonista''' if appex.is_running_extension(): if appex.get_url(): copy_url(appex.get_url()) appex.finish() else: console.hud_alert('No input URL found', 'error') else: console.hud_alert('This script must be run from the sharing extension', 'error') import doctest doctest.testmod()
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()
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()
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()
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()
def main(): """ Script for iOS Safari share extension to parse HTML and save to iCloud of shared page in Safari """ home = "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/" if not appex.is_running_extension(): print('Running in Pythonista app, using test data...\n') url = 'http://example.com/index.html' else: url = appex.get_url() if url: soup = BeautifulSoup(requests.get(url).text, "html.parser").prettify() urlpath = urlsplit(url).path basename = posixpath.basename(unquote(urlpath)) with open(f"{home}" + f"{basename}.txt", "w", encoding="utf-8") as f: f.write(soup) else: print('No input URL found.') appex.finish()
def main(rootpath="data/"): logger = Logger(rootpath + "log.txt", "ExtAddApp.py", True) configService = ConfigService(rootpath) if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return url = appex.get_url() if not url: console.alert("Error", "No input URL found.", 'OK', hide_cancel_button=True) if (configService.getLog().getData() == 1): logger.error("No input URL found.") return # 选择添加到愿望单还是收藏夹 star = True if (console.alert("添加应用", "请选择添加到愿望单还是收藏夹", "愿望单", "收藏夹", hide_cancel_button=True) == 2): star = False console.hud_alert("正在抓取数据,请等待...", "success") appSerVice = AppService(rootpath) res = appSerVice.addApp(url, star) if (res.equal(ResultEnum.APP_UPDATE)): console.hud_alert("应用更新成功!", 'success') elif (res.equal(ResultEnum.SUCCESS)): console.hud_alert("应用添加成功!", 'success') else: console.hud_alert(res.getInfo(), 'error') appex.finish()
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()
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()
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()
def main(): if appex.is_running_extension(): content = None attachments = appex.get_attachments() filepaths = appex.get_file_path() if attachments and attachments[0].rstrip() and appex.get_file_path(): with open(attachments[0], 'r') as f: content = f.read() attachment_name = filepaths.split(os.sep)[-1] else: print('No attachment found.') sys.exit(1) sel = console.alert('Save: %s' % attachment_name, button1='File', button2='Clipboard') if sel == 1: file_name = '{:%Y%m%d-%H%M%S}_{}'.format(datetime.datetime.now(), attachment_name) save_dir_name = get_save_dir() save_dir_path = os.path.join(BASE_DIR, save_dir_name) save_file_rel_path = os.path.join(save_dir_name, file_name) save_file_path = os.path.join(BASE_DIR, save_file_rel_path) try: # check dirs and save if not os.path.exists(save_dir_path): os.makedirs(save_dir_path) with open(save_file_path, 'w') as f: f.write(content) # wrapup msg = 'Saved: %s' % save_file_rel_path except Exception as e: msg = str(e) console.alert(msg, button1='OK', hide_cancel_button=True) elif sel == 2: clipboard.set(content) if appex.is_running_extension(): appex.finish()
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()
def main(): if not appex.is_running_extension(): print('Running in Pythonista app, using test data...\n') text = u""" - «project_name» @parallel(false) @due(«due») - This task needs to be done at least 1 week before «project_name» is due @due(«due» -1w) - This task needs to be done at least 2 days before «project_name» is due @due(«due» -2d) """ else: text = '\n'.join(appex.get_text().split('\n')[1:]) if text: # print 'Input text: %s' % text out = fill_placeholders(text) if out == None: return # print('\nPlaceholders filled:\n{}'.format(out)) encoded_text = urllib.parse.quote(out) omnifocus_url = "omnifocus:///paste?target=projects&content=%s" % encoded_text # print '\nOmniFocus URL = %s\n' % omnifocus_url appex.finish() open_url(omnifocus_url) else: print('No input text found.')
def main(): # get text from app share or clipboard if appex.is_running_extension(): text = appex.get_text() else: text = clipboard.get() # get file save info save_dir_name = get_save_dir() file_name = 'txt-{:%Y%m%d-%H%M%S}.txt'.format(datetime.datetime.now()) save_dir = os.path.join(BASE_DIR, save_dir_name) file_path = os.path.join(save_dir, file_name) # check dirs and save if not os.path.exists(save_dir): os.makedirs(save_dir) with open(file_path, 'w') as f: f.write(text) f.close() # wrapup console.hud_alert('Saved to: ' + os.path.join(save_dir_name, file_name)) if appex.is_running_extension(): appex.finish()
p=urlparse(url) urlfilename=unquote(unquote(urlparse(appex.get_url()).path.split('/')[-1])) console.hud_alert('Downloading the Gist, please wait.') console.show_activity() if p.netloc.startswith('gist.github.com'): gist_id=urlfilename data=requests.get('https://api.github.com/gists/{}'.format(gist_id)).json() if data: gistpath=os.path.expanduser('~/Documents/Downloaded Gists/') destpath=os.path.join(gistpath,gist_id) for pth in [gistpath, destpath]: if not os.path.exists(pth): os.mkdir(pth) for f in data['files'].values(): filename=f['filename'] console.hud_alert('writing '+filename) content=f['content'] with open(os.path.join(destpath,filename),'w') as file: file.write(content) else: console.hud_alert('could not download') else: destpath=urlfilename with open(destpath,'wb') as file: file.write(requests.get(url).content) console.hud_alert('Download complete') console.hide_activity() appex.finish()
def main(): global splash if appex.is_running_extension(): # copy input file to sandbox folder dest_path_short = '~/Documents/inbox' dest_path = os.path.expanduser(dest_path_short) if not os.path.isdir(dest_path): print('Create ' + dest_path_short) os.mkdir(dest_path) file = appex.get_file_path() print('Input path: %s' % file) if (file == None): console.alert("Error", "Unable to process the input data. Import failed.", "Ok", hide_cancel_button=True) appex.finish() return filename = os.path.join(dest_path, os.path.basename(file)) filename = getuniquename(filename, '') shutil.copy(file, filename) print('Saved in %s' % dest_path_short) if not os.path.exists(filename): print(' > Error file %s not found !' % os.path.basename(filename)) # prompt for a new adventure name s = os.path.basename(file).replace(".thz", "") name = console.input_alert("Import Adventure", "Please enter the imported adventure name", s, "OK") name = name.replace("/", "") name = name.replace(".", "") name = name.replace(" ", "") res = False if name != "": if not os.path.exists(name): try: os.mkdir(name) res = True except: console.alert("Please enter a valid or non-existing name") if not res: appex.finish() return # unzip the file decompress_zipfile(filename, "./" + name) os.remove(filename) # check decompressed file integrity : does it include game files ? res = True if not os.path.exists("./" + name + "/Definition.txt"): res = False if res: console.alert("Adventure successfully imported!", "", "Ok", hide_cancel_button=True) else: recurseDeleteFolder(name) console.alert( "File corrupted!", "The adventure you tried to import is corrupted, import failed.", "Ok", hide_cancel_button=True) appex.finish() # launch game console.set_idle_timer_disabled(True) # Get the GPS info. location.start_updates() # Compass motion.start_updates() launchTitleScreen()
#Read page contents import requests r = requests.get(url) source = r.text ct = r.headers['Content-Type'] # A fancier version could use the mimetypes module to guess the proper file extension... extension = '.html' if ct.startswith('text/html') else '.txt' # ... #Read page contents #f=urllib2.urlopen(url) #source=f.read() #f.close() #Detect the type of page we're viewing #test=source.lower().strip() #if '<html>' in test or test.startswith('<!doctype html>'): #Page is HTML #extension='.html' #else: #fallback to .txt #extension='.txt' #Where to save the source filename='source'+extension filepath=getDocPath()+filename #Save the source with open(filepath,'w') as f: f.write(source) #Close appex window appex.finish() #Open in pythonista openUrl('pythonista://'+filename)
def main(): if not appex.is_running_extension(): raise RuntimeError('is not in running extention') text = appex.get_text() if text == '': return # split lines lines = text.split('\n') if len(lines) < 1: raise RuntimeError('insufficient lines') # retrieve poi and address poi = '' addr = '' if lines[0].startswith('[네이버 지도]'): if len(lines) < 3: raise RuntimeError('insufficient lines for NaverMap') if len(lines) > 3: poi = lines[1].strip() addr = lines[2].strip() else: addr = lines[1].strip() elif lines[0].startswith('[카카오맵]'): if len(lines) < 2: raise RuntimeError('insufficient lines for KakaoMap') ss = lines[0].split(' ', 1) if len(ss) > 1: poi = ss[1].strip() addr = lines[1].strip() # check poi and address if poi == '': poi = addr if poi == '' or addr == '': raise RuntimeError('failed to retrieve addr from clipboard') # do job with shelve.open(DB_NAME) as db: bmw_api = bmw.BMW(db) kakao_api = kakao.KakaoLocal(db) # get lat,lon from address lat, lon = kakao_api.address_to_coord(addr) # send to message vehicle bmw_api.send_message(poi, addr, lat, lon) # alert to user console.alert('BMW SendCar', 'succeed to send to vehicle\nDestination: %s' % poi, 'OK', hide_cancel_button=True) appex.finish()
def will_close(self): appex.finish()
def main(): get_path = None if appex.is_running_extension() and appex.get_file_path(): get_path = appex.get_file_path() if not re.match(r'.+\.(ipa|zip)$', get_path): console.hud_alert('Not supported file types', 'error', 1) appex.finish() exit() else: console.hud_alert('No file input', 'error', 1) appex.finish() exit() plist = extract_plist_data(get_path) if plist is None: console.hud_alert('No Info.plist file', 'error', 1) appex.finish() exit() else: url_schemes = extract_scheme(plist) if url_schemes: result = dialogs.list_dialog('Select to Clips', url_schemes) if result: clipboard.set(result + '://') console.hud_alert('Copied Success!', '', 1) appex.finish() exit() else: appex.finish() exit() else: console.hud_alert('No Url Schemes', 'error', 1) appex.finish() exit()
def will_close(self): if appex.is_running_extension(): appex.finish()