cli.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. def date_format_handler(
  89. ctx: click.core.Context,
  90. param: Union[click.core.Option, click.core.Parameter],
  91. value: Any,
  92. ) -> str:
  93. if param.name == "date_format":
  94. if ctx.params.get('date_format') and param.default == value: # 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. iso8601: Any,
  198. skip_existing_media: bool,
  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. print(date_format)
  205. print(iso8601)
  206. quit()
  207. if ctx.invoked_subcommand is not None:
  208. return False
  209. click.echo(f"Notes directory: {notepath}")
  210. click.echo(f"Media directory: {mediapath}")
  211. keep = login(user, password, token)
  212. if not notepath.exists():
  213. click.echo("Notes directory does not exist, creating.")
  214. notepath.mkdir(parents=True)
  215. if not mediapath.exists():
  216. click.echo("Media directory does not exist, creating.")
  217. mediapath.mkdir(parents=True)
  218. click.echo("Indexing local files.")
  219. local_index = index_existing_files(notepath)
  220. click.echo("Indexing remote notes.")
  221. keep_notes = dict([(note.id, note) for note in keep.all()])
  222. skipped_notes, updated_notes, new_notes = 0, 0, 0
  223. downloaded_media = 0
  224. deleted_notes, deleted_media = delete_local_only_files(
  225. local_index, keep_notes, delete_local
  226. )
  227. for note in keep_notes.values(): # type: gkeepapi._node.Note
  228. local_note = local_index.get(note.id)
  229. if not local_note:
  230. click.echo(f"Downloading new note {note.id}")
  231. new_notes += 1
  232. target_path = build_note_unique_path(notepath, note, date_format, local_index)
  233. local_path = local_index.get(note.id, LocalNote(note.id)).path
  234. if local_path:
  235. if rename_local and local_path != target_path:
  236. target_path = try_rename_note(local_index[note.id], target_path)
  237. else:
  238. target_path = local_path
  239. # decide to skip after the rename (due to date format change) has a chance
  240. if local_note:
  241. if local_note.timestamp_updated == note.timestamps.updated:
  242. skipped_notes += 1
  243. continue
  244. else:
  245. updated_notes += 1
  246. click.echo(f"Updating existing file for note {note.id}")
  247. images, downloaded = download_media(keep, note, mediapath, skip_existing_media)
  248. markdown = build_markdown(note, images)
  249. downloaded_media += downloaded
  250. write_note(target_path, header, note, markdown)
  251. click.echo("Finished syncing.")
  252. click.echo(
  253. f"Notes: {skipped_notes} unchanged, {updated_notes} updated, {new_notes} new, {deleted_notes} deleted"
  254. )
  255. click.echo(f"Media: {downloaded_media} downloaded, {deleted_media} deleted")
  256. @main.command()
  257. @click.pass_context
  258. def savetoken(ctx):
  259. """Saves the master token to your configuration file. Avoids re-logging in every time an export happens."""
  260. user, password, token = (
  261. ctx.parent.params.get("user", ""),
  262. ctx.parent.params.get("password", ""),
  263. ctx.parent.params.get("token", ""),
  264. )
  265. keep = login(user, password)
  266. click.echo("Saving master token.")
  267. config_file = ctx.parent.params.get("config", None)
  268. if config_file:
  269. config_obj = ConfigObj(config_file, unrepr=True)
  270. if keep.getMasterToken() != config_obj.get("token", ""):
  271. config_obj["token"] = keep.getMasterToken()
  272. config_obj.write()
  273. click.echo("Master token written to configuration file.")
  274. if __name__ == "__main__":
  275. # pylint: disable=no-value-for-parameter
  276. main()