Exemple #1
0
 def row_selected(self, ds):
     note = self.notes[ds.selected_row]
     #print note
     console.show_activity('Getting note...')
     note_detail = pb.get_note_details(note.get('id'))
     console.hide_activity()
     note_view = NoteView(note_detail)
Exemple #2
0
def wordnik(word: str):
    """Return the WordNik definition of a word.

    If can't connect to WordNik API, then return opted() instead.
    """
    try:
        console.show_activity()
        defs = wn_api.getDefinitions(word, limit=5) or []
        suggs = wn_api.getWord(word, includeSuggestions=True)
        console.hide_activity()
        suggestions = suggs.suggestions or []
        definitions = [{
            'text': d.text,
            'partOfSpeech': d.partOfSpeech
        } for d in defs]
        if defs:
            attribution = defs[0].attributionText
            attribution_url = defs[0].attributionUrl
        else:
            attribution = ''
            attribution_url = ''
        data = {
            'definitions': definitions,
            'attribution': attribution,
            'attributionUrl': attribution_url,
            'suggestions': suggestions,
            'messages': []
        }
    except URLError:
        data = opted(word)
        data['messages'].append('''WordRoom couldn't connect to WordNik.com to
                                retrieve online definitions.''')
    return data
def main():
    console.alert(
        'Shortcut Generator',
        "This script adds a shortcut icon to running the MetreiOS app on your homepage. Your default browser MUST be Safari",
        'Continue')
    # Fetch config json
    root_dir = os.path.abspath(os.path.expanduser('~Documents/' + 'MetreiOS'))
    with open('../metre_ios_install_config.json') as f:
        configs = json.load(f)

    currentversion = configs['git_repo']
    label = 'MetreiOS'
    url = 'pythonista3://MetreiOS' + '/' + currentversion + '/MainMetre.py?action=run'

    img = Image.open(
        BytesIO(
            urllib.request.urlopen(
                "https://drive.google.com/uc?export=view&id=1--lLdK8dHtBOBwsZyFu0g3TRIjhA_0XK"
            ).read()))

    console.show_activity('Preparing Configuration profile...')
    data_buffer = BytesIO()
    img.save(data_buffer, 'PNG')
    icon_data = data_buffer.getvalue()
    unique_id = uuid.uuid4().urn[9:].upper()
    config = {
        'PayloadContent': [{
            'FullScreen': True,
            'Icon': plistlib.Data(icon_data),
            'IsRemovable': True,
            'Label': label,
            'PayloadDescription': 'Configures Web Clip',
            'PayloadDisplayName': label,
            'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id,
            'PayloadOrganization': 'omz:software',
            'PayloadType': 'com.apple.webClip.managed',
            'PayloadUUID': unique_id,
            'PayloadVersion': 1,
            'Precomposed': True,
            'URL': url
        }],
        'PayloadDescription':
        label,
        'PayloadDisplayName':
        label + ' (Shortcut)',
        'PayloadIdentifier':
        'com.omz-software.shortcut.' + unique_id,
        'PayloadOrganization':
        'omz:software',
        'PayloadRemovalDisallowed':
        False,
        'PayloadType':
        'Configuration',
        'PayloadUUID':
        unique_id,
        'PayloadVersion':
        1
    }
    console.hide_activity()
    run_server(config)
def get_location():
    import location
    console.show_activity()
    location.start_updates()
    ldata = location.get_location()
    city = location.reverse_geocode(ldata)[0].get('City')
    return city
def main():
	console.alert('Shortcut Generator', 'This script adds a "Webclip" shortcut to your homescreen. The shortcut can be used to open a web page in full-screen mode, or to launch a custom URL (e.g. a third-party app). You\'ll be asked for a title, a URL, and an icon (from your camera roll).', 'Continue')
	label = console.input_alert('Shortcut Title', 'Please enter a short title for the homescreen icon.', '', 'Continue')
	if not label:
		return
	url = console.input_alert('Shortcut URL', 'Please enter the full URL that the shortcut should launch.', '', 'Continue')
	if not url:
		return
	icon = photos.pick_image()
	if not icon:
		return
	console.show_activity('Preparing Configuration profile...')
	data_buffer = BytesIO()
	icon.save(data_buffer, 'PNG')
	icon_data = data_buffer.getvalue()
	unique_id = uuid.uuid4().urn[9:].upper()
	config = {'PayloadContent': [{'FullScreen': True,
            'Icon': plistlib.Data(icon_data), 'IsRemovable': True,
            'Label': label, 'PayloadDescription': 'Configures Web Clip', 
            'PayloadDisplayName': label,
            'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 
            'PayloadOrganization': 'omz:software', 
            'PayloadType': 'com.apple.webClip.managed',
            'PayloadUUID': unique_id, 'PayloadVersion': 1,
            'Precomposed': True, 'URL': url}], 
            'PayloadDescription': label,
            'PayloadDisplayName': label + ' (Shortcut)', 
            'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id,
            'PayloadOrganization': 'omz:software', 
            'PayloadRemovalDisallowed': False, 'PayloadType': 
            'Configuration', 'PayloadUUID': unique_id, 'PayloadVersion': 1}
	console.hide_activity()
	run_server(config)
