cli.py 9.8 KB

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