Beispiel #1
0
def PythonistaTest():
    '''A test of the module for iOS devices running Pythonista'''
    import console, photos, clipboard
    #Ask the user to either take a photo or choose an existing one
    capture = console.alert("Image2ASCII",
                            button1="Take Photo",
                            button2="Pick Photo")
    if capture == 1:
        im = photos.capture_image()
    elif capture == 2:
        im = photos.pick_image(original=False)
    photos.save_image(im)
    console.show_activity()
    out = image2ASCII(im, 200)
    outim = RenderASCII(out, bgcolor='#ededed')
    stitchImages(im, outim).show()
    console.hide_activity()
    outim.save('image.jpg')
    console.quicklook('image.jpg')
    mode = console.alert("Image2ASCII", "You can either:", "Share Text",
                         "Share Image")
    if mode == 1:
        file = open('output.txt', 'w')
        file.write(out)
        file.close()
        console.open_in('output.txt')
    elif mode == 2:
        console.open_in('image.jpg')
    time.sleep(5)
    console.clear()
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()
Beispiel #3
0
def PythonistaTest():
	'''A test of the module for iOS devices running Pythonista'''
	import console,photos,clipboard
	#Ask the user to either take a photo or choose an existing one
	capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo")
	if capture == 1:
		im = photos.capture_image()
	elif capture == 2:
		im = photos.pick_image(original=False)
	photos.save_image(im)
	console.show_activity()
	out = image2ASCII(im, 200)
	outim = RenderASCII(out, bgcolor = '#ededed')
	stitchImages(im, outim).show()
	console.hide_activity()
	outim.save('image.jpg')
	console.quicklook('image.jpg')
	mode = console.alert("Image2ASCII", "You can either:","Share Text","Share Image")
	if mode == 1:
		file = open('output.txt', 'w')
		file.write(out)
		file.close()
		console.open_in('output.txt')
	elif mode == 2:
		console.open_in('image.jpg')
	time.sleep(5)
	console.clear()
def download(video_url):
    available_formats = []
    with youtube_dl.YoutubeDL({}) as ydl:
        meta = ydl.extract_info(video_url, download=False)
    formats = meta.get('formats', [meta])

    descriptions = ['Best']
    for format in formats:
        f = Format(format['format_id'], format['format'], format['ext'])
        available_formats.append(f)
        descriptions.append(f.description)
    selected_format = dialogs.list_dialog(title='Select a Format',
                                          items=descriptions)
    if selected_format is None:
        return
    format_to_use = 'best'
    ext = 'mp4'
    for format in available_formats:
        if selected_format == format.description:
            format_to_use = format.id
            ext = format.ext
    with youtube_dl.YoutubeDL({'format': format_to_use}) as ydl:
        ydl.download([video_url])

    list_of_files = glob.glob('*.*')
    latest_file = max(list_of_files, key=os.path.getctime)
    console.open_in(latest_file)
    if ext in latest_file:
        os.remove(latest_file)
Beispiel #5
0
 def open_in(path):
     """
     Open a file in another application.
     If possible, let the user decide the application
     :param path: path to file
     :type path: str
     """
     console.open_in(path)
Beispiel #6
0
 def btn_OpenIn(self, sender):
     sel_rows = len(self.view['tableview1'].selected_rows)
     if sel_rows == 1:
       row = self.view['tableview1'].selected_row[1]
       filename = self.view['tableview1'].data_source.items[row]['title']
       file = self.path + '/' + filename
       console.open_in(file)
     else:
       self.btn_Help(None,message='Please select one file.',name='Error')
Beispiel #7
0
def share_binary(bytes, extension):
    if bytes:
        filename = uuid.uuid1().hex + "." + extension
        with open(filename, "wb") as f:
            f.write(bytes)
        console.open_in(filename)
        os.remove(filename)
        print('success!')
    else:
        print("no file found")
def __merge_all_pdfs():
    dest = PyPDF2.PdfFileMerger()
    for count in range(__get_next_counter()):
        filename = str(count) + ".pdf"
        try:
            with open(filename, "rb") as pdf:
                dest.append(PyPDF2.PdfFileReader(pdf))
        except FileNotFoundError:
            raise FileNotFoundError(
                "Somehow one of the files you queued up is missing!")
    with open("outfile.pdf", "wb") as outfile:
        dest.write(outfile)
    console.open_in("outfile.pdf")
Beispiel #9
0
def my_hook(d):
    if d['status'] == 'finished':
        console.hide_output()
        chosen = console.alert(
            'Download Finished',
            "Video is already in Pythonista.\nWaht else do you want to do with it?",
            'Quick Look', 'Open in', 'Save to Album')
        if chosen == 1:
            console.quicklook(d['filename'])
        elif chosen == 2:
            console.open_in(d['filename'])
        elif chosen == 3:
            save_video(d['filename'].encode('utf-8'))