Exemple #6
0
    def scan(self):
        self.result = []
        _gate_way = '.'.join(self.current_ip.split('.')[:3])
        # gate_way = _gate_way+'.1'  # pyflakes says this is not used
        if self.alert:
            console.show_activity('Scanning.....')
        for x in range(1, 256):
            ip = '{}.{}'.format(_gate_way, x)
            self.thread_limit.acquire()
            threading.Thread(target=self.pscan,
                             args=(ip, self.port),
                             name='PortScanner').start()

        thread_list = [
            x for x in threading.enumerate() if x.name == 'PortScanner'
        ]
        for _ in thread_list:
            _.join()
        if self.alert:
            if self.result:
                console.hud_alert(' '.join(self.result), 'success', 1)
            else:
                console.hud_alert('Not found', 'error', 1)
            console.hide_activity()
        return self.result
def git_download(url):
    base = 'https://codeload.github.com'
    archive = 'zip'
    m = extract_git_id(url)
    if m:
        g = m.groupdict()
        if not g['branch']:
            g['branch'] = 'master'

        u = '/'.join((base, g['user'], g['repo'], archive, g['branch']))
        #print u
        #console.hud_alert('Downloading Github repo ...' + u)
        console.hud_alert('Starting, please wait.')
        console.show_activity()
        try:
            with tempfile.NamedTemporaryFile(mode='w+b', suffix='.zip') as f:
                console.hud_alert('Downloading the zip.')
                urllib.urlretrieve(u,
                                   f.name,
                                   reporthook=functools.partial(dlProgress, u))

                z = zipfile.ZipFile(f)
                githubpath = os.path.expanduser(
                    '~/Documents/Downloaded from Github/')
                if not os.path.exists(githubpath):
                    os.mkdir(githubpath)
                z.extractall(path=githubpath)
                console.hud_alert('Extracting zip.')
                print z.namelist()
        except:
            print('git url did not return zip file')
        console.hud_alert('Files saved in "Downloaded from Github" directory.')
        console.hud_alert('All done.')
    else:
        print('could not determine repo url from clipboard or argv')
    def __init__(self):
        console.show_activity()

        # edit to make your own #
        self.domain_name = ""
        self.username = ""
        self.port = 22
        self.key_file = ""  # ssh key file
        self.web_root = ""  # your web servers root folder where you'll want to store your uploaded photos
        #                       #

        # dates
        self.year = str(time.strftime("%Y"))
        self.month = str(time.strftime("%m"))
        self.day = str(time.strftime("%d"))
        self.hour_min_sec = str(time.strftime("%H%M%S"))

        # variable setup
        self.file_count = 0
        self.link_list = []
        self.pkey = paramiko.RSAKey.from_private_key_file(self.key_file)
        self.file_name = "{0}-{1}@.jpg".format(self.day, self.hour_min_sec)  # the @ gets replaced with count
        self.remote_path = os.path.join(self.web_root, self.year, self.month)

        self.get_photo()
        self.architect()
        self.upload_logic()
        self.clippy()
Exemple #9
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 get_location_ios():
    try:
        console.show_activity()
        location.start_updates()
        coordinates = location.get_location()
        location.stop_updates()
        console.hide_activity()
        results = location.reverse_geocode(coordinates)

        if not results:
            results = [{'City': 'N/A', 'Country': 'N/A'}]

        dms_lat, dms_lng = dd2dms(coordinates['latitude'],
                                  coordinates['longitude'])

        return SimpleNamespace(**{
            'latitude': coordinates['latitude'],
            'longitude': coordinates['longitude'],
            'city': results[0]['City'],
            'country': results[0]['Country'],
            'altitude': float(coordinates['altitude']),
            'dms_latitude': dms_lat,
            'dms_longitude': dms_lng,
        })
    except Exception as e:
        print(e.with_traceback)
        print('Não foi possível obter a localização atual.'
              '\nA utilizar predefinição...\n')
        console.hide_activity()
        return None
