예제 #1
0
def main():
    text = None
    if len(sys.argv) > 1:
        text = sys.argv[1]
    else:
        try:
            import appex
            import clipboard
            if appex.is_running_extension():
                if appex.get_url():
                    text = appex.get_url()
                else:
                    text = appex.get_text()
            else:
                text = clipboard.get()
        except ImportError:
            pass

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

        base_url, username, jsessionid = get_conf_info()

        if check_jsessionid(base_url, jsessionid):
            get_issue_info(base_url, jsessionid, key)
        else:
            jsessionid = get_new_cookie(base_url, username)
            get_issue_info(base_url, jsessionid, key)
    else:
        print('No input text found.')
예제 #2
0
def main():
    if appex.is_running_extension():
        if appex.get_url():
            text = appex.get_url()
        else:
            text = appex.get_text()
    else:
        text = clipboard.get()
    if not text:
        text = console.input_alert('Jira ID')

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

    basepath = os.path.expanduser('~/Documents/')
    fpath = appex.get_file_path()
    if fpath:
        fname = os.path.split(fpath)[1]
        try:
            import_from_file(fname, fpath, basepath)
        except:
            fpath = appex.get_text()
            if os.path.isfile(fpath):
                fname = os.path.split(fpath)[1]
                import_from_text(fname, fpath, basepath)
    elif appex.get_text():
        fpath = appex.get_text()
        ask = 'Choose File Extension', 'py', 'txt', 'pyui'
        resp = console.alert('Import file as..', *ask,
                             hide_cancel_button=False)
        fname = 'imported.' + ask[resp]
        import_from_text(fname, fpath, basepath)
    elif appex.get_url():
        fpath = appex.get_url()
        fname = os.path.split(fpath)[1]
        import_from_url(fname, fpath, basepath)
    else:
        console.hud_alert('Not a file!', icon='error')
예제 #4
0
def main():
    text = None
    if len(sys.argv) > 1:
        text = sys.argv[1]
    else:
        try:
            import appex
            import clipboard
            if appex.is_running_extension():
                if appex.get_url():
                    text = appex.get_url()
                else:
                    text = appex.get_text()
            else:
                text = clipboard.get()
        except ImportError:
            pass

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

        base_url, username, jsessionid = get_conf_info()

        if check_jsessionid(base_url, jsessionid):
            get_issue_info(base_url, jsessionid, key)
        else:
            jsessionid = get_new_cookie(base_url, username)
            get_issue_info(base_url, jsessionid, key)
    else:
        print('No input text found.')
예제 #5
0
def main():
    if appex.is_running_extension():
        if appex.get_url():
            text = appex.get_url()
        else:
            text = appex.get_text()
    else:
        text = clipboard.get()
    if not text:
        text = console.input_alert('Jira ID')

    if text:
        ids = JIRA_PAT.findall(text)
        if len(ids) == 0:
            text = console.input_alert('Jira ID')
        ids = JIRA_PAT.findall(text)
        if len(ids) > 0:
            id = ids[0]
            base_url, username = get_conf_info()
            url = '%s/browse/%s' % (base_url, id)
            console.hud_alert('Jira ID: %s' % id)
            app = UIApplication.sharedApplication()
            url = nsurl(url)
            app.openURL_(url)
        else:
            console.hud_alert('No Jira ID found.')
    else:
        console.hud_alert('No input text found.')
    if appex.is_running_extension():
        appex.finish()
예제 #6
0
def git_download_from_args(args):
    if len(args) == 2:
        url = args[1]
    elif appex.get_url():
        url = appex.get_url()
    else:
        url = clipboard.get()
    git_download(url)
예제 #7
0
def main():
    '''App extension logic, with unit tests if run within Pythonista'''

    if appex.is_running_extension():
        if appex.get_url():
            copy_url(appex.get_url())
            appex.finish()
        else:
            console.hud_alert('No input URL found', 'error')
    else:
        console.hud_alert('This script must be run from the sharing extension', 'error')
        import doctest
        doctest.testmod()