Beispiel #10
0
    def zip(self, si):
        try:
            zn = console.input_alert("Enter the zip file name")
            if not zn.endswith(".zip"):
                zn += ".zip"
            logger.debug("Saving contents to the zip %r", zn)
            for i in si:
                self.fileManager.save_as_zip(zn, i["d_path"], i["d_type"])

            logger.debug("Saved contents to the zip %r", zn)
            console.hud_alert("Zipped", "success")
            console.open_in(os.path.abspath(zn))
        except KeyboardInterrupt as e:
            logger.warning("User cancled the procces")
Beispiel #11
0
def onShareButton(sender):
    global AdventureFolder
    global mustSave
    if mustSave:
        id = console.alert(
            'Warning',
            'Un-saved modifications detected, do you want to save them?',
            'Yes',
            'No',
            hide_cancel_button=True)
        if id == 1:
            saveAdventure()
    mustSave = False
    make_zipfile("./" + AdventureFolder + ".thz", "./" + AdventureFolder + "/")
    console.open_in(AdventureFolder + ".thz")
Beispiel #12
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()
Beispiel #13
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)
 def tableview_did_select(self, tableview, section, row):
     # Called when the user selects a row
     if section == 0:
         if self.type == 0:
             # actions for folders
             if row == 0:
                 # Go Here in Shellista
                 nav.close()
                 print("Launching Shellista...")
                 try:
                     from Shellista import Shell
                 except ImportError as err:
                     print("Failed to import Shellista: " + err.message)
                     print("See note on Shellista integration at the top of filenav.py.")
                     print("> logout")
                     return
                 shell = Shell()
                 shell.prompt = '> '
                 shell.onecmd("cd " + self.path)
                 print("> cd " + self.path)
                 shell.cmdloop()
         elif self.type == 1:
             # actions for files
             if row == 0:
                 # Quick Look
                 nav.close()
                 time.sleep(1) # ui thread will hang otherwise
                 console.quicklook(self.path)
             elif row == 1:
                 # Open in Editor
                 open_path(self.path)
                 nav.close()
             elif row == 2:
                 # Copy & Open
                 destdir = full_path(os.path.join(SCRIPT_ROOT, "temp"))
                 if not os.path.exists(destdir):
                     os.mkdir(destdir)
                 destfile = full_path(os.path.join(destdir, os.path.basename(self.path).lstrip(".")))
                 shutil.copy(self.path, destfile)
                 editor.reload_files()
                 open_path(destfile)
                 nav.close()
             elif row == 3:
                 # Copy & Open as Text
                 destdir = full_path(os.path.join(SCRIPT_ROOT, "temp"))
                 if not os.path.exists(destdir):
                     os.mkdir(destdir)
                 destfile = full_path(os.path.join(destdir, os.path.basename(self.path).lstrip(".") + ".txt"))
                 shutil.copy(self.path, destfile)
                 editor.reload_files()
                 open_path(destfile)
                 nav.close()
             elif row == 4:
                 # Open In
                 if console.open_in(self.path):
                     nav.close()
                 else:
                     console.hud_alert("Failed to Open", "error")
Beispiel #15
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     key = self.lists[section][1][row][0]
     if key == "ios.quick_look":
         # Preview - Quick Look
         self.app.close()
         time.sleep(ANIM_DELAY)
         console.quicklook(self.fi.path)
     elif key == "editor.edit":
         # Open in Editor - editor
         open_path(self.fi.path)
         self.app.close()
     elif key == "editor.copy_edit":
         # Copy & Open - editor
         destdir = full_path(
             os.path.join(full_path(u"~"), u"Documents/temp"))
         if not os.path.exists(destdir):
             os.mkdir(destdir)
         destfile = full_path(
             os.path.join(destdir,
                          self.fi.basename().lstrip(u".")))
         shutil.copy(self.fi.path, destfile)
         editor.reload_files()
         open_path(destfile)
         self.app.close()
     elif key == "editor.copy_edit_txt":
         # Copy & Open as Text - editor
         destdir = full_path(
             os.path.join(full_path(u"~"), u"Documents/temp"))
         if not os.path.exists(destdir):
             os.mkdir(destdir)
         destfile = full_path(
             os.path.join(destdir,
                          self.fi.basename().lstrip(u".") + u".txt"))
         shutil.copy(self.fi.path, destfile)
         editor.reload_files()
         open_path(destfile)
         self.app.close()
     elif key == "console.print_image":
         # Show in Console - console
         console.show_image(self.fi.path)
     elif key == "sound.play_sound":
         # Play Sound - sound
         spath = rel_to_app(self.fi.path.rsplit(u".", 1)[0])
         sound.load_effect(spath)
         sound.play_effect(spath)
     elif key == "webbrowser.open":
         # Open Website - webbrowser
         webbrowser.open(u"file://" + self.fi.path)
         self.app.close()
     elif key == "ios.open_in":
         # Open In - External Apps
         if console.open_in(self.fi.path):
             self.app.close()
         else:
             console.hud_alert(u"Failed to Open", "error")