Exemple #11
0
    def populate_table(self):
        console.show_activity()
        if callable(self.items):
            items = self.items()
        else:
            items = self.items

        dropdownlist = []
        self.listsource.items = dropdownlist
        self.tbl.reload()
        for item in items:

            def ani():
                dropdownlist.append(item)
                offset = self.tbl.content_offset
                self.listsource.items = dropdownlist
                self.tbl.reload()
                try:
                    self.listsource.selected_row = self.listsource.items.index(
                        self.textfield.text)
                    self.listsource.tableview.selected_row = (
                        0, self.listsource.selected_row)
                except ValueError:
                    #self.listsource.selected_row=-1
                    self.listsource.tableview.selected_row = (0, -1)
                self.tbl.content_offset = tuple(offset)

            ui.animate(ani, 0.1)
        console.hide_activity()
Exemple #12
0
 def tableview_did_select(self, tableview, section, row):
     # Called when the user selects a row
     if not tableview.editing:
         fi = self.lists[section][row]
         if section == 0:
             console.show_activity()
             nav.push_view(make_file_list(fi))
             console.hide_activity()
         elif section == 1:
             filetype = fi.fileinfo.filetype
             if fi.fileinfo.file_ext in ("htm", "html"):
                 webbrowser.open("file://" + fi.path)
                 nav.close()
             elif filetype in ("code", "code_tags", "text"):
                 open_path(fi.path)
                 nav.close()
             elif filetype == "audio":
                 spath = rel_to_app(fi.path.rsplit(".", 1)[0])
                 sound.load_effect(spath)
                 sound.play_effect(spath)
             elif filetype == "image":
                 console.show_image(fi.path)
             else:
                 console.quicklook(fi.path)
                 nav.close()
Exemple #13
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     if not tableview.editing:
         console.show_activity()
         self.app.push_view(self.app.make_file_list(FileItem(self.entries[row][0])))
         console.hide_activity()
Exemple #14
0
def main():
    ### CHANGE THESE VALUES:
    to = console.input_alert('Send Email To', 'Enter an email address below')
    subject = console.input_alert('Subject',
                                  'Enter the subject of the email below')
    gmail_pwd = keychain.get_password('Gmail', '*****@*****.**')
    gmail_user = '******'

    #Load a sample image, modify as needed:
    image = clipboard.get_image()

    print 'Connecting...'
    smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
    console.show_activity()
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(gmail_user, gmail_pwd)

    print 'Preparing message...'
    outer = MIMEMultipart()
    outer['Subject'] = subject
    outer['To'] = to
    outer['From'] = gmail_user
    outer.preamble = 'You will not see this in a MIME-aware email reader.\n'
    attachment = get_attachment(image)
    outer.attach(attachment)
    composed = outer.as_string()

    print 'Sending...'
    smtpserver.sendmail(gmail_user, to, composed)
    smtpserver.close()
    console.hide_activity()
    sound.play_effect('Bleep')
    print 'Done.'
Exemple #15
0
def load_comic(view, num):
    if num == 404:
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num/latest
        view.comic = None
        objc_util.ObjCInstance(view.navigation_view).navigationController().topViewController().title = objc_util.ns('404 - Not Found')
        return 
    console.show_activity()
    comic = get_info(num)
    if comic:
        if num in faves:
            view['fav'].image = ui.Image('iob:ios7_heart_32')
        else:
            view['fav'].image = ui.Image('iob:ios7_heart_outline_32')
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num/latest
        view.comic = comic
        
        #view['comic'].image = get_comic(view.comic['img'])
        view['wv'].load_url(get_comic(view.comic['img']))
        objc_util.ObjCInstance(view.navigation_view).navigationController().topViewController().title = objc_util.ns(view.comic['title'])
    
    console.hide_activity()
Exemple #16
0
 def populate_table(self):
     console.show_activity()
     if callable(self.items):
         items=self.items()
     else:
         items=self.items
         
     dropdownlist=[]
     self.listsource.items=dropdownlist
     self.tbl.reload()        
     for item in items:
       def ani():
         dropdownlist.append(item)
         offset=self.tbl.content_offset
         self.listsource.items=dropdownlist
         self.tbl.reload()
         try:
             self.listsource.selected_row = self.listsource.items.index(self.textfield.text)
             self.listsource.tableview.selected_row = (0,self.listsource.selected_row)
         except ValueError:
             #self.listsource.selected_row=-1
             self.listsource.tableview.selected_row=(0,-1)
         self.tbl.content_offset=tuple(offset)
       ui.animate(ani,0.1)
     console.hide_activity()
