Esempio n. 1
0
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()
Esempio n. 2
0
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
Esempio n. 3
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)
Esempio n. 4
0
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()
Esempio n. 5
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')
Esempio n. 6
0
def main():
    if appex.is_running_extension():
        get_path = appex.get_file_path()
        file_name = os.path.basename(get_path)
        file_ext = os.path.splitext(file_name)[-1]
        if os.path.exists(TEMP_PATH):
            shutil.rmtree(TEMP_PATH)
        os.mkdir(TEMP_PATH)
        if os.path.exists(TARGE_PATH):
            shutil.rmtree(TARGE_PATH)
        os.mkdir(TARGE_PATH)

        if file_ext == '.p4thor':
            dstpath = os.path.join(TEMP_PATH, '666.p4thor')
            try:
                shutil.copy(get_path, dstpath)
                p4thor_parse(dstpath,
                             os.path.join(TARGE_PATH, str(download_dir)))

            except Exception as eer:
                print(eer)
                console.hud_alert('解析失败!', 'error', 1)
            finally:
                # 清理临时文件
                shutil.rmtree(TARGE_PATH)
                shutil.rmtree(TEMP_PATH)
        else:
            console.hud_alert('非 p4thor 文件无法解析', 'error', 2)
        #appex.finish()
    else:
        console.hud_alert('请在分享扩展中打开本脚本', 'error', 2)
Esempio n. 7
0
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)
Esempio n. 8
0
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()
Esempio n. 9
0
def main():
	console.clear()
	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)
	if not appex.is_running_extension():
		print('Using clipboard content...')
		text = clipboard.get()
		assert text, 'No text on the clipboard!'
		resp = console.alert('Alert!', 'Choose File Extension', '.py', '.pyui', hide_cancel_button=False)
		if resp==1:
			ext = '.py'
		elif resp==2:
			ext = '.pyui'
		filename=os.path.join(dest_path,'clipboard')
		filename=getuniquename(filename,ext)
		while os.path.isfile(filename):
			filename = '{} {}{}'.format(root, filenum, extension)
			filenum += 1
		with open(filename,'w') as f:
			f.write(text)
		print('Done!')
	else:
		file = appex.get_file_path()
		print('Input path: %s' % file)
		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))
	else:
		print(' > as %s' % os.path.basename(filename))
Esempio n. 10
0
def save(folder):
    if appex.is_running_extension():
        sFp = appex.get_file_path()
        if sFp:
            console.hud_alert('Saving...')
            print('Destination folder: ', os.path.join(folder, os.path.basename(sFp)))
            shutil.copy(sFp, folder)
            console.hud_alert('Saved')
Esempio n. 11
0
def save(folder):
    if appex.is_running_extension():
        sFp = appex.get_file_path()
        if sFp:
            console.hud_alert('Saving...')
            print 'Destination folder: ', os.path.join(folder, os.path.basename(sFp))
            shutil.copy(sFp, folder)
            console.hud_alert('Saved')
Esempio n. 12
0
def save():
	if appex.is_running_extension():
		sFp = appex.get_file_path()
		if sFp:
			console.hud_alert('Saving...')
			with open(sFp, 'rb') as f1:
				with open(os.path.basename(sFp), 'wb') as f2:
					f2.write(f1.read())
			console.hud_alert('Saved')
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()
Esempio n. 14
0
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()
Esempio n. 15
0
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()
Esempio n. 16
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()
Esempio n. 17
0
def main():
    console.clear()
    dest_path_short = '~/Documents'
    dest_path = os.path.expanduser(dest_path_short)
    if not os.path.isdir(dest_path):
        print('Create ' + dest_path_short)
        os.mkdir(dest_path)
    if not appex.is_running_extension():
        print('正在获取剪贴板文本...')
        txt = clipboard.get()
        tet = txt.encode('utf-8')  #转码
        #print(tet)
        text = tet.decode("utf-8")
        #print (text)

        assert text, '剪贴板没有文本内容!'
        resp = console.alert('honzou友情提示',
                             '请选择新建文件的类型:',
                             '.py',
                             '.pyui',
                             '.text',
                             hide_cancel_button=False)
        if resp == 1:
            ext = '.py'
        elif resp == 2:
            ext = '.pyui'
        elif resp == 3:
            ext = '.text'
        clipboards = input('创建文件名:')
        filename = os.path.join(dest_path, clipboards)
        filename = getuniquename(filename, ext)
        while os.path.isfile(filename):
            filename = '{} {}{}'.format(root, filenum, extension)
            filenum += 1
        with codecs.open(filename, 'w', 'utf-8') as f:  #再次定义文本编码

            f.write(text)
        print('成功写入!')
    else:
        file = appex.get_file_path()
        print('Input path: %s' % file)
        filename = os.path.join(dest_path, os.path.basename(file))
        filename = getuniquename(filename, '')
        shutil.copy(file, filename)
    print('文件已保存到 %s' % dest_path_short)
    if not os.path.exists(filename):
        print(' > Error file %s not found !' % os.path.basename(filename))
    else:
        print('请到该目录查看文件:%s' % os.path.basename(filename))