예제 #8
0
def main():
    '''App extension logic, with unit tests if run within Pythonista'''

    if appex.is_running_extension():
        if appex.get_url():
            copy_url(appex.get_url())
            appex.finish()
        else:
            console.hud_alert('No input URL found', 'error')
    else:
        console.hud_alert('This script must be run from the sharing extension', 'error')
        import doctest
        doctest.testmod()
def main():
    linkdump_url = 'http://*****:*****@localhost:9292'
    if not appex.is_running_extension():
        print('This script is intended to be run from the sharing extension.')
        return
    url = appex.get_url()

    tags = dialogs.input_alert('Tags:', '')

    if not url:
        print('No input URL found.')
        return
    print(url)

    headers = {
        'Content-Type': 'application/json',
    }

    data = '{' +\
             '"url": "' + url + '",' +\
             '"tags": "' + tags + '"' +\
           '}'

    r = requests.post(linkdump_url + '/api/links', headers=headers, data=data)
    print(r.status_code)
예제 #10
0
def main():
    if not appex.is_running_extension():
        print 'This script is intended to be run from the sharing extension.'
        return

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

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

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

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

    print openurl
    app.openURL_(openurl)
    appex.finish()
예제 #11
0
def main():
	if not appex.is_running_extension():
		print('This script is intended to be run from the sharing extension.')
		print('falling back to a test url')
		url = 'http://twitter.com'
	else:
	  url = appex.get_url()
	if not url:
		print('No input URL found.')
		return
	#print(url)
	
	#do http request
	req = requests.request('GET', url);
	if req.status_code != 200:
	  print('result not 200. no good')
	  return
	
	soup = BeautifulSoup(req.text, 'html5lib')
	# get all img src attributes
	imgUrls = list(map((lambda img: img.get('src')), soup.find_all('img')))
	# filter to just .jpg .png .gif
	imgUrls = [i for i in imgUrls if i != None and i.endswith(('.jpg', '.png', '.gif'))]
	# remove duplicates
	imgUrls = list(set(imgUrls))
	
	v = ui.load_view('GetImagesAtUrl')
	tv = v['tableview']
	tv.delegate = MyTableViewDelegate(imgUrls, v)
	tv.data_source = MyTableViewDataSource(imgUrls)
	v.present()
예제 #12
0
def main():
    if not appex.is_running_extension():
        print 'Running in Pythonista app, using test data...\n'
        url = 'https://raw.githubusercontent.com/marcus67/pyzipista/master/build/pyzipista_zip.py'
    else:
        url = appex.get_url()
    if url:
        # TODO: Your own logic here...
        print 'Input URL: %s' % (url, )

        attempts = 0
        success = False

        while attempts < 3:
            try:
                response = urllib2.urlopen(url, timeout=5)
                content = response.read()
                f = open("archive.py", 'w')
                f.write(content)
                f.close()
                success = True
                break
            except urllib2.URLError as e:
                attempts += 1
                print type(e)

        if success:
            import archive
            archive.main()

    else:
        print 'No input URL found.'
예제 #13
0
def main():
    if appex.is_running_extension():
        url = appex.get_url()
    else:
        url = clipboard.get().strip()
        if not RE_URL.match(url):
            try:
                url = console.input_alert("Enter gamefaqs URL", "", "https://www.gamefaqs.com/")
            except KeyboardInterrupt:
                sys.exit(0)
    
    newurl = "{0}?print=1".format(url)
    #baseurl = http://www.gamefaqs.com/ps3/959558-fallout-new-vegas/faqs/61226
    if RE_URL.match(url):
        h = html2text.HTML2Text()
        r = requests.get(
                         url=newurl, 
                         headers={"User-agent": "Mozilla/5.0{0:06}".format(random.randrange(999999))}
                         )
        html_content = r.text.decode('utf-8')
        rendered_content = html2text.html2text(html_content)
        filename = url.partition("gamefaqs.com/")[-1].partition("/")[-1].partition("/faqs")[0]+".txt"
        filepath = os.path.join(os.path.expanduser("~/Documents"), filename)
        
        with open(filepath, "w") as fo:
            fo.write(rendered_content)
        
        console.hud_alert('Success! Saved {0}'.format(filename), "success")