Exemple #17
0
    def __init__(self):
        console.show_activity()

        # edit to make your own #
        self.domain_name = ''
        self.username = ''
        self.port = 22
        self.key_file = ''  # ssh key file
        self.web_root = ''  # your web servers root folder where you'll want to store your uploaded photos
        #                       #

        # dates
        self.year = str(time.strftime("%Y"))
        self.month = str(time.strftime("%m"))
        self.day = str(time.strftime("%d"))
        self.hour_min_sec = str(time.strftime("%H%M%S"))

        # variable setup
        self.file_count = 0
        self.link_list = []
        self.pkey = paramiko.RSAKey.from_private_key_file(self.key_file)
        self.file_name = '{0}-{1}@.jpg'.format(
            self.day, self.hour_min_sec)  # the @ gets replaced with count
        self.remote_path = os.path.join(self.web_root, self.year, self.month)

        self.get_photo()
        self.architect()
        self.upload_logic()
        self.clippy()
  def query(self, sender):
    global imdb_id
    
    if not api_key:
      console.hud_alert('An api key is required to continue.', 'error', 3)
      sys.exit()
    
    # Make requests_cache optional
    try:
      import requests_cache
      requests_cache.install_cache(cache_name = 'tmdb_cache', backend = 'sqlite', expire_after = 300)
      #requests_cache.core.remove_expired_responses()
    except ImportError:
      console.hud_alert('No api caching available')
    
    console.show_activity()
    console.hud_alert('Searching for {}...'.format(self.tf1.text))
    
    # Clear keyboard from screen
    self.tf1.end_editing()
    self.tf2.end_editing()

    if self.sc.selected_index == 0:
      # Searching movie-tv title
      my_title = self.tf1.text
      my_year = self.tf2.text if self.tf2.text else ''
      
      # Error checking
      try:
        # Query api for titles
        the_titles = query_titles(my_title, my_year)
      except:
        console.hide_activity()
        console.hud_alert('Search Error', 'error', 3)
        sys.exit()
      
      # If query yields results...
      if len(the_titles) != 0:
        self.load_titles_tableview(the_titles)
      else:
        console.hide_activity()
        console.hud_alert('Nothing Returned', 'error', 3)
        sys.exit()
    else:
      # Searching for a actor-actress name
      name = self.tf1.text
      name = name.strip()
      
      try:
        bio, movies, tv, movie_crew, tv_crew = query_person(name)
      except:
        console.hide_activity()
        console.hud_alert('Nothing Returned', 'error', 3)
        sys.exit()

      results = person_info(bio, movies, tv, movie_crew, tv_crew)
      
      imdb_id = bio['imdb_id']
      self.load_textview(results)
    console.hide_activity()
Exemple #19
0
 def checkForUpdate(self):
     try:
         console.show_activity('Checking for update...')
         response = requests.get(self.latestReleaseUrl)
         data = json.loads(response.text)
         rel = release(data)
         console.hide_activity()
         if rel.prerelease == False:
             if LooseVersion(self.currentVersion) < LooseVersion(
                     rel.tag_name.replace('v', '')):
                 ret = console.alert(
                     'Update available',
                     rel.tag_name +
                     ' is available, would you like to install it. \n\n Details: '
                     + rel.body.replace('\r\n', '\n'),
                     hide_cancel_button=True,
                     button1='No',
                     button2='Yes')
                 if ret == 2:
                     self.install(rel)
             else:
                 console.alert('No update available',
                               'v' + self.currentVersion +
                               ' is the current version.',
                               hide_cancel_button=True,
                               button1='Ok')
     except requests.exceptions.ConnectionError as e:
         console.alert('Check your internet connection',
                       'Unable to check for update.',
                       hide_cancel_button=True,
                       button1='Ok')
Exemple #20
0
 def url_to_local_file(in_url, in_file_name):
     short_name = in_file_name.rpartition('/')[2] or in_file_name
     console.show_activity('Downloading: ' + short_name)
     time.sleep(1)
     with open(in_file_name, 'w') as out_file:
         out_file.write(requests.get(in_url).content)
     console.hide_activity()
Exemple #21
0
 def reinstallCurrentVersion(self):
     if not os.path.exists('.version'):
         console.alert('Install error',
                       'Unable to determine current version.',
                       hide_cancel_button=True,
                       button1='Ok')
     else:
         console.show_activity('Checking for v' + self.currentVersion +
                               ' install files...')
         releases = self.getAllReleases(getAll=True)
         try:
             console.hide_activity()
             release = releases[self.currentVersion]
             self.install(release)
         except KeyError as e:
             console.hide_activity()
             res = console.alert(
                 'Install error',
                 'Unable to find v' + self.currentVersion +
                 ' install files. Would you like to install the latest version?',
                 hide_cancel_button=True,
                 button1='No',
                 button2='Yes')
             if res == 2:
                 self.checkForUpdate()