Esempio n. 18
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()
Esempio n. 19
0
def simple_import():

    if appex.is_running_extension():
        get_path = appex.get_file_path()
        file_name = path.basename(get_path)
        dstpath = path.join(save_dir, file_name)
        file_pure_name = path.splitext(file_name)[0]
        file_ext = path.splitext(file_name)[-1]
        if file_ext == '.py':
            new_file_name = ''
            number = 1
            while (path.exists(dstpath)):
                new_file_name = file_pure_name + str(number) + file_ext
                dstpath = path.join(save_dir, new_file_name)
                number += 1
            if new_file_name:
                try:
                    while True:
                        newname = console.input_alert('文件名已存在',
                                                      '重命名如下?',
                                                      new_file_name,
                                                      '确认',
                                                      hide_cancel_button=False)
                        if not path.exists(path.join(save_dir, newname)):
                            break
                except:
                    exit()
            else:
                try:
                    newname = console.input_alert('确认',
                                                  '文件名',
                                                  file_name,
                                                  '确认',
                                                  hide_cancel_button=False)
                except:
                    exit()
            dstpath = path.join(save_dir, newname)
            try:
                shutil.copy(get_path, dstpath)
                console.hud_alert('导入成功!', '', 1)
            except Exception as eer:
                print(eer)
                console.hud_alert('导入失败!', 'error', 1)
        else:
            console.hud_alert('非py文件无法导入', 'error', 2)
    else:
        console.hud_alert('请在分享扩展中打开本脚本', 'error', 2)
Esempio n. 20
0
def get_size():
	if appex.is_running_extension():
		path = appex.get_file_path()
		if not os.path.exists(path):
			raise Exception('文件路径不存在')
		if os.path.isfile(path):
			size = os.path.getsize(path)
		else:
			size = folder_size(path)
		console.clear()
		console.set_color(0.3,0.3,1)
		console.set_font('Menlo',20)
		print('文件名称: ' + path.split('/')[-1])	
		print('文件大小: ' + actualSize(size))
		print('占用空间: ' + capacitySize(size))
	else:
		console.hud_alert('请在分享扩展中打开本脚本', 'error', 2)