def index():
    access_token = ""

    token_info = sp_oauth.get_cached_token()

    if token_info:
        print("Found cached token!")
        access_token = token_info["access_token"]
    else:
        url = request.url
        code = sp_oauth.parse_response_code(url)
        if code:
            token_info = sp_oauth.get_access_token(code)
            access_token = token_info["access_token"]

    if access_token:
        sp = spotipy.Spotify(auth=access_token)
        #results = sp.current_user()
        url = appex.get_url()
        id = url.split('/')[-1].split('?')[0]
        print(url, id)
        playlist_id = f"spotify:playlist:{id}"
        username = user_config["username"]
        playlist = sp.playlist(playlist_id)
        results = spotifork.get_tracks(sp, playlist["id"])
        spotifork.write_tracks(sp, username, playlist, results)
        #sys.stderr.close()
        return results

    else:
        return htmlForLoginButton()
예제 #15
0
def main():
    if appex.is_running_extension():
        url = appex.get_url() or appex.get_text()
    else:
        import console

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

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

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

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

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

    except Exception as e:
        print(f'Failed to get <code> element values: {e}')
예제 #16
0
def main(rootpath="data/"):
	logger=Logger(rootpath+"log.txt","ExtAddApp.py",True)
	configService=ConfigService(rootpath)
	
	if not appex.is_running_extension():
		print('This script is intended to be run from the sharing extension.')
		return
		
	url = appex.get_url()
	if not url:
		console.alert("Error","No input URL found.",'OK', hide_cancel_button=True)
		
		if(configService.getLog().getData()==1):
			logger.error("No input URL found.")
		return
	
	console.hud_alert("正在抓取数据,请等待...","success")
		
	appSerVice=AppService(rootpath)	
	res=appSerVice.addApp(url)
		
	if(res.equal(ResultEnum.APP_UPDATE)):
		console.hud_alert("应用更新成功!",'success')
	elif(res.equal(ResultEnum.SUCCESS)):
		console.hud_alert("应用添加成功!",'success')
	else:
		console.hud_alert(res.getInfo(),'error')
def main():
    lst = []
    if use_appex:
        url = appex.get_url()
    else:
        url = clipboard.get()

    if 'omz-forums' not in url or len(url.splitlines()) > 1:
        #print 'No forum URL'
        lst.append('-1')  # i know this is crappy.
        return lst

    import requests
    import bs4
    html = requests.get(url).text
    soup = bs4.BeautifulSoup(html)
    pre_tags = soup.find_all('pre')
    if pre_tags:
        text = ''
        #text = ('\n#%s\n\n' % ('=' * 30)).join([p.get_text() for p in pre_tags])

        for p in pre_tags:
            lst.append(p.get_text())
        #clipboard.set(text)
        #print 'Code copied (%i lines)' % (len(text.splitlines()))
    else:
        #print 'No code found'
        pass

    return lst
예제 #18
0
def main():
    if not appex.is_running_extension():
        print('This script is intended to be run from the sharing extension.')
        return
    else:
        url = appex.get_url()

    if url:
        parsed_url = urlparse(url)

        if parsed_url.hostname == 'github.com':
            path = parsed_url.path
            last_path = path.split("/")[-1]

            is_directory = last_path.find(".") == -1
            if not is_directory:
                ext = last_path.split(".")[-1]
            else:
                ext = None

            if not is_directory and ext == "ipynb":
                new_url = COLAB_URL + parsed_url.path
                webbrowser.open_new_tab(new_url)
            else:
                print('This page is directory or not jupyter notebook.')
        else:
            print('This script is intended to be run from github.')
    else:
        print('No input URL found.')