Beispiel #16
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     key = self.lists[section][1][row][0]
     if key == "ios.quick_look":
         # Preview - Quick Look
         self.app.close()
         time.sleep(ANIM_DELAY)
         console.quicklook(self.fi.path)
     elif key == "editor.edit":
         # Open in Editor - editor
         open_path(self.fi.path)
         self.app.close()
     elif key == "editor.copy_edit":
         # Copy & Open - editor
         destdir = full_path(os.path.join(full_path(u"~"), u"Documents/temp"))
         if not os.path.exists(destdir):
             os.mkdir(destdir)
         destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(u".")))
         shutil.copy(self.fi.path, destfile)
         editor.reload_files()
         open_path(destfile)
         self.app.close()
     elif key == "editor.copy_edit_txt":
         # Copy & Open as Text - editor
         destdir = full_path(os.path.join(full_path(u"~"), u"Documents/temp"))
         if not os.path.exists(destdir):
             os.mkdir(destdir)
         destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(u".") + u".txt"))
         shutil.copy(self.fi.path, destfile)
         editor.reload_files()
         open_path(destfile)
         self.app.close()
     elif key == "console.print_image":
         # Show in Console - console
         console.show_image(self.fi.path)
     elif key == "sound.play_sound":
         # Play Sound - sound
         spath = rel_to_app(self.fi.path.rsplit(u".", 1)[0])
         sound.load_effect(spath)
         sound.play_effect(spath)
     elif key == "webbrowser.open":
         # Open Website - webbrowser
         webbrowser.open(u"file://" + self.fi.path)
         self.app.close()
     elif key == "ios.open_in":
         # Open In - External Apps
         if console.open_in(self.fi.path):
             self.app.close()
         else:
             console.hud_alert(u"Failed to Open", "error")
Beispiel #17
0
 def tableview_did_select(self, tableview, section, row):
     # Called when the user selects a row
     key = self.lists[section][1][row][0]
     if key == "shellista-cd":
         # Go Here - Shellista
         nav.close()
         print("Launching Shellista...")
         try:
             from Shellista import Shell
         except ImportError as err:
             print("Failed to import Shellista: " + err.message)
             print("See note on Shellista integration at the top of filenav.py.")
             print("> logout")
             return
         shell = Shell()
         shell.prompt = '> '
         shell.onecmd("cd " + self.fi.path)
         print("> cd " + self.fi.path)
         shell.cmdloop()
     elif key == "ios-qlook":
         # Preview - Quick Look
         nav.close()
         time.sleep(1) # ui thread will hang otherwise
         console.quicklook(self.fi.path)
     elif key == "pysta-edit":
         # Open in Editor - Pythonista
         open_path(self.fi.path)
         nav.close()
     elif key == "pysta-cpedit":
         # Copy & Open - Pythonista
         destdir = full_path(os.path.join(SCRIPT_ROOT, "temp"))
         if not os.path.exists(destdir):
             os.mkdir(destdir)
         destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(".")))
         shutil.copy(self.fi.path, destfile)
         editor.reload_files()
         open_path(destfile)
         nav.close()
     elif key == "pysta-cptxt":
         # Copy & Open as Text - Pythonista
         destdir = full_path(os.path.join(SCRIPT_ROOT, "temp"))
         if not os.path.exists(destdir):
             os.mkdir(destdir)
         destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(".") + ".txt"))
         shutil.copy(self.fi.path, destfile)
         editor.reload_files()
         open_path(destfile)
         nav.close()
     elif key == "console-printimg":
         # Show in Console - console
         console.show_image(self.fi.path)
     elif key == "sound-playsound":
         # Play Sound - sound
         spath = rel_to_app(self.fi.path.rsplit(".", 1)[0])
         sound.load_effect(spath)
         sound.play_effect(spath)
     elif key == "webbrowser-open":
         # Open Website - webbrowser
         webbrowser.open("file://" + self.fi.path)
         nav.close()
     elif key == "ios-openin":
         # Open In - External Apps
         if console.open_in(self.fi.path):
             nav.close()
         else:
             console.hud_alert("Failed to Open", "error")
Beispiel #18
0
 def share_action(self, sender):
     file_name = self['file name'].text
     console.open_in(file_name)
Beispiel #19
0
		#Ask the user to either take a photo or choose an existing one
		capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo")
	
		if capture == 1:
			im = photos.capture_image()
		elif capture == 2:
			im = photos.pick_image(original=False)
		
		console.show_activity()
	
		out = image2ASCII(im, 200)
		outim = RenderASCII(out, bgcolor = '#ff0000')
		stitchImages(im, outim).show()
	
		console.hide_activity()
		
		outim.save('image.jpg')
		console.quicklook('image.jpg')
		
		mode = console.alert("Image2ASCII", "You can either:","Share Text","Share Image")
		if mode == 1:
			file = open('output.txt', 'w')
			file.write(out)
			file.close()
			console.open_in('output.txt')
		elif mode == 2:
			console.open_in('image.jpg')
		
		time.sleep(5)
		console.clear()
