4
0

cli.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 (
  95. ctx.params.get("date_format") and param.default == value
  96. ): # If date_format is already set by some other flag, return that same data
  97. return ctx.params.get("date_format")
  98. else:
  99. return value # otherwise, set the format to the passed value
  100. else:
  101. if value:
  102. ctx.params["date_format"] = param.metavar
  103. return value
  104. @click.group(
  105. invoke_without_command=True,
  106. # invoke_without_command=False,
  107. context_settings={"max_content_width": 160, "help_option_names": ["-h", "--help"]},
  108. )
  109. @click.pass_context
  110. @click_config_file.configuration_option(
  111. config_file_name=click.get_app_dir(APP_NAME),
  112. default=click.get_app_dir(APP_NAME),
  113. show_default=True,
  114. expose_value=True,
  115. )
  116. @click.option(
  117. "--user",
  118. "-u",
  119. prompt=True,
  120. required=True,
  121. envvar="GKEEP_USER",
  122. show_envvar=True,
  123. help="Google account email (prompt if empty)",
  124. )
  125. @click.option(
  126. "--password",
  127. "-p",
  128. envvar="GKEEP_PASSWORD",
  129. show_envvar=True,
  130. help="Google account password (prompt if empty). Either this or token is required.",
  131. hide_input=True,
  132. )
  133. @click.option(
  134. "--token",
  135. "-t",
  136. envvar="GKEEP_TOKEN",
  137. help="Google account token from prior run. Either this or password is required.",
  138. callback=token_callback_password_or_token,
  139. )
  140. @click.option(
  141. "--directory",
  142. "-d",
  143. default="./gkeep-export",
  144. show_default=True,
  145. help="Output directory for exported notes",
  146. type=click.Path(file_okay=False, dir_okay=True, writable=True),
  147. )
  148. @click.option(
  149. "--header/--no-header",
  150. default=True,
  151. show_default=True,
  152. help="Choose to include or exclude the frontmatter header",
  153. )
  154. @click.option(
  155. "--delete-local/--no-delete-local",
  156. default=False,
  157. show_default=True,
  158. help="Choose to delete or leave as-is any notes that exist locally but not in Google Keep",
  159. )
  160. @click.option(
  161. "--rename-local/--no-rename-local",
  162. default=False,
  163. show_default=True,
  164. help="Choose to rename or leave as-is any notes that change titles in Google Keep",
  165. )
  166. @click.option( # Other date-options (e.g --iso8601) must come after this one
  167. "--date-format",
  168. "date_format",
  169. default="%Y-%m-%d",
  170. is_flag=False,
  171. show_default=True,
  172. help="Date format to prefix the note filenames. Reflects the created date of the note. uses strftime()",
  173. callback=date_format_handler,
  174. )
  175. @click.option(
  176. "--iso8601",
  177. metavar="%Y-%m-%dT%H:%M:%S", # use `metavar` for the format instead of default or flag_value, hack around click stuff
  178. default=False,
  179. is_flag=True,
  180. help="Format dates in ISO8601 format.",
  181. callback=date_format_handler,
  182. )
  183. @click.option(
  184. "--skip-existing-media/--no-skip-existing-media",
  185. default=True,
  186. show_default=True,
  187. help="Skip existing media if it appears unchanged from the local copy.",
  188. )
  189. def main(
  190. ctx,
  191. directory: str,
  192. user: str,
  193. password: Optional[str],
  194. token: Optional[str],
  195. header: bool,
  196. delete_local: bool,
  197. rename_local: bool,
  198. date_format: str,
  199. iso8601: Any,
  200. skip_existing_media: bool,
  201. config: str, # required to be here, despite being as-of-yet unused.
  202. ):
  203. """A simple utility to export google keep notes to markdown files with metadata stored as a frontmatter header."""
  204. notepath = pathlib.Path(directory).resolve()
  205. mediapath = notepath.joinpath("media/")
  206. print(date_format)
  207. print(iso8601)
  208. quit()
  209. if ctx.invoked_subcommand is not None:
  210. return False
  211. click.echo(f"Notes directory: {notepath}")
  212. click.echo(f"Media directory: {mediapath}")
  213. keep = login(user, password, token)
  214. if not notepath.exists():
  215. click.echo("Notes directory does not exist, creating.")
  216. notepath.mkdir(parents=True)
  217. if not mediapath.exists():
  218. click.echo("Media directory does not exist, creating.")
  219. mediapath.mkdir(parents=True)
  220. click.echo("Indexing local files.")
  221. local_index = index_existing_files(notepath)
  222. click.echo("Indexing remote notes.")
  223. keep_notes = dict([(note.id, note) for note in keep.all()])
  224. skipped_notes, updated_notes, new_notes = 0, 0, 0
  225. downloaded_media = 0
  226. deleted_notes, deleted_media = delete_local_only_files(
  227. local_index, keep_notes, delete_local
  228. )
  229. for note in keep_notes.values(): # type: gkeepapi._node.Note
  230. local_note = local_index.get(note.id)
  231. if not local_note:
  232. click.echo(f"Downloading new note {note.id}")
  233. new_notes += 1
  234. target_path = build_note_unique_path(notepath, note, date_format, local_index)
  235. local_path = local_index.get(note.id, LocalNote(note.id)).path
  236. if local_path:
  237. if rename_local and local_path != target_path:
  238. target_path = try_rename_note(local_index[note.id], target_path)
  239. else:
  240. target_path = local_path
  241. # decide to skip after the rename (due to date format change) has a chance
  242. if local_note:
  243. if local_note.timestamp_updated == note.timestamps.updated:
  244. skipped_notes += 1
  245. continue
  246. else:
  247. updated_notes += 1
  248. click.echo(f"Updating existing file for note {note.id}")
  249. images, downloaded = download_media(keep, note, mediapath, skip_existing_media)
  250. markdown = build_markdown(note, images)
  251. downloaded_media += downloaded
  252. write_note(target_path, header, note, markdown)
  253. click.echo("Finished syncing.")
  254. click.echo(
  255. f"Notes: {skipped_notes} unchanged, {updated_notes} updated, {new_notes} new, {deleted_notes} deleted"
  256. )
  257. click.echo(f"Media: {downloaded_media} downloaded, {deleted_media} deleted")
  258. @main.command()
  259. @click.pass_context
  260. def savetoken(ctx):
  261. """Saves the master token to your configuration file. Avoids re-logging in every time an export happens."""
  262. user, password, token = (
  263. ctx.parent.params.get("user", ""),
  264. ctx.parent.params.get("password", ""),
  265. ctx.parent.params.get("token", ""),
  266. )
  267. keep = login(user, password)
  268. click.echo("Saving master token.")
  269. config_file = ctx.parent.params.get("config", None)
  270. if config_file:
  271. config_obj = ConfigObj(config_file, unrepr=True)
  272. if keep.getMasterToken() != config_obj.get("token", ""):
  273. config_obj["token"] = keep.getMasterToken()
  274. config_obj.write()
  275. click.echo("Master token written to configuration file.")
  276. if __name__ == "__main__":
  277. # pylint: disable=no-value-for-parameter
  278. main()