├── .github
└── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── docker-compose.yml
├── docs
├── assets
│ ├── export.jpeg
│ ├── original.jpeg
│ └── snapshot.jpeg
└── progress.md
├── makefile
├── notionsnapshot
├── __main__.py
├── argparser.py
├── driver.py
├── injections
│ ├── injection.css
│ └── injection.js
└── logger.py
├── requirements.in
├── requirements.txt
└── test.sh
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: sueszli
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | snapshots/
2 | google-chrome-stable_current_amd64.deb
3 |
4 | # ____________________________________________________________________________
5 |
6 | # Created by https://www.toptal.com/developers/gitignore/api/r,vim,emacs,latex,linux,macos,python,windows,jetbrains+all,visualstudiocode,c++
7 | # Edit at https://www.toptal.com/developers/gitignore?templates=r,vim,emacs,latex,linux,macos,python,windows,jetbrains+all,visualstudiocode,c++
8 |
9 | ### C++ ###
10 | # Prerequisites
11 | *.d
12 |
13 | # Compiled Object files
14 | *.slo
15 | *.lo
16 | *.o
17 | *.obj
18 |
19 | # Precompiled Headers
20 | *.gch
21 | *.pch
22 |
23 | # Compiled Dynamic libraries
24 | *.so
25 | *.dylib
26 | *.dll
27 |
28 | # Fortran module files
29 | *.mod
30 | *.smod
31 |
32 | # Compiled Static libraries
33 | *.lai
34 | *.la
35 | *.a
36 | *.lib
37 |
38 | # Executables
39 | *.exe
40 | *.out
41 | *.app
42 |
43 | ### Emacs ###
44 | # -*- mode: gitignore; -*-
45 | *~
46 | \#*\#
47 | /.emacs.desktop
48 | /.emacs.desktop.lock
49 | *.elc
50 | auto-save-list
51 | tramp
52 | .\#*
53 |
54 | # Org-mode
55 | .org-id-locations
56 | *_archive
57 |
58 | # flymake-mode
59 | *_flymake.*
60 |
61 | # eshell files
62 | /eshell/history
63 | /eshell/lastdir
64 |
65 | # elpa packages
66 | /elpa/
67 |
68 | # reftex files
69 | *.rel
70 |
71 | # AUCTeX auto folder
72 | /auto/
73 |
74 | # cask packages
75 | .cask/
76 | dist/
77 |
78 | # Flycheck
79 | flycheck_*.el
80 |
81 | # server auth directory
82 | /server/
83 |
84 | # projectiles files
85 | .projectile
86 |
87 | # directory configuration
88 | .dir-locals.el
89 |
90 | # network security
91 | /network-security.data
92 |
93 |
94 | ### JetBrains+all ###
95 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
96 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
97 |
98 | # User-specific stuff
99 | .idea/**/workspace.xml
100 | .idea/**/tasks.xml
101 | .idea/**/usage.statistics.xml
102 | .idea/**/dictionaries
103 | .idea/**/shelf
104 |
105 | # AWS User-specific
106 | .idea/**/aws.xml
107 |
108 | # Generated files
109 | .idea/**/contentModel.xml
110 |
111 | # Sensitive or high-churn files
112 | .idea/**/dataSources/
113 | .idea/**/dataSources.ids
114 | .idea/**/dataSources.local.xml
115 | .idea/**/sqlDataSources.xml
116 | .idea/**/dynamic.xml
117 | .idea/**/uiDesigner.xml
118 | .idea/**/dbnavigator.xml
119 |
120 | # Gradle
121 | .idea/**/gradle.xml
122 | .idea/**/libraries
123 |
124 | # Gradle and Maven with auto-import
125 | # When using Gradle or Maven with auto-import, you should exclude module files,
126 | # since they will be recreated, and may cause churn. Uncomment if using
127 | # auto-import.
128 | # .idea/artifacts
129 | # .idea/compiler.xml
130 | # .idea/jarRepositories.xml
131 | # .idea/modules.xml
132 | # .idea/*.iml
133 | # .idea/modules
134 | # *.iml
135 | # *.ipr
136 |
137 | # CMake
138 | cmake-build-*/
139 |
140 | # Mongo Explorer plugin
141 | .idea/**/mongoSettings.xml
142 |
143 | # File-based project format
144 | *.iws
145 |
146 | # IntelliJ
147 | out/
148 |
149 | # mpeltonen/sbt-idea plugin
150 | .idea_modules/
151 |
152 | # JIRA plugin
153 | atlassian-ide-plugin.xml
154 |
155 | # Cursive Clojure plugin
156 | .idea/replstate.xml
157 |
158 | # SonarLint plugin
159 | .idea/sonarlint/
160 |
161 | # Crashlytics plugin (for Android Studio and IntelliJ)
162 | com_crashlytics_export_strings.xml
163 | crashlytics.properties
164 | crashlytics-build.properties
165 | fabric.properties
166 |
167 | # Editor-based Rest Client
168 | .idea/httpRequests
169 |
170 | # Android studio 3.1+ serialized cache file
171 | .idea/caches/build_file_checksums.ser
172 |
173 | ### JetBrains+all Patch ###
174 | # Ignore everything but code style settings and run configurations
175 | # that are supposed to be shared within teams.
176 |
177 | .idea/*
178 |
179 | !.idea/codeStyles
180 | !.idea/runConfigurations
181 |
182 | ### LaTeX ###
183 | ## Core latex/pdflatex auxiliary files:
184 | *.aux
185 | *.lof
186 | *.log
187 | *.lot
188 | *.fls
189 | *.toc
190 | *.fmt
191 | *.fot
192 | *.cb
193 | *.cb2
194 | .*.lb
195 |
196 | ## Intermediate documents:
197 | *.dvi
198 | *.xdv
199 | *-converted-to.*
200 | # these rules might exclude image files for figures etc.
201 | # *.ps
202 | # *.eps
203 | # *.pdf
204 |
205 | ## Generated if empty string is given at "Please type another file name for output:"
206 | .pdf
207 |
208 | ## Bibliography auxiliary files (bibtex/biblatex/biber):
209 | *.bbl
210 | *.bcf
211 | *.blg
212 | *-blx.aux
213 | *-blx.bib
214 | *.run.xml
215 |
216 | ## Build tool auxiliary files:
217 | *.fdb_latexmk
218 | *.synctex
219 | *.synctex(busy)
220 | *.synctex.gz
221 | *.synctex.gz(busy)
222 | *.pdfsync
223 |
224 | ## Build tool directories for auxiliary files
225 | # latexrun
226 | latex.out/
227 |
228 | ## Auxiliary and intermediate files from other packages:
229 | # algorithms
230 | *.alg
231 | *.loa
232 |
233 | # achemso
234 | acs-*.bib
235 |
236 | # amsthm
237 | *.thm
238 |
239 | # beamer
240 | *.nav
241 | *.pre
242 | *.snm
243 | *.vrb
244 |
245 | # changes
246 | *.soc
247 |
248 | # comment
249 | *.cut
250 |
251 | # cprotect
252 | *.cpt
253 |
254 | # elsarticle (documentclass of Elsevier journals)
255 | *.spl
256 |
257 | # endnotes
258 | *.ent
259 |
260 | # fixme
261 | *.lox
262 |
263 | # feynmf/feynmp
264 | *.mf
265 | *.mp
266 | *.t[1-9]
267 | *.t[1-9][0-9]
268 | *.tfm
269 |
270 | #(r)(e)ledmac/(r)(e)ledpar
271 | *.end
272 | *.?end
273 | *.[1-9]
274 | *.[1-9][0-9]
275 | *.[1-9][0-9][0-9]
276 | *.[1-9]R
277 | *.[1-9][0-9]R
278 | *.[1-9][0-9][0-9]R
279 | *.eledsec[1-9]
280 | *.eledsec[1-9]R
281 | *.eledsec[1-9][0-9]
282 | *.eledsec[1-9][0-9]R
283 | *.eledsec[1-9][0-9][0-9]
284 | *.eledsec[1-9][0-9][0-9]R
285 |
286 | # glossaries
287 | *.acn
288 | *.acr
289 | *.glg
290 | *.glo
291 | *.gls
292 | *.glsdefs
293 | *.lzo
294 | *.lzs
295 | *.slg
296 | *.sls
297 |
298 | # uncomment this for glossaries-extra (will ignore makeindex's style files!)
299 | # *.ist
300 |
301 | # gnuplot
302 | *.gnuplot
303 | *.table
304 |
305 | # gnuplottex
306 | *-gnuplottex-*
307 |
308 | # gregoriotex
309 | *.gaux
310 | *.glog
311 | *.gtex
312 |
313 | # htlatex
314 | *.4ct
315 | *.4tc
316 | *.idv
317 | *.lg
318 | *.trc
319 | *.xref
320 |
321 | # hyperref
322 | *.brf
323 |
324 | # knitr
325 | *-concordance.tex
326 | # TODO Uncomment the next line if you use knitr and want to ignore its generated tikz files
327 | # *.tikz
328 | *-tikzDictionary
329 |
330 | # listings
331 | *.lol
332 |
333 | # luatexja-ruby
334 | *.ltjruby
335 |
336 | # makeidx
337 | *.idx
338 | *.ilg
339 | *.ind
340 |
341 | # minitoc
342 | *.maf
343 | *.mlf
344 | *.mlt
345 | *.mtc[0-9]*
346 | *.slf[0-9]*
347 | *.slt[0-9]*
348 | *.stc[0-9]*
349 |
350 | # minted
351 | _minted*
352 | *.pyg
353 |
354 | # morewrites
355 | *.mw
356 |
357 | # newpax
358 | *.newpax
359 |
360 | # nomencl
361 | *.nlg
362 | *.nlo
363 | *.nls
364 |
365 | # pax
366 | *.pax
367 |
368 | # pdfpcnotes
369 | *.pdfpc
370 |
371 | # sagetex
372 | *.sagetex.sage
373 | *.sagetex.py
374 | *.sagetex.scmd
375 |
376 | # scrwfile
377 | *.wrt
378 |
379 | # svg
380 | svg-inkscape/
381 |
382 | # sympy
383 | *.sout
384 | *.sympy
385 | sympy-plots-for-*.tex/
386 |
387 | # pdfcomment
388 | *.upa
389 | *.upb
390 |
391 | # pythontex
392 | *.pytxcode
393 | pythontex-files-*/
394 |
395 | # tcolorbox
396 | *.listing
397 |
398 | # thmtools
399 | *.loe
400 |
401 | # TikZ & PGF
402 | *.dpth
403 | *.md5
404 | *.auxlock
405 |
406 | # titletoc
407 | *.ptc
408 |
409 | # todonotes
410 | *.tdo
411 |
412 | # vhistory
413 | *.hst
414 | *.ver
415 |
416 | # easy-todo
417 | *.lod
418 |
419 | # xcolor
420 | *.xcp
421 |
422 | # xmpincl
423 | *.xmpi
424 |
425 | # xindy
426 | *.xdy
427 |
428 | # xypic precompiled matrices and outlines
429 | *.xyc
430 | *.xyd
431 |
432 | # endfloat
433 | *.ttt
434 | *.fff
435 |
436 | # Latexian
437 | TSWLatexianTemp*
438 |
439 | ## Editors:
440 | # WinEdt
441 | *.bak
442 | *.sav
443 |
444 | # Texpad
445 | .texpadtmp
446 |
447 | # LyX
448 | *.lyx~
449 |
450 | # Kile
451 | *.backup
452 |
453 | # gummi
454 | .*.swp
455 |
456 | # KBibTeX
457 | *~[0-9]*
458 |
459 | # TeXnicCenter
460 | *.tps
461 |
462 | # auto folder when using emacs and auctex
463 | ./auto/*
464 | *.el
465 |
466 | # expex forward references with \gathertags
467 | *-tags.tex
468 |
469 | # standalone packages
470 | *.sta
471 |
472 | # Makeindex log files
473 | *.lpz
474 |
475 | # xwatermark package
476 | *.xwm
477 |
478 | # REVTeX puts footnotes in the bibliography by default, unless the nofootinbib
479 | # option is specified. Footnotes are the stored in a file with suffix Notes.bib.
480 | # Uncomment the next line to have this generated file ignored.
481 | #*Notes.bib
482 |
483 | ### LaTeX Patch ###
484 | # LIPIcs / OASIcs
485 | *.vtc
486 |
487 | # glossaries
488 | *.glstex
489 |
490 | ### Linux ###
491 |
492 | # temporary files which can be created if a process still has a handle open of a deleted file
493 | .fuse_hidden*
494 |
495 | # KDE directory preferences
496 | .directory
497 |
498 | # Linux trash folder which might appear on any partition or disk
499 | .Trash-*
500 |
501 | # .nfs files are created when an open file is removed but is still being accessed
502 | .nfs*
503 |
504 | ### macOS ###
505 | # General
506 | .DS_Store
507 | .AppleDouble
508 | .LSOverride
509 |
510 | # Icon must end with two \r
511 | Icon
512 |
513 |
514 | # Thumbnails
515 | ._*
516 |
517 | # Files that might appear in the root of a volume
518 | .DocumentRevisions-V100
519 | .fseventsd
520 | .Spotlight-V100
521 | .TemporaryItems
522 | .Trashes
523 | .VolumeIcon.icns
524 | .com.apple.timemachine.donotpresent
525 |
526 | # Directories potentially created on remote AFP share
527 | .AppleDB
528 | .AppleDesktop
529 | Network Trash Folder
530 | Temporary Items
531 | .apdisk
532 |
533 | ### macOS Patch ###
534 | # iCloud generated files
535 | *.icloud
536 |
537 | ### Python ###
538 | # Byte-compiled / optimized / DLL files
539 | __pycache__/
540 | *.py[cod]
541 | *$py.class
542 |
543 | # C extensions
544 |
545 | # Distribution / packaging
546 | .Python
547 | build/
548 | develop-eggs/
549 | downloads/
550 | eggs/
551 | .eggs/
552 | lib/
553 | lib64/
554 | parts/
555 | sdist/
556 | var/
557 | wheels/
558 | share/python-wheels/
559 | *.egg-info/
560 | .installed.cfg
561 | *.egg
562 | MANIFEST
563 |
564 | # PyInstaller
565 | # Usually these files are written by a python script from a template
566 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
567 | *.manifest
568 | *.spec
569 |
570 | # Installer logs
571 | pip-log.txt
572 | pip-delete-this-directory.txt
573 |
574 | # Unit test / coverage reports
575 | htmlcov/
576 | .tox/
577 | .nox/
578 | .coverage
579 | .coverage.*
580 | .cache
581 | nosetests.xml
582 | coverage.xml
583 | *.cover
584 | *.py,cover
585 | .hypothesis/
586 | .pytest_cache/
587 | cover/
588 |
589 | # Translations
590 | *.mo
591 | *.pot
592 |
593 | # Django stuff:
594 | local_settings.py
595 | db.sqlite3
596 | db.sqlite3-journal
597 |
598 | # Flask stuff:
599 | instance/
600 | .webassets-cache
601 |
602 | # Scrapy stuff:
603 | .scrapy
604 |
605 | # Sphinx documentation
606 | docs/_build/
607 |
608 | # PyBuilder
609 | .pybuilder/
610 | target/
611 |
612 | # Jupyter Notebook
613 | .ipynb_checkpoints
614 |
615 | # IPython
616 | profile_default/
617 | ipython_config.py
618 |
619 | # pyenv
620 | # For a library or package, you might want to ignore these files since the code is
621 | # intended to run in multiple environments; otherwise, check them in:
622 | # .python-version
623 |
624 | # pipenv
625 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
626 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
627 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
628 | # install all needed dependencies.
629 | #Pipfile.lock
630 |
631 | # poetry
632 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
633 | # This is especially recommended for binary packages to ensure reproducibility, and is more
634 | # commonly ignored for libraries.
635 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
636 | #poetry.lock
637 |
638 | # pdm
639 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
640 | #pdm.lock
641 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
642 | # in version control.
643 | # https://pdm.fming.dev/#use-with-ide
644 | .pdm.toml
645 |
646 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
647 | __pypackages__/
648 |
649 | # Celery stuff
650 | celerybeat-schedule
651 | celerybeat.pid
652 |
653 | # SageMath parsed files
654 | *.sage.py
655 |
656 | # Environments
657 | .env
658 | .venv
659 | env/
660 | venv/
661 | ENV/
662 | env.bak/
663 | venv.bak/
664 |
665 | # Spyder project settings
666 | .spyderproject
667 | .spyproject
668 |
669 | # Rope project settings
670 | .ropeproject
671 |
672 | # mkdocs documentation
673 | /site
674 |
675 | # mypy
676 | .mypy_cache/
677 | .dmypy.json
678 | dmypy.json
679 |
680 | # Pyre type checker
681 | .pyre/
682 |
683 | # pytype static type analyzer
684 | .pytype/
685 |
686 | # Cython debug symbols
687 | cython_debug/
688 |
689 | # PyCharm
690 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
691 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
692 | # and can be added to the global gitignore or merged into this file. For a more nuclear
693 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
694 | #.idea/
695 |
696 | ### Python Patch ###
697 | # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
698 | poetry.toml
699 |
700 | # ruff
701 | .ruff_cache/
702 |
703 | # LSP config files
704 | pyrightconfig.json
705 |
706 | ### R ###
707 | # History files
708 | .Rhistory
709 | .Rapp.history
710 |
711 | # Session Data files
712 | .RData
713 | .RDataTmp
714 |
715 | # User-specific files
716 | .Ruserdata
717 |
718 | # Example code in package build process
719 | *-Ex.R
720 |
721 | # Output files from R CMD build
722 | /*.tar.gz
723 |
724 | # Output files from R CMD check
725 | /*.Rcheck/
726 |
727 | # RStudio files
728 | .Rproj.user/
729 |
730 | # produced vignettes
731 | vignettes/*.html
732 | vignettes/*.pdf
733 |
734 | # OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3
735 | .httr-oauth
736 |
737 | # knitr and R markdown default cache directories
738 | *_cache/
739 | /cache/
740 |
741 | # Temporary files created by R markdown
742 | *.utf8.md
743 | *.knit.md
744 |
745 | # R Environment Variables
746 | .Renviron
747 |
748 | # pkgdown site
749 | # docs/
750 |
751 | # translation temp files
752 | po/*~
753 |
754 | # RStudio Connect folder
755 | rsconnect/
756 |
757 | ### R.Bookdown Stack ###
758 | # R package: bookdown caching files
759 | /*_files/
760 |
761 | ### Vim ###
762 | # Swap
763 | [._]*.s[a-v][a-z]
764 | !*.svg # comment out if you don't need vector files
765 | [._]*.sw[a-p]
766 | [._]s[a-rt-v][a-z]
767 | [._]ss[a-gi-z]
768 | [._]sw[a-p]
769 |
770 | # Session
771 | Session.vim
772 | Sessionx.vim
773 |
774 | # Temporary
775 | .netrwhist
776 | # Auto-generated tag files
777 | tags
778 | # Persistent undo
779 | [._]*.un~
780 |
781 | ### VisualStudioCode ###
782 | .vscode/*
783 | !.vscode/settings.json
784 | !.vscode/tasks.json
785 | !.vscode/launch.json
786 | !.vscode/extensions.json
787 | !.vscode/*.code-snippets
788 |
789 | # Local History for Visual Studio Code
790 | .history/
791 |
792 | # Built Visual Studio Code Extensions
793 | *.vsix
794 |
795 | ### VisualStudioCode Patch ###
796 | # Ignore all local history of files
797 | .history
798 | .ionide
799 |
800 | ### Windows ###
801 | # Windows thumbnail cache files
802 | Thumbs.db
803 | Thumbs.db:encryptable
804 | ehthumbs.db
805 | ehthumbs_vista.db
806 |
807 | # Dump file
808 | *.stackdump
809 |
810 | # Folder config file
811 | [Dd]esktop.ini
812 |
813 | # Recycle Bin used on file shares
814 | $RECYCLE.BIN/
815 |
816 | # Windows Installer files
817 | *.cab
818 | *.msi
819 | *.msix
820 | *.msm
821 | *.msp
822 |
823 | # Windows shortcuts
824 | *.lnk
825 |
826 | # End of https://www.toptal.com/developers/gitignore/api/r,vim,emacs,latex,linux,macos,python,windows,jetbrains+all,visualstudiocode,c++
827 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ```
2 | _ __ __ _ _____ __ __
3 | / | / /___ / /_(_)___ ____ / ___/____ ____ _____ _____/ /_ ____ / /_
4 | / |/ / __ \/ __/ / __ \/ __ \ \__ \/ __ \/ __ `/ __ \/ ___/ __ \/ __ \/ __/
5 | / /| / /_/ / /_/ / /_/ / / / / ___/ / / / / /_/ / /_/ (__ ) / / / /_/ / /_
6 | /_/ |_/\____/\__/_/\____/_/ /_/ /____/_/ /_/\__,_/ .___/____/_/ /_/\____/\__/
7 | /_/
8 | ```
9 |
10 | |
|
|
|
11 | | :---------------------------------------------: | :-----------------------------------------------: | :-----------------------------------------------: |
12 | | Export with Notion | Scraped with ✨NotionSnapshot✨ | Original page |
13 |
14 | # usage
15 |
16 | this project is a work in progress. pull requests are welcome. a docker script is provided for reproducibility.
17 |
18 | for a more reliable backup strategy check out: [NotionBackup](https://github.com/sueszli/notionBackup)
19 |
20 | ```bash
21 | # install chrome (in case you're using windows subsystem for linux)
22 | sudo apt update && sudo apt upgrade -y
23 | wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
24 | sudo dpkg -i google-chrome-stable_current_amd64.deb
25 | sudo apt --fix-broken install
26 | rm -rf google-chrome-stable_current_amd64.deb
27 |
28 | # clone project
29 | git clone https://github.com/sueszli/notionSnapshot
30 | cd notionSnapshot
31 | pip install -r requirements.txt
32 |
33 | # demo
34 | python notionsnapshot --help
35 | python notionsnapshot --dark-mode https://sueszli.notion.site/NotionSnapshot-Test-tiny-page-4dfa05657f774b45993542da4a8530c2
36 | ```
37 | # kudos
38 |
39 | many thanks to:
40 |
41 | - [@leoncvlt](https://github.com/leoncvlt) who laid the foundation of this project through loconotion (this project is a complete rewrite)
42 | - [@mjdeligan](https://github.com/MJDeligan) who heavily optimized the performance and implemented the caching and recursive crawling functionality
43 | - [@stefnotch](https://github.com/stefnotch/) and [@thomasbiede](https://github.com/ThomasBiede) who helped me set the project up
44 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | services:
2 | main:
3 | container_name: notionsnapshot
4 | volumes:
5 | - type: bind
6 | source: .
7 | target: /workspace
8 | working_dir: /workspace
9 |
10 | build:
11 | context: .
12 | dockerfile_inline: |
13 | FROM --platform=linux/amd64 ubuntu:20.04
14 |
15 | ARG DEBIAN_FRONTEND=noninteractive
16 |
17 | RUN apt-get update
18 | RUN apt-get install -y git
19 |
20 | # get selenium chrome driver
21 | RUN apt-get install -y wget curl unzip
22 | RUN wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
23 | RUN apt-get install -y ./google-chrome-stable_current_amd64.deb
24 |
25 | # get python 3.11
26 | RUN apt-get update && apt-get install -y software-properties-common && add-apt-repository -y ppa:deadsnakes/ppa && apt-get update && apt install -y python3.11
27 | RUN apt-get install -y python3-pip
28 |
29 | RUN pip install -r requirements.txt
30 |
31 | CMD ["tail", "-f", "/dev/null"]
32 |
--------------------------------------------------------------------------------
/docs/assets/export.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sueszli/notionSnapshot/15fc34df1c93e25810ffa446a0c2d30ca501431d/docs/assets/export.jpeg
--------------------------------------------------------------------------------
/docs/assets/original.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sueszli/notionSnapshot/15fc34df1c93e25810ffa446a0c2d30ca501431d/docs/assets/original.jpeg
--------------------------------------------------------------------------------
/docs/assets/snapshot.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sueszli/notionSnapshot/15fc34df1c93e25810ffa446a0c2d30ca501431d/docs/assets/snapshot.jpeg
--------------------------------------------------------------------------------
/docs/progress.md:
--------------------------------------------------------------------------------
1 | # progress
2 |
3 | ## choosing a scraping library
4 |
5 | the following libraries were considered because they are the most popular and well supported (for python as of march 2023):
6 |
7 | - playwright: https://playwright.dev/python/docs/intro
8 | - selenium: https://selenium-python.readthedocs.io/ ✅
9 |
10 | usually when installing a web driver you have to download the driver and add it to your `$path`. this is inconvenient for the end user.
11 |
12 | playwright mitigates this problem by downloading the driver automatically when you install the library with your operating system's package manager. but this is again inconvenient, as we want this tool to be as easy to use as possible.
13 |
14 | but we managed to find a way to install selenium directly through pip by using the `webdriver_manager` library.
15 |
16 | this makes selenium the best option for our use case and makes using python just as convenient as node.js for this project.
17 |
18 | ## building on top of similar projects
19 |
20 | there are already a few tools that do something very similar to what we want to do. we should try to build on top of these tools instead of reinventing the wheel.
21 |
22 | i did a lot of research (i really mean a lot - i spent like 2 full days on this) and found the following tools to have the best replication of the original styling:
23 |
24 | - loconotion: https://github.com/leoncvlt/loconotion/ (clearly the best option but it does not support all features - such as file attachments)
25 | - fruition: https://github.com/stephenou/fruitionsite/ (this one inspired locotion)
26 |
27 | we should just continue where loconotion left off, because it is the best option although it is far from perfect.
28 |
29 | we should make loconotion simpler and more opinionated such that the tools becomes more accessible to the average user.
30 |
31 | ## what's next?
32 |
33 | - [ ] support more blocks (ie. file attachmet types) with selenium actions (see: https://www.selenium.dev/selenium/docs/api/py/webdriver/selenium.webdriver.common.action_chains.html)
34 |
35 | - [ ] make using it more convenient by writing a "github actions" script to automatically scrape and deploy pages after entering an url
36 |
37 | # supported blocks
38 |
39 | this list is based on the notion snapshot test page (see: `test.sh`)
40 |
41 | _blocks_
42 |
43 | - [x] basic blocks
44 | - [ ] media
45 | - [ ] embedded video (mp4)
46 | - [ ] embedded music (mp3) - calls notion api for a download
47 | - [ ] databases
48 | - [ ] table view (glitches horizontally, doesn't link to subpages correctly)
49 | - [ ] timeline view (works, but is too small)
50 | - [x] advanced blocks (buttons break, but we were removing all javascript on purpose)
51 | - [x] inlines
52 | - [ ] embeds
53 | - [ ] embedded pdfs
54 |
55 | _pages_
56 |
57 | - [x] comments
58 | - [x] serif page
59 | - [x] monoserif page
60 | - [x] small text page
61 | - [x] full width page
62 | - [x] board page
63 | - [ ] table page (glitches horizontally, doesn't link to subpages correctly)
64 | - [x] timeline page
65 | - [x] calendar page
66 | - [x] list page
67 | - [x] gallery page
68 |
--------------------------------------------------------------------------------
/makefile:
--------------------------------------------------------------------------------
1 | # --------------------------------------------------------------- venv
2 |
3 | .PHONY: init # initialize venv
4 | init:
5 | # get requirements.in
6 | pip install pip --upgrade
7 | pip install pipreqs
8 | rm -rf requirements.txt requirements.in
9 | pipreqs . --mode no-pin --encoding utf-8 --ignore .venv
10 | mv requirements.txt requirements.in
11 |
12 | # get requirements.txt
13 | pip install pip-tools
14 | pip-compile requirements.in -o requirements.txt -vvv
15 |
16 | # install everything in venv
17 | rm -rf .venv
18 | python3 -m venv .venv
19 | @bash -c "source .venv/bin/activate && pip install -r requirements.txt"
20 |
21 | .PHONY: lock # freeze pip and lock reqs
22 | lock:
23 | @bash -c "source .venv/bin/activate && pip freeze > requirements.in"
24 | pip-compile requirements.in -o requirements.txt -vvv
25 |
26 | # --------------------------------------------------------------- docker
27 |
28 | .PHONY: docker-install # run docker container
29 | docker-install:
30 | docker-compose up --detach
31 | @echo "to exec into docker container, run: docker exec -it main bash"
32 |
33 | .PHONY: docker-build # save changes to container
34 | docker-build:
35 | docker-compose build
36 |
37 | .PHONY: docker-clean # wipe everything in docker
38 | docker-clean:
39 | docker-compose down
40 |
41 | -docker stop $$(docker ps -a -q)
42 | -docker rm $$(docker ps -a -q)
43 | -docker rmi $$(docker images -q)
44 | yes | docker container prune
45 | yes | docker image prune
46 | yes | docker volume prune
47 | yes | docker network prune
48 | yes | docker system prune
49 |
50 | docker ps --all
51 | docker images
52 | docker system df
53 | docker volume ls
54 | docker network ls
55 |
56 | # --------------------------------------------------------------- utils
57 |
58 | .PHONY: fmt # format codebase
59 | fmt:
60 | pip install isort
61 | pip install ruff
62 | pip install autoflake
63 |
64 | isort .
65 | autoflake --remove-all-unused-imports --recursive --in-place .
66 | ruff format --config line-length=500 .
67 |
68 | .PHONY: sec # check for vulns
69 | sec:
70 | pip install bandit
71 | pip install safety
72 |
73 | bandit -r .
74 | safety check --full-report
75 |
76 | .PHONY: up # pull and push changes
77 | up:
78 | git pull
79 | git add .
80 | if [ -z "$(msg)" ]; then git commit -m "up"; else git commit -m "$(msg)"; fi
81 | git push
82 |
83 | .PHONY: help # generate help message
84 | help:
85 | @echo "Usage: make [target]\n"
86 | @grep '^.PHONY: .* #' Makefile | sed 's/\.PHONY: \(.*\) # \(.*\)/\1 \2/' | expand -t20
87 |
88 |
--------------------------------------------------------------------------------
/notionsnapshot/__main__.py:
--------------------------------------------------------------------------------
1 | import urllib.parse
2 | import urllib.request
3 | import os
4 | import shutil
5 | import glob
6 | import hashlib
7 | import mimetypes
8 | import re
9 | import uuid
10 | import time
11 | from pathlib import Path
12 | from typing import List, Optional, Tuple, Set
13 |
14 | from selenium import webdriver
15 | from selenium.webdriver.support.wait import WebDriverWait
16 | from selenium.webdriver.common.by import By
17 | from selenium.webdriver.remote.webelement import WebElement
18 | from selenium.common.exceptions import TimeoutException, ElementClickInterceptedException
19 | from bs4 import BeautifulSoup, Tag
20 | import html5lib # implicitly used by bs4
21 | import requests
22 | import cssutils
23 | from appdirs import user_cache_dir
24 |
25 | from argparser import ARGS
26 | from driver import DriverInitializer
27 | from logger import LOG_SINGLETON as LOG, trace
28 |
29 |
30 | class FileManager:
31 | output_dir: str = ""
32 | assets_dir: str = ""
33 | cache_dir: str = ""
34 | css_injection_file: str = ""
35 | js_injection_file: str = ""
36 |
37 | @staticmethod
38 | def setup() -> None:
39 | page_name = FileManager.get_page_name()
40 | FileManager.output_dir = os.path.join("snapshots", page_name)
41 | FileManager.assets_dir = os.path.join(FileManager.output_dir, "assets")
42 |
43 | cache_base_dir = user_cache_dir(appname="notion-snapshot", appauthor="sueszli")
44 | FileManager.cache_dir = os.path.join(cache_base_dir, page_name)
45 |
46 | FileManager._init_output_dir()
47 |
48 | css_file, js_file = FileManager._copy_injections_to_assets_dir()
49 | FileManager.css_injection_file = css_file
50 | FileManager.js_injection_file = js_file
51 |
52 | @staticmethod
53 | def get_page_name() -> str:
54 | page_id = urllib.parse.urlparse(ARGS.url).path[1:]
55 | return page_id[: page_id.rfind("-")].lower()
56 |
57 | @trace()
58 | @staticmethod
59 | def _init_output_dir() -> None:
60 | if not ARGS.disable_caching and os.path.exists(FileManager.assets_dir):
61 | shutil.copytree(FileManager.assets_dir, FileManager.cache_dir, dirs_exist_ok=True)
62 | LOG.info("cached assets from previous snapshot for this url")
63 |
64 | if os.path.exists(FileManager.output_dir):
65 | shutil.rmtree(FileManager.output_dir)
66 | LOG.info(f"removed previous snapshot for this url")
67 |
68 | os.makedirs(FileManager.output_dir, exist_ok=True)
69 | os.makedirs(FileManager.assets_dir, exist_ok=True)
70 | if not ARGS.disable_caching:
71 | os.makedirs(FileManager.cache_dir, exist_ok=True)
72 |
73 | @staticmethod
74 | def _copy_injections_to_assets_dir() -> Tuple[str, str]:
75 | injection_dir = Path(__file__).parent / "injections"
76 | css_out = Path(FileManager.assets_dir) / "injection.css"
77 | js_out = Path(FileManager.assets_dir) / "injection.js"
78 | shutil.copy(injection_dir / "injection.js", js_out)
79 | shutil.copy(injection_dir / "injection.css", css_out)
80 | relative_css_out = str(css_out.relative_to(FileManager.output_dir)).replace("\\", "/")
81 | relative_js_out = str(js_out.relative_to(FileManager.output_dir)).replace("\\", "/")
82 | return relative_css_out, relative_js_out
83 |
84 | @trace()
85 | @staticmethod
86 | def download_asset(url: str, filename: str = "") -> str:
87 | if not filename:
88 | filename = FileManager._generate_filename(url)
89 |
90 | already_downloaded = glob.glob(os.path.join(FileManager.assets_dir, filename + ".*"))
91 | if already_downloaded:
92 | LOG.info(f"asset '{filename}' was already downloaded")
93 | return str(Path(already_downloaded[0]).relative_to(FileManager.output_dir)).replace("\\", "/")
94 |
95 | if not ARGS.disable_caching and (cached := FileManager._load_from_cache(filename)) is not None:
96 | LOG.info(f"asset '{filename}' was found in cache")
97 | return cached
98 |
99 | destination = Path(FileManager.assets_dir) / filename
100 | try:
101 | session = requests.Session()
102 | session.trust_env = False
103 | response = session.get(url)
104 | response.raise_for_status()
105 |
106 | missing_file_extension = not bool(destination.suffix)
107 | if missing_file_extension:
108 | suffix = Path(urllib.parse.urlparse(url).path).suffix
109 | question_mark = "%3f"
110 | if suffix:
111 | if question_mark in suffix.lower():
112 | suffix = re.split(question_mark, suffix, flags=re.IGNORECASE)[0]
113 | destination = destination.with_suffix(suffix)
114 | else:
115 | content_type = response.headers.get("content-type")
116 | assert content_type is not None
117 | mimetype = mimetypes.guess_extension(content_type)
118 | assert mimetype is not None
119 | destination = destination.with_suffix(mimetype)
120 |
121 | with open(destination, "wb") as f:
122 | f.write(response.content)
123 |
124 | return str(destination.relative_to(FileManager.output_dir)).replace("\\", "/")
125 |
126 | except Exception as error:
127 | LOG.critical(f"error downloading asset on '{url}' - the online link to it will be used instead \n\t{error}")
128 | return str(Path(url)).replace("\\", "/")
129 |
130 | @staticmethod
131 | def _generate_filename(url: str) -> str:
132 | parsed_url = urllib.parse.urlparse(url)
133 | queryless_url = parsed_url.netloc + parsed_url.path
134 | params = urllib.parse.parse_qs(parsed_url.query)
135 | # having width in hash as name allows fetching different image resolutions
136 | if "width" in params.keys():
137 | queryless_url = queryless_url + f"?width={params['width']}"
138 | filename = hashlib.sha1(str.encode(queryless_url)).hexdigest()
139 | return filename
140 |
141 | @staticmethod
142 | def _load_from_cache(filename: str) -> Optional[str]:
143 | filename = filename if Path(filename).suffix else filename + ".*"
144 | cache_path = os.path.join(FileManager.cache_dir, filename)
145 | cached = glob.glob(cache_path)
146 | if cached:
147 | shutil.copy(cached[0], FileManager.assets_dir)
148 | return os.path.join("assets", os.path.basename(cached[0]))
149 | return None
150 |
151 | @staticmethod
152 | def save_page(soup: BeautifulSoup, url: str) -> None:
153 | # don't prettify html, it breaks the page
154 | html_str = str(soup)
155 | filename = FileManager.get_filename_from_url(url)
156 | output_path = Path(FileManager.output_dir + "/" + filename)
157 | with open(output_path, "wb") as f:
158 | f.write(html_str.encode("utf-8").strip())
159 | LOG.info(f"saved page\n\n\n\n\n\n\n")
160 |
161 | @staticmethod
162 | def get_filename_from_url(url: str) -> str:
163 | id = urllib.parse.urlparse(url).path[1:]
164 | filename = id[: id.rfind("-")].lower() + ".html"
165 | if url == ARGS.url:
166 | filename = "index.html"
167 | return filename
168 |
169 |
170 | class Scraper:
171 | driver_download_path: str = os.path.abspath("snapshots/" + FileManager.get_page_name() + "/assets")
172 | driver: webdriver.Chrome = DriverInitializer.get_driver(driver_download_path)
173 |
174 | will_visit: Set[str] = set([ARGS.url])
175 | visited: Set[str] = set()
176 |
177 | @staticmethod
178 | def run() -> None:
179 | while Scraper.will_visit:
180 | url = Scraper.will_visit.pop()
181 |
182 | Scraper._load_page(url)
183 | Scraper._expand_toggle_blocks()
184 | soup = BeautifulSoup(Scraper.driver.page_source, "html5lib")
185 | Scraper._clean_up(soup)
186 | Scraper._download_images(soup)
187 | Scraper._download_stylesheets(soup)
188 | Scraper._download_pdfs(soup)
189 | Scraper._insert_injection_hooks(soup)
190 | Scraper._link_to_table_view_subpages(soup)
191 | subpage_urls = Scraper._link_anchors(soup)
192 | FileManager.save_page(soup, url)
193 |
194 | Scraper.visited.add(url)
195 | Scraper.will_visit.update(page for page in subpage_urls if page not in Scraper.visited)
196 | LOG.info(f"pages left to scrape: {len(Scraper.will_visit)}")
197 |
198 | Scraper.driver.quit()
199 |
200 | @trace()
201 | @staticmethod
202 | def _load_page(url: str) -> None:
203 | prev_page = ""
204 |
205 | def is_page_loaded(d: webdriver.Chrome) -> bool:
206 | nonlocal prev_page
207 | root_block = d.find_elements(By.CLASS_NAME, "notion-presence-container")
208 | if root_block:
209 | unknown_blocks = d.find_elements(By.CLASS_NAME, "notion-unknown-block")
210 | loading_spinners = d.find_elements(By.CLASS_NAME, "loading-spinner")
211 | scrollers = d.find_elements(By.CLASS_NAME, "notion-scroller")
212 | scrollers_with_children = [scroller for scroller in scrollers if scroller.find_elements(By.TAG_NAME, "div")]
213 | page_changed = prev_page != d.page_source
214 | all_scrollers_loaded = len(scrollers_with_children) == len(scrollers)
215 | if all_scrollers_loaded and not unknown_blocks and not loading_spinners and not page_changed:
216 | return True
217 | LOG.info(f"waiting for: {len(unknown_blocks)} unknown blocks - {len(loading_spinners)} loading spinners - {len(scrollers_with_children)}/{len(scrollers)} scrollers with children")
218 | prev_page = d.page_source
219 | return False
220 |
221 | Scraper.driver.get(url)
222 | try:
223 | WebDriverWait(Scraper.driver, ARGS.timeout).until(is_page_loaded)
224 | except TimeoutException:
225 | LOG.info("timed out waiting for page to load, proceeding anyways (might be because of infinite spinners)")
226 | time.sleep(10)
227 | LOG.info("page loaded")
228 |
229 | mode = "dark" if ARGS.dark_mode else "light"
230 | Scraper.driver.execute_script("__console.environment.ThemeStore.setState({ mode: '" + mode + "' })")
231 | LOG.info(f"set theme to {mode}-mode")
232 |
233 | @trace(print_args=False)
234 | @staticmethod
235 | def _expand_toggle_blocks(expanded_toggle_blocks=[]) -> None:
236 | def get_toggle_blocks() -> List[WebElement]:
237 | toggle_blocks = Scraper.driver.find_elements(By.CLASS_NAME, "notion-toggle-block")
238 | header_toggle_blocks = []
239 | queries = [f"notion-selectable.notion-{type}-block" for type in ["header", "sub_header", "sub_sub_header"]]
240 | for query in queries:
241 | blocks = Scraper.driver.find_elements(By.CLASS_NAME, query)
242 | for block in blocks:
243 | if block.find_elements(By.CSS_SELECTOR, "div[role=button]"):
244 | header_toggle_blocks.append(block)
245 | toggle_blocks += header_toggle_blocks
246 | return toggle_blocks
247 |
248 | def is_block_expanded(b: WebElement) -> bool:
249 | content = b.find_element(By.CSS_SELECTOR, "div:not([style]")
250 | unknown_children = b.find_elements(By.CLASS_NAME, "notion-unknown-block")
251 | is_loading = b.find_elements(By.CLASS_NAME, "loading-spinner")
252 | return content and not unknown_children and not is_loading
253 |
254 | toggle_blocks = get_toggle_blocks()
255 | toggle_blocks = [block for block in toggle_blocks if block not in expanded_toggle_blocks]
256 | assert all(isinstance(block, WebElement) for block in toggle_blocks), "toggle blocks should be web elements"
257 |
258 | for block in toggle_blocks:
259 | toggle_block_button = block.find_element(By.CSS_SELECTOR, "div[role=button]")
260 | block_style = toggle_block_button.find_element(By.TAG_NAME, "svg").get_attribute("style")
261 | assert isinstance(block_style, str), "toggle block style should be string"
262 | assert block_style is not None
263 | is_expanded = "(180deg)" in block_style
264 | if not is_expanded:
265 | Scraper.driver.execute_script("arguments[0].click();", toggle_block_button)
266 | try:
267 | assert isinstance(block, WebElement), "toggle block should be web element"
268 | WebDriverWait(Scraper.driver, ARGS.timeout).until(lambda d: is_block_expanded(block))
269 | except TimeoutException:
270 | LOG.critical("timeout while expanding block - manually check if it's expanded in the snapshot")
271 | continue
272 | expanded_toggle_blocks.append(block)
273 |
274 | nested_toggle_blocks = [block for block in get_toggle_blocks() if block not in expanded_toggle_blocks]
275 | LOG.info(f"expanded {len(expanded_toggle_blocks)} toggle blocks so far - found {len(nested_toggle_blocks)} nested blocks expand next")
276 | if nested_toggle_blocks:
277 | Scraper._expand_toggle_blocks(expanded_toggle_blocks)
278 |
279 | @staticmethod
280 | def _clean_up(soup: BeautifulSoup) -> None:
281 | for script in soup.findAll("script"):
282 | script.decompose()
283 | for aif_production in soup.findAll("iframe", {"src": "https://aif.notion.so/aif-production.soup"}):
284 | aif_production.decompose()
285 | for intercom_frame in soup.findAll("iframe", {"id": "intercom-frame"}):
286 | intercom_frame.decompose()
287 | for intercom_div in soup.findAll("div", {"class": "intercom-lightweight-app"}):
288 | intercom_div.decompose()
289 | for overlay_div in soup.findAll("div", {"class": "notion-overlay-container"}):
290 | overlay_div.decompose()
291 | for vendors_css in soup.find_all("link", href=lambda text: bool(text) and "vendors~" in text):
292 | vendors_css.decompose()
293 | for collection_selector in soup.findAll("div", {"class": "notion-collection-view-select"}):
294 | collection_selector.decompose()
295 | for tag in ["description", "twitter:card", "twitter:site", "twitter:title", "twitter:description", "twitter:image", "twitter:url", "apple-itunes-app"]:
296 | unwanted_tag = soup.find("meta", attrs={"name": tag})
297 | if unwanted_tag and isinstance(unwanted_tag, Tag):
298 | unwanted_tag.decompose()
299 | for tag in ["og:site_name", "og:type", "og:url", "og:title", "og:description", "og:image"]:
300 | unwanted_og_tag = soup.find("meta", attrs={"property": tag})
301 | if unwanted_og_tag and isinstance(unwanted_og_tag, Tag):
302 | unwanted_og_tag.decompose()
303 |
304 | @trace()
305 | @staticmethod
306 | def _download_images(soup: BeautifulSoup) -> None:
307 | images = [img for img in soup.findAll("img") if img.has_attr("src") and not (img.has_attr("class") and "notion-emoji" in img["class"])]
308 | LOG.info(f"found {len(images)} images to download")
309 | for img in images:
310 | is_notion_asset = img["src"].startswith("/")
311 | if "data:image" not in img["src"]:
312 | img_src = img["src"]
313 | if is_notion_asset:
314 | img_src = f'https://www.notion.so{img["src"]}'
315 | img["src"] = FileManager.download_asset(img_src)
316 | elif is_notion_asset:
317 | img["src"] = f'https://www.notion.so{img["src"]}'
318 |
319 | emojis = [img for img in soup.findAll("img") if img.has_attr("class") and "notion-emoji" in img["class"]]
320 | LOG.info(f"found {len(emojis)} emojis to download")
321 | for img in emojis:
322 | style = cssutils.parseStyle(img["style"])
323 | spritesheet = style["background"]
324 | spritesheet_url = spritesheet[spritesheet.find("(") + 1 : spritesheet.find(")")]
325 | download_path = FileManager.download_asset(f"https://www.notion.so{spritesheet_url}")
326 | style["background"] = spritesheet.replace(spritesheet_url, download_path)
327 | img["style"] = style.cssText
328 |
329 | is_in_both = lambda img: img in images and img in emojis
330 | shared = [is_in_both(img) for img in images + emojis]
331 | assert not any(shared), "img is both an image and an emoji"
332 |
333 | @trace()
334 | @staticmethod
335 | def _download_stylesheets(soup: BeautifulSoup) -> None:
336 | def is_stylesheet(link):
337 | return link.has_attr("href") and link["href"].startswith("/") and "vendors~" not in link["href"]
338 |
339 | stylesheets = [link for link in soup.findAll("link", rel="stylesheet") if is_stylesheet(link)]
340 | base_url = "https://www.notion.so"
341 |
342 | for link in stylesheets:
343 | download_path = FileManager.download_asset(f'{base_url}{link["href"]}')
344 |
345 | css_file_path = os.path.join(FileManager.output_dir, download_path)
346 | # Open file with UTF-8 encoding
347 | with open(css_file_path, "r", encoding="utf-8") as f:
348 | css_content = f.read()
349 |
350 | # Write back with UTF-8 encoding
351 | with open(css_file_path, "w", encoding="utf-8") as f:
352 | url_pattern = re.compile(r"url\((https?:\/\/www\.notion\.so)?(\/[^)]+)\)")
353 |
354 | def url_replacer(match):
355 | full_url, partial_url = match.groups()
356 | if not full_url:
357 | font_file_name = os.path.basename(partial_url)
358 | font_download_url = f"{base_url}{partial_url}"
359 | font_local_path = FileManager.download_asset(font_download_url, font_file_name)
360 | return f"url({font_local_path})"
361 | return match.group(0)
362 |
363 | # Replace the URLs in the CSS content
364 | modified_css_content = url_pattern.sub(url_replacer, css_content)
365 | f.write(modified_css_content)
366 |
367 | link["href"] = download_path
368 |
369 | @trace()
370 | @staticmethod
371 | def _download_pdfs(soup: BeautifulSoup) -> None:
372 | driver_blocks = Scraper.driver.find_elements(By.CLASS_NAME, "notion-file-block")
373 | driver_names = [[c.text for c in b.find_elements(By.XPATH, ".//*")][-2] for b in driver_blocks]
374 | assert len(driver_blocks) == len(driver_names), "number of driver blocks and names do not match"
375 | driver_pairs = [nb for nb in list(zip(driver_names, driver_blocks)) if nb[0].endswith(".pdf")]
376 | LOG.info(f"found {len(driver_pairs)} pdfs to download")
377 |
378 | # notion unpredictably adds spaces to names
379 | is_equal = lambda str1, str2: str1.replace(" ", "") == str2.replace(" ", "")
380 | is_in_list = lambda str1, str_list: any(is_equal(str1, str2) for str2 in str_list)
381 |
382 | for driver_name, driver_block in driver_pairs:
383 | download_name = driver_name.replace("/", "_").replace(":", "_")
384 | LOG.info(f"downloading file named '{download_name}'")
385 |
386 | if download_name in os.listdir(FileManager.assets_dir):
387 | LOG.info("pdf with same name was found in assets")
388 |
389 | elif not ARGS.disable_caching and FileManager._load_from_cache(download_name) is not None:
390 | LOG.info("pdf with same name was found in cache")
391 |
392 | else:
393 | assets_before_download = set(os.listdir(FileManager.assets_dir))
394 |
395 | try:
396 | driver_block.click()
397 | except ElementClickInterceptedException:
398 | webdriver.ActionChains(Scraper.driver).move_to_element(driver_block).click(driver_block).perform()
399 | Scraper.driver.execute_script("arguments[0].click();", driver_block)
400 | LOG.critical("clicking on pdf block was unsuccessful, consider running again with '-b' and clicking on it yourself")
401 |
402 | get_new_files = lambda: set(os.listdir(FileManager.assets_dir)) - assets_before_download
403 | is_downloaded = lambda: len(get_new_files()) == 1 and is_in_list(download_name, list(get_new_files()))
404 | while not is_downloaded():
405 | time.sleep(0.25)
406 | LOG.info(f"{get_new_files()} doesn't contain '{download_name}' yet")
407 | LOG.info(f"downloaded '{download_name}'")
408 | assert not re.compile(rf"{download_name} \(\d+\)\.pdf") in get_new_files(), "downloaded same pdf multiple times"
409 |
410 | soup_blocks = soup.findAll("div", {"class": "notion-file-block"})
411 | soup_names = [[c.text for c in b.find_all("div")][-2] for b in soup_blocks]
412 | assert len(soup_blocks) == len(soup_names), "number of soup blocks and names do not match"
413 | assert is_in_list(driver_name, soup_names), "driver name not found in soup names"
414 |
415 | soup_block = soup_blocks[soup_names.index(next(n for n in soup_names if is_equal(n, driver_name)))]
416 | soup_block.name = "a"
417 | soup_block["href"] = "./assets/" + download_name
418 | soup_block["style"] = "text-decoration: none; color: inherit;"
419 | soup_block["target"] = "_blank"
420 |
421 | @staticmethod
422 | def _insert_injection_hooks(soup: BeautifulSoup) -> None:
423 | # add ids and classes for 'injection.js' to work
424 | toggle_blocks = soup.findAll("div", {"class": "notion-toggle-block"})
425 | for query in ["header", "sub_header", "sub_sub_header"]:
426 | header_toggle_blocks = soup.findAll("div", {"class": f"notion-selectable notion-{query}-block"})
427 | [toggle_blocks.append(block) for block in header_toggle_blocks if block.select_one("div[role=button]") is not None]
428 | for toggle_block in toggle_blocks:
429 | toggle_button = toggle_block.select_one("div[role=button]")
430 | toggle_content = toggle_block.find("div", {"class": None, "style": ""})
431 | if toggle_button and toggle_content:
432 | toggle_button["class"] = toggle_block.get("class", []) + ["notionsnapshot-toggle-button"]
433 | toggle_content["class"] = toggle_content.get("class", []) + ["notionsnapshot-toggle-content"]
434 | toggle_content.attrs["notionsnapshot-toggle-id"] = toggle_button.attrs["notionsnapshot-toggle-id"] = uuid.uuid4()
435 |
436 | assert soup.head is not None
437 | soup.head.insert(-1, soup.new_tag("link", rel="stylesheet", href=FileManager.css_injection_file))
438 | assert soup.body is not None
439 | soup.body.insert(-1, soup.new_tag("script", type="text/javascript", src=FileManager.js_injection_file))
440 |
441 | @trace()
442 | @staticmethod
443 | def _link_to_table_view_subpages(soup: BeautifulSoup) -> None:
444 | # this function broke with a recent notion update
445 | tables = soup.findAll("div", {"class": "notion-table-view"})
446 | LOG.info(f"found {len(tables)} tables")
447 | for table in tables:
448 | rows = table.findAll("div", {"class": "notion-collection-item"})
449 | LOG.info(f"found {len(rows)} rows with links to subpages in table")
450 | for row in rows:
451 | subpage_path = "/" + row["data-block-id"].replace("-", "")
452 | row_name_span = row.find("span")
453 | # row_name_span["style"] = row_name_span["style"].replace("pointer-events: none;", "")
454 | subpage_anchor = soup.new_tag(
455 | "a",
456 | attrs={"href": subpage_path, "style": "cursor: pointer; color: inherit; text-decoration: none; fill: inherit;"},
457 | )
458 | row_name_span.wrap(subpage_anchor)
459 |
460 | @trace()
461 | @staticmethod
462 | def _link_anchors(soup: BeautifulSoup) -> List[str]:
463 | subpage_urls = []
464 |
465 | domain = f'{ARGS.url.split("notion.site")[0]}notion.site'
466 | anchors = soup.find_all("a", href=True)
467 |
468 | for a in anchors:
469 | url = a["href"]
470 |
471 | is_relative_url = url.startswith("/")
472 | if is_relative_url:
473 | url = f'{domain}/{a["href"].split("/")[-1]}'
474 |
475 | is_external_url = not url.startswith(domain)
476 | if is_external_url:
477 | continue
478 |
479 | scroller_parent = a.find_parent("div", class_="notion-scroller")
480 | is_scroller = scroller_parent is not None and len(scroller_parent) > 0
481 | topbar_parent = a.find_parent("div", class_="notion-topbar")
482 | is_topbar = topbar_parent is not None and len(topbar_parent) > 0
483 | is_table_of_contents = "#" in url
484 |
485 | if is_table_of_contents:
486 | # add ids and classes for 'injection.js' to work
487 | arr = url.split("#")
488 | url = arr[0]
489 | a["href"] = f"#{arr[-1]}"
490 | a["class"] = a.get("class", []) + ["notionsnapshot-anchor-link"]
491 |
492 | elif is_scroller or is_topbar:
493 | filename = FileManager.get_filename_from_url(url)
494 | a["href"] = filename
495 | subpage_urls.append(url)
496 |
497 | else:
498 | # remove all other links
499 | del a["href"]
500 | a.name = "span"
501 | children = [child for child in ([a] + a.find_all()) if child.has_attr("style")]
502 | for child in children:
503 | style = cssutils.parseStyle(child["style"])
504 | style["cursor"] = "default"
505 | child["style"] = style.cssText
506 |
507 | return subpage_urls
508 |
509 |
510 | if __name__ == "__main__":
511 | FileManager.setup()
512 | Scraper().run()
513 |
--------------------------------------------------------------------------------
/notionsnapshot/argparser.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import urllib.parse
3 | import urllib.request
4 |
5 |
6 | class ArgParser:
7 | @staticmethod
8 | def get_arguments() -> argparse.Namespace:
9 | args = ArgParser._parse_arguments()
10 | ArgParser._validate_url(args.url)
11 | ArgParser._validate_timeout(args.timeout)
12 | return args
13 |
14 | @staticmethod
15 | def _parse_arguments() -> argparse.Namespace:
16 | parser = argparse.ArgumentParser()
17 | parser.add_argument("-b", "--show-browser", help="disable headless mode and show browser window", action="store_true")
18 | parser.add_argument("-d", "--dark-mode", help="scrape pages in dark mode", action="store_true")
19 | parser.add_argument("-t", "--timeout", help="specify download timeout in seconds", type=int, default=10, metavar="TIMEOUT")
20 | parser.add_argument("-c", "--disable-caching", help="disable caching of assets", action="store_true")
21 | parser.add_argument("url", help="url of the notion.so page to scrape", metavar="URL")
22 | return parser.parse_args()
23 |
24 | @staticmethod
25 | def _validate_timeout(timeout: int) -> None:
26 | if timeout < 0:
27 | raise argparse.ArgumentTypeError("timeout argument not a positive integer")
28 |
29 | @staticmethod
30 | def _validate_url(url_str: str) -> None:
31 | url = urllib.parse.urlparse(url_str)
32 | if url.scheme != "https":
33 | raise argparse.ArgumentTypeError("url argument doesn't start with https://")
34 | if not url.netloc.endswith(".notion.site"):
35 | raise argparse.ArgumentTypeError("url argument is missing 'notion.site' domain")
36 | if not url.path.startswith("/"):
37 | raise argparse.ArgumentTypeError("url argument doesn't contain an id")
38 | if url.fragment:
39 | raise argparse.ArgumentTypeError("url argument contains a fragment ('#')")
40 |
41 |
42 | ARGS = ArgParser.get_arguments()
43 |
--------------------------------------------------------------------------------
/notionsnapshot/driver.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | from selenium import webdriver
4 | from selenium.webdriver.chrome.service import Service as ChromeService
5 | from webdriver_manager.chrome import ChromeDriverManager
6 | from selenium.webdriver.chrome.options import Options
7 | from selenium.webdriver.common.service import Service
8 |
9 | from argparser import ARGS
10 |
11 |
12 | class DriverInitializer:
13 | @staticmethod
14 | def get_driver(file_download_path: str) -> webdriver.Chrome:
15 | # see: https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md
16 | opts = Options()
17 | opts.add_argument("--disable-client-side-phishing-detection")
18 | opts.add_argument("--no-first-run")
19 | opts.add_argument("--enable-automation")
20 | opts.add_argument("--no-sandbox")
21 | opts.add_argument("--disable-dev-shm-usage")
22 | opts.add_argument("--disable-gpu")
23 | opts.add_argument("--silent")
24 | opts.add_argument("--disable-logging")
25 | opts.add_argument("--headless=new") if not ARGS.show_browser else opts.add_argument("window-size=900,1200")
26 | opts.add_experimental_option("excludeSwitches", ["enable-logging"])
27 |
28 | # see: https://stackoverflow.com/questions/43470535/python-download-pdf-embedded-in-a-page/43471196#43471196
29 | profile = {
30 | "plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}],
31 | "download.default_directory": file_download_path,
32 | "download.extensions_to_open": "",
33 | "plugins.always_open_pdf_externally": True,
34 | }
35 | opts.add_experimental_option("prefs", profile)
36 |
37 | os.environ["WDM_PROGRESS_BAR"] = str(0)
38 | os.environ["WDM_LOG"] = str(logging.NOTSET)
39 |
40 | executable_path = ChromeDriverManager().install()
41 | chrome_executable: Service = ChromeService(executable_path=executable_path)
42 | driver = webdriver.Chrome(service=chrome_executable, options=opts)
43 | return driver
44 |
--------------------------------------------------------------------------------
/notionsnapshot/injections/injection.css:
--------------------------------------------------------------------------------
1 | /* enable hover effect on buttons */
2 | div[role="button"]:not(.notion-record-icon):hover {
3 | background: rgba(55, 53, 47, 0.08);
4 | }
5 |
6 | /* hide loading spinners */
7 | .loading-spinner {
8 | display: none !important;
9 | }
10 |
11 | /* hide elements on the top right (search box, duplicate, notion shortcut) */
12 | .notion-topbar > div > div:not(:first-child) {
13 | display: none !important;
14 | }
15 |
16 | /* stop inline databases from overflowing horizontally */
17 | .notion-frame {
18 | max-width: 100%;
19 | width: 100vw !important;
20 | }
21 |
22 | .notion-selectable {
23 | max-width: 100% !important;
24 | }
25 |
26 | .notion-scroller .notion-collection_view-block {
27 | width: 100% !important;
28 | max-width: 100% !important;
29 | }
30 |
31 | /* resize inline databases */
32 | .notion-scroller .notion-collection_view-block > div,
33 | .notion-scroller .notion-collection_view-block > div > div > div,
34 | .notion-scroller .notion-collection_view-block .notion-list-view,
35 | .notion-scroller .notion-collection_view-block .notion-gallery-view,
36 | .notion-scroller .notion-collection_view-block .notion-table-view,
37 | .notion-scroller .notion-collection_view-block .notion-board-view,
38 | .notion-scroller .notion-collection_view-block .notion-calendar-view {
39 | max-width: 100% !important;
40 | padding-left: unset !important;
41 | padding-right: unset !important;
42 | }
43 |
44 | /* pull alias arrows back inline */
45 | svg.alias {
46 | display: inline-block !important;
47 | height: auto !important;
48 | }
49 |
50 | /* stop text from overflowing past max-width on bookmark blocks; */
51 | .notion-bookmark-block div {
52 | white-space: unset !important;
53 | }
54 |
55 | /* fix oversized page properties on Safari */
56 | .notion-scroller
57 | > div:nth-child(2):not(.notion-page-content)
58 | > div:not([data-block-id])
59 | div:not(.notion-page-details-controls) {
60 | height: auto !important;
61 | }
62 |
63 | /* fix possible stray header on tables */
64 | .notion-collection_view_page-block > div:first-child {
65 | transform: unset !important;
66 | }
67 |
68 | /* fix oversize icons in inline page links */
69 | a[data-token-index] svg.page {
70 | height: auto !important;
71 | }
72 |
73 | /* mobile fixes */
74 | @media only screen and (max-width: 960px) {
75 | :root {
76 | --mobile-width: 90vw;
77 | }
78 |
79 | /* normalize banner / page title width */
80 | .notion-scroller > div:not([class]),
81 | .notion-scroller > div > div:not([class]) {
82 | width: var(--mobile-width) !important;
83 | margin: auto !important;
84 |
85 | max-width: 960px !important;
86 | padding-left: 0 !important;
87 | padding-right: 0 !important;
88 | }
89 |
90 | /* normalize content width */
91 | .notion-page-content,
92 | .notion-page-content > .notion-collection_view-block,
93 | .notion-page-content > .notion-collection_view-block > div,
94 | .notion-page-content > .notion-collection_view-block > .notion-scroller > div {
95 | width: var(--mobile-width) !important;
96 | margin: auto !important;
97 |
98 | /* max-width: unset !important; */
99 | padding-right: 0 !important;
100 | padding-left: 0 !important;
101 | }
102 |
103 | /* add padding to banner, but not to image */
104 | .notion-frame > .notion-scroller > div:first-child > div:last-child {
105 | padding-right: 2em !important;
106 | padding-left: 2em !important;
107 | }
108 |
109 | /* add padding to content */
110 | .notion-scroller > div:not([class]):not(:first-child),
111 | .notion-scroller > .notion-page-content,
112 | .notion-frame > .notion-scroller > .notion-scroller > .notion-list-view,
113 | .notion-frame > .notion-scroller > .notion-scroller > .notion-gallery-view,
114 | .notion-frame > .notion-scroller > .notion-scroller > .notion-table-view,
115 | .notion-frame > .notion-scroller > .notion-scroller > .notion-board-view,
116 | .notion-frame > .notion-scroller > .notion-scroller > .notion-calendar-view {
117 | padding-right: 2em !important;
118 | padding-left: 2em !important;
119 | flex-wrap: wrap
120 | }
121 |
122 | /* collapse flex rows into columns */
123 | .notion-column_list-block > div {
124 | flex-direction: column;
125 | }
126 | .notion-column_list-block > div > * {
127 | width: unset !important;
128 | }
129 |
130 | /* force gallery to wrap around pages */
131 | .notion-gallery-view {
132 | width: 100vw;
133 | }
134 |
135 | /* enable horizontal scroll for lists and tables on mobile */
136 | .notion-collection-item > a {
137 | overflow: visible !important;
138 | }
139 | .notion-collection-item > a > div {
140 | width: unset !important;
141 | }
142 | .notion-scroller.horizontal {
143 | overflow-x: scroll;
144 | }
145 |
146 | /* make the top border on overflowing list reach the full width of the list */
147 | .notion-list-view > .notion-collection_view_page-block {
148 | width: fit-content;
149 | }
150 |
151 | .notion-scroller
152 | > div:nth-child(2):not(.notion-page-content)
153 | > div:not([data-block-id])
154 | div:not(.notion-page-details-controls) {
155 | padding-left: 0!important;
156 | padding-right: 0!important;
157 | }
158 | }
159 |
160 | .pseudoAfter:after {
161 | color: var(--pseudoAfter--color);
162 | content: var(--pseudoAfter--content);
163 | border: var(--pseudoAfter--border);
164 | width: var(--pseudoAfter--width);
165 | height: var(--pseudoAfter--height);
166 | display: var(--pseudoAfter--display);
167 | background: var(--pseudoAfter--background);
168 | }
169 |
170 | .pseudoBefore:before {
171 | color: var(--pseudoBefore--color);
172 | content: var(--pseudoBefore--content);
173 | border: var(--pseudoBefore--border);
174 | width: var(--pseudoBefore--width);
175 | height: var(--pseudoBefore--height);
176 | display: var(--pseudoBefore--display) !important;
177 | background: var(--pseudoBefore--background);
178 | }
179 |
180 | .pseudoSelection ::selection {
181 | color: var(--pseudoSelection--color);
182 | background: var(--pseudoSelection--background);
183 | text-shadow: var(--pseudoSelection--textShadow);
184 | }
185 |
--------------------------------------------------------------------------------
/notionsnapshot/injections/injection.js:
--------------------------------------------------------------------------------
1 | /**
2 | * re-implement toggle buttons
3 | */
4 | const showToggle = (content, arrow) => {
5 | arrow.style.transform = 'rotateZ(180deg)'
6 | content.style.display = 'block'
7 | }
8 |
9 | const hideToggle = (content, arrow) => {
10 | arrow.style.transform = 'rotateZ(90deg)'
11 | content.style.display = 'none'
12 | }
13 |
14 | const toggleButtons = document.getElementsByClassName('notionsnapshot-toggle-button')
15 | for (toggleButton of toggleButtons) {
16 | const toggleId = toggleButton.getAttribute('notionsnapshot-toggle-id')
17 | const toggleContent = document.querySelector(
18 | `.notionsnapshot-toggle-content[notionsnapshot-toggle-id='${toggleId}']`
19 | )
20 | const toggleArrow = toggleButton.querySelector('svg')
21 | if (toggleButton && toggleContent) {
22 | hideToggle(toggleContent, toggleArrow)
23 | toggleButton.addEventListener('click', () => {
24 | if (toggleContent.style.display == 'none') {
25 | showToggle(toggleContent, toggleArrow)
26 | } else {
27 | hideToggle(toggleContent, toggleArrow)
28 | }
29 | })
30 | }
31 | }
32 |
33 | /**
34 | * re-implement anchor links
35 | */
36 | const anchorLinks = document.querySelectorAll('a.notionsnapshot-anchor-link')
37 | for (anchorLink of anchorLinks) {
38 | const id = anchorLink.getAttribute('href').replace('#', '')
39 | const targetBlockId =
40 | id.slice(0, 8) + '-' + id.slice(8, 12) + '-' + id.slice(12, 16) + '-' + id.slice(16, 20) + '-' + id.slice(20)
41 | anchorLink.addEventListener('click', (e) => {
42 | e.preventDefault()
43 | console.log(targetBlockId)
44 | document.querySelector(`div[data-block-id='${targetBlockId}']`).scrollIntoView({
45 | behavior: 'smooth',
46 | block: 'start',
47 | })
48 | })
49 | }
50 |
51 | /**
52 | * set all iframes' parent container opacity to 1
53 | */
54 | const pendingIframes = document.getElementsByTagName('iframe')
55 | for (let i = 0; i < pendingIframes.length; i++) {
56 | pendingIframes.item(i).parentElement.style.opacity = 1
57 | }
58 |
59 | /**
60 | * hide search box on inline databases
61 | */
62 | const collectionSearchBoxes = document.getElementsByClassName('collectionSearch')
63 | for (let i = 0; i < collectionSearchBoxes.length; i++) {
64 | const collectionSearchBox = collectionSearchBoxes.item(i).parentElement
65 | collectionSearchBox.style.display = 'none'
66 | }
67 |
68 | /**
69 | * remove extra padding in Webkit renderers on iOS devices
70 | */
71 | const imgs = document.querySelectorAll('img:not(.notion-emoji)')
72 | for (let i = 0; i < imgs.length; i++) {
73 | parent = imgs[i].parentElement
74 | let style = parent.getAttribute('style')
75 | style = style.replace(/padding-bottom: 133\.333\%;/, '')
76 | style = style + '; height:auto!important;'
77 | parent.setAttribute('style', style)
78 | }
79 |
--------------------------------------------------------------------------------
/notionsnapshot/logger.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import inspect
3 |
4 | import traceback
5 | import functools
6 | from rich.logging import RichHandler
7 | import os
8 | from bs4 import BeautifulSoup
9 | import cssutils
10 |
11 | from argparser import ARGS
12 |
13 |
14 | BANNER_ASCII = """
15 | _ __ __ _ _____ __ __
16 | / | / /___ / /_(_)___ ____ / ___/____ ____ _____ _____/ /_ ____ / /_
17 | / |/ / __ \\/ __/ / __ \\/ __ \\ \\__ \\/ __ \\/ __ `/ __ \\/ ___/ __ \\/ __ \\/ __/
18 | / /| / /_/ / /_/ / /_/ / / / / ___/ / / / / /_/ / /_/ (__ ) / / / /_/ / /_
19 | /_/ |_/\\____/\\__/_/\\____/_/ /_/ /____/_/ /_/\\__,_/ .___/____/_/ /_/\\____/\\__/
20 | /_/
21 | """
22 | HIGHLIGHTED_WORDS = ["pages left to scrape:"]
23 | IGNORED_STACK_FRAMES = 8
24 |
25 |
26 | class LogWrapper(logging.LoggerAdapter):
27 | def process(self, msg, kwargs):
28 | # add indentation based on stack depth
29 | tab_char = " " * 3
30 | indentation_level = len(traceback.extract_stack()) - IGNORED_STACK_FRAMES
31 | return f"{tab_char * indentation_level}{msg}", kwargs
32 |
33 |
34 | class LogInitializer:
35 | @staticmethod
36 | def get_log() -> logging.LoggerAdapter:
37 | # see: https://rich.readthedocs.io/en/stable/reference/logging.html
38 | rich_handler = RichHandler(rich_tracebacks=True, show_time=False, show_path=False, keywords=HIGHLIGHTED_WORDS)
39 | logging.basicConfig(level=logging.INFO, format="%(message)s", handlers=[rich_handler])
40 | cssutils.log.setLevel(logging.CRITICAL) # type: ignore
41 |
42 | os.system("cls" if os.name == "nt" else "clear")
43 | print(BANNER_ASCII)
44 | return LogWrapper(logging.getLogger("scrape-logger"), {})
45 |
46 |
47 | LOG_SINGLETON = LogInitializer.get_log()
48 |
49 |
50 | def trace(print_args: bool = True):
51 | def decorator(func):
52 | # see: https://realpython.com/primer-on-python-decorators/#debugging-code
53 | @functools.wraps(func)
54 | def wrapper(*args, **kwargs):
55 | input_string = "⮕ "
56 | input_string += func.__name__ + "("
57 | if print_args:
58 | not_html = [arg for arg in args if not isinstance(arg, BeautifulSoup)]
59 | input_string += ", ".join([str(arg) for arg in not_html]) # arg[0] might be self
60 | input_string += ")"
61 | LOG_SINGLETON.info(input_string)
62 |
63 | result = func(*args, **kwargs)
64 |
65 | output_string = result if result is not None else ""
66 | LOG_SINGLETON.info(f"⬅ {output_string if print_args else ''}")
67 | return result
68 |
69 | return wrapper
70 |
71 | return decorator
72 |
--------------------------------------------------------------------------------
/requirements.in:
--------------------------------------------------------------------------------
1 | appdirs
2 | beautifulsoup4
3 | cssutils
4 | html5lib
5 | Requests
6 | rich
7 | selenium
8 | webdriver_manager
9 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | #
2 | # This file is autogenerated by pip-compile with Python 3.11
3 | # by the following command:
4 | #
5 | # pip-compile --output-file=requirements.txt requirements.in
6 | #
7 | appdirs==1.4.4
8 | # via -r requirements.in
9 | attrs==24.2.0
10 | # via
11 | # outcome
12 | # trio
13 | beautifulsoup4==4.12.3
14 | # via -r requirements.in
15 | certifi==2024.8.30
16 | # via
17 | # requests
18 | # selenium
19 | charset-normalizer==3.3.2
20 | # via requests
21 | cssutils==2.11.1
22 | # via -r requirements.in
23 | h11==0.14.0
24 | # via wsproto
25 | html5lib==1.1
26 | # via -r requirements.in
27 | idna==3.9
28 | # via
29 | # requests
30 | # trio
31 | markdown-it-py==3.0.0
32 | # via rich
33 | mdurl==0.1.2
34 | # via markdown-it-py
35 | more-itertools==10.5.0
36 | # via cssutils
37 | outcome==1.3.0.post0
38 | # via trio
39 | packaging==24.1
40 | # via webdriver-manager
41 | pygments==2.18.0
42 | # via rich
43 | pysocks==1.7.1
44 | # via urllib3
45 | python-dotenv==1.0.1
46 | # via webdriver-manager
47 | requests==2.32.3
48 | # via
49 | # -r requirements.in
50 | # webdriver-manager
51 | rich==13.8.1
52 | # via -r requirements.in
53 | selenium==4.24.0
54 | # via -r requirements.in
55 | six==1.16.0
56 | # via html5lib
57 | sniffio==1.3.1
58 | # via trio
59 | sortedcontainers==2.4.0
60 | # via trio
61 | soupsieve==2.6
62 | # via beautifulsoup4
63 | trio==0.26.2
64 | # via
65 | # selenium
66 | # trio-websocket
67 | trio-websocket==0.11.1
68 | # via selenium
69 | typing-extensions==4.12.2
70 | # via selenium
71 | urllib3[socks]==2.2.3
72 | # via
73 | # requests
74 | # selenium
75 | webdriver-manager==4.0.2
76 | # via -r requirements.in
77 | webencodings==0.5.1
78 | # via html5lib
79 | websocket-client==1.8.0
80 | # via selenium
81 | wsproto==1.2.0
82 | # via trio-websocket
83 |
--------------------------------------------------------------------------------
/test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | FULL_TEST="https://sueszli.notion.site/NotionSnapshot-Test-5ab361d19688436fb22f319e84b53a07"
4 | NOTION_TEMPLATES="https://sueszli.notion.site/NotionSnapshot-Test-full-templates-cfbba0e4a3244e84b3242b137c2f640e"
5 | TINY_TEST="https://sueszli.notion.site/NotionSnapshot-Test-tiny-page-4dfa05657f774b45993542da4a8530c2"
6 | PDF_TEST="https://sueszli.notion.site/NotionSnapshot-Test-pdf-ede3b5b97b104ab59d508f3645c0a513"
7 |
8 | python3 notionsnapshot -d -c $FULL_TEST > ./log.txt
9 |
--------------------------------------------------------------------------------