예제 #19
0
def get_safe_text():
    url_ext = appex.get_url()
    url_clp = clipboard.get()
    txt_ext = appex.get_text()

    if url_ext:
        if check_anews(url_ext):
            url = redirect_anews(url_ext)
            return get_text(url)
        else:
            return get_text(url_ext)
    elif txt_ext:
        return txt_ext
    elif url_clp:
        if url_clp.startswith('http'):
            if check_anews(url_clp):
                url = redirect_anews(url_clp)
                return get_text(url)
            else:
                return get_text(url_clp)
        else:
            return url_clp
    else:
        raise ValueError(
            'no text or url received from app extension or clipboard')
예제 #20
0
파일: url.py 프로젝트: timkphd/examples
def main():
    if not appex.is_running_extension():
        #print('Running in Pythonista app, using test data...\n')
        url = 'http://example.com'
        url = console.input_alert("Hello", "Enter URL",
                                  "http://inside.mines.edu/~tkaiser/golf.py")
    else:
        url = appex.get_url()
    if url:
        # TODO: Your own logic here...
        print('Input URL: %s' % (url, ))
        r = requests.get(url)
        text = r.text
        print(text)
        top = startdir()
        if len(text) > 0:
            # TODO: Your own logic here...
            #		print('Input text: %s' % text)
            diddir = setdir(top)
            newfile = ""
            if diddir:
                newfile = dialogs.input_alert("File", "Create file:")
                if newfile is None:
                    newfile = ""
                if len(newfile) > 0:
                    file = open(newfile, "w")
                    file.write(text)
                    file.close()
    else:
        print('No input URL found.')
예제 #21
0
파일: iref.py 프로젝트: csience/saving-time
def main():
    if not appex.is_running_extension():
        print('This script is intended to be run from the sharing extension.')
        return
    # My bit.ly access token for https://a.ref.sh/ for demonstration purposes. Change this value for your use.
    ACCESS_TOKEN = "c946a815f11eec030dea06056c146115102c1d1d"
    url = "https://api-ssl.bitly.com/v3/shorten"
    querystring = {"access_token": ACCESS_TOKEN}

    appurl = appex.get_url()
    if not appurl:
        print('No input URL found.')
        return
    querystring["longUrl"] = appurl

    # HTTP header(s)
    headers = {'cache-control': "no-cache"}

    # GET HTTP request to bit.ly API stored in requests.request object
    response = requests.request("GET",
                                url,
                                headers=headers,
                                params=querystring)

    # decode as JSON formatted text from requests.request object to dict
    try:
        d = response.json()
        # Print shortened url to console.
        print((d['data']).get('long_url'))
        print((d['data']).get('url'))

    except ValueError:
        print('JSON decoding failed.')
def main():
    #Check to see if the main method is being run from the share sheet
    try:
        if not appex.is_running_extension():
            #if this if statement is true, clarify that we're running in the app
            print('Running in Pythonista app, using test data...\n')

            #get the clipboard for the url
            url = str(clipboard.get())

            #check that the clipboard is a url. if not, set as None for error production
            if not url.startswith('http'):
                url = None
        else:
            #Get url from app extension if running from extension
            url = appex.get_url()
    except:
        url = input('Enter the URL you want to save')

    #Check if url has a value
    if url:
        #Give user feedback about what is happening
        print('Input URL: %s' % (url, ))

        #Get the instapaper URL for adding url as bookmark
        u = getInstapaperURL(url)

        #Add u to Instapaper
        addToInstapaper(u)

        #Tell  the user that the action is complete
        print('\n\nComplete!')
    else:
        #Tell the user that there was an error
        print('No input URL found.')