Beispiel #20
0
def main(args=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('-c',
                    '--current-file',
                    action='store_true',
                    help='Use file currently opened in editor as input')
    ap.add_argument('-e',
                    '--edit-buffer',
                    action='store_true',
                    help='Use content of current editor buffer as input')
    ap.add_argument('infile', nargs='?', help='Input file name')

    args = ap.parse_args(args if args is not None else sys.argv[1:])

    if args.edit_buffer or args.current_file:
        pdf_bn = make_pdf_filename(editor.get_path())

    if args.current_file:
        with open(editor.get_path()) as f:
            md = f.read()
    elif args.edit_buffer:
        md = editor.get_text()
    elif args.infile:
        pfd_bn = make_pdf_filename(args.infile)
        with open(args.infile) as f:
            md = f.read()
    else:
        pdf_bn = 'markdown2pdf.pdf'

        try:
            choice = console.alert('Markdown to PDF', '', 'Show README',
                                   'Convert Clipboard', 'Convert URL')
        except KeyboardInterrupt:
            return

        if choice == 1:
            md = __doc__
        elif choice == 2:
            import clipboard
            md = clipboard.get()
        elif choice == 3:
            import re
            import clipboard
            try:
                cb = clipboard.get().strip()
                if not re.search('^(ht|f)tps?://', cb):
                    cb = ''
                url = console.input_alert('Enter URL',
                                          'Download Markdown from URL:', cb,
                                          'Download')
            except KeyboardInterrupt:
                return
            else:
                import urllib2
                import urlparse
                try:
                    r = urllib2.urlopen(url)
                except urllib2.URLError as exc:
                    print(exc)
                    console.hud_alert("Download error (see console)", 'error')
                    return
                else:
                    md = r.read()

                url = urlparse.urlparse(r.geturl())
                fn = make_pdf_filename(url.path)
                if fn:
                    pdf_bn = fn

    if not md:
        return

    tempdir = tempfile.mkdtemp()
    pdf_path = join(tempdir, pdf_bn)
    console.show_activity()
    status = markdown2pdf(md, pdf_path)
    console.hide_activity()

    try:
        choice = console.alert('Select Ouput', '', 'Save to file...',
                               'Open in...', 'View')
    except KeyboardInterrupt:
        return

    if choice == 1:
        try:
            filename = console.input_alert(
                "Filename",
                "Enter PDF output filename\n(will overwrite existing files!):",
                pdf_bn, 'Save')
            os.rename(pdf_path, filename)
        except KeyboardInterrupt:
            return
        except (IOError, OSError) as exc:
            console.alert("Error", "Error writing PDF file:\n\n%s" % exc)
            return 1
    elif choice == 2:
        console.open_in(pdf_path)
    elif choice == 3:
        console.quicklook(pdf_path)

    try:
        os.unlink(pdf_path)
        os.rmdir(tempdir)
    except:
        pass
Beispiel #21
0
if len(sys.argv) != 2:
    raise IndexError('usage: %s url' % (sys.argv[0]))
url = sys.argv[1]
print('url: %s' % (url))

choices = (
    ('Audio', 'bestaudio[ext=m4a]', 'm4a'),
    ('Video', 'best[ext=mp4]', 'mp4'),
)
choice = console.alert('youtube-dl', 'Version to extract:',
                       *(c[0] for c in choices))

_, format, ext = choices[choice - 1]
print('format: %s' % (format))

opts = {'format': format}
with YoutubeDL(opts) as ydl:
    ydl.download([url])

file = max(glob.glob('*.' + ext), key=os.path.getctime)
if not file:
    raise IndexError('downloaded file not found')
print('downloaded: %s' % (file))

try:
    console.open_in(file)
finally:
    os.remove(file)
    print('deleted: %s' % (file))
Beispiel #22
0
def action_export(sender):
    """Open the iOS share dialog to send the vocabulary data file."""
    vocab.save_json_file(indent=1)
    console.open_in(VOCABULARY_FILE)
Beispiel #23
0
    def bt_save_hours_action(self, sender):
        '''save the content of the actual view of hours per day/week/month to csv.file
        '''
        #console.show_activity()
        start = self.view["datepicker"].date

        if self.state == 6:  # year
            mstart = start.replace(month=1,
                                   day=1,
                                   hour=0,
                                   minute=0,
                                   second=0,
                                   microsecond=0)
            mend = mstart.replace(year=mstart.year + 1,
                                  day=1,
                                  hour=0,
                                  minute=0,
                                  second=0,
                                  microsecond=0)

            lc = self.myCalender.findBetween(mstart, mend)
            self.LogMessage(f"save year of {mstart.strftime('%a %d.%m.%y')}")
            fname = f"{mstart.strftime('%y-%m-%d')}_year_hours.csv"

        elif self.state == 5:  # month
            mstart = start.replace(day=1,
                                   hour=0,
                                   minute=0,
                                   second=0,
                                   microsecond=0)
            mend = mstart + timedelta(
                weeks=0, days=32, hours=0, minutes=0, seconds=0)
            mend = mend.replace(day=1,
                                hour=0,
                                minute=0,
                                second=0,
                                microsecond=0)

            lc = self.myCalender.findBetween(mstart, mend)
            self.LogMessage(f"save week of {mstart.strftime('%a %d.%m.%y')}")
            fname = f"{mstart.strftime('%y-%m-%d')}_month_hours.csv"

        elif self.state == 4:  # week
            start = start.replace(hour=0, minute=0, second=0, microsecond=0)
            monday = start - timedelta(days=start.weekday())
            satday = monday + timedelta(days=5)

            lc = self.myCalender.findBetween(monday, satday)

            self.LogMessage(f"save week of {monday.strftime('%a %d.%m.%y')}")
            fname = f"{monday.strftime('%y-%m-%d')}_week_hours.csv"

        elif self.state == 3:  #day
            start = start.replace(hour=0, minute=0, second=0, microsecond=0)
            end = start + timedelta(days=1)

            lc = self.myCalender.findBetween(start, end)

            self.LogMessage(f"save day of {start.strftime('%a %d.%m.%y')}")
            fname = f"{start.strftime('%y-%m-%d')}_day_hours.csv"

        else:
            self.LogMessage(f"saving the calender")
            count = self.myCalender.SaveCal()
            self.view['l_Calender'].text = f"{count} calender entries saved"
            console.hud_alert("calender saved", 'success', 1)
            #   NOTE: console.hide_activity dismisses the hud. return of hud dont resets activity
            # console.hide_activity()
            return

        with open(fname, "w", encoding="utf-8") as f:
            lc.WriteDurationsToCSV(f)

        self.LogMessage(f"File {fname} with hours written")
        console.hud_alert("file saved", 'success', 1)
        #console.hide_activity()

        if self.view['switch_share_hours'].value:
            console.open_in(fname)
def main():# --------------------
excludelist.append(zip_dir)
source_dir=os.path.join(os.path.expanduser("~"),"Documents")
zip_dir_full=os.path.join(source_dir,zip_dir)
fname=datetime.datetime.now().strftime("scripts-%Y%m%dT%H%M%S.zip")
zip_file=os.path.join(zip_dir_full,fname)

try:
	os.stat(zip_dir_full)
except:
	os.mkdir(zip_dir_full)
if not os.path.isdir(zip_dir_full):
	print "could not create zip dest dir {zdf}".format(zdf=zip_dir_full)
	sys.exit()
	
make_zipfile(zip_file,source_dir,excludelist)
print
print "{fs} bytes written".format(fs=os.path.getsize(zip_file))
print "Done."

if open_in_quicklook:
	console.quicklook(zip_file)
	
if open_in_other_app:
	console.open_in(zip_file)
	
# --------------------

import os, sys, zipfile, datetime, console, time
from dropbox import client, rest, session
import webbrowser

EXCLUDES=['local-packages', 'Backups', '.Trash'] # any folders you want to exclude from backup

ZIP_DIR = 'Backups'             # default folder where the finished .zip file will reside.
				# Folder will be created if doesn't exist and is automatically
				# excluded from the backup.
				
				
def dropbox(APP_KEY, APP_SECRET, ACCESS_TYPE, upload_file):
	global client
	sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
	request_token = sess.obtain_request_token()
	url = sess.build_authorize_url(request_token)
	
	# Make the user sign in and authorize this token
	webbrowser.open(url, modal=False, stop_when_done=False)
	raw_input()
	
	# This will fail if the user didn't visit the above URL and hit 'Allow'
	access_token = sess.obtain_access_token(request_token)
	client = client.DropboxClient(sess)
	response = client.put_file(upload_file, upload_file)
	
def main():
	zip_dir=ZIP_DIR
	excludelist=EXCLUDES
	
	excludelist.append(zip_dir)
	source_dir=os.path.join(os.path.expanduser("~"),"Documents")
	zip_dir_full=os.path.join(source_dir,zip_dir)
	fname=datetime.datetime.now().strftime("Scripts Backup - %m%d%Y - %I:%M %p.zip")
	zip_file=os.path.join(zip_dir_full,fname)
	
	try:
		os.stat(zip_dir_full)
	except:
		os.mkdir(zip_dir_full)
	if not os.path.isdir(zip_dir_full):
		console.hud_alert("Could not create zip dest dir {zdf}".format(zdf=zip_dir_full), 'error', 1.5)
		sys.exit()
		
	make_zipfile(zip_file,source_dir,excludelist)
	bytes = "Backup Successfully Created - {fs} bytes written".format(fs=os.path.getsize(zip_file))
	console.hud_alert(bytes, 'success', 1.5)
	dropbox('rso5vcsund16lw9','wqivu6pzm3ef93s', 'dropbox', zip_file)
	
# http://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory

def make_zipfile(output_filename, source_dir, excludelist):
	relroot = os.path.abspath(os.path.join(source_dir, os.pardir))
	with zipfile.ZipFile(output_filename, "w", zipfile.ZIP_DEFLATED) as zip:
		for root, dirs, files in os.walk(source_dir,topdown=True):
			path_element=os.path.relpath(root,source_dir)
			# incredibly hacky and non-optimal way to implement an exclude list
			nextiter=False
			for path_ex in excludelist:
				if os.path.commonprefix([path_ex,path_element])==path_ex:
					nextiter=True
					break
			if nextiter==True:
				continue
			str = ("Adding {pe}").format(pe=path_element)
			console.show_activity(str)
			time.sleep(1)
			zip.write(root, os.path.relpath(root, relroot))
			for file in files:
				filename = os.path.join(root, file)
				if os.path.isfile(filename): # regular files only
					arcname = os.path.join(os.path.relpath(root, relroot), file)
					zip.write(filename, arcname)
			console.hide_activity()
			
if __name__ == "__main__":
	main()# --------------------
Beispiel #25
0
def main(args=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('-c', '--current-file', action='store_true',
        help='Use file currently opened in editor as input')
    ap.add_argument('-e', '--edit-buffer', action='store_true',
        help='Use content of current editor buffer as input')
    ap.add_argument('infile', nargs='?', help='Input file name')
    
    args = ap.parse_args(args if args is not None else sys.argv[1:])

    if args.edit_buffer or args.current_file:
        pdf_bn = make_pdf_filename(editor.get_path())

    if args.current_file:
        with open(editor.get_path()) as f:
            md = f.read()
    elif args.edit_buffer:
        md = editor.get_text()
    elif args.infile:
        pfd_bn = make_pdf_filename(args.infile)
        with open(args.infile) as f:
            md = f.read()
    else:
        pdf_bn = 'markdown2pdf.pdf'

        try:
            choice = console.alert('Markdown to PDF', '',
                'Show README', 'Convert Clipboard', 'Convert URL')
        except KeyboardInterrupt:
            return

        if choice == 1:
            md = __doc__
        elif choice == 2:
            import clipboard
            md = clipboard.get()
        elif choice == 3:
            import re
            import clipboard
            try:
                cb = clipboard.get().strip()
                if not re.search('^(ht|f)tps?://', cb):
                    cb = ''
                url = console.input_alert('Enter URL', 'Download Markdown from URL:',
                    cb, 'Download')
            except KeyboardInterrupt:
                return
            else:
                import urllib2
                import urlparse
                try:
                    r = urllib2.urlopen(url)
                except urllib2.URLError as exc:
                    print(exc)
                    console.hud_alert("Download error (see console)", 'error')
                    return
                else:
                    md = r.read()

                url = urlparse.urlparse(r.geturl())
                fn = make_pdf_filename(url.path)
                if fn:
                    pdf_bn = fn

    if not md:
        return

    tempdir = tempfile.mkdtemp()
    pdf_path = join(tempdir, pdf_bn)
    console.show_activity()
    status = markdown2pdf(md, pdf_path)
    console.hide_activity()

    try:
        choice = console.alert('Select Ouput', '',
            'Save to file...', 'Open in...', 'View')
    except KeyboardInterrupt:
        return

    if choice == 1:
        try:
            filename = console.input_alert("Filename",
                "Enter PDF output filename\n(will overwrite existing files!):",
                pdf_bn, 'Save')
            os.rename(pdf_path, filename)
        except KeyboardInterrupt:
            return
        except (IOError, OSError) as exc:
            console.alert("Error", "Error writing PDF file:\n\n%s" % exc)
            return 1
    elif choice == 2:
        console.open_in(pdf_path)
    elif choice == 3:
        console.quicklook(pdf_path)

    try:
        os.unlink(pdf_path)
        os.rmdir(tempdir)
    except: pass
Beispiel #26
0
 def shareForIphone(self):
     if self.onPythonista():
         import console
         console.open_in(self.file_name)
     else:
         pass
Beispiel #27
0
    def client_run(self):
        #try_connect = True
        while self.recv_try_connect:
            try:
                self.show_lock.acquire()
                self.window.text += 'try to connect with ' + str(
                    self.partner_address) + '\n'
                self.show_lock.release()
                #print('try to connect with :',self.partner_address)
                self.recv_server.connect(self.partner_address)
                self.recv_try_connect = False
                self.recv_connect = True

                #self.recv_file = self.recv_server.makefile('rb')
                self.show_lock.acquire()
                self.window.text += "get server....\n"
                self.show_lock.release()
            except:
                self.recv_server = socket.socket(socket.AF_INET,
                                                 socket.SOCK_STREAM)

        while self.recv_loop:
            self.recv_file = self.recv_server.makefile('rb')
            try:
                content_type = self.recv_file.readline()

                content_type = content_type.decode('utf-8')
                content_type = content_type.rstrip('\r\n')

                content_length = self.recv_file.readline()
                content_length = content_length.decode('utf-8')
                content_length = int(content_length.rstrip('\r\n'))

                data = self.recv_file.read(content_length)
                self.recv_file.close()
                data = self.parse_data(data, content_type)
            except:
                self.recv_file.close()

            try:
                if content_type == 'message':
                    self.show_lock.acquire()
                    self.window.text += (data + '\n')
                    self.show_lock.release()

                elif content_type == 'file':
                    file_size, times, filename = data

                    self.show_lock.acquire()
                    self.window.text += ('server send ' + filename + '\n')
                    self.show_lock.release()
                    filename = '/private/var/mobile/Containers/Shared/AppGroup/E728DF28-D52D-499B-8B9E-470DB2B87247/Pythonista3/Documents/inbox/' + filename
                    length = 0
                    with open(
                            filename, 'wb'
                    ) as fi:  #18.4.9 0:05 文件传输出现错误,无法读取足够长度的内容,未知错误出在何处,发送或者接受?
                        while True:
                            #data = self.recv_file.read(self.recv_size)
                            data = self.recv_server.recv(self.recv_size)
                            length += len(data)
                            fi.write(data)
                            self.get_bar.set_value(length / file_size)
                            if length >= file_size:
                                self.show_lock.acquire()
                                self.window.text += "file recv done\n"
                                self.show_lock.release()
                                break
                    console.open_in(filename)
            except:
                self.recv_server.close()
Beispiel #28
0
 def btn_OpenIn(self, sender):
     file = self.path + '/' + self.filename
     console.open_in(file)
Beispiel #29
0
 def tableview_did_select(self, tableview, section, row):
     # Called when the user selects a row
     key = self.lists[section][1][row][0]
     if key == "shellista-cd":
         # Go Here - Shellista
         nav.close()
         print("Launching Shellista...")
         try:
             from Shellista import Shell
         except ImportError as err:
             print("Failed to import Shellista: " + err.message)
             print("See note on Shellista integration at the top of filenav.py.")
             print("> logout")
             return
         shell = Shell()
         shell.prompt = "> "
         shell.onecmd("cd " + self.fi.path)
         print("> cd " + self.fi.path)
         shell.cmdloop()
     elif key == "ios-qlook":
         # Preview - Quick Look
         nav.close()
         time.sleep(1)  # ui thread will hang otherwise
         console.quicklook(self.fi.path)
     elif key == "pysta-edit":
         # Open in Editor - Pythonista
         open_path(self.fi.path)
         nav.close()
     elif key == "pysta-cpedit":
         # Copy & Open - Pythonista
         destdir = full_path(os.path.join(SCRIPT_ROOT, "temp"))
         if not os.path.exists(destdir):
             os.mkdir(destdir)
         destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(".")))
         shutil.copy(self.fi.path, destfile)
         editor.reload_files()
         open_path(destfile)
         nav.close()
     elif key == "pysta-cptxt":
         # Copy & Open as Text - Pythonista
         destdir = full_path(os.path.join(SCRIPT_ROOT, "temp"))
         if not os.path.exists(destdir):
             os.mkdir(destdir)
         destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(".") + ".txt"))
         shutil.copy(self.fi.path, destfile)
         editor.reload_files()
         open_path(destfile)
         nav.close()
     elif key == "console-printimg":
         # Show in Console - console
         console.show_image(self.fi.path)
     elif key == "sound-playsound":
         # Play Sound - sound
         spath = rel_to_app(self.fi.path.rsplit(".", 1)[0])
         sound.load_effect(spath)
         sound.play_effect(spath)
     elif key == "webbrowser-open":
         # Open Website - webbrowser
         webbrowser.open("file://" + self.fi.path)
         nav.close()
     elif key == "ios-openin":
         # Open In - External Apps
         if console.open_in(self.fi.path):
             nav.close()
         else:
             console.hud_alert("Failed to Open", "error")