Exemple #22
0
def gh_create(args):
    '''Usage: gh create [options] <name> 

	Options:
	-h, --help             This message
	-s <desc>, --description <desc>		Repo description
	-h <url>, --homepage <url>				Homepage url
	-p, --private          private
	-i, --has_issues       has issues
	-w, --has_wiki  			 has wiki
	-d, --has_downloads    has downloads
	-a, --auto_init     		create readme and first commit
	-g <ign>, --gitignore_template <ign>  create gitignore using string
	
	
	'''
    kwargs = {
        key[2:]: value
        for key, value in args.items() if key.startswith('--') and value
    }
    console.show_activity()
    try:
        g, user = setup_gh()
        r = user.create_repo(args['<name>'], **kwargs)
        print('Created %s' % r.html_url)
    finally:
        console.hide_activity()
Exemple #23
0
 def __init__(self):
     console.show_activity('Loading...')
     self.docsetFolder = 'Docsets'
     self.setup()
     self.dbmanager = DBManager.DBManager()
     self.theme_manager = ThemeManager.ThemeManager('Themes')
     self.docset_manager = DocsetManager.DocsetManager(
         'Images/icons', 'Images/types', ServerManager.ServerManager())
     self.cheatsheet_manager = CheatsheetManager.CheatsheetManager(
         ServerManager.ServerManager(), 'Images/icons', 'Images/types')
     self.usercontributed_manager = UserContributedManager.UserContributedManager(
         ServerManager.ServerManager(), 'Images/icons', 'Images/types')
     self.stackoverflow_manager = StackOverflowManager.StackOverflowManager(
         ServerManager.ServerManager(), 'Images/icons', 'Images/types')
     self.webSearchManager = WebSearchManager.WebSearchManager(
         'Images/types')
     self.main_view = self.setup_main_view()
     self.navigation_view = self.setup_navigation_view()
     self.docset_management_view = self.setup_docset_management_view()
     self.cheatsheet_management_view = self.setup_cheatsheetmanagement_view(
     )
     self.usercontributed_management_view = self.setup_usercontributedmanagement_view(
     )
     self.stackoverflow_management_view = self.setup_stackoverflowmanagement_view(
     )
     self.settings_view = self.setup_settings_view()
     self.docsetView = self.setup_docset_view()
     self.docsetIndexView = self.setup_docsetindex_view()
     self.docsetWebView = self.setup_docsetweb_view()
     UISearchControllerWrapper.Theme_manager = self.theme_manager
     console.hide_activity()
Exemple #24
0
def get_folders():
	try:
		console.show_activity()
		ftp.cwd(txtRemotePath)
		data = []
		ftp.retrlines('MLSD', data.append)
		dir = []
		for line in data:
			facts_found, _, name = line.rstrip('CRLF').partition(' ')
			entry = {}
			for fact in facts_found[:-1].split(";"):
				key, _, value = fact.partition("=")
				entry[key.lower()] = value
			if entry['type'] == 'dir':
				dir.append(name)

		count = 0
		folders = []
		for eachDir in dir:
			folder = eachDir.partition("-")[2]
			folders.append([count,eachDir,folder])
			count +=1
		
		return folders

	except Exception as e:
		print("Unable to get folder listing")
Exemple #25
0
def _download_release_zip(release):
    _info('Downloading ZIP...')

    name = release['name']
    path = os.path.join(_TMP_DIR, '{}-{}.zip'.format(_REPOSITORY, name))

    _cleanup_paths.append(path)

    response = requests.get(release['zipball_url'], stream=True)

    console.show_activity()
    if not response.ok:
        console.hide_activity()
        _terminate('GitHub ZIP ball request failed with {}'.format(
            response.status_code))

    try:
        with open(path, 'wb') as output:
            for data in response.iter_content(8192):
                output.write(data)
    except Exception as e:
        console.hide_activity()
        _error(e)
        _terminate('Failed to save ZIP file')

    console.hide_activity()
    return path
Exemple #26
0
def exporti(sender):
	console.show_activity()
	ishare['colorbox'].end_editing()
	
	color = ishare['colorbox'].text
	
	if color != '':
		if not color.startswith('#'):
			color = '#'+color
		if len(color) != 7:
			raise ValueError('Must be hexidecimal')
		im = RenderASCII(out, bgcolor=color)
		i.image = pil_to_ui(im)
		rootView.background_color = color
		view2.draw()
		
		
	else:
		im = outim
	
	
	b = BytesIO()
	im.save(b, 'PNG')
	img_data = b.getvalue()
	
	console.hide_activity()
	
	_dialogs.share_image_data(img_data)