Esempio n. 21
0
def main():
    if not appex.is_running_extension():
        print(
            'Run this script from the share sheet extension in the Playgrounds app'
        )
        return
    pg_path = appex.get_file_path()
    if not pg_path or not pg_path.endswith('.playgroundbook'):
        print('No Playground book found in share sheet input')
        return
    tmpdir = tempfile.gettempdir()
    pg_name = os.path.split(pg_path)[1]
    dest_path = os.path.join(tmpdir, pg_name)
    try:
        shutil.rmtree(dest_path)
    except IOError:
        pass
    shutil.copytree(pg_path, dest_path)
    chapters_path = os.path.join(dest_path, 'Contents/Chapters')
    chapter_names = os.listdir(chapters_path)
    chapter = dialogs.list_dialog('Chapter', chapter_names)
    if chapter is None:
        return
    try:
        page_title = dialogs.input_alert('New Page Title')
    except KeyboardInterrupt:
        return
    chapter_path = os.path.join(chapters_path, chapter)
    with open(os.path.join(chapter_path, 'Manifest.plist'), 'rb') as f:
        chapter_manifest = plistlib.readPlist(f)
    chapter_manifest['Pages'].append(page_title + '.playgroundpage')
    with open(os.path.join(chapter_path, 'Manifest.plist'), 'wb') as f:
        plistlib.dump(chapter_manifest, f)
    page_path = os.path.join(chapter_path,
                             'Pages/' + page_title + '.playgroundpage')
    os.mkdir(page_path)
    os.mkdir(os.path.join(page_path, 'Resources'))
    img = Image.open('test:Pythonista')
    img.save(os.path.join(page_path, 'Resources/Pythonista.png'))
    with open(os.path.join(page_path, 'Contents.swift'), 'w') as f:
        f.write(swift)
    manifest = manifest_tpl.replace('{{NAME}}', page_title)
    with open(os.path.join(page_path, 'Manifest.plist'), 'w') as f:
        f.write(manifest)
    console.open_in(dest_path)
    shutil.rmtree(dest_path)
Esempio n. 22
0
def main():
    fn = None
    if appex.is_running_extension():
        fn = appex.get_file_path()

    if fn is None:
        print('no file to untar!')
        return

    with tarfile.open(fn) as f:
        console.clear()
        print(f.list())
        print('ok to extract? [y/N]', )
        yn = input()
        if yn == 'y':
            f.extractall()
            print('extracted')
        else:
            print('did not extract')
Esempio n. 23
0
def main():
    # get the file path from the share sheet
    # write file out came from:
    # https://forum.omz-software.com/topic/3606/script-to-import-any-file-in-pythonista-from-any-app
    if appex.is_running_extension():
        # file from Git2Go
        source_file = appex.get_file_path()
        file_name_alone = source_file.split('/')
        file_name_alone = file_name_alone[len(file_name_alone) - 1]

        # directory where you want it placed
        full_files_destination = file_picker_dialog(
            'Pick some directory to place file in.',
            multiple=True,
            select_dirs=True,
            file_pattern=r'^.*\.py$')
        #print(full_files_destination[0])
        # need to remove app diectory stuff and start at ~/Documents
        files_destination = full_files_destination[0].split('Documents')
        #print(files_destination[1])
        short_path = ('~/Documents' + files_destination[1] + '/' +
                      file_name_alone)
        #print(short_path)
        dest_path = full_files_destination[0]

        #file = appex.get_file_path()
        #print('Input path: %s' % file)
        filename = os.path.join(dest_path, os.path.basename(source_file))
        unique_filename = getuniquename(filename, '')
        if unique_filename != filename:
            # you will be over-writing the file, ask
            try:
                alert_response = console.alert(
                    'You will overwrite\n' + short_path + '\n\nAre you sure?',
                    '', 'Yes')
                #print(alert_response)
                shutil.copy(source_file, filename)
                print(short_path + '\nhas been overwritten')
            except KeyboardInterrupt:
                print('Operation canceled')
        else:
            shutil.copy(source_file, filename)
            print(short_path + '\nhas been written out')
Esempio n. 24
0
def main():
    global my_ui_view, total_file_size, transmit_file_size

    w, h = (540, 620)
    disp_mode = 'sheet'
    my_ui_view = MyView(w, h)
    my_ui_view.background_color = 'white'
    my_ui_view.name = 'Upload'
    my_ui_view.present(disp_mode, hide_title_bar=False)

    # Sharing: receive file
    fil = appex.get_file_path()
    if fil == None:
        print('no file passed')
        return

    server = 'Xxxxx'
    user = '******'
    pwd = 'xxxx'
    server_file = os.path.basename(fil)
    my_ui_view['msg_label'].text = server_file

    try:
        ftp = FTP(server)  #connect
        ftp.encoding = 'utf-8'
        ftp.login(user, pwd)
        ipad_file = open(fil, 'rb')
        transmit_file_size = 0
        total_file_size = os.path.getsize(fil)
        ftp.storbinary('STOR ' + server_file,
                       ipad_file,
                       blocksize=8192,
                       callback=callback)
        ipad_file.close()
        ftp.close()
    except Exception as e:
        print(str(e))
