export.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. #!/usr/bin/env python3
  2. # pylint: disable=protected-access
  3. import datetime
  4. import mimetypes
  5. import pathlib
  6. from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union, ValuesView
  7. import click
  8. # import click_config_file
  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 all_note_media(
  16. note: gkeepapi._node.Note,
  17. ) -> List[Union[NodeImage, NodeDrawing, NodeAudio]]:
  18. """
  19. Returns a filtered list of only "media" blobs associate with the note.
  20. Currently NodeDrawing, NodeImage, and NodeMedia.
  21. There are other blob types, but they don't seem actionable as media.
  22. """
  23. return note.images + note.drawings + note.audio
  24. def download_media(
  25. keep: gkeepapi.Keep,
  26. note: gkeepapi._node.Note,
  27. mediapath: pathlib.Path,
  28. skip_existing: bool,
  29. ) -> Tuple[List[pathlib.Path], int]:
  30. note_media = all_note_media(note)
  31. if not note_media:
  32. return ([], 0)
  33. ret = []
  34. downloaded_media = 0
  35. for media in note_media:
  36. meta = media.blob.save()
  37. # ocr = meta["extracted_text"] # TODO save ocr as metadata? in markdown or image?
  38. if meta.get("type", "") == "DRAWING":
  39. extension = mimetypes.guess_extension(
  40. meta.get("drawingInfo", {})
  41. .get("snapshotData", {})
  42. .get("mimetype", "image/png")
  43. ) # All drawings seem to be pngs
  44. elif meta.get("type") == "IMAGE":
  45. extension = mimetypes.guess_extension(meta.get("mimetype", "image/jpeg"))
  46. # .jpe just feels weird, but it's my default in testing
  47. if extension == ".jpe":
  48. extension = ".jpg"
  49. else: # 'AUDIO'
  50. extension = mimetypes.guess_extension(meta.get("mimetype", "audio/3gpp"))
  51. # nest media files under folders named by the note's ID
  52. # this simplifies figuring out the note media files came from
  53. note_media_path = mediapath / note.id
  54. note_media_path.mkdir(exist_ok=True)
  55. media_file = (
  56. note_media_path / f"{sanitize_filename(media.id,max_len=135)}{extension}"
  57. )
  58. # checking size isn't perfect, and drawings don't have a size,
  59. # but it doesn't seem right to always re-download images that likely
  60. # haven't changed
  61. if (
  62. skip_existing
  63. and media_file.exists()
  64. and hasattr(media.blob, "byte_size")
  65. and media_file.stat().st_size == media.blob.byte_size
  66. ):
  67. click.echo(
  68. f"Media file f{media_file} exists and is same size as in Google Keep. Skipping."
  69. )
  70. else:
  71. print(f"Downloading media {meta.get('type')} {media.id} for note {note.id}")
  72. url = keep._media_api.get(media)
  73. media_data = keep._media_api._session.get(url)
  74. with media_file.open("wb") as file_handle:
  75. file_handle.write(media_data.content)
  76. downloaded_media += 1
  77. ret.append(media_file)
  78. return (ret, downloaded_media)
  79. def build_frontmatter(note: gkeepapi._node.Note, markdown: str) -> frontmatter.Post:
  80. metadata = {
  81. "title": note.title,
  82. "url": note.url,
  83. "pinned": note.pinned,
  84. "archived": note.archived,
  85. "trashed": note.trashed,
  86. # "deleted": note.deleted, # unused, when google keep actually ~deletes~ a note, the api no longer returns it
  87. "tags": [label.name for label in note.labels.all()],
  88. "color": note.color.name,
  89. "timestamps": {
  90. "created": note.timestamps.created.timestamp(),
  91. "edited": note.timestamps.edited.timestamp(),
  92. "updated": note.timestamps.updated.timestamp(),
  93. },
  94. "google_keep_id": note.id,
  95. "type": note.type.name,
  96. "parent_id": note.parent_id,
  97. "sort": note.sort,
  98. }
  99. # gkeepapi appears to be treating "0" as a timestamp rather than null.
  100. # Sometimes the data structure does not have the key at all instead of 0.
  101. if note.timestamps.trashed and note.timestamps.trashed.year > 1970:
  102. metadata["timestamps"]["trashed"] = note.timestamps.trashed.timestamp()
  103. if note.timestamps.deleted and note.timestamps.deleted.year > 1970:
  104. metadata["timestamps"]["deleted"] = note.timestamps.deleted.timestamp()
  105. return frontmatter.Post(markdown, handler=None, **metadata)
  106. def build_markdown(note: gkeepapi._node.Note, images: List[pathlib.Path]) -> str:
  107. doc = MdUtils(
  108. ""
  109. ) # mdutils requires a string file name. We're not using it to write files, ignore it.
  110. doc.new_header(1, note.title)
  111. doc.new_header(2, "Note")
  112. text = note.text
  113. text = text.replace("☑ ", "- [X] ")
  114. text = text.replace("☐ ", "- [ ] ")
  115. doc.new_paragraph(text)
  116. if note.annotations.links:
  117. doc.new_line()
  118. doc.new_line()
  119. doc.new_header(2, "Links")
  120. doc.new_list(
  121. [
  122. doc.new_inline_link(link=link.url, text=link.title)
  123. for link in note.annotations.links
  124. ]
  125. )
  126. if images:
  127. doc.new_line()
  128. doc.new_header(2, "Attached Media")
  129. for image in images:
  130. doc.new_line(doc.new_inline_image("", image.name))
  131. return doc.file_data_text
  132. def write_note(target_path, header, note, markdown):
  133. """Writes built notes to disk, optionally builds a header/frontmatter too."""
  134. with target_path.open("wb+") as file_handle:
  135. if header:
  136. front_matter = build_frontmatter(note, markdown)
  137. frontmatter.dump(
  138. front_matter, file_handle, sort_keys=False
  139. ) # don't sort frontmatter keys
  140. else:
  141. file_handle.write(markdown.encode("utf-8"))
  142. LocalMedia = NamedTuple(
  143. "LocalMedia",
  144. [
  145. ("path", pathlib.Path),
  146. ("google_keep_note_id", str),
  147. ("google_keep_media_id", str),
  148. ],
  149. )
  150. class LocalNote:
  151. def __init__(
  152. self,
  153. google_keep_id: str,
  154. path: Optional[pathlib.Path] = None,
  155. timestamp_updated: Optional[datetime.datetime] = None,
  156. local_media: Dict[str, LocalMedia] = None,
  157. ):
  158. self.google_keep_id = google_keep_id
  159. self.path = path
  160. self.timestamp_updated = timestamp_updated
  161. if not local_media:
  162. self.local_media: Dict[str, LocalMedia] = {}
  163. else:
  164. self.local_media = local_media
  165. def index_existing_files(directory: pathlib.Path) -> Dict[str, LocalNote]:
  166. """
  167. Scans the output folder looking for existing markdown files
  168. and media files and builds an index by google_keep_id of those files
  169. using the metadata in the markdown frontmatter and the filenames
  170. of the media files.
  171. """
  172. index: Dict[str, LocalNote] = {}
  173. keep_notes = 0
  174. unknown_notes = 0
  175. errors = 0
  176. media = 0
  177. for file in directory.rglob("*"):
  178. if not file.is_file():
  179. continue
  180. # markdown file
  181. if file.name.endswith(".md"):
  182. try:
  183. with open(file, "r") as file_handle:
  184. fm = frontmatter.load(file_handle)
  185. google_keep_id: str = fm.metadata.get("google_keep_id")
  186. if google_keep_id:
  187. if google_keep_id in index and index[google_keep_id].path:
  188. click.echo(
  189. f"Same Google Keep ID {google_keep_id} in multiple files:\n"
  190. f" {file}\n"
  191. f" {index[google_keep_id].path}\n"
  192. f"Only the last file will be updated."
  193. )
  194. keep_notes += 1
  195. index.setdefault(google_keep_id, LocalNote(google_keep_id))
  196. updated: datetime.datetime = datetime.datetime.fromtimestamp(
  197. fm.metadata.get("timestamps", {}).get("updated")
  198. )
  199. index[google_keep_id].timestamp_updated = updated
  200. index[google_keep_id].path = file
  201. else:
  202. unknown_notes += 1
  203. except IOError as ex:
  204. errors = 0
  205. click.echo(
  206. f"Unable to open Markdown file {file}. Skipping: {str(ex)}",
  207. err=True,
  208. )
  209. # media file
  210. else:
  211. media += 1
  212. google_keep_id = file.parent.name
  213. media_id = ".".join(file.name.split(".")[0:2])
  214. index.setdefault(google_keep_id, LocalNote(google_keep_id))
  215. index[google_keep_id].local_media[media_id] = LocalMedia(
  216. file, google_keep_id, media_id
  217. )
  218. click.echo(
  219. f"Indexed local files: {keep_notes} Google Keep notes, {unknown_notes} unknown markdown files, {media} media files, {errors} errors"
  220. )
  221. return index
  222. def try_rename_note(note: LocalNote, target_file: pathlib.Path) -> pathlib.Path:
  223. """
  224. Attempts to rename an existing note to the new canonical filename,
  225. but accepts failures to rename. Returns the path the note now exists
  226. in, either the old path or the new renamed path.
  227. """
  228. if not note.path:
  229. return target_file
  230. click.echo(f"Renaming [{note.path}] to [{target_file}]")
  231. try:
  232. note.path.rename(target_file)
  233. return target_file
  234. except Exception as ex:
  235. click.echo(f"Unable to rename note. Using existing name: {ex}", err=True)
  236. return note.path
  237. def build_note_unique_path(
  238. notepath: pathlib.Path,
  239. note: gkeepapi._node.Note,
  240. date_format: str,
  241. local_index: Dict[str, LocalNote],
  242. ) -> pathlib.Path:
  243. title = note.title.strip()
  244. if not len(title):
  245. title = "untitled"
  246. date_str = note.timestamps.created.strftime(date_format)
  247. filename = f'{sanitize_filename(f"{date_str} - " + title,max_len=135)}.md'
  248. target_path = notepath / filename
  249. local_note = local_index.get(note.id)
  250. local_path = local_note.path if local_note else None
  251. if local_path:
  252. # if the note filename matches the current filename for that note, then we're good
  253. if local_path == target_path:
  254. return local_path
  255. # if re-naming would result in having to de-dupe the target filename, keep the
  256. # exising filename - initial pass at fixing this just resulted in bouncing between
  257. # two different filenames each pass
  258. if target_path.exists():
  259. click.echo(
  260. f"Note {note.id} will not be renamed. Target file [{target_path}] exists."
  261. )
  262. return local_path
  263. # otherwise, if the file already exists avoid overwriting it
  264. # put the unique note ID and an incrementing index at the end of the filename
  265. dedupe_index = 1
  266. while target_path.exists():
  267. filename = f'{sanitize_filename(f"{date_str} - " + title,max_len=135)}.{note.id}.{dedupe_index}.md'
  268. target_path = notepath / filename
  269. dedupe_index += 1
  270. return target_path
  271. def delete_local_only_files(
  272. local_index: Dict[str, LocalNote],
  273. keep_notes: Dict[str, List[gkeepapi.node.Note]],
  274. delete_local: bool,
  275. ) -> Tuple[int, int]:
  276. """
  277. Checks the local index for any notes or media that exist only locally
  278. and were not returned in the Google Keep API call.
  279. """
  280. deleted_notes, deleted_media = 0, 0
  281. local_only_note_ids = set(local_index.keys()).difference(set(keep_notes.keys()))
  282. if local_only_note_ids:
  283. if not delete_local:
  284. click.echo(
  285. f"{len(local_only_note_ids)} notes exist locally, but not in Google Keep. Add argument [--delete-local] to delete."
  286. )
  287. else:
  288. click.echo(
  289. f"{len(local_only_note_ids)} notes exist locally, but not in Google Keep. Trashing local files."
  290. )
  291. for note_id in local_only_note_ids:
  292. note_path = local_index[note_id].path
  293. deleted_notes += 1
  294. if note_path:
  295. click.echo(
  296. f" Deleting unknown local note [{note_id}] file [{local_index[note_id].path}]"
  297. )
  298. note_path.unlink()
  299. local_only_media: Set[Tuple[str, str]] = set(
  300. [
  301. (local_media.google_keep_note_id, local_media.google_keep_media_id)
  302. for local_note in local_index.values()
  303. for local_media in local_note.local_media.values()
  304. if local_media.google_keep_note_id and local_media.google_keep_media_id
  305. ]
  306. )
  307. notes: ValuesView[gkeepapi._node.Note] = keep_notes.values()
  308. keep_media: Set[Tuple[str, str]] = set(
  309. [
  310. (keep_note.id, keep_media.id)
  311. for keep_note in notes
  312. for keep_media in all_note_media(keep_note)
  313. ]
  314. )
  315. local_only_media_ids = local_only_media.difference(keep_media)
  316. if not local_only_media_ids:
  317. return (deleted_notes, 0)
  318. if not delete_local:
  319. click.echo(
  320. f"{len(local_only_note_ids)} media files exist locally, but not in Google Keep. Add argument [--delete-local] to delete."
  321. )
  322. return (deleted_notes, 0)
  323. for (note_id, media_id) in local_only_media_ids:
  324. media = local_index[note_id].local_media[media_id]
  325. click.echo(
  326. f" Deleting media [{media_id}] for note [{note_id}] file [{media.path}]"
  327. )
  328. media.path.unlink()
  329. deleted_media += 1
  330. return (deleted_notes, deleted_media)