Exemple #27
0
def main(im):
    # Create the ASCII
    global out
    console.show_activity("Processing...")
    out = image2ASCII(im)
    console.hide_activity()
    # Render onto an image
    global outim
    console.show_activity("Rendering...")
    outim = RenderASCII(out)
    console.hide_activity()

    rootView.background_color = 0.92

    global i
    i = ui.ImageView()

    i.frame = (0, 10, 1024, 768)
    i.content_mode = ui.CONTENT_SCALE_ASPECT_FIT

    i.image = pil_to_ui(outim)
    rootView.add_subview(i)

    close.bring_to_front()

    view2.remove_subview(ishare)
    view2.x = 247
    view2.y = -285
    rootView.add_subview(view2)

    time.sleep(1.5)
    ui.animate(pulldown, 1)
Exemple #28
0
def load_comic(view, num):
    if num == 404:
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num / latest
        view.comic = None
        objc_util.ObjCInstance(view.navigation_view).navigationController(
        ).topViewController().title = objc_util.ns('404 - Not Found')
        return
    console.show_activity()
    comic = get_info(num)
    if comic:
        if num in faves:
            view['fav'].image = ui.Image('iob:ios7_heart_32')
        else:
            view['fav'].image = ui.Image('iob:ios7_heart_outline_32')
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num / latest
        view.comic = comic

        #view['comic'].image = get_comic(view.comic['img'])
        view['wv'].load_url(get_comic(view.comic['img']))
        objc_util.ObjCInstance(view.navigation_view).navigationController(
        ).topViewController().title = objc_util.ns(view.comic['title'])

    console.hide_activity()
Exemple #29
0
 def url_to_local_file(in_url, in_file_name):
     short_name = in_file_name.rpartition('/')[2] or in_file_name
     console.show_activity('Downloading: ' + short_name)
     time.sleep(1)
     with open(in_file_name, 'w') as out_file:
         out_file.write(requests.get(in_url).content)
     console.hide_activity()
Exemple #30
0
 def tableview_did_select(self, tableview, section, row):
     # Called when the user selects a row
     if not tableview.editing:
         fi = self.lists[section][row]
         if section == 0:
             console.show_activity()
             nav.push_view(make_file_list(fi))
             console.hide_activity()
         elif section == 1:
             filetype = fi.fileinfo.filetype
             if fi.fileinfo.file_ext in ("htm", "html"):
                 webbrowser.open("file://" + fi.path)
                 nav.close()
             elif filetype in ("code", "code_tags", "text"):
                 open_path(fi.path)
                 nav.close()
             elif filetype == "audio":
                 spath = rel_to_app(fi.path.rsplit(".", 1)[0])
                 sound.load_effect(spath)
                 sound.play_effect(spath)
             elif filetype == "image":
                 console.show_image(fi.path)
             else:
                 console.quicklook(fi.path)
                 nav.close()
Exemple #31
0
def get_location():
    import location
    console.show_activity()
    location.start_updates()
    ldata = location.get_location()
    city = location.reverse_geocode(ldata)[0].get('City')
    return city
Exemple #32
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     if not tableview.editing:
         fi = self.lists[section][row]
         if section == 0:
             console.show_activity("Loading file list...")
             self.app.push_view(self.app.make_file_list(fi))
             console.hide_activity()
         elif section == 1:
             group = fi.constants.group
             if fi.constants.ext in (u"htm", u"html"):
                 webbrowser.open(u"file://" + fi.path)
                 self.app.close()
             elif group in ("code", "code_tags", "text"):
                 open_path(fi.path)
                 self.app.close()
             elif group == "audio":
                 spath = rel_to_app(fi.path.rsplit(u".", 1)[0])
                 sound.load_effect(spath)
                 sound.play_effect(spath)
             elif group == "image":
                 console.show_image(fi.path)
             else:
                 self.app.close()
                 time.sleep(ANIM_DELAY)
                 console.quicklook(fi.path)
Exemple #33
0
def start_gui(check_wakeup):
    global logger

    console.show_activity("Scanning repositories...")
    if check_wakeup:
        logger.info("Checking if wakeup is required...")

    sync_tools = []
    configs = sync.find_sync_configs()
    working_copy_configs = []
    working_copy_configs.extend(filter(lambda config: config.repository.working_copy_wakeup, configs))
    working_copy_active = ENABLE_WORKING_COPY_SUPPORT and len(working_copy_configs) > 0

    if working_copy_active and check_wakeup:
        wakeup_webdav_server(working_copy_configs[0])
        logger.info("Exiting to await callback from Working Copy...")
        console.hide_activity()
        return

    logger.info("Starting GUI...")

    for config in configs:
        logger.info("Found configuration '%s'..." % config.repository.name)

        try:
            sync_tool = sync.SyncTool(config)
            sync_tools.append(sync_tool)

        except Exception as e:
            logger.exception("Error '%s' while processing configuration '%s'" % (str(e), config.repository.name))

    selector = sync_selector.SyncSelector()
    console.hide_activity()
    selector.select(sync_tools, working_copy_active=working_copy_active)