Esempio n. 25
0
def main():
    if not appex.is_running_extension():
        print(
            'Running in Pythonista app. Use via sharing extension with a .zip file instead.'
        )
        exit(1)

    config = ConfigFile(config_path)
    if not config.key_exists('FIRST_RUN'):
        first_run(config)

    root = config.get('ROOT')
    dest = config.get('DEST')
    zip_src = appex.get_file_path()
    zip_name = zip_src.split(os.sep)[-1]

    cv = ConfirmView.load_view(dest, zip_name)
    cv.present()
    cv.wait_modal()

    if cv.proceed:
        new_dest = cv.path
        clear_first = cv.clearfirst
        if dest != new_dest:
            config.set('DEST', new_dest)
            dest = new_dest
            config.save()
        os.chdir(root)
        if clear_first and os.path.exists(dest):
            shutil.rmtree(dest)
        if not os.path.exists(dest):
            os.makedirs(dest)
        with ZipFile(zip_src, 'r') as zipo:
            zipo.extractall(dest)
        print('Done.')
    else:
        print('Cancelled by user.')
def finalize_pdf():
    infile = appex.get_file_path()
    __add_file_to_queue(infile)
    __merge_all_pdfs()
    __cleanup()
Esempio n. 27
0
        return parser.convert()


def get_account(account_name, api_client, budget):
    try:
        for a in accounts_response.data.accounts:
            if a.name == account_name:
                return a.id
        return None
    except ynab.rest.ApiException as e:
        print("When trying to get accounts, encounted the error %s" % e)


if appex.is_running_extension():
    ofx_file = appex.get_file_path()
else:
    ofx_file = sys.argv[1]

key_file = open("key.txt", 'r')
key = key_file.readline().strip()
key_file.close()

ynab_config = ynab.configuration.Configuration()
ynab_config.api_key['Authorization'] = key
ynab_config.api_key_prefix['Authorization'] = 'Bearer'

api_client = ynab.api_client.ApiClient(configuration=ynab_config)

# Get which budget to import into
try:
def add_file():
    infile = appex.get_file_path()
    __add_file_to_queue(infile)
Esempio n. 29
0
# https://forum.omz-software.com/topic/3915/clearing-notability-document-backgrounds

import console, shutil, appex, os.path, zipfile, os, glob, re, plistlib

# Install biplist (I could not get plistlib to read the plist file, even
# when I used fmt=plistlib.FMT_BINARY))
# Rather than using pip, I just put the contents of this url in ./lib/biplist.py
# https://raw.githubusercontent.com/wooster/biplist/master/biplist/__init__.py

from lib.biplist import *

tmpPath = './jtziptmp/'
extractedPath = './jtziptmp/extracted/'
tmpFileName = 'tmpfile.zip'
newFileName = tmpPath + os.path.basename(
    appex.get_file_path()) + '_bgstripped.note'
shutil.rmtree(tmpPath)
os.mkdir(tmpPath)
os.mkdir(extractedPath)
shutil.copy(appex.get_file_path(), tmpPath + tmpFileName)
shutil.unpack_archive(tmpPath + tmpFileName, extractedPath)

pattern = "^.*pdf$"
mypath = extractedPath
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.match(pattern, x), files):
        os.remove(os.path.join(root, file))  # remove the pdf bg