예제 #23
0
def main():
    if appex.is_running_extension():
        url = appex.get_url()
    else:
        url = clipboard.get().strip()
        if not RE_URL.match(url):
            try:
                url = console.input_alert("Enter gamefaqs URL", "", "https://www.gamefaqs.com/")
            except KeyboardInterrupt:
                sys.exit(0)
    
    newurl = "{0}?print=1".format(url)
    if RE_URL.match(url):
        h = html2text.HTML2Text()
        r = requests.get(
                         url=newurl, 
                         headers={"User-agent": "Mozilla/5.0{0:06}".format(random.randrange(999999))}
                         )
        html_content = r.text.decode('utf-8')
        rendered_content = html2text.html2text(html_content)
        filename = url.partition("gamefaqs.com/")[-1].partition("/")[-1].partition("/faqs")[0]+".txt"
        filepath = os.path.join(os.path.expanduser("~/Documents"), filename)
        
        with open(filepath, "w") as fo:
            fo.write(rendered_content)
        
        console.hud_alert("Success! Saved to '~/Documents/{0}'".format(filename), "success")
        dialogs.share_url("file:///"+filepath)
예제 #24
0
def main():
   if not appex.is_running_extension():
      print('Running in Pythonista app, using test data...\n')
      url = 'http://example.com'
   True

      url = appex.get_url()
		   if get_url()
예제 #25
0
def main():

    # get text from app share or clipboard
    if appex.is_running_extension():
        text = appex.get_url()
    else:
        text = clipboard.get().strip()

    # get url
    url = ''
    try:
        url = [mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text)][0]
    except:
        url = console.input_alert("URL", "", url)
    if url:
        if not 'http' in url:
            url = 'http://' + url
    else:
        console.hud_alert('No URL found.')
        sys.exit()

    sel = console.alert('Save: %s ?' % url,
                        button1='File',
                        button2='Clipboard')

    # get url info
    url_items = url.split("?")[0].split("/")
    # if url ends with /, last item is an empty string
    file_name = url_items[-1] if url_items[-1] else url_items[-2]
    try:
        content = urllib2.urlopen(url).read()
    except Exception as e:
        console.alert(e.message)
        sys.exit()

    if sel == 1:
        # get file save info
        save_dir_name = get_save_dir()
        save_dir = os.path.join(BASE_DIR, save_dir_name)
        file_path = os.path.join(save_dir, file_name)
        try:
            # check dirs and save
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            with open(file_path, 'w') as f:
                f.write(content)
                f.close()
            # wrapup
            console.alert('Saved to: %s' % file_path,
                          hide_cancel_button=True,
                          button1='OK')
        except Exception as e:
            console.alert(str(e), button1='OK', hide_cancel_button=True)
    elif sel == 2:
        clipboard.set(content)

    if appex.is_running_extension():
        appex.finish()
def main():
    if not appex.is_running_extension():
        print 'This script is intended to be run from the sharing extension.'
        return
    url = appex.get_url()
    if not url:
        print 'No input url'
        return
    open_in_safari_vc(url)
예제 #27
0
    def log(self):
        console.show_activity()
        try:
            url_match = re.match(
                r'^https?://(?:www\.)?imdb\.com/title/(tt\d+)/?',
                appex.get_url())
            params = {
                'api_key': self.moviedb_api,
                'external_source': 'imdb_id'
            }
            return self.getmovie(
                'https://api.themoviedb.org/3/movie/%s' % (url_match.group(1)),
                params)
        except TypeError:
            params = {
                'api_key':
                self.moviedb_api,
                'query':
                console.input_alert('Search for movie', '',
                                    sys.argv[1] if len(sys.argv) > 1 else '')
            }

            if len(params.get('query')) == 0:
                self.edit_config()
            else:
                req = requests.post(
                    'https://api.themoviedb.org/3/search/movie', params=params)

                if req.status_code == 200:
                    res = json.loads(req.text)

                    if res['total_results'] > 1:
                        results_map = {
                            e['title'] + self.getyear(e['release_date']): e
                            for e in res['results']
                        }
                        movie_pick = dialogs.list_dialog(
                            'Pick a movie', [
                                e['title'] + self.getyear(e['release_date'])
                                for e in res['results']
                            ])
                        if movie_pick is not None:
                            return self.getmovie(
                                'https://api.themoviedb.org/3/movie/%s' %
                                (results_map[movie_pick]['id']),
                                {'api_key': self.moviedb_api})
                        else:
                            raise NoMoviePickError()
                    elif res['total_results'] == 1:
                        return self.getmovie(
                            'https://api.themoviedb.org/3/movie/%s' %
                            (res['results'][0]['id']),
                            {'api_key': self.moviedb_api})
                    else:
                        raise NoResultsError()
                else:
                    raise TmdbConnectionError(req.text)
