예제 #1
0
def get_keep_groceries_list():
    try:
        config = get_config_dictionary()
        username = config['GKeepUsername']
        psw = config['GKeepPassword']
        groceries_list_id = config['GKeepGroceriesId']

        keep = gkeepapi.Keep()
        success = keep.login(username, psw)

        if success:

            groceries = keep.get(groceries_list_id)
            groceries_items = groceries.unchecked

            groceries_list = []

            for _ in groceries_items:
                groceries_list.append(_.text)

            return {"Status": True, "Items": groceries_list}
        else:
            return {"Status": False, "Exception": str(success)}

    except Exception as ex:

        print(ex)
        return {"Status": False, "Exception": str(ex)}
예제 #2
0
def getKeep(username):
  keep = gkeepapi.Keep()
  token = keyring.get_password(KEYRING_KEY, username)
  print(token)
  keep.resume(token)

  return keep
예제 #3
0
def cli(ctx, debug, auth):
    keep = gkeepapi.Keep()
    try:
        keep.login(*get_auth(auth))
    except LoginException:
        raise LoginError
    ctx.obj = {'keep': keep}
예제 #4
0
 def __init__(self, em):
     self.k = gk.Keep()
     self.k.login(em.cfg.from_email, em.cfg.from_pwd)
     self.t_label = self.find_create_label(TODO_label)
     self.d_label = self.find_create_label(DONE_label)
     self.red = gk.node.ColorValue.Red
     self.green = gk.node.ColorValue.Green
예제 #5
0
def generate_config():
    if len(sys.argv) != 4:
        print("Please provide email, password, notes_root in the exactly same order")
        exit(1)

    config = {
        "email": sys.argv[1],
        "password": sys.argv[2],
        "notes_root": sys.argv[3]
    }

    if not path.exists(CONFIG_FOLDER_PATH):
        mkdir(CONFIG_FOLDER_PATH, 0o700)  # Grant access to the user only!

    if not path.exists(DEFAULT_CONFIG_PATH):
        open(DEFAULT_CONFIG_PATH, 'x').close()

    config_path = environ.get('GKEEP_CONFIG_PATH', DEFAULT_CONFIG_PATH)

    keep = gkeepapi.Keep()
    keep.login(config['email'], config['password'])

    config['token'] = keep.getMasterToken()

    json.dump(config, open(config_path, 'w'), indent=2)

    print(f"You can find the config on: {config_path}")
예제 #6
0
def get_notes(wf, query):
    import gkeepapi
    import json

    keep = gkeepapi.Keep()

    if query == u'#':
        return None
    log.info("正在查询文件...")
    # Load cache
    fh = open('state.json', 'r')
    state = json.load(fh)
    keep.restore(state)

    gnotes = []

    # 默认查询固定笔记
    if not query:
        notes = keep.find(pinned=True)
    # 以#开头时按标签查询
    elif query.startswith('#'):
        notes = keep.find(labels=[keep.findLabel(to_ascii(query[1:]))])
    # 按关键词查询
    else:
        notes = keep.find(query=query)

    result = []
    for note in notes:
        f = open(wf.cachefile(note.server_id + ".md"), "w")
        f.write("#" + note.title + "\n\n" + note.text)
        result.append(note)

    if len(result) < 1:
        return None
    return result
예제 #7
0
 def __init__(self):
     try:
         self.keep = gkeepapi.Keep()
         self.keep.login(settings.keep_user, settings.keep_pswd)
     except Exception as e:
         logging.error(e)
         raise e
예제 #8
0
def authenticate(
):  # the first steps that are executed once a user hits 'sign in'
    # print(dir(session))
    if 'credentials' not in session:
        req = request.get_json(force=True)
        # print(req)
        # print (request.get_json(force=True))
        session['keep-user'] = req['login']
        session['keep-pass'] = req['password']
        if req['type'] == "keep":

            try:
                print("b4 keep")
                keepAPI = gkeepapi.Keep()
                keepAPI.login(req['login'], req['password'])
                print("afta keep")
                config.clientServices[req[
                    'login']] = keepAPI  # may result in errror in main loop
                config.servicesCount += 0.5
                return redirect('/authorize')
            except Exception as e:
                print(e)
                return jsonify("Bad Authentication")
        else:

            config.clientServices[
                req['login']] = "noKeep"  # may result in errror in main loop
            config.servicesCount += 0.5
            return redirect('/authorize')

    else:
        print(session['credentials'])
        return ('', 204)