Exemple #34
0
def get_folders():
	try:
		console.show_activity()
		ftp.cwd(txtRemotePath)
		data = []
		ftp.retrlines('MLSD', data.append)
		dir = []
		for line in data:
			facts_found, _, name = line.rstrip('CRLF').partition(' ')
			entry = {}
			for fact in facts_found[:-1].split(";"):
				key, _, value = fact.partition("=")
				entry[key.lower()] = value
			if entry['type'] == 'dir':
				dir.append(name)

		count = 0
		folders = []
		for eachDir in dir:
			folder = eachDir.partition("-")[2]
			folders.append([count,eachDir,folder])
			count +=1
		
		return folders

	except Exception as e:
		print "Unable to get folder listing"
Exemple #35
0
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
Exemple #36
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()
Exemple #37
0
    def install(self, release):
        console.show_activity('Installing ' + release.tag_name)
        request = requests.get(release.zipball_url)
        file = zipfile.ZipFile(BytesIO(request.content))
        toRemove = file.namelist()[0]

        filelist = [
            f for f in os.listdir('.') if not f in [
                'Docsets', '.wcsync', '.themesConfig', '.migrations.db',
                '.settings'
            ]
        ]
        for f in filelist:
            if os.path.isdir(f):
                shutil.rmtree(f)
            else:
                os.remove(f)
        file.extractall()
        for filename in os.listdir(toRemove):
            shutil.move(os.path.join(toRemove, filename), filename)
        shutil.rmtree(toRemove)
        file.close()

        f = open('.version', 'w')
        f.write(release.tag_name.replace('v', ''))
        f.close()
        console.hide_activity()
        console.alert('Installed',
                      release.tag_name +
                      ' installed, please restart Pythonista',
                      hide_cancel_button=True,
                      button1='Ok')
Exemple #38
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     if not tableview.editing:
         fi = self.lists[section][row]
         if section == 0:
             console.show_activity()
             self.app.push_view(self.app.make_file_list(fi))
             console.hide_activity()
         elif section == 1:
             group = fi.constants.group
             if fi.constants.ext in (u"htm", u"html"):
                 webbrowser.open(u"file://" + fi.path)
                 self.app.close()
             elif group in ("code", "code_tags", "text"):
                 open_path(fi.path)
                 self.app.close()
             elif group == "audio":
                 spath = rel_to_app(fi.path.rsplit(u".", 1)[0])
                 sound.load_effect(spath)
                 sound.play_effect(spath)
             elif group == "image":
                 console.show_image(fi.path)
             else:
                 self.app.close()
                 time.sleep(ANIM_DELAY)
                 console.quicklook(fi.path)
def main():
    console.alert(
        'Shortcut Generator',
        'This script adds a "Webclip" shortcut to your homescreen. The shortcut can be used to open a web page in full-screen mode, or to launch a custom URL (e.g. a third-party app). You\'ll be asked for a title, a URL, and an icon (from your camera roll).',
        'Continue')
    label = console.input_alert(
        'Shortcut Title',
        'Please enter a short title for the homescreen icon.', '', 'Continue')
    if not label:
        return
    url = console.input_alert(
        'Shortcut URL',
        'Please enter the full URL that the shortcut should launch.', '',
        'Continue')
    if not url:
        return
    icon = photos.pick_image()
    if not icon:
        return
    console.show_activity('Preparing Configuration profile...')
    data_buffer = BytesIO()
    icon.save(data_buffer, 'PNG')
    icon_data = data_buffer.getvalue()
    unique_id = uuid.uuid4().urn[9:].upper()
    config = {
        'PayloadContent': [{
            'FullScreen': True,
            'Icon': plistlib.Data(icon_data),
            'IsRemovable': True,
            'Label': label,
            'PayloadDescription': 'Configures Web Clip',
            'PayloadDisplayName': label,
            'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id,
            'PayloadOrganization': 'omz:software',
            'PayloadType': 'com.apple.webClip.managed',
            'PayloadUUID': unique_id,
            'PayloadVersion': 1,
            'Precomposed': True,
            'URL': url
        }],
        'PayloadDescription':
        label,
        'PayloadDisplayName':
        label + ' (Shortcut)',
        'PayloadIdentifier':
        'com.omz-software.shortcut.' + unique_id,
        'PayloadOrganization':
        'omz:software',
        'PayloadRemovalDisallowed':
        False,
        'PayloadType':
        'Configuration',
        'PayloadUUID':
        unique_id,
        'PayloadVersion':
        1
    }
    console.hide_activity()
    run_server(config)