예제 #28
0
def main():
	if key == "":
	
	
		if not appex.is_running_extension():
			print('Running in Pythonista app, using test data...\n')
				url = "https://github.com/owner/reponame/pull/1"
		else:
			url = appex.get_url()
def main():
    if not appex.is_running_extension():
        print 'This script is intended to be run from the sharing extension.'
        return
    url = appex.get_url()
    if not url:
        print 'No input url'
        return
    open_in_safari_vc(url)
예제 #30
0
def create_message():
	url = appex.get_url()
	
	title = get_title(url)
	
	msg = MIMEText(url)
	msg['Subject'] = title
	
	return msg
예제 #31
0
파일: ClipLink.py 프로젝트: nu0hh/makelink
def main():
	if appex.is_running_extension():
		text = appex.get_url()
		with codecs.open('LinkStack.txt', 'a', 'utf-8') as f:
			f.write('%s\n' % (text))
		count=0
		with codecs.open('LinkStack.txt', 'r', 'utf-8') as f:
			for line in f:
				count = count + 1
		console.alert('ClippedLink : %i' % count, '', 'OK', hide_cancel_button=True)
예제 #32
0
def main():
	if key == "":
		print("You need to fill out key with value from Working Copy settings.")
		quit()
			
		if not appex.is_running_extension():
			print('Running in Pythonista app, using test data...\n')
			url = "https://github.com/owner/reponame/pull/1"
		else:
			url = appex.get_url()
예제 #33
0
def main():
	if not appex.is_running_extension():
		print '\nRunning using test data...'
		url = 'http://xkcd.com'
	else:
		url = appex.get_url()
	if url:
		pick(url)
	else:
		print 'No input URL found.'
예제 #34
0
def main():
    
    # get text from app share or clipboard
    if appex.is_running_extension():
        text = appex.get_url()
    else:
        text = clipboard.get().strip()

    # get url
    url = ''
    try:
        url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0]
    except:
        url = console.input_alert("URL", "", url)
    if url:
        if not 'http' in url:
            url = 'http://' + url
    else:
        console.hud_alert('No URL found.')
        sys.exit()

    sel = console.alert('Save: %s ?' % url, button1='File', button2='Clipboard')

    # get url info
    url_items = url.split("?")[0].split("/")
    # if url ends with /, last item is an empty string
    file_name = url_items[-1] if url_items[-1] else url_items[-2]
    try:
        content = urllib2.urlopen(url).read()
    except Exception as e:
        console.alert(e.message)
        sys.exit()

    if sel == 1:
        # get file save info
        save_dir_name = get_save_dir()
        save_dir = os.path.join(BASE_DIR, save_dir_name)
        file_path = os.path.join(save_dir, file_name)
        try:
            # check dirs and save
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            with open(file_path, 'w') as f:
                f.write(content)
                f.close()
            # wrapup
            console.alert('Saved to: %s' % file_path, hide_cancel_button=True, button1='OK')
        except Exception as e:
            console.alert(str(e), button1='OK',hide_cancel_button=True)
    elif sel == 2:
        clipboard.set(content)


    if appex.is_running_extension():
        appex.finish()
예제 #35
0
def main():
	if not appex.is_running_extension():
		print('This script is intended to be run from the sharing extension.')
		return
	url = appex.get_url()
	if not url:
		print('No input URL found.')
		return
	print(url)
	img = qrcode.make(url)
	img.show()