def lambda_handler(event, context):

    #setting environment variables
    user = os.environ['GKEEP_USERNAME']
    pw = os.environ['GKEEP_APP_PASSWORD']
    noteId = os.environ['GKEEP_NOTE_ID']
    authToken = os.environ['EVERNOTE_DEV_TOKEN']
    noteGuid = os.environ['EVERNOTE_NOTE_ID']

    #keep login
    keep = gkeepapi.Keep()
    keep.login(user, pw)

    #getting keep note contents and converting to html
    syncnote = keep.get(noteId)
    syncnotebody = syncnote.text
    enotepayload = textile.textile(syncnotebody)

    #evernote login
    client = EvernoteClient(token=authToken)
    userStore = client.get_user_store()
    user = userStore.getUser()

    #updating the evernote note with the keep note contents
    noteStore = client.get_note_store()
    note = ttypes.Note()
    note.guid = noteGuid
    note.title = 'Shopping List'  #not sure if I should make this a variable
    note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note>' + enotepayload + '</en-note>'
    noteStore.updateNote(authToken, note)

    return 0
예제 #10
0
    def __init__(self) -> None:
        if self._instance is None:
            self._keep_instance = gkeepapi.Keep()
            self._active_users_ids = []
            self._cmd_list = {
                'start': self._start,
                'help': self._help,
                'log_in': self._log_in,
                'log_out': self._log_out,
                'create': self._create_note,
                'read': self._read_note,
                'update': self._update_note,
                'delete': self._delete_note,
                'list': self._list_notes
            }

            self._required_login_cmd_list = ('create', 'read', 'update',
                                             'delete', 'list', 'log_out')

            self._registered_users = GKeepUser.query.all()

            GKeepHandler._instance = self

        else:
            raise Exception('This class is a singleton.')
예제 #11
0
 async def _test_credentials(self, username, password):
     """Return true if credentials is valid."""
     try:
         gkeep = gkeepapi.Keep()
         return gkeep.login(username, password)
     except Exception:  # pylint: disable=broad-except
         pass
     return False
예제 #12
0
def export(liste):
    user = '******'utilisateur compte google'
    password= '******'
    keep = gkeepapi.Keep()
    keep.login(user,password)
    liste_export=[(str(item)+" "+key,False) for key,item in liste.items()]
    keep.createList('liste course',liste_export)
    keep.sync()
예제 #13
0
파일: test.py 프로젝트: isbur/work-paradise
def test_call():
    keep = gkeepapi.Keep()
    success = keep.login('*****@*****.**', 'EpZiL6xOeH')

    note = keep.createNote('Todo', 'Eat breakfast')
    note.pinned = True
    note.color = gkeepapi.node.ColorValue.Red
    keep.sync()
예제 #14
0
def login(username, password):
    keep = gkeepapi.Keep()

    keep.login(username, password)
    masterToken = keep.getMasterToken()
    keyring.set_password(KEYRING_KEY, username, masterToken)

    return keep
예제 #15
0
def initialize_keep(email: str) -> gkeepapi.Keep:
    local_keep = gkeepapi.Keep()

    # Login
    token = keyring.get_password('google-keep-token', email)
    local_keep.resume(email, token)

    return local_keep
예제 #16
0
def login():
    keep = gkeepapi.Keep()
    success = keep.login(UN, PW)

    if success:
        return keep
    else:
        return None
예제 #17
0
 def g_keep_login(self):
     with open(str(self.credential_path), "r") as cred:
         self.config = json.load(cred)
     self.keep = gkeepapi.Keep()
     example = self.keep.login(self.config["username"],
                               self.config["password"])
     token = self.keep.getMasterToken()
     self.g_keep_search()
     self.keep.sync()