pattern = "^Session.plist$"
mypath = extractedPath
for root, dirs, files in os.walk(mypath):
Esempio n. 30
0
    def __init__(self, close_event):
        if appex.is_running_extension():
            self.file_path = appex.get_file_path()
            self.v = ui.load_view("inner_ui")
            self.v.set_close(close_event)
            self.window = self.v['show']
            self.message_box = self.v['message_box']
            self.message_label = self.v["message_label"]
            self.send = self.v['send']
            self.done = self.v['done']
            self.done.hidden = True
            de = TextViewDelegate()
            self.message_box.delegate = de
            de.set_button(self.done)
            self.device_source = DeviceSource()
            self.device_label = self.v["device_label"]
            self.device_table = self.v["device_table"]
            self.device_table.data_source = self.device_table.delegate = self.device_source

            self.device_source.set_tableview(self.device_table)

            self.process = self.v['bar']

            self.get_process = self.v["bar"]

            self.file_button = self.v['file_button']
            self.file_button.action = self.file_button_action

            self.start_page = [self.device_label, self.device_table]
            self.second_page = [
                self.window, self.message_box, self.message_label, self.send,
                self.file_button, self.process, self.get_process
            ]
            self.third_page = []
            self.show(1)

        else:
            self.v = ui.load_view("File_transfer")
            self.v.set_close(close_event)
            self.window = self.v['show']
            self.file_button = self.v['file_button']
            self.file_close = self.v['file_close']
            self.message_box = self.v['message_box']
            self.message_label = self.v["message_label"]
            self.send = self.v['send']
            self.done = self.v['done']
            self.done.hidden = True
            de = TextViewDelegate()
            self.message_box.delegate = de
            de.set_button(self.done)
            self.file_button.action = self.file_choose
            self.file_close.action = self.file_close_action

            self.device_source = DeviceSource()
            self.device_label = self.v["device_label"]
            self.device_table = self.v["device_table"]
            self.device_table.data_source = self.device_table.delegate = self.device_source

            self.device_source.set_tableview(self.device_table)

            #self.file_label = self.v["file_label"]
            self.process = self.v['bar']

            self.get_process = self.v["bar"]

            lst, source = make_new_table("~")
            self.file_nav = ui.NavigationView(lst)
            self.file_source = source
            source.set_nav(self.file_nav)
            source.set_show(self.show)
            self.file_nav.x = 6
            self.file_nav.y = 62
            self.file_nav.width = 308
            self.file_nav.height = 403
            self.file_nav.border_color = '#f0f0f0'
            self.file_nav.border_width = 1
            self.v.add_subview(self.file_nav)

            self.start_page = [self.device_label, self.device_table]
            self.second_page = [
                self.window, self.message_box, self.message_label, self.send,
                self.file_button, self.process, self.get_process
            ]
            self.third_page = [self.file_close, self.file_nav]

            self.show(1)