Exemple #40
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     if not tableview.editing:
         console.show_activity("Loading file list...")
         self.app.push_view(
             self.app.make_file_list(FileItem(self.entries[row][0])))
         console.hide_activity()
def main():
    set_img = photos.pick_image()
    photos.save_image(set_img)
    console.clear()
    print "Generating image..."
    console.show_activity()
    sketch(set_img).show()
    console.hide_activity()
def backup_youtubedl(sender):
    console.show_activity('Checking for youtube-dl')
    if os.path.isdir(youtubedl_location+youtubedl_dir):
        console.show_activity('Backing up youtube-dl')
        if not os.path.exists(backup_location):
            os.makedirs(backup_location)
        shutil.move(youtubedl_location+youtubedl_dir,backup_location+youtubedl_dir+ time.strftime('%Y%m%d%H%M%S'))
    console.hide_activity()
Exemple #43
0
 def run(self):
     """runs the client."""
     console.show_activity()
     self.manager.start()
     self.present(style="fullscreen",
                  orientations=("landscape", ),
                  hide_title_bar=True)
     atexit.register(self.on_quit)
Exemple #44
0
def backup_youtubedl(sender):
    console.show_activity('Checking for youtube-dl')
    if os.path.isdir(youtubedl_location+youtubedl_dir):
        console.show_activity('Backing up youtube-dl')
        if not os.path.exists(backup_location):
            os.makedirs(backup_location)
        shutil.move(youtubedl_location+youtubedl_dir,backup_location+youtubedl_dir+ time.strftime('%Y%m%d%H%M%S'))
    console.hide_activity()
def main():
	set_img = photos.pick_image()
	photos.save_image(set_img)
	console.clear()
	print "Generating image..."
	console.show_activity()
	sketch(set_img).show()
	console.hide_activity()
Exemple #46
0
def gh_pull(args):
    '''Usage: 
	gh pull <reponame> <base> [<head>]
	gh pull <reponame> <base> [<head>] --title <title> [--body <body>]
	gh pull <reponame> <base> [<head>] -i <issue>

Options:
	-h, --help   							This message
	-t <title>, --title <title>  	Title of pull request
	-b <body>, --body <body>  		Body of pull request [default: ]
	-i <issue>, --issue <issue>  	Issue number
Examples:
	gh pull stash ywangd jsbain 
	gh pull stash ywangd:dev jsbain:dev
	gh pull stash :dev :master
			
	base and head should be in the format owner:branch.
	if base owner is omitted, owner of parent repo is used.
	if head owner is omitted, user is used
	'''

    console.show_activity()
    try:
        g, user = setup_gh()
        reponame = args['<reponame>']
        baseowner, basebranch = parse_branch(args['<base>'])
        if not baseowner:
            baseowner = parent_owner(reponame)
        if not args['<head>']:
            args['<head>'] = ':'
        headowner, headbranch = parse_branch(args['<head>'])
        if not headowner:
            headowner = user.login

        baserepo = g.get_user(baseowner).get_repo(reponame)

        kwargs = {}
        if args['--issue']:
            kwargs['issue'] = baserepo.get_issue(args['--issue'])
        elif not args['--title']:
            kwargs['title'] = input('Enter pull title:')
            kwargs['body'] = input('Enter pull body:')
        else:
            kwargs['title'] = args['--title']
            kwargs['body'] = args['--body'] or ''

        kwargs['base'] = basebranch
        kwargs['head'] = ':'.join([headowner, headbranch])
        pullreq = baserepo.create_pull(**kwargs)

        print('Created pull %s' % pullreq.html_url)
        print('Commits:')
        print([(x.sha, x.commit.message) for x in pullreq.get_commits()])
        print('Changed Files:')
        print([x.filename for x in pullreq.get_files()])
    finally:
        console.hide_activity()
    print('success')
Exemple #47
0
		def func_wrapper(*args, **kwargs):
			console.show_activity(msg)
			try:
				result = func(*args, **kwargs)
				console.hide_activity()
				return result
			except Exception:
				console.hide_activity()
				raise
Exemple #48
0
 def network(self):
     if config.ios:
         if self.network:
             console.hide_activity()
             self.network = False
         else:
             console.show_activity()
             self.network = True
     else:
         pass
Exemple #49
0
def get_tweets(sender):
	tlist = []
	tweets = twitter.get_home_timeline(account)
	console.show_activity('Refreshing')
	time.sleep(1)
	for t in tweets:
		tlist.append(t.get('text'))
	timeline.data_source = ui.ListDataSource(items=tlist)
	timeline.reload()
	console.hide_activity()