예제 #36
0
def main():
    if not appex.is_running_extension():
        print 'This script is intended to be run from the sharing extension.'
        return
    url = appex.get_url()
    if not url:
        print 'No input URL found.'
        return
    print url
    img = qrcode.make(url)
    img.show()
예제 #37
0
def main():
    if not appex.is_running_extension():
        print('This script is intended to be run from the sharing extension.')
        return
    url = appex.get_url()
    if not url:
        url = clipboard.get()
    console.hud_alert('url: ' + url)
    local_filename = download_file(url)
    console.hud_alert('copying to ' + local_filename)
    console.quicklook(local_filename)
def main():
    if not appex.is_running_extension():
        print('This script is intended to be run from the sharing extension.')
        return
    url = appex.get_url()
    if not url:
        print('No input URL found.')
        return
    url = urlsplit(url)
    url = 'textastic://' + url.netloc + url.path + url.query + url.fragment
    print(url)
    webbrowser.open(url)
예제 #39
0
def main():
	if not appex.is_running_extension():
		print 'Running in Pythonista app, using test data...\n'
		url = 'http://example.com'
	else:
		url = appex.get_url()
	if url:
		out_file = open(url.split('/')[-1], 'wb')
		out_file.write(requests.get(url).content)
		out_file.close()
	else:
		print 'No input URL found.'
예제 #40
0
def main():
    url = appex.get_url() if use_appex else clipboard.get()
    if 'omz-forums' not in url or len(url.splitlines()) > 1:
        #print 'No forum URL'
        return ['-1']  # i know this is crappy.

    import requests
    import bs4
    html = requests.get(url).text
    soup = bs4.BeautifulSoup(html)
    pre_tags = soup.find_all('pre')
    return [line.get_text() for line in soup.find_all('pre')]
예제 #41
0
def main():
    if not appex.is_running_extension():
        url = 'http://google.com/hmm'
    else:
        url = appex.get_url()
    if url:
        # TODO: Your own logic here...
        print 'Input URL: %s' % (url,)
        p = urlparse(url)
        print(p.path)
    else:
        print 'No input URL found.'
예제 #42
0
def main():
    if not appex.is_running_extension():
        print 'Running in Pythonista app, using test data...\n'
        url = 'http://example.com'
    else:
        url = appex.get_url()
    if url:
        # TODO: Your own logic here...
        print 'Input URL: %s' % (url,)
        print 'Response headers:'
        print '\n'.join('%s: %s' % (k, v) for k, v in requests.head(url).headers.iteritems())
    else:
        print 'No input URL found.'
예제 #43
0
파일: Download.py 프로젝트: andreiw/ios-py
def main():
	if not appex.is_running_extension():
		print('This script is intended to be run from the sharing extension.')
		return
		
	url = appex.get_url()
	if not url:
		print('No URL?')
		return
		
	fname = url.split('/')[-1]
	fname = os.path.join(os.path.expanduser('~/Documents/Downloads'), fname)

	http = urllib3.PoolManager()
	response = http.request('GET', url)
	with open(fname, 'wb') as f:
		f.write(response.data)
	console.hud_alert('done')
예제 #44
0
def main():
    if appex.is_running_extension():
        url = appex.get_url()
        if url == None:
            text = appex.get_text()
            url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0]
    else:
        text = clipboard.get().strip()
        url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0]
        if not "http" in url:
            url = "http://"
        try:
            url = console.input_alert("URL", "", url)
        except:
            return True

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

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

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

    launch_e = console.alert('Markdown copied to clipboard. Launch Evernote?', button1='Yes', button2='No', hide_cancel_button=True)
    if launch_e ==1:
        _eurl = "evernote://x-callback-url/new-note?type=clipboard&title=DRAFT&text="
        app=UIApplication.sharedApplication()
        eurl=nsurl(_eurl)
        app.openURL_(eurl)
    appex.finish()