Esempio n. 31
0
def main():
	# Step one, open the zipfile
	word_file = appex.get_file_path()
	if not word_file:
		return
	if not zipfile.is_zipfile(word_file):
		return
	
	with zipfile.ZipFile(word_file, 'r') as pkg:
		w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
		# Step two, read and save all character styles and paragraph styles
		styles = {}
		style_tags = xml.etree.ElementTree.parse(pkg.open("word/styles.xml")).getroot()
		search_str = './/{{{ns}}}style'.format(ns=w)
		print search_str
		tally = 0
		for style in style_tags.findall(search_str):
			tally += 1
			# TODO: Get styles and save them in a class maybe?
			# <w:style w:type="paragraph" w:styleId="Heading1">
			if style.get('{{{ns}}}type'.format(ns=w)) == 'paragraph' or style.get('{{{ns}}}type'.format(ns=w)) == 'character':
				style_id = style.get('styleId')

				bold_tag = style.find('.//{{{ns}}}rPr/{{{ns}}}b'.format(ns=w))
				if bold_tag is not None:
					bold = bold_tag.get('{{{ns}}}val'.format(ns=w)) != '0' and bold_tag.get('{{{ns}}}val'.format(ns=w)) != 'false' and bold_tag.get('{{{ns}}}val'.format(ns=w)) != 'f'
				else:
					bold = None

				italic_tag = style.find('.//{{{ns}}}rPr/{{{ns}}}i'.format(ns=w))
				if italic_tag is not None:
					italic = italic_tag.get('{{{ns}}}val'.format(ns=w)) != '0' and italic_tag.get('{{{ns}}}val'.format(ns=w)) != 'false' and italic_tag.get('{{{ns}}}val'.format(ns=w)) != 'f'
				else:
					italic = None

				styles[style_id] = { 'bold' : bold, 'italic' : italic }
		print "Found: {0} styles".format(tally)
		# Step three, grab all paragraphs from document.xml
		markdown = []
		document = xml.etree.ElementTree.parse(pkg.open("word/document.xml")).getroot()
		search_str = './/{{{ns}}}p'.format(ns=w)
		print search_str
		tally = 0
		for paragraph in document.findall(search_str):
			tally += 1
			paragraph_style = { 'bold' : False, 'italic' : False }

			style_id = paragraph.get('{{{ns}}}pStyle'.format(ns=w))
			if style_id:
				referenced_style = styles[style_id]
				if referenced_style:
					paragraph_style['bold'] = referenced_style['bold']
					paragraph_style['italic'] = referenced_style['italic']

			if paragraph_style['italic']:
				markdown.append("_")
			if paragraph_style['bold']:
				markdown.append("**")

			# Step four, grab all runs within each paragraph
			for run in paragraph.findall('.//{{{ns}}}r'.format(ns=w)):
				# Step five, apply styles to each run & render all <w:t> and <w:br> tags
				# Get run_style id for any document-level styles
				run_style = { 'bold' : False, 'italic' : False }

				style_id = run.get('{{{ns}}}rStyle'.format(ns=w))
				if style_id:
					referenced_style = styles[style_id]
					if referenced_style:
						run_style['bold'] = referenced_style['bold']
						run_style['italic'] = referenced_style['italic']
				
				# Get rPr for any local styles
				bold_tag = run.find('.//{{{ns}}}rPr/{{{ns}}}b'.format(ns=w))
				if bold_tag is not None:
					inline_bold = bold_tag.get('{{{ns}}}val'.format(ns=w)) != '0' and bold_tag.get('{{{ns}}}val'.format(ns=w)) != 'false' and bold_tag.get('{{{ns}}}val'.format(ns=w)) != 'f'
				else:
					inline_bold = None
				
				italic_tag = run.find('.//{{{ns}}}rPr/{{{ns}}}i'.format(ns=w))
				if italic_tag is not None:
					inline_italic = italic_tag.get('{{{ns}}}val'.format(ns=w)) != '0' and italic_tag.get('{{{ns}}}val'.format(ns=w)) != 'false' and italic_tag.get('{{{ns}}}val'.format(ns=w)) != 'f'
				else:
					inline_italic = None

				# Combine styles to come up with whether or not we're actually supposed to be bold or italic here
				if inline_bold != None:
					run_style['bold'] = inline_bold
				if inline_italic != None:
					run_style['italic'] = inline_italic				

				# ' _**', ' **', ' _', '**_ ', '** ', '_ ', '** _', '_ **'
				prepend = ''
				append = ''

				if not paragraph_style['bold'] and run_style['bold'] == True and not paragraph_style['italic'] and run_style['italic'] == True:
					prepend = ' _**'
					append = '**_ '
				elif not paragraph_style['bold'] and run_style['bold'] == True and not paragraph_style['italic'] and not run_style['italic']:
					prepend = ' **'
					append = '** '
				elif not paragraph_style['bold'] and not run_style['bold'] and not paragraph_style['italic'] and run_style['italic'] == True:
					prepend = ' _'
					append = '_ '
				elif paragraph_style['bold'] == True and run_style['bold'] == False and paragraph_style['italic'] == True and run_style['italic'] == False:
					prepend = '**_ '
					append = ' _**'
				elif paragraph_style['bold'] == True and run_style['bold'] == False and not paragraph_style['italic'] and not run_style['italic']:
					prepend = '** '
					append = ' **'
				elif not paragraph_style['bold'] and not run_style['bold'] and paragraph_style['italic'] == True and run_style['italic'] == False:
					prepend = '_ '
					append =' _'
				elif paragraph_style['bold'] == True and run_style['bold'] == False and not paragraph_style['italic'] and run_style['italic'] == True:
					prepend = '** _'
					append = '_ **'
				elif not paragraph_style['bold'] and run_style['bold'] == True and paragraph_style['italic'] == True and run_style['italic'] == False:
					prepend = '_ **'
					append = '** _'

				markdown.append(prepend)

				for child in run:
					if child.tag == '{{{ns}}}t'.format(ns=w):
						markdown.append(child.text)
					elif child.tag == '{{{ns}}}br'.format(ns=w):
						markdown.append("  \n")

				markdown.append(append)

			if paragraph_style['bold']:
				markdown.append("**")
			if paragraph_style['italic']:
				markdown.append("_")		 
			markdown.append("\n")

		print "Found {0} paragraphs".format(tally)
		# Concatenate all text from all runs from all paragraphs and output it!
		out = ''.join(markdown)
		clipboard.set(out)		
