def refresh_cache():
    wf = Workflow()
    # Start the OAuth flow to retrieve credentials
    flow = flow_from_clientsecrets(
        config.CLIENT_SECRET_FILE, scope=config.OAUTH_SCOPE)
    http = httplib2.Http()

    try:
        credentials = OAuth2Credentials.from_json(
            wf.get_password('gmail_credentials'))
        if credentials is None or credentials.invalid:
            credentials = run(flow, PseudoStorage(), http=http)
            wf.save_password('gmail_credentials', credentials.to_json())
            wf.logger.debug('Credentials securely updated')

        # Authorize the httplib2.Http object with our credentials
        http = credentials.authorize(http)
        # Build the Gmail service from discovery
        gmail_service = build('gmail', 'v1', http=http)

        wf.cache_data('gmail_list', get_list(wf, http, gmail_service))

    except PasswordNotFound:
        wf.logger.debug('Credentials not found')
        credentials = run(flow, PseudoStorage(), http=http)
        wf.save_password('gmail_credentials', credentials.to_json())
        wf.logger.debug('New Credentials securely saved')
Exemple #2
0
def hipchat_keys():
    wflw = Workflow()
    try:
        keys = wflw.get_password('hipchat_api_key')
    except PasswordNotFound:
        wflw.add_item(title='No API key set. Please run hipchat_api_token', valid=False)
        wflw.send_feedback()
        return 0
    return keys.split(",")
Exemple #3
0
def main():
    wf = Workflow()
    error = None
    try:
        # initialize client
        access_token = wf.get_password('pocket_access_token')
        pocket_instance = Pocket(config.CONSUMER_KEY, access_token)

        since = wf.cached_data('pocket_since', max_age=0) or 0
        links = wf.cached_data('pocket_list', max_age=0) or {}

        next_since = 0
        offset = 0
        while True:
            get = pocket_instance.get(
                detailType='complete',
                since=since,
                state='all',
                count=LINK_LIMIT,
                offset=offset
            )[0]

            data = get['list']
            next_since = get['since']

            if get['status'] != 1 or len(data) == 0:
                break

            links.update(data)
            offset += LINK_LIMIT

        # Delete obsolete entries
        for item_id in links.keys():
            if links[item_id]['status'] == '2':
                del links[item_id]

        wf.cache_data('pocket_since', next_since)
        wf.cache_data('pocket_list', links)
        tags = list(set([t for l in links.values() if 'tags' in l
                         for t in l['tags'].keys()]))
        wf.cache_data('pocket_tags', tags)

        # update fulltext search index
        for item_id in links.keys():
            url = links[item_id]['given_url']
            if not FullText.has_link(url):
                FullText.get_instance().add_page(url)
            time.sleep(.1)

    except (AuthException, URLError, PocketException, PasswordNotFound), e:
        error = type(e).__name__
        wf.cache_data('pocket_error', error)

        # delete token if authentication failed
        if error == 'AuthException':
            wf.delete_password('pocket_access_token')
Exemple #4
0
def slack_keys():
    wf_password = Workflow()
    try:
        slack_keys = wf_password.get_password("slack_api_key")
    except PasswordNotFound:
        wf.add_item(title="No API key set. Please run slt", valid=False)
        wf.send_feedback()
        return 0
    keys = slack_keys.split(",")

    return keys
def slack_keys():
    wf = Workflow()
    try:
        slack_keys = wf.get_password('slack_api_key')
    except PasswordNotFound:
        wf.add_item(title='No API key set. Please run slt', valid=False)
        wf.send_feedback()
        return 0
    keys = slack_keys.split(",")

    return keys
def main():
    wf = Workflow()
    error = None
    try:
        # initialize client
        access_token = wf.get_password('pocket_access_token')
        pocket_instance = Pocket(config.CONSUMER_KEY, access_token)

        state = None
        since = wf.cached_data('pocket_since', max_age=0) or 0
        links = {}
        # fetch cached links if since is not 0
        if since > 0:
            links = wf.cached_data('pocket_list', max_age=0) or {}
            
            # Only use delta syncing if dict is not empty
            if links:
                state = 'all'

        next_since = 0
        offset = 0
        while True:
            get = pocket_instance.get(
                sort='newest',
                detailType='complete',
                since=since,
                state=state,
                count=LINK_LIMIT,
                offset=offset
            )[0]

            data = get['list']
            next_since = get['since']

            if get['status'] != 1 or len(data) == 0:
                break

            links = sync_data(links, data)
            offset += LINK_LIMIT

        wf.cache_data('pocket_since', next_since)
        wf.cache_data('pocket_list', links)

    except (AuthException, URLError, PocketException, PasswordNotFound), e:
        error = type(e).__name__
        wf.cache_data('pocket_error', error)

        # delete token if authentication failed
        if error == 'AuthException':
            wf.delete_password('pocket_access_token')