Beispiel #30
0
def main():
	tempdir = tempfile.mkdtemp(prefix="ddbtoxml_")
	comependiumxml = os.path.join(tempdir, "compendium.xml")
	playersdir = os.path.join(tempdir, "players")
	os.mkdir(playersdir)
	with open(comependiumxml,mode='a',encoding='utf-8') as comependium:
		comependium.write("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<compendium>\n")
	args = sys.argv
	if len(args) == 2 and args[1].startswith("--campaign"):
		regex = re.compile("<a[^>]*href=\"(/profile/.*/[0-9]+)\"[^>]*class=\"ddb-campaigns-character-card-header-upper-details-link\"[^>]*>")
		if args[1] == "--campaign":
			readin = sys.stdin
		elif os.path.isfile(args[1][11:]):
			readin = open(args[1][11:],'r')
		else:
			readin = base64.b64decode(args[1][11:]).decode("utf-8").splitlines()
		args = [sys.argv[0]]
		for line in readin:
			m = regex.search(line)
			if m:
				characterurl = m.group(1)
				if not characterurl.startswith("https://www.dndbeyond.com/"):
					args.append("https://www.dndbeyond.com"+characterurl)
				else:
					args.append(characterurl)
		try:
			readin.close()
		except:
			pass
	characters = []
	for i in range(len(args)):
		if args[i] == __file__:
			continue
		if os.path.isfile(args[i]):
				with open(args[i]) as infile:
					try:
						json.load(infile)
						characters.append(args[i])
					except JSONDecodeError:
						found = findURLS(infile)
						characters.extend(found)
		else:
			characters.append(args[i])
	if len(characters) == 0:
		characters.append("-")
	for i in range(len(characters)):
		if  characters[i] == '-' or os.path.isfile(characters[i]):
			if os.path.isfile(characters[i]):
				with open(characters[i],"r") as jsonfile:
					charjson = json.loads(jsonfile.read())
			else:
				charjson = json.loads(sys.stdin.read())
			if "character" in charjson:
				character = charjson["character"]
			else:
				character = charjson
		else:
			character = getJSON(characters[i])
		if character is not None:
			xmloutput = genXML(character)
			with open(comependiumxml,mode='a',encoding='utf-8') as comependium:
				comependium.write(xmloutput)
			if character["avatarUrl"] != "":
				local_filename = os.path.join(playersdir,character["avatarUrl"].split('/')[-1])
				r = requests.get(character["avatarUrl"], stream=True)
				if r.status_code == 200:
					with open(local_filename, 'wb') as f:
						for chunk in r.iter_content(chunk_size=8192):
							f.write(chunk)
	with open(comependiumxml,mode='a',encoding='utf-8') as comependium:
		comependium.write("</compendium>")

	zipfile = shutil.make_archive("ddbxml","zip",tempdir)
	os.rename(zipfile,os.path.join(os.getcwd(),"ddbxml.compendium"))
	zipfile = os.path.join(os.getcwd(),"ddbxml.compendium")
	try:
		import console
		console.open_in (zipfile)
	except ImportError:
		print(zipfile)

	try:
		shutil.rmtree(tempdir)
	except:
		print("Warning: error trying to delete the temporal directory:", file=sys.stderr)
		print(traceback.format_exc(), file=sys.stderr)