Esempio n. 32
0
    def __init__(self, close_event):
        if appex.is_running_extension():
            self.file_path = appex.get_file_path()
            self.v = ui.load_view("inner_ui")
            #self.have_to_close = self.v.have_to_close
            self.v.set_close(close_event)
            self.window = self.v['show']
            self.message_box = self.v['message_box']
            self.message_label = self.v["message_label"]
            self.send = self.v['send']

            self.device_source = DeviceSource()
            self.device_label = self.v["device_label"]
            self.device_table = self.v["device_table"]
            self.device_table.data_source = self.device_table.delegate = self.device_source

            self.device_source.set_tableview(self.device_table)

            self.process = self.v['bar']

            self.get_process = self.v["bar"]

            self.file_button = self.v['file_button']
            self.file_button.action = self.file_button_action

            self.start_page = [self.device_label, self.device_table]
            self.second_page = [
                self.window, self.message_box, self.message_label, self.send,
                self.file_button, self.process, self.get_process
            ]

            self.show(1)

        else:
            self.v = ui.load_view("File_transfer")
            #print(type(close_event))
            self.v.set_close(close_event)
            self.window = self.v['show']

            self.message_box = self.v['message_box']
            self.message_label = self.v["message_label"]
            self.send = self.v['send']

            self.device_source = DeviceSource()
            self.device_label = self.v["device_label"]
            self.device_table = self.v["device_table"]
            self.device_table.data_source = self.device_table.delegate = self.device_source

            self.device_source.set_tableview(self.device_table)

            self.file_label = self.v["file_label"]
            self.process = self.v['bar']

            self.get_process = self.v["bar"]

            lst, source = make_new_table("~")
            self.file_nav = ui.NavigationView(lst)
            self.file_source = source
            source.set_nav(self.file_nav)
            self.file_nav.x = 390
            self.file_nav.y = 265
            self.file_nav.width = 361
            self.file_nav.height = 331
            self.file_nav.border_color = '#f0f0f0'
            self.file_nav.border_width = 1
            self.v.add_subview(self.file_nav)

            self.start_page = [self.device_label, self.device_table]
            self.second_page = [
                self.window, self.message_box, self.message_label, self.send,
                self.file_label, self.file_nav, self.process, self.get_process
            ]

            self.show(1)
Esempio n. 33
0
#!/usr/bin/env python3
# coding: utf-8

# Pythonista appex script to copy and unpack a repo zipfile from GitHub

import appex, os, zipfile  # noqa

if appex.is_running_extension():
    srce_path = appex.get_file_path()
    from_gh = os.path.abspath(os.path.expanduser('from GitHub'))
    os.makedirs(from_gh, exist_ok=True)
    with zipfile.ZipFile(srce_path) as zip_file:
        zip_file.extractall(from_gh)
    dir_name, _ = os.path.splitext(os.path.split(srce_path)[-1])
    msg = 'Files were unzipped into ~/'
    print(msg + os.path.relpath(os.path.join(from_gh, dir_name)))
else:  # Error handling...
    print('''=====
* In Safari browser, navigate to a GitHub repo of interest.
* Tap the green 'Clone or download' button.
* Tap 'Download ZIP'.  (Big repos may take seveal seconds to download).
* Tap 'Open in...'.
* Tap 'Run Pythonista Script'.
* Pick this script and tap the run button.
* When you return to Pythonista the files should be in '~/from GitHub/'.''')