export.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. #!/usr/bin/env python3
  2. import datetime
  3. import mimetypes
  4. import os
  5. import pathlib
  6. import typing
  7. from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union, ValuesView
  8. import click
  9. import frontmatter
  10. import gkeepapi
  11. from gkeepapi.node import NodeAudio, NodeDrawing, NodeImage
  12. from mdutils.mdutils import MdUtils
  13. from pathvalidate import sanitize_filename
  14. mimetypes.add_type("audio/3gpp", ".3gp")
  15. def login(user_email: str, password: str) -> gkeepapi.Keep:
  16. keep = gkeepapi.Keep()
  17. try:
  18. keep.login(user_email, password)
  19. except gkeepapi.exception.LoginException as ex:
  20. raise click.BadParameter(f"Login failed: {str(ex)}")
  21. return keep
  22. def all_note_media(
  23. note: gkeepapi._node.Note,
  24. ) -> List[Union[NodeImage, NodeDrawing, NodeAudio]]:
  25. """
  26. Returns a filtered list of only "media" blobs associate with the note.
  27. Currently NodeDrawing, NodeImage, and NodeMedia.
  28. There are other blob types, but they don't seem actionable as media.
  29. """
  30. return note.images + note.drawings + note.audio
  31. def download_images(
  32. keep: gkeepapi.Keep,
  33. note: gkeepapi._node.Note,
  34. mediapath: pathlib.Path,
  35. skip_existing: bool,
  36. ) -> Tuple[List[pathlib.Path], int]:
  37. note_media = all_note_media(note)
  38. if not note_media:
  39. return ([], 0)
  40. ret = []
  41. downloaded_media = 0
  42. for media in note_media:
  43. meta = media.blob.save()
  44. # ocr = meta["extracted_text"] # TODO save ocr as metadata? in markdown or image?
  45. if meta.get("type", "") == "DRAWING":
  46. extension = mimetypes.guess_extension(
  47. meta.get("drawingInfo", {})
  48. .get("snapshotData", {})
  49. .get("mimetype", "image/png")
  50. ) # All drawings seem to be pngs
  51. elif meta.get("type") == "IMAGE":
  52. extension = mimetypes.guess_extension(meta.get("mimetype", "image/jpeg"))
  53. # .jpe just feels weird, but it's my default in testing
  54. if extension == ".jpe":
  55. extension = ".jpg"
  56. else: # 'AUDIO'
  57. extension = mimetypes.guess_extension(meta.get("mimetype", "audio/3gpp"))
  58. # nest media files under folders named by the note's ID
  59. # this simplifies figuring out the note media files came from
  60. note_media_path = mediapath / note.id
  61. note_media_path.mkdir(exist_ok=True)
  62. media_file = (
  63. note_media_path / f"{sanitize_filename(media.id,max_len=135)}{extension}"
  64. )
  65. # checking size isn't perfect, and drawings don't have a size,
  66. # but it doesn't seem right to always re-download images that likely
  67. # haven't changed
  68. if (
  69. skip_existing
  70. and media_file.exists()
  71. and hasattr(media.blob, "byte_size")
  72. and media_file.stat().st_size == media.blob.byte_size
  73. ):
  74. click.echo(
  75. f"Media file f{media_file} exists and is same size as in Google Keep. Skipping."
  76. )
  77. else:
  78. print(f"Downloading media {meta.get('type')} {media.id} for note {note.id}")
  79. url = keep._media_api.get(media)
  80. media_data = keep._media_api._session.get(url)
  81. with media_file.open("wb") as f:
  82. f.write(media_data.content)
  83. downloaded_media += 1
  84. ret.append(media_file)
  85. return (ret, downloaded_media)
  86. def build_frontmatter(note: gkeepapi._node.Note, markdown: str) -> frontmatter.Post:
  87. metadata = {
  88. "google_keep_id": note.id,
  89. "title": note.title,
  90. "pinned": note.pinned,
  91. "trashed": note.trashed,
  92. "deleted": note.deleted,
  93. "color": note.color.name,
  94. "type": note.type.name,
  95. "parent_id": note.parent_id,
  96. "sort": note.sort,
  97. "url": note.url,
  98. "tags": [label.name for label in note.labels.all()],
  99. "timestamps": {
  100. "created": note.timestamps.created.timestamp(),
  101. "edited": note.timestamps.edited.timestamp(),
  102. "updated": note.timestamps.updated.timestamp(),
  103. },
  104. }
  105. # gkeepapi appears to be treating "0" as a timestamp rather than null. Sometimes the data structure does not have the key at all instead of 0.
  106. if note.timestamps.trashed and note.timestamps.trashed.year > 1970:
  107. metadata["timestamps"]["trashed"] = note.timestamps.trashed.timestamp()
  108. if note.timestamps.deleted and note.timestamps.deleted.year > 1970:
  109. metadata["timestamps"]["deleted"] = note.timestamps.deleted.timestamp()
  110. return frontmatter.Post(markdown, handler=None, **metadata)
  111. def build_markdown(note: gkeepapi._node.Note, images: List[pathlib.Path]) -> str:
  112. doc = MdUtils(
  113. ""
  114. ) # mdutils requires a string file name. Since we're not using it to write files, we can ignore that.
  115. doc.new_header(1, note.title)
  116. doc.new_header(2, "Note")
  117. text = note.text
  118. text = text.replace("☑ ", "- [X] ")
  119. text = text.replace("☐ ", "- [ ] ")
  120. doc.new_paragraph(text)
  121. if note.annotations.links:
  122. doc.new_line()
  123. doc.new_line()
  124. doc.new_header(2, "Links")
  125. doc.new_list(
  126. [
  127. doc.new_inline_link(link=link.url, text=link.title)
  128. for link in note.annotations.links
  129. ]
  130. )
  131. if images:
  132. doc.new_line()
  133. doc.new_header(2, "Attached Media")
  134. for image in images:
  135. doc.new_line(doc.new_inline_image("", image.name))
  136. return doc.file_data_text
  137. LocalMedia = NamedTuple(
  138. "LocalMedia",
  139. [
  140. ("path", pathlib.Path),
  141. ("google_keep_note_id", str),
  142. ("google_keep_media_id", str),
  143. ],
  144. )
  145. class LocalNote:
  146. def __init__(
  147. self,
  148. google_keep_id: str,
  149. path: Optional[pathlib.Path] = None,
  150. timestamp_updated: Optional[datetime.datetime] = None,
  151. local_media: Dict[str, LocalMedia] = None,
  152. ):
  153. self.google_keep_id = google_keep_id
  154. self.path = path
  155. self.timestamp_updated = timestamp_updated
  156. if not local_media:
  157. self.local_media: Dict[str, LocalMedia] = {}
  158. else:
  159. self.local_media = local_media
  160. def index_existing_files(directory: pathlib.Path) -> Dict[str, LocalNote]:
  161. """
  162. Scans the output folder looking for existing markdown files
  163. and media files and builds an index by google_keep_id of those files
  164. using the metadata in the markdown frontmatter and the filenames
  165. of the media files.
  166. """
  167. index: Dict[str, LocalNote] = {}
  168. keep_notes = 0
  169. unknown_notes = 0
  170. errors = 0
  171. media = 0
  172. for file in directory.rglob("*"):
  173. if not file.is_file():
  174. continue
  175. # markdown file
  176. if file.name.endswith(".md"):
  177. try:
  178. with open(file, "r") as f:
  179. fm = frontmatter.load(f)
  180. google_keep_id: str = fm.metadata.get("google_keep_id")
  181. if google_keep_id:
  182. if google_keep_id in index and index[google_keep_id].path:
  183. click.echo(
  184. f"Same Google Keep ID {google_keep_id} in multiple files:\n"
  185. f" {file}\n"
  186. f" {index[google_keep_id].path}\n"
  187. f"Only the last file will be updated."
  188. )
  189. keep_notes += 1
  190. index.setdefault(google_keep_id, LocalNote(google_keep_id))
  191. updated: datetime.datetime = datetime.datetime.fromtimestamp(
  192. fm.metadata.get("timestamps", {}).get("updated")
  193. )
  194. index[google_keep_id].timestamp_updated = updated
  195. index[google_keep_id].path = file
  196. else:
  197. unknown_notes += 1
  198. except IOError as ex:
  199. errors = 0
  200. click.echo(
  201. "Unable to open Markdown file [{os.path.join(root, file)}]. Skipping: {str(ex)}",
  202. err=True,
  203. )
  204. # media file
  205. else:
  206. media += 1
  207. google_keep_id = file.parent.name
  208. media_id = ".".join(file.name.split(".")[0:2])
  209. index.setdefault(google_keep_id, LocalNote(google_keep_id))
  210. index[google_keep_id].local_media[media_id] = LocalMedia(
  211. file, google_keep_id, media_id
  212. )
  213. click.echo(
  214. f"Indexed local files: {keep_notes} Google Keep notes, {unknown_notes} unknown markdown files, {media} media files, {errors} errors"
  215. )
  216. return index
  217. def try_rename_note(note: LocalNote, target_file: pathlib.Path) -> pathlib.Path:
  218. """
  219. Attempts to rename an existing note to the new canonical filename,
  220. but accepts failures to rename. Returns the path the note now exists
  221. in, either the old path or the new renamed path.
  222. """
  223. if not note.path:
  224. return target_file
  225. click.echo(f"Renaming [{note.path}] to [{target_file}]")
  226. try:
  227. note.path.rename(target_file)
  228. return target_file
  229. except Exception as ex:
  230. click.echo(f"Unable to rename note. Using existing name: %s" % ex, err=True)
  231. return note.path
  232. def build_note_unique_path(
  233. notepath: pathlib.Path,
  234. note: gkeepapi._node.Note,
  235. date_format: str,
  236. local_index: Dict[str, LocalNote],
  237. ) -> pathlib.Path:
  238. title = note.title.strip()
  239. if not len(title):
  240. title = "untitled"
  241. date_str = note.timestamps.created.strftime(date_format)
  242. filename = f'{sanitize_filename(f"{date_str} - " + title,max_len=135)}.md'
  243. target_path = notepath / filename
  244. local_note = local_index.get(note.id)
  245. local_path = local_note.path if local_note else None
  246. if local_path:
  247. # if the note filename matches the current filename for that note, then we're good
  248. if local_path == target_path:
  249. return local_path
  250. # if re-naming would result in having to de-dupe the target filename, keep the
  251. # exising filename - initial pass at fixing this just resulted in bouncing between
  252. # two different filenames each pass
  253. if target_path.exists():
  254. click.echo(
  255. f"Note {note.id} will not be renamed. Target file [{target_path}] exists."
  256. )
  257. return local_path
  258. # otherwise, if the file already exists avoid overwriting it
  259. # put the unique note ID and an incrementing index at the end of the filename
  260. dedupe_index = 1
  261. while target_path.exists():
  262. filename = f'{sanitize_filename(f"{date_str} - " + title,max_len=135)}.{note.id}.{dedupe_index}.md'
  263. target_path = notepath / filename
  264. dedupe_index += 1
  265. return target_path
  266. def delete_local_only_files(
  267. local_index: Dict[str, LocalNote],
  268. keep_notes: Dict[str, List[gkeepapi.node.Note]],
  269. delete_local: bool,
  270. ) -> Tuple[int, int]:
  271. """
  272. Checks the local index for any notes or media that exist only locally
  273. and were not returned in the Google Keep API call.
  274. """
  275. deleted_notes, deleted_media = 0, 0
  276. local_only_note_ids = set(local_index.keys()).difference(set(keep_notes.keys()))
  277. if local_only_note_ids:
  278. if not delete_local:
  279. click.echo(
  280. f"{len(local_only_note_ids)} notes exist locally, but not in Google Keep. Add argument [--delete-local] to delete."
  281. )
  282. else:
  283. click.echo(
  284. f"{len(local_only_note_ids)} notes exist locally, but not in Google Keep. Trashing local files."
  285. )
  286. for note_id in local_only_note_ids:
  287. note_path = local_index[note_id].path
  288. deleted_notes += 1
  289. if note_path:
  290. click.echo(
  291. f" Deleting unknown local note [{note_id}] file [{local_index[note_id].path}]"
  292. )
  293. note_path.unlink()
  294. local_only_media: Set[Tuple[str, str]] = set(
  295. [
  296. (local_media.google_keep_note_id, local_media.google_keep_media_id)
  297. for local_note in local_index.values()
  298. for local_media in local_note.local_media.values()
  299. if local_media.google_keep_note_id and local_media.google_keep_media_id
  300. ]
  301. )
  302. notes: ValuesView[gkeepapi._node.Note] = keep_notes.values()
  303. keep_media: Set[Tuple[str, str]] = set(
  304. [
  305. (keep_note.id, keep_media.id)
  306. for keep_note in notes
  307. for keep_media in all_note_media(keep_note)
  308. ]
  309. )
  310. local_only_media_ids = local_only_media.difference(keep_media)
  311. if not local_only_media_ids:
  312. return (deleted_notes, 0)
  313. if not delete_local:
  314. click.echo(
  315. f"{len(local_only_note_ids)} media files exist locally, but not in Google Keep. Add argument [--delete-local] to delete."
  316. )
  317. return (deleted_notes, 0)
  318. for (note_id, media_id) in local_only_media_ids:
  319. media = local_index[note_id].local_media[media_id]
  320. click.echo(
  321. f" Deleting media [{media_id}] for note [{note_id}] file [{media.path}]"
  322. )
  323. media.path.unlink()
  324. deleted_media += 1
  325. return (deleted_notes, deleted_media)
  326. @click.command(
  327. context_settings={"max_content_width": 120, "help_option_names": ["-h", "--help"]}
  328. )
  329. @click.option(
  330. "--user",
  331. "-u",
  332. prompt=True,
  333. required=True,
  334. envvar="GKEEP_USER",
  335. show_envvar=True,
  336. help="Google account email (prompt if empty)",
  337. )
  338. @click.option(
  339. "--password",
  340. "-p",
  341. prompt=True,
  342. required=True,
  343. envvar="GKEEP_PASSWORD",
  344. show_envvar=True,
  345. help="Google account password (prompt if empty)",
  346. hide_input=True,
  347. )
  348. @click.option(
  349. "--directory",
  350. "-d",
  351. default="./gkeep-export",
  352. show_default=True,
  353. help="Output directory for exported notes",
  354. type=click.Path(file_okay=False, dir_okay=True, writable=True),
  355. )
  356. @click.option(
  357. "--header/--no-header",
  358. default=True,
  359. show_default=True,
  360. help="Choose to include or exclude the frontmatter header",
  361. )
  362. @click.option(
  363. "--delete-local/--no-delete-local",
  364. default=False,
  365. show_default=True,
  366. help="Choose to delete or leave as-is any notes that exist locally but not in Google Keep",
  367. )
  368. @click.option(
  369. "--rename-local/--no-rename-local",
  370. default=False,
  371. show_default=True,
  372. help="Choose to rename or leave as-is any notes that change titles in Google Keep",
  373. )
  374. @click.option(
  375. "--date-format",
  376. default="%Y-%m-%d",
  377. show_default=True,
  378. help="Date format to use for the prefix of the note filenames. Reflects the created date of the note.",
  379. )
  380. @click.option(
  381. "--skip-existing-media/--no-skip-existing-media",
  382. default=True,
  383. show_default=True,
  384. help="Skip existing media if it appears unchanged from the local copy.",
  385. )
  386. def main(
  387. directory: str,
  388. user: str,
  389. password: str,
  390. header: bool,
  391. delete_local: bool,
  392. rename_local: bool,
  393. date_format: str,
  394. skip_existing_media: bool,
  395. ):
  396. """A simple utility to export google keep notes to markdown files with metadata stored as a frontmatter header."""
  397. notepath = pathlib.Path(directory).resolve()
  398. mediapath = notepath.joinpath("media/")
  399. click.echo(f"Notes directory: {notepath}")
  400. click.echo(f"Media directory: {mediapath}")
  401. click.echo("Logging in.")
  402. keep = login(user, password)
  403. if not notepath.exists():
  404. click.echo("Notes directory does not exist, creating.")
  405. notepath.mkdir(parents=True)
  406. if not mediapath.exists():
  407. click.echo("Media directory does not exist, creating.")
  408. mediapath.mkdir(parents=True)
  409. click.echo("Indexing local files.")
  410. local_index = index_existing_files(notepath)
  411. click.echo("Indexing remote notes.")
  412. keep_notes = dict([(note.id, note) for note in keep.all()])
  413. skipped_notes, updated_notes, new_notes = 0, 0, 0
  414. downloaded_media = 0
  415. deleted_notes, deleted_media = delete_local_only_files(
  416. local_index, keep_notes, delete_local
  417. )
  418. for note in keep_notes.values(): # type: gkeepapi._node.Note
  419. local_note = local_index.get(note.id)
  420. if local_note:
  421. if local_note.timestamp_updated == note.timestamps.updated:
  422. skipped_notes += 1
  423. continue
  424. else:
  425. updated_notes += 1
  426. click.echo(f"Updating existing file for note {note.id}")
  427. else:
  428. click.echo(f"Downloading new note {note.id}")
  429. new_notes += 1
  430. target_path = build_note_unique_path(notepath, note, date_format, local_index)
  431. local_path = local_index.get(note.id, LocalNote(note.id)).path
  432. if local_path:
  433. if rename_local and local_path != target_path:
  434. target_path = try_rename_note(local_index[note.id], target_path)
  435. else:
  436. target_path = local_path
  437. images, downloaded = download_images(keep, note, mediapath, skip_existing_media)
  438. markdown = build_markdown(note, images)
  439. downloaded_media += downloaded
  440. with target_path.open("wb+") as f:
  441. if header:
  442. fmatter = build_frontmatter(note, markdown)
  443. frontmatter.dump(fmatter, f)
  444. else:
  445. f.write(markdown.encode("utf-8"))
  446. click.echo("Finished syncing.")
  447. click.echo(
  448. f"Notes: {skipped_notes} unchanged, {updated_notes} updated, {new_notes} new, {deleted_notes} deleted"
  449. )
  450. click.echo(f"Media: {downloaded_media} downloaded, {deleted_media} deleted")
  451. if __name__ == "__main__":
  452. main()