Beispiel #31
0
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):
    for file in filter(lambda x: re.match(pattern, x), files):
        plist = readPlist(os.path.join(root, file))
        plist['$objects'][1]['paperIndex'] = 12  # set white bg
        writePlist(plist, os.path.join(root, file))

shutil.make_archive(newFileName, 'zip', extractedPath)
shutil.move(newFileName + '.zip', newFileName)
console.open_in(newFileName)
# --------------------
    return [asset.get_image() for asset in album.assets]


if __name__ == '__main__':
    handler = Selection_Handler()

    handler.make_selection()

    #here we make a 2-staged for loop making a tempfile for each individual image and adding each to the pdf file we will be sharing
    for album in handler.albums:
        pdf_writer = PdfFileWriter()
        for image in get_images(album):
            file = NamedTemporaryFile('wb')
            image.save(file.file, 'PDF')
            pdf_file_data = PdfFileReader(file.name)
            pdf_writer.addPage(pdf_file_data.getPage(0))
        file_name = album.title + '.pdf'
        pdf_writer.write(open(file_name, 'wb'))

        #here we will be able to share the pdf with any app/person that would be able to recieve them.
        console.open_in(file_name)

        #since I have made the program in such a way that the PDF is named after the album that was used to create it I have to manually remove the file since you can't directly name a temporary filew
        os.remove(file_name)

        title = 'Delete Pictures?'
        choices = ['Yes', 'No']
        delete_pics = dialogs.list_dialog(title=title, items=choices)
        if delete_pics == 'Yes':
            photos.batch_delete(album.assets)