예제 #45
0
def main():
	if not appex.is_running_extension():
		alert("Error", "This script is intended to be run from the sharing extension.", "Exit", hide_cancel_button=True)
		return
	
	url = appex.get_url()
	if not url:
		alert("ERROR", "No input URL found.  Execute this script from the sharing extension.", "Quit", hide_cancel_button=True) 
		return
	
	while True:
		filename = input_alert("Download File", "You have chosen to download file at URL:\n " + url + "\n\nEnter filename to save locally.  Press Cancel to abort.")
		if os.path.exists(filename):
			if os.path.isfile(filename):
				confirm = alert("Warning", "File %s exists.  Overwrite?" % filename, "Overwrite", "Change Filename", hide_cancel_button=True)
				if confirm == 1:
					os.remove(filename)
					break
			else:
				alert("Critical Error.", "Path exists but is not a file.  Exiting.", "Exit", hide_cancel_button=True)
				return
		else:
			break

	r = requests.get(url)
	if r.status_code != 200:
		alert("Invalid HTTP Response: %d, Exiting." %r.status_code, "Exit", hide_cancel_button=True)
		return
	
	confirm = alert("Confirm Download", "Text length: %d, Press OK to Save, Cancel to Quit" %len(r.text), "Save", "Cancel", hide_cancel_button=True)
	if confirm == 1:
		outfile = open(filename, "w")
		for line in r.text:
			outfile.write(line)
		outfile.close()
		alert("Success", "File Saved.", "Exit", hide_cancel_button=True)
	r.close()
	return
예제 #46
0
def main():
    speech.stop()
    if not appex.is_running_extension():
        console.hud_alert('Reading clipboard')
        text = clipboard.get()
        url = None
    else:
        text = appex.get_text()
        url = appex.get_url()

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

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

    if text:
        speech.say(text)
        stop = console.alert('Done?', hide_cancel_button=True, button1='OK')
        speech.stop()
    else:
        console.hud_alert('No text found.')
예제 #47
0
import appex
import urllib2
from objc_util import *
#Helper functions
def openUrl(url):
    '''Allows webbrowser.open()-esque functionality from the app extension'''
    app=UIApplication.sharedApplication()
    app._openURL_(nsurl(url))
def getDocPath():
    '''Gets the path to ~/Documents'''
    split=__file__.split('/')
    path=split[:split.index('Documents')+1]
    return '/'.join(path)+'/'
#Get the url    
url=appex.get_url()

# ...
#Read page contents
import requests
r = requests.get(url)
source = r.text
ct = r.headers['Content-Type']
# A fancier version could use the mimetypes module to guess the proper file extension...
extension = '.html' if ct.startswith('text/html') else '.txt'
# ...

#Read page contents
#f=urllib2.urlopen(url)
#source=f.read()
#f.close()
예제 #48
0
# https://forum.omz-software.com/topic/2358/appex-safari-content

# coding: utf-8
import urllib2, appex
response = urllib2.urlopen(appex.get_url()')
html = response.read()
def title_of_url(url):
  try:
    soup = BeautifulSoup(urllib2.urlopen(url))
    return soup.title.string
u  except:
    return ''


guid = '__YOUR_NOTE_GUID_HERE__'

input = ''

if appex.is_running_extension():
	LKEvernoteApi.log_progress('load url provided to app extension')
	input = appex.get_url()
else:
	LKEvernoteApi.log_progress('not running from extension, checking arguments')
	if len(sys.argv) > 1:
		evernote.log_progress('argument found, use that')
		input = sys.argv[1]
	else:
		LKEvernoteApi.log_progress('no arguments found, will use clipboard text')
		input = clipboard.get()
		if clipboard.get() == '':
			sys.exit('Clipboard is empty, no arguments passed to script')

LKEvernoteApi.log_progress('Loading title of passed url')
url_title = ' (' + title_of_url(input) + ') '

if url_title is ' () ':