Exemple #7
0
def main():
    wf = Workflow()
    error = None
    try:
        # initialize client
        access_token = wf.get_password('pocket_access_token')
        pocket_instance = Pocket(config.CONSUMER_KEY, access_token)

        since = wf.cached_data('pocket_since', max_age=0) or 0
        links = wf.cached_data('pocket_list', max_age=0) or {}

        next_since = 0
        offset = 0
        while True:
            get = pocket_instance.get(
                detailType='complete',
                since=since,
                state='all',
                count=LINK_LIMIT,
                offset=offset
            )[0]

            data = get['list']
            next_since = get['since']

            if get['status'] != 1 or len(data) == 0:
                break

            links.update(data)
            offset += LINK_LIMIT

        # Delete obsolete entries
        for item_id in links.keys():
            if links[item_id]['status'] == '2':
                del links[item_id]

        wf.cache_data('pocket_since', next_since)
        wf.cache_data('pocket_list', links)
        tags = list(set([t for l in links.values() if 'tags' in l
                        for t in l['tags'].keys()]))
        wf.cache_data('pocket_tags', tags)

    except (AuthException, URLError, PocketException, PasswordNotFound), e:
        error = type(e).__name__
        wf.cache_data('pocket_error', error)

        # delete token if authentication failed
        if error == 'AuthException':
            wf.delete_password('pocket_access_token')
def main():
    wf = Workflow()
    error = None
    try:
        # initialize client
        access_token = wf.get_password('pocket_access_token')
        pocket_instance = Pocket(config.CONSUMER_KEY, access_token)

        since = wf.cached_data('pocket_since', max_age=0) or 0
        links = wf.cached_data('pocket_list', max_age=0) or {}

        next_since = 0
        offset = 0
        while True:
            get = pocket_instance.get(detailType='complete',
                                      since=since,
                                      state='all',
                                      count=LINK_LIMIT,
                                      offset=offset)[0]

            data = get['list']
            next_since = get['since']

            if get['status'] != 1 or len(data) == 0:
                break

            links.update(data)
            offset += LINK_LIMIT

        # Delete obsolete entries
        for item_id in links.keys():
            if links[item_id]['status'] == '2':
                del links[item_id]

        wf.cache_data('pocket_since', next_since)
        wf.cache_data('pocket_list', links)

    except (AuthException, URLError, PocketException, PasswordNotFound), e:
        error = type(e).__name__
        wf.cache_data('pocket_error', error)

        # delete token if authentication failed
        if error == 'AuthException':
            wf.delete_password('pocket_access_token')
def getConfigValue(configName):
    '''Returns the stored value for a configuration item Workflow settings or MacOS Keychain.

----------
	@param str configName: The name of a configuration item-, e.g. 'dueDate'.
	'''
    wf = Workflow()
    log = wf.logger
    if configName == confNames['confApi']:
        try:
            value = wf.get_password('clickUpAPI')
        except PasswordNotFound:
            value = None
            pass
    else:
        if configName in wf.settings:
            value = wf.settings[configName]
        else:
            value = None

    return value
Exemple #10
0

if (__name__ == "__main__"):
    wf = Workflow()

    if (len(wf.args)):
        query = wf.args[0]

    URL = wf.stored_data('url')
    if (not URL):
        URL = "canvas.instructure.com"
        wf.store_data('url', "canvas.instructure.com")

    if (query[0:13] != "!save_api_key" and query[0:13] != "!api_key_save"):
        try:
            ACCESS_TOKEN = wf.get_password("api-key")
        except:
            wf.add_item(
                title="API key not found.",
                subtitle="Select this action to get your access token.",
                valid=True,
                arg="!open_url https://%s/profile/settings" % URL)
            wf.add_item(
                title="Enter API key",
                subtitle=
                "Select this action when you're ready to paste your API key.",
                valid=True,
                arg="!save_api_key ")
            wf.send_feedback()
            sys.exit(0)
Exemple #11
0
            sys.exit()
        if params[1] == '':
            wf.add_item('Please enter your YouTrack %s' % yt_title(params[0]),subtitle=u'Cannot be empty!', icon=ICON_SETTINGS)
        else:
            wf.add_item('Set your YouTrack %s to \'%s\'' % (yt_title(params[0]),params[1]),
                        subtitle=u'Hit enter to set.',
                        icon=ICON_SETTINGS,
                        arg=wf.pargs.set + SEPARATOR,
                        valid=True)
        wf.send_feedback()

    settings = {}
    settings['yt_url'] = wf.stored_data('yt_url')
    settings['yt_username'] = wf.stored_data('yt_username')
    try:
        settings['yt_password'] = wf.get_password(u'yt_password')
    except:
        settings['yt_password'] = None
    missing_settings = {key: value for (key, value) in settings.iteritems() if not value}
    if len(missing_settings.keys()):
        for k in missing_settings:
            wf.add_item(u'Youtrack %s not set.' % yt_title(k),
                        subtitle='Set your Youtrack %s' % yt_title(k),
                        modifier_subtitles={'cmd':'Please don\' press cmd on the settings option, there be dragons'},
                        arg='%s' % k.lower(),
                        valid=True,
                        icon=ICON_SETTINGS)
        wf.send_feedback()
        sys.exit()

    if wf.pargs.issue:
Exemple #12
0
import argparse
import os
import subprocess
import urlparse
from pocket_api import Pocket, InvalidQueryException
from workflow import Workflow
import config

WF = Workflow()
POCKET = Pocket(config.CONSUMER_KEY, WF.get_password('pocket_access_token'))

FRONTMOST_APP = """\
osascript -e 'application (path to frontmost application as text)'\
"""
BROWSER_SCRIPTS = {
    'Firefox': {
        'url': """\
osascript -e 'tell application "Firefox" to activate\n \
  set old_clipboard to the clipboard\n \
  tell application "System Events"\n \
      repeat until (exists window 1 of process "Firefox") \n \
        delay 0.1 \n \
      end repeat\n \
      keystroke "l" using command down\n \
      keystroke "c" using command down\n \
  end tell\n \
  delay .5\n \
  set new_clipboard to the clipboard\n \
  set the clipboard to old_clipboard\n \
  return new_clipboard' \
""",
Exemple #13
0
 def wrapped(*args, **kwargs):
     wf = Workflow()
     yt_conn = Connection(wf.stored_data('yt_url'), wf.stored_data('yt_username'), wf.get_password(u'yt_password'))
     r = f(*args, yt_conn = yt_conn, **kwargs)
     return r
from time import time

from urllib2 import URLError
from pocket import Pocket, AuthException, PocketException
from workflow import Workflow, PasswordNotFound

import config

LINK_LIMIT = 2000

if __name__ == '__main__':
    wf = Workflow()
    error = None
    try:
        access_token = wf.get_password('pocket_access_token')
        pocket_instance = Pocket(config.CONSUMER_KEY, access_token)

        item_list = wf.cached_data('pocket_list', max_age=0)
        
        # only use delta syncing if list is not empty
        if item_list and len(item_list) > 0:
            since = wf.cached_data('pocket_since', max_age=0)
        else:
            since = 0

        if not type(item_list) is list:
            item_list = []

        state = 'all' if len(item_list) > 0 else None

        next_since = 0
Exemple #15
0
import argparse
import os
import urlparse
from pocket_api import Pocket, InvalidQueryException
from workflow import Workflow
import config

WF = Workflow()
POCKET = Pocket(config.CONSUMER_KEY, WF.get_password('pocket_access_token'))


def main(_):
    args = parse_args(WF.args)

    if args.add_and_archive:
        add_method = add_and_archive_link
    else:
        add_method = add_link

    # Get tags
    tags = ["alfred"]
    if args.tags:
        tags += [str(s.strip()) for s in args.tags.split(',')]

    current_app = frontmost_app()
    if current_app in ['Google Chrome', 'Safari']:
        link = get_browser_link(current_app)
        if not add_method(link, tags):
            print "%s link invalid." % current_app
            return
        print "%s link added to Pocket." % current_app
    }

    keep = gkeepapi.Keep()
    keep.login(email, password)

    note = keep.createNote(note_dict.get('title', ''),
                           note_dict.get('content', ''))

    if note_dict.get('color', None):
        note.color = color_dict[note_dict['color']]
    if note_dict.get('label', None):
        label_name = note_dict.get('label')
        label = keep.findLabel(label_name)
        if not label:
            label = keep.createLabel(label_name)
        note.labels.add(label)
    keep.sync()
    return note.id


if __name__ == u"__main__":
    wf = Workflow(libraries=['./lib'])
    logger = wf.logger
    import gkeepapi
    args = parser.parse_args()
    note = json.loads(args.query)
    email = wf.get_password('google_keep_email')
    password = wf.get_password('google_keep_password')
    note_id = create_note(note, email, password)
    sys.stdout.write("#NOTE/{}".format(note_id))
Exemple #17
0
        for item in sorted(get_list.values(), key=lambda x: int(x['time_added']), reverse=True):
            item_list.append(item)

        return item_list

    except AuthException:
        return 'error1'
        wf.delete_password('pocket_access_token')
        wf.logger.error(
            'There was a problem receiving your Pocket list. The workflow has been deauthenticated automatically. Please try again!')
    except Exception:
        return 'error2'
        wf.logger.error(
            'Could not contact getpocket.com. Please check your Internet connection and try again!')

    return None

if __name__ == '__main__':
    wf = Workflow()

    try:
        access_token = wf.get_password('pocket_access_token')

        def wrapper():
            return get_list(wf, access_token)

        wf.cached_data('pocket_list', data_func=wrapper, max_age=1)

    except PasswordNotFound:
        wf.logger.error('Password not found!')