Beispiel #33
0
def share(sender):
    open_in(share_item)
def get_and_tar_images():
    images_data = make_images_data(appex.get_images_data())
    tarfilename = str(datetime.datetime.now()) + ".tar.gz"
    outfile = tar_images(images_data, tarfilename)
    console.open_in(outfile)
    os.remove(outfile)
# present the view to the user
view.present('sheet')
# get download link from clipboard OR sys.argv
fileUrl = clipboard.get() 
if len(sys.argv)>1:
	fileUrl = sys.argv[1]

# download file in /Downloads folder with original file name
fileName="Downloads/"+os.path.basename(fileUrl)

# display filename to the user
label1.text = "Downloading "+os.path.basename(fileUrl)+"..."

# download the file and call dlProgress for each block downloaded
urllib.urlretrieve(fileUrl, fileName, reporthook=dlProgress)

# tell the user that the download is completed and enabled button(s)
label2.text = "Dowload completed!"
openButton.enabled = True 
openButton.border_color = openButton.tint_color

# wait for the user to perform an action
view.wait_modal()

# if the user has cloased the view with "open in..." than open the file 
# in another app and remove it 
if(openFile):
	console.open_in(fileName)
	os.remove(fileName)
import console,editor

console.open_in(editor.get_path())
Beispiel #37
0
# coding: utf-8

# https://forum.omz-software.com/topic/2719/file-sharing-and-storage-to-onedrive/5

It's relatively easy to get this functionality back. Here's how:

Create a new script, and call it something like "Open in"
Paste the following code:
import console, editor
console.open_in(editor.get_path())
Tap the "wrench" icon
Tap Edit inside the "wrench" menu, then the (+) button that appears
Optionally select a nice icon and color for your action
Tap Done
A "Copy to OneDrive" option should appear in the menu that pops up when you select the new editor action you created.

Beispiel #38
0
 def btn_OpenIn(self, sender):
     file = self.path + '/' + self.filename
     console.open_in(file)
Beispiel #39
0
 def _open_in(self):
     console.open_in(self.filename)
 def share_action(self, sender):
     file_name = self['file name'].text
     console.open_in(file_name)