cli.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #!/usr/bin/env python3
  2. """keep_exporter command line interface module. Provides the actual user interactions to `export.py`."""
  3. __version__ = "2.0.0"
  4. __author__ = "Nathan Beals, Matthew Bafford"
  5. APP_NAME = "Keep Exporter"
  6. import pathlib
  7. from typing import Any, Optional, Tuple, Union
  8. import click
  9. import click_config_file
  10. import frontmatter
  11. import gkeepapi
  12. from configobj import ConfigObj
  13. # from .export import *
  14. from keep_exporter.export import build_frontmatter # login,
  15. from keep_exporter.export import (
  16. LocalNote,
  17. build_markdown,
  18. build_note_unique_path,
  19. delete_local_only_files,
  20. download_media,
  21. index_existing_files,
  22. try_rename_note,
  23. write_note,
  24. )
  25. def login(
  26. user_email: str, password: Optional[str], token: Optional[str] = None
  27. ) -> gkeepapi.Keep:
  28. """Logs in with the given email and password or token.
  29. Args:
  30. user_email (str): user's google email address
  31. password (Optional[str]): account password, either this or `token` are *required*
  32. token (Optional[str], optional): account token, either this or `password` are **required**. Defaults to None.
  33. Raises:
  34. click.BadParameter: Login failed
  35. Returns:
  36. gkeepapi.Keep: the `keep <gkeepapi.Keep>` object
  37. """
  38. keep = gkeepapi.Keep()
  39. if token:
  40. try:
  41. click.echo("Logging in with token")
  42. keep.resume(user_email, token)
  43. return keep
  44. except gkeepapi.exception.LoginException as ex:
  45. raise click.BadParameter(f"Token login (resume) failed: {str(ex)}")
  46. if password:
  47. try:
  48. click.echo("Logging in with password")
  49. keep.login(user_email, password)
  50. return keep
  51. except gkeepapi.exception.LoginException as ex:
  52. raise click.BadParameter(f"Password login failed: {str(ex)}")
  53. raise click.BadParameter(f"Neither password nor token provided to login.")
  54. def get_click_supplied_value(ctx: click.core.Context, param_name: str) -> Any:
  55. """Find the value passed to Click through the following priority:
  56. #1 - a parameter passed on the command line
  57. #2 - a config value passed through @click_config_file
  58. #3 - None
  59. """
  60. # I didn't find in the docs for Click a simpler way to get the
  61. # parameter if specified, fall back to the default_map if not, None if neither
  62. # but this feels like a standard thing that should be built-in
  63. if param_name in ctx.params:
  64. return ctx.params[param_name]
  65. if ctx.default_map:
  66. return ctx.default_map.get(param_name)
  67. return None
  68. def token_callback_password_or_token(
  69. ctx: click.core.Context,
  70. param: Union[click.core.Option, click.core.Parameter],
  71. value: Any,
  72. ) -> Any:
  73. """
  74. On the token param (after password), ensure that either a password
  75. or token were supplied, and if neither was, prompt for the password.
  76. """
  77. if value:
  78. token = value
  79. else:
  80. token = get_click_supplied_value(ctx, "token")
  81. password = get_click_supplied_value(ctx, "password")
  82. if not token and not password:
  83. click.echo("Neither password nor token provided. Prompting for password")
  84. password = click.prompt("Password", hide_input=True)
  85. ctx.params["password"] = password
  86. return None
  87. return token
  88. @click.group(
  89. invoke_without_command=True,
  90. # invoke_without_command=False,
  91. context_settings={"max_content_width": 160, "help_option_names": ["-h", "--help"]},
  92. )
  93. @click.pass_context
  94. @click_config_file.configuration_option(
  95. config_file_name=click.get_app_dir(APP_NAME),
  96. default=click.get_app_dir(APP_NAME),
  97. show_default=True,
  98. expose_value=True,
  99. )
  100. @click.option(
  101. "--user",
  102. "-u",
  103. prompt=True,
  104. required=True,
  105. envvar="GKEEP_USER",
  106. show_envvar=True,
  107. help="Google account email (prompt if empty)",
  108. )
  109. @click.option(
  110. "--password",
  111. "-p",
  112. envvar="GKEEP_PASSWORD",
  113. show_envvar=True,
  114. help="Google account password (prompt if empty). Either this or token is required.",
  115. hide_input=True,
  116. )
  117. @click.option(
  118. "--token",
  119. "-t",
  120. envvar="GKEEP_TOKEN",
  121. help="Google account token from prior run. Either this or password is required.",
  122. callback=token_callback_password_or_token,
  123. )
  124. @click.option(
  125. "--directory",
  126. "-d",
  127. default="./gkeep-export",
  128. show_default=True,
  129. help="Output directory for exported notes",
  130. type=click.Path(file_okay=False, dir_okay=True, writable=True),
  131. )
  132. @click.option(
  133. "--header/--no-header",
  134. default=True,
  135. show_default=True,
  136. help="Choose to include or exclude the frontmatter header",
  137. )
  138. @click.option(
  139. "--delete-local/--no-delete-local",
  140. default=False,
  141. show_default=True,
  142. help="Choose to delete or leave as-is any notes that exist locally but not in Google Keep",
  143. )
  144. @click.option(
  145. "--rename-local/--no-rename-local",
  146. default=False,
  147. show_default=True,
  148. help="Choose to rename or leave as-is any notes that change titles in Google Keep",
  149. )
  150. @click.option(
  151. "--iso8601",
  152. "date_format",
  153. flag_value="%Y-%m-%dT%H:%M:%S",
  154. is_flag=True,
  155. help="Format dates in ISO8601 format."
  156. )
  157. @click.option( # Other date-options (e.g --iso8601) must come before this one
  158. "--date-format",
  159. "date_format",
  160. default="%Y-%m-%d",
  161. is_flag=False,
  162. show_default=True,
  163. help="Date format to prefix the note filenames. Reflects the created date of the note. uses strftime()",
  164. )
  165. @click.option(
  166. "--skip-existing-media/--no-skip-existing-media",
  167. default=True,
  168. show_default=True,
  169. help="Skip existing media if it appears unchanged from the local copy.",
  170. )
  171. def main(
  172. ctx,
  173. directory: str,
  174. user: str,
  175. password: Optional[str],
  176. token: Optional[str],
  177. header: bool,
  178. delete_local: bool,
  179. rename_local: bool,
  180. date_format: str,
  181. skip_existing_media: bool,
  182. config: str, # required to be here, despite being as-of-yet unused.
  183. ):
  184. """A simple utility to export google keep notes to markdown files with metadata stored as a frontmatter header."""
  185. notepath = pathlib.Path(directory).resolve()
  186. mediapath = notepath.joinpath("media/")
  187. if ctx.invoked_subcommand is not None:
  188. return False
  189. click.echo(f"Notes directory: {notepath}")
  190. click.echo(f"Media directory: {mediapath}")
  191. keep = login(user, password, token)
  192. if not notepath.exists():
  193. click.echo("Notes directory does not exist, creating.")
  194. notepath.mkdir(parents=True)
  195. if not mediapath.exists():
  196. click.echo("Media directory does not exist, creating.")
  197. mediapath.mkdir(parents=True)
  198. click.echo("Indexing local files.")
  199. local_index = index_existing_files(notepath)
  200. click.echo("Indexing remote notes.")
  201. keep_notes = dict([(note.id, note) for note in keep.all()])
  202. skipped_notes, updated_notes, new_notes = 0, 0, 0
  203. downloaded_media = 0
  204. deleted_notes, deleted_media = delete_local_only_files(
  205. local_index, keep_notes, delete_local
  206. )
  207. for note in keep_notes.values(): # type: gkeepapi._node.Note
  208. local_note = local_index.get(note.id)
  209. if not local_note:
  210. click.echo(f"Downloading new note {note.id}")
  211. new_notes += 1
  212. target_path = build_note_unique_path(notepath, note, date_format, local_index)
  213. local_path = local_index.get(note.id, LocalNote(note.id)).path
  214. if local_path:
  215. if rename_local and local_path != target_path:
  216. target_path = try_rename_note(local_index[note.id], target_path)
  217. else:
  218. target_path = local_path
  219. # decide to skip after the rename (due to date format change) has a chance
  220. if local_note:
  221. if local_note.timestamp_updated == note.timestamps.updated:
  222. skipped_notes += 1
  223. continue
  224. else:
  225. updated_notes += 1
  226. click.echo(f"Updating existing file for note {note.id}")
  227. images, downloaded = download_media(keep, note, mediapath, skip_existing_media)
  228. markdown = build_markdown(note, images)
  229. downloaded_media += downloaded
  230. write_note(target_path, header, note, markdown)
  231. click.echo("Finished syncing.")
  232. click.echo(
  233. f"Notes: {skipped_notes} unchanged, {updated_notes} updated, {new_notes} new, {deleted_notes} deleted"
  234. )
  235. click.echo(f"Media: {downloaded_media} downloaded, {deleted_media} deleted")
  236. @main.command()
  237. @click.pass_context
  238. def savetoken(ctx):
  239. """Saves the master token to your configuration file. Avoids re-logging in every time an export happens."""
  240. user, password, token = (
  241. ctx.parent.params.get("user", ""),
  242. ctx.parent.params.get("password", ""),
  243. ctx.parent.params.get("token", ""),
  244. )
  245. keep = login(user, password)
  246. click.echo("Saving master token.")
  247. config_file = ctx.parent.params.get("config", None)
  248. if config_file:
  249. config_obj = ConfigObj(config_file, unrepr=True)
  250. if keep.getMasterToken() != config_obj.get("token", ""):
  251. config_obj["token"] = keep.getMasterToken()
  252. config_obj.write()
  253. click.echo("Master token written to configuration file.")
  254. if __name__ == "__main__":
  255. # pylint: disable=no-value-for-parameter
  256. main()