export.py 13 KB

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