예제 #18
0
파일: keep.py 프로젝트: mgckind/keepcli
 def __init__(self, auth_file, conf_file, offline=False):
     # super().__init__()
     cmd.Cmd.__init__(self)
     self.do_clear(None)
     print(
         '\nWelcome to keepcli {}, '
         'use help or ? to list possible commands.\n\n'.format(__version__))
     self.offline = offline
     self.auth_file = auth_file
     self.conf_file = conf_file
     self.current = None
     self.update_config()
     self.kcli_path = os.path.dirname(self.auth_file)
     if self.offline:
         self.autosync = False
     self.prompt = 'keepcli [] ~> '
     self.keep = gkeepapi.Keep()
     if not self.offline:
         try:
             with open(auth_file, 'r') as auth:
                 conn = yaml.load(auth)
         except FileNotFoundError:
             conn = {}
             print('\nAuth file {} not found, will create one... '
                   '(Google App password is strongly recommended)\n'.format(
                       auth_file))
             conn['user'] = input('Enter username : '******'passwd'] = getpass.getpass(prompt='Enter password : '******'\nLogging {} in...\n'.format(
             colored(conn['user'], 'green', self.termcolor)))
         try:
             self.connect = self.keep.login(conn['user'], conn['passwd'])
             with open(auth_file, 'w') as auth:
                 yaml.dump(conn, auth, default_flow_style=False)
             self.username = conn['user']
         except (gkeepapi.exception.LoginException, ValueError) as e:
             if e.__class__.__name__ == 'ValueError':
                 print(
                     "\n Can't login and sync from empty content, please create a note online"
                 )
             else:
                 print(
                     '\nUser/Password not valid (auth file : {})\n'.format(
                         auth_file))
             sys.exit(1)
         self.do_refresh(None, force_sync=True)
     else:
         print(colored('\nRunning Offline\n', "red", self.termcolor))
     self.complete_ul = self.complete_useList
     self.complete_un = self.complete_useNote
     self.do_useNote(self.conf['current'])
     self.do_useList(self.conf['current'])
     self.doc_header = colored(' *Other Commands*', "cyan",
                               self.termcolor) + ' (type help <command>):'
     self.keep_header = colored(' *Keep Commands*', "cyan",
                                self.termcolor) + ' (type help <command>):'
예제 #19
0
def get_api(name):
    keep = gkeepapi.Keep()
    keep.resume(USERNAME, GOOGLE_TOKEN)

    gnote = list(keep.find(name))

    if len(gnote) != 1:
        return None, None
    todolist = gnote[0]

    return keep, todolist
예제 #20
0
    def __init__(self):
        # find Google Account ID and Password
        with open(SECRET_TXT, "r", encoding="utf-8") as Secret:
            reader = Secret.read().split()
            self.account_id = reader[0]
            self.password = reader[1]

        self.keep = gkeepapi.Keep()

        # pass login
        self.keep.login(self.account_id, self.password)
예제 #21
0
def getFromKeep(email, token, name):
    keep = gkeepapi.Keep()
    success = keep.login(email, token)

    gnotes = keep.find(query=name)
    for note in gnotes:
        gnote = note
    # noda = nodes['177b5438cd8.82b17d320d61d816']

    keep.sync()
    return gnote.text.split('\n')
예제 #22
0
 def run(self):
     self.keep = gkeepapi.Keep()
     self.keep.login(self.username, self.password)
     
     # try:
     note = self.keep.createNote(self.parser.k.mandatoryPhrase.titlePhrase, self.parser.k.mandatoryPhrase.textPhrase)
     note.pinned = self.parser.k.optionalPhrase.pinned
     note.color = self.parser.k.optionalPhrase.color
     # except Exception as error:
     #     raise RuntimeError("Error creating note: %s" % str(error))
     self.keep.sync()
예제 #23
0
def main(stdscr):
    fh = open('config.yml', 'r')
    config = yaml.load(fh, Loader=yaml.Loader)
    fh.close()

    password = keyring.get_password('google-keep', config['username'])

    keep = gkeepapi.Keep()
    keep.login(config['username'], password)

    ui = KeepUI(stdscr, keep, config)
    ui.process()
예제 #24
0
def keep_api_test():
    # a package from the 'https://github.com/kiwiz/gkeepapi' project
    import gkeepapi

    print('--keep_api_test')
    with open('usr') as f:
        usr = f.read()
    # with open('psw') as f: psw = f.read()
    psw = getpass('')
    keep = gkeepapi.Keep()
    success = keep.login(usr, psw)

    print('connected:', success)
예제 #25
0
def get_checklist_from_keep():
    logging.info("Connecting to Google Keep")
    keep = gkeepapi.Keep()
    success = keep.login(SECRETS.KEEP_GOOGLE_ACCOUNT, SECRETS.KEEP_AUTH_TOKEN)
    if success:
        gnotes = keep.find(query=SECRETS.KEEP_NOTE_NAME,pinned=True)
        list_gnotes=list(gnotes)
        # logging.info(gnotes.title)
    if len(list_gnotes)>1:
        logging.exception("Too many notes !")
        raise ValueError(f"Too Many Pinned notes in keep with the name {SECRETS.KEEP_NOTE_NAME}")

    return keep,list_gnotes[0]
예제 #26
0
    def __init__(self):
        self.keep = gkeepapi.Keep()
        self.config = configparser.ConfigParser()
        self.config.read('config.ini')
        self.username = self.config['credentials']['username']
        self.password = self.config['credentials']['password']
        self.notes_root = pathlib.Path(self.config['paths']['notes_root'])
        self.token = keyring.get_password('google-keep-token', self.username)

        if not self.token:
            self.login(self.username, self.password)
        else:
            self.resume(self.username, self.token)
    def __init__(self, login, pwd, cache_path=None, **kwargs):
        self.keep = gkeepapi.Keep()
        self.keep.login(login, pwd)

        if cache_path is not None:
            cachefile_path = os.path.join(cache_path, self.NOTES_CACHEFILE)
            # restore dat from cache
            if os.path.exists(cachefile_path):
                with open(cachefile_path, 'r') as fh:
                    self.keep.restore(json.load(fh))
            # update data
            try:
                self.keep.sync()
            except gkeepapi.exception.ResyncRequiredException:
                self.keep = gkeepapi.Keep()
                self.keep.login(login, pwd)
                self.keep.sync()
            # save updated data to cache
            with open(cachefile_path, 'w') as fh:
                json.dump(self.keep.dump(), fh)
        else:
            self.keep.sync()
예제 #28
0
def get_gkeep():
    keep = gkeepapi.Keep()
    if os.path.isfile(ConfigGKeep.PATH_TO_FILE):
        with open(ConfigGKeep.PATH_TO_FILE, 'r') as f:
            keep.resume(ConfigGKeep.EMAIL,
                        ConfigGKeep.TOKEN,
                        state=json.load(f))
    else:
        with open(ConfigGKeep.PATH_TO_FILE, 'w') as f:
            keep.resume(ConfigGKeep.EMAIL, ConfigGKeep.TOKEN)
            json.dump(keep.dump(), f)

    return keep
    def __init__(self):

        self.title = []
        self.content = []
        self.year = []
        self.month = []
        self.day = []

        # find Google Account ID and Password
        self.keep = gkeepapi.Keep()
        r = self.keep.login(ACCOUNT_ID, PASSWORD)
        print("LOGIN :"******"#" * 30, r, "#" * 30)

        self.keep.sync()
예제 #30
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Google Keep Notes sensor platform."""
    import gkeepapi

    name = config.get(CONF_NAME)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    list_id = config.get(CONF_LIST_ID)

    keep = gkeepapi.Keep()

    keep.login(username, password)

    add_devices([KeepNotesSensor(hass, name, keep, list_id)])