├── .coveragerc ├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── pytest.ini ├── setup.cfg ├── setup.py ├── src └── jupyter_notebook_gist │ ├── __init__.py │ ├── config.py │ ├── handlers.py │ └── static │ ├── common.js │ ├── notebook-extension.js │ └── tree-extension.js ├── tests └── test_handlers.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = jupyter_notebook_gist 4 | 5 | [paths] 6 | source = 7 | src/jupyter_notebook_gist 8 | .tox/*/lib/python*/site-packages/jupyter_notebook_gist 9 | .tox/pypy*/site-packages/jupyter_notebook_gist 10 | 11 | [report] 12 | show_missing = True 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | 64 | node_modules/ 65 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | sudo: false 3 | cache: pip 4 | python: 5 | - '2.7' 6 | - '3.4' 7 | - '3.5' 8 | - '3.6' 9 | - pypy 10 | install: 11 | - pip install tox-travis 12 | script: 13 | - tox -v 14 | after_success: 15 | - bash <(curl -s https://codecov.io/bash) 16 | jobs: 17 | include: 18 | - stage: deploy 19 | python: '3.5' 20 | script: skip 21 | deploy: 22 | provider: pypi 23 | user: jezdez 24 | password: 25 | secure: ViRTTMj8HW1zlR4/FYqNO86pSPIWYWq5FTp527yo9lQ9TPqX0uWmOlVvLOhY/mQDAWvbq1F2KaLds4o1Gl2QadsnToxmze6oqp9yam4XlNdekD8P3IBjOfuRBlE9pOG5VHae/U7bh6hneKAa5WEMYM1bu1mvMGQVtn+BHMgmiTBt1x8soUwqxNQfesKHnerf4ApdlpiZQqLY+PLGK823lwvX8BIa1UGtyExdPASAOks8EAruiC4tQynnHBsMRAM/TJsy5hqX22wNZvScWt+0TjVFID6N2FOl74cWxpPWTgLVa0Lm7dpy+LniU59nfOtCdA1R4oe/Q7V1VdPZAfiz7jrzBl4bbZngZXgbFWF4qMy4mV9CPtukKZqowfKnyIk9jRWAsmnmhzbJ23/UFW78SJDTrUSE2oQjlRA1vz5CX0MIF3K9RHqAanLh861odDZjruOSKJFbl/AIIFMHeOAHBAxGePxiGYHr8KWCLjMbthLJ1oHt4rn24tg3i2v3PEKT3HEEBnSz2AslgScDIK12lTwBDr47iXfC6uQlY+tZ05P6TnuAX+9z6+gjNZyU/GV+AwCUXkZ7K1p0A7cw+OEYMYMvm6NHmWg5TsYSZzfpNR04VFqEuXoojN2jBvV7IFcLL+DOmzVlRpdEGiiOk41THdlyJSmruobIwfQvaWQ3o28= 26 | distributions: sdist bdist_wheel 27 | on: 28 | tags: true 29 | repo: mozilla/jupyter-notebook-gist 30 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Community Participation Guidelines 2 | 3 | This repository is governed by Mozilla's code of conduct and etiquette guidelines. 4 | For more details, please read the 5 | [Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). 6 | 7 | ## How to Report 8 | For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page. 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License, version 2.0 2 | 3 | 1. Definitions 4 | 5 | 1.1. "Contributor" 6 | 7 | means each individual or legal entity that creates, contributes to the 8 | creation of, or owns Covered Software. 9 | 10 | 1.2. "Contributor Version" 11 | 12 | means the combination of the Contributions of others (if any) used by a 13 | Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | 17 | means Covered Software of a particular Contributor. 18 | 19 | 1.4. "Covered Software" 20 | 21 | means Source Code Form to which the initial Contributor has attached the 22 | notice in Exhibit A, the Executable Form of such Source Code Form, and 23 | Modifications of such Source Code Form, in each case including portions 24 | thereof. 25 | 26 | 1.5. "Incompatible With Secondary Licenses" 27 | means 28 | 29 | a. that the initial Contributor has attached the notice described in 30 | Exhibit B to the Covered Software; or 31 | 32 | b. that the Covered Software was made available under the terms of 33 | version 1.1 or earlier of the License, but not also under the terms of 34 | a Secondary License. 35 | 36 | 1.6. "Executable Form" 37 | 38 | means any form of the work other than Source Code Form. 39 | 40 | 1.7. "Larger Work" 41 | 42 | means a work that combines Covered Software with other material, in a 43 | separate file or files, that is not Covered Software. 44 | 45 | 1.8. "License" 46 | 47 | means this document. 48 | 49 | 1.9. "Licensable" 50 | 51 | means having the right to grant, to the maximum extent possible, whether 52 | at the time of the initial grant or subsequently, any and all of the 53 | rights conveyed by this License. 54 | 55 | 1.10. "Modifications" 56 | 57 | means any of the following: 58 | 59 | a. any file in Source Code Form that results from an addition to, 60 | deletion from, or modification of the contents of Covered Software; or 61 | 62 | b. any new file in Source Code Form that contains any Covered Software. 63 | 64 | 1.11. "Patent Claims" of a Contributor 65 | 66 | means any patent claim(s), including without limitation, method, 67 | process, and apparatus claims, in any patent Licensable by such 68 | Contributor that would be infringed, but for the grant of the License, 69 | by the making, using, selling, offering for sale, having made, import, 70 | or transfer of either its Contributions or its Contributor Version. 71 | 72 | 1.12. "Secondary License" 73 | 74 | means either the GNU General Public License, Version 2.0, the GNU Lesser 75 | General Public License, Version 2.1, the GNU Affero General Public 76 | License, Version 3.0, or any later versions of those licenses. 77 | 78 | 1.13. "Source Code Form" 79 | 80 | means the form of the work preferred for making modifications. 81 | 82 | 1.14. "You" (or "Your") 83 | 84 | means an individual or a legal entity exercising rights under this 85 | License. For legal entities, "You" includes any entity that controls, is 86 | controlled by, or is under common control with You. For purposes of this 87 | definition, "control" means (a) the power, direct or indirect, to cause 88 | the direction or management of such entity, whether by contract or 89 | otherwise, or (b) ownership of more than fifty percent (50%) of the 90 | outstanding shares or beneficial ownership of such entity. 91 | 92 | 93 | 2. License Grants and Conditions 94 | 95 | 2.1. Grants 96 | 97 | Each Contributor hereby grants You a world-wide, royalty-free, 98 | non-exclusive license: 99 | 100 | a. under intellectual property rights (other than patent or trademark) 101 | Licensable by such Contributor to use, reproduce, make available, 102 | modify, display, perform, distribute, and otherwise exploit its 103 | Contributions, either on an unmodified basis, with Modifications, or 104 | as part of a Larger Work; and 105 | 106 | b. under Patent Claims of such Contributor to make, use, sell, offer for 107 | sale, have made, import, and otherwise transfer either its 108 | Contributions or its Contributor Version. 109 | 110 | 2.2. Effective Date 111 | 112 | The licenses granted in Section 2.1 with respect to any Contribution 113 | become effective for each Contribution on the date the Contributor first 114 | distributes such Contribution. 115 | 116 | 2.3. Limitations on Grant Scope 117 | 118 | The licenses granted in this Section 2 are the only rights granted under 119 | this License. No additional rights or licenses will be implied from the 120 | distribution or licensing of Covered Software under this License. 121 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 122 | Contributor: 123 | 124 | a. for any code that a Contributor has removed from Covered Software; or 125 | 126 | b. for infringements caused by: (i) Your and any other third party's 127 | modifications of Covered Software, or (ii) the combination of its 128 | Contributions with other software (except as part of its Contributor 129 | Version); or 130 | 131 | c. under Patent Claims infringed by Covered Software in the absence of 132 | its Contributions. 133 | 134 | This License does not grant any rights in the trademarks, service marks, 135 | or logos of any Contributor (except as may be necessary to comply with 136 | the notice requirements in Section 3.4). 137 | 138 | 2.4. Subsequent Licenses 139 | 140 | No Contributor makes additional grants as a result of Your choice to 141 | distribute the Covered Software under a subsequent version of this 142 | License (see Section 10.2) or under the terms of a Secondary License (if 143 | permitted under the terms of Section 3.3). 144 | 145 | 2.5. Representation 146 | 147 | Each Contributor represents that the Contributor believes its 148 | Contributions are its original creation(s) or it has sufficient rights to 149 | grant the rights to its Contributions conveyed by this License. 150 | 151 | 2.6. Fair Use 152 | 153 | This License is not intended to limit any rights You have under 154 | applicable copyright doctrines of fair use, fair dealing, or other 155 | equivalents. 156 | 157 | 2.7. Conditions 158 | 159 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in 160 | Section 2.1. 161 | 162 | 163 | 3. Responsibilities 164 | 165 | 3.1. Distribution of Source Form 166 | 167 | All distribution of Covered Software in Source Code Form, including any 168 | Modifications that You create or to which You contribute, must be under 169 | the terms of this License. You must inform recipients that the Source 170 | Code Form of the Covered Software is governed by the terms of this 171 | License, and how they can obtain a copy of this License. You may not 172 | attempt to alter or restrict the recipients' rights in the Source Code 173 | Form. 174 | 175 | 3.2. Distribution of Executable Form 176 | 177 | If You distribute Covered Software in Executable Form then: 178 | 179 | a. such Covered Software must also be made available in Source Code Form, 180 | as described in Section 3.1, and You must inform recipients of the 181 | Executable Form how they can obtain a copy of such Source Code Form by 182 | reasonable means in a timely manner, at a charge no more than the cost 183 | of distribution to the recipient; and 184 | 185 | b. You may distribute such Executable Form under the terms of this 186 | License, or sublicense it under different terms, provided that the 187 | license for the Executable Form does not attempt to limit or alter the 188 | recipients' rights in the Source Code Form under this License. 189 | 190 | 3.3. Distribution of a Larger Work 191 | 192 | You may create and distribute a Larger Work under terms of Your choice, 193 | provided that You also comply with the requirements of this License for 194 | the Covered Software. If the Larger Work is a combination of Covered 195 | Software with a work governed by one or more Secondary Licenses, and the 196 | Covered Software is not Incompatible With Secondary Licenses, this 197 | License permits You to additionally distribute such Covered Software 198 | under the terms of such Secondary License(s), so that the recipient of 199 | the Larger Work may, at their option, further distribute the Covered 200 | Software under the terms of either this License or such Secondary 201 | License(s). 202 | 203 | 3.4. Notices 204 | 205 | You may not remove or alter the substance of any license notices 206 | (including copyright notices, patent notices, disclaimers of warranty, or 207 | limitations of liability) contained within the Source Code Form of the 208 | Covered Software, except that You may alter any license notices to the 209 | extent required to remedy known factual inaccuracies. 210 | 211 | 3.5. Application of Additional Terms 212 | 213 | You may choose to offer, and to charge a fee for, warranty, support, 214 | indemnity or liability obligations to one or more recipients of Covered 215 | Software. However, You may do so only on Your own behalf, and not on 216 | behalf of any Contributor. You must make it absolutely clear that any 217 | such warranty, support, indemnity, or liability obligation is offered by 218 | You alone, and You hereby agree to indemnify every Contributor for any 219 | liability incurred by such Contributor as a result of warranty, support, 220 | indemnity or liability terms You offer. You may include additional 221 | disclaimers of warranty and limitations of liability specific to any 222 | jurisdiction. 223 | 224 | 4. Inability to Comply Due to Statute or Regulation 225 | 226 | If it is impossible for You to comply with any of the terms of this License 227 | with respect to some or all of the Covered Software due to statute, 228 | judicial order, or regulation then You must: (a) comply with the terms of 229 | this License to the maximum extent possible; and (b) describe the 230 | limitations and the code they affect. Such description must be placed in a 231 | text file included with all distributions of the Covered Software under 232 | this License. Except to the extent prohibited by statute or regulation, 233 | such description must be sufficiently detailed for a recipient of ordinary 234 | skill to be able to understand it. 235 | 236 | 5. Termination 237 | 238 | 5.1. The rights granted under this License will terminate automatically if You 239 | fail to comply with any of its terms. However, if You become compliant, 240 | then the rights granted under this License from a particular Contributor 241 | are reinstated (a) provisionally, unless and until such Contributor 242 | explicitly and finally terminates Your grants, and (b) on an ongoing 243 | basis, if such Contributor fails to notify You of the non-compliance by 244 | some reasonable means prior to 60 days after You have come back into 245 | compliance. Moreover, Your grants from a particular Contributor are 246 | reinstated on an ongoing basis if such Contributor notifies You of the 247 | non-compliance by some reasonable means, this is the first time You have 248 | received notice of non-compliance with this License from such 249 | Contributor, and You become compliant prior to 30 days after Your receipt 250 | of the notice. 251 | 252 | 5.2. If You initiate litigation against any entity by asserting a patent 253 | infringement claim (excluding declaratory judgment actions, 254 | counter-claims, and cross-claims) alleging that a Contributor Version 255 | directly or indirectly infringes any patent, then the rights granted to 256 | You by any and all Contributors for the Covered Software under Section 257 | 2.1 of this License shall terminate. 258 | 259 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user 260 | license agreements (excluding distributors and resellers) which have been 261 | validly granted by You or Your distributors under this License prior to 262 | termination shall survive termination. 263 | 264 | 6. Disclaimer of Warranty 265 | 266 | Covered Software is provided under this License on an "as is" basis, 267 | without warranty of any kind, either expressed, implied, or statutory, 268 | including, without limitation, warranties that the Covered Software is free 269 | of defects, merchantable, fit for a particular purpose or non-infringing. 270 | The entire risk as to the quality and performance of the Covered Software 271 | is with You. Should any Covered Software prove defective in any respect, 272 | You (not any Contributor) assume the cost of any necessary servicing, 273 | repair, or correction. This disclaimer of warranty constitutes an essential 274 | part of this License. No use of any Covered Software is authorized under 275 | this License except under this disclaimer. 276 | 277 | 7. Limitation of Liability 278 | 279 | Under no circumstances and under no legal theory, whether tort (including 280 | negligence), contract, or otherwise, shall any Contributor, or anyone who 281 | distributes Covered Software as permitted above, be liable to You for any 282 | direct, indirect, special, incidental, or consequential damages of any 283 | character including, without limitation, damages for lost profits, loss of 284 | goodwill, work stoppage, computer failure or malfunction, or any and all 285 | other commercial damages or losses, even if such party shall have been 286 | informed of the possibility of such damages. This limitation of liability 287 | shall not apply to liability for death or personal injury resulting from 288 | such party's negligence to the extent applicable law prohibits such 289 | limitation. Some jurisdictions do not allow the exclusion or limitation of 290 | incidental or consequential damages, so this exclusion and limitation may 291 | not apply to You. 292 | 293 | 8. Litigation 294 | 295 | Any litigation relating to this License may be brought only in the courts 296 | of a jurisdiction where the defendant maintains its principal place of 297 | business and such litigation shall be governed by laws of that 298 | jurisdiction, without reference to its conflict-of-law provisions. Nothing 299 | in this Section shall prevent a party's ability to bring cross-claims or 300 | counter-claims. 301 | 302 | 9. Miscellaneous 303 | 304 | This License represents the complete agreement concerning the subject 305 | matter hereof. If any provision of this License is held to be 306 | unenforceable, such provision shall be reformed only to the extent 307 | necessary to make it enforceable. Any law or regulation which provides that 308 | the language of a contract shall be construed against the drafter shall not 309 | be used to construe this License against a Contributor. 310 | 311 | 312 | 10. Versions of the License 313 | 314 | 10.1. New Versions 315 | 316 | Mozilla Foundation is the license steward. Except as provided in Section 317 | 10.3, no one other than the license steward has the right to modify or 318 | publish new versions of this License. Each version will be given a 319 | distinguishing version number. 320 | 321 | 10.2. Effect of New Versions 322 | 323 | You may distribute the Covered Software under the terms of the version 324 | of the License under which You originally received the Covered Software, 325 | or under the terms of any subsequent version published by the license 326 | steward. 327 | 328 | 10.3. Modified Versions 329 | 330 | If you create software not governed by this License, and you want to 331 | create a new license for such software, you may create and use a 332 | modified version of this License if you rename the license and remove 333 | any references to the name of the license steward (except to note that 334 | such modified license differs from this License). 335 | 336 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 337 | Licenses If You choose to distribute Source Code Form that is 338 | Incompatible With Secondary Licenses under the terms of this version of 339 | the License, the notice described in Exhibit B of this License must be 340 | attached. 341 | 342 | Exhibit A - Source Code Form License Notice 343 | 344 | This Source Code Form is subject to the 345 | terms of the Mozilla Public License, v. 346 | 2.0. If a copy of the MPL was not 347 | distributed with this file, You can 348 | obtain one at 349 | http://mozilla.org/MPL/2.0/. 350 | 351 | If it is not possible or desirable to put the notice in a particular file, 352 | then You may include the notice in a location (such as a LICENSE file in a 353 | relevant directory) where a recipient would be likely to look for such a 354 | notice. 355 | 356 | You may add additional accurate notices of copyright ownership. 357 | 358 | Exhibit B - "Incompatible With Secondary Licenses" Notice 359 | 360 | This Source Code Form is "Incompatible 361 | With Secondary Licenses", as defined by 362 | the Mozilla Public License, v. 2.0. 363 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md pytest.ini tox.ini 2 | recursive-include src *.js 3 | recursive-include tests *.py 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### jupyter-notebook-gist 2 | 3 | [![No Maintenance Intended](http://unmaintained.tech/badge.svg)](http://unmaintained.tech/) 4 | [![Build Status](https://travis-ci.org/mozilla/jupyter-notebook-gist.svg?branch=master)](https://travis-ci.org/mozilla/jupyter-notebook-gist) 5 | [![codecov](https://codecov.io/gh/mozilla/jupyter-notebook-gist/branch/master/graph/badge.svg)](https://codecov.io/gh/mozilla/jupyter-notebook-gist) 6 | 7 | **NOTE: This project is currently unmaintained, if anyone would like to take over maintenance please [let us know](https://github.com/mozilla/jupyter-notebook-gist/issues/75).** 8 | 9 | Create a gist from the Jupyter Notebook UI. 10 | 11 | ## Installation 12 | 13 | To install, simply run: 14 | 15 | ``` 16 | pip install jupyter-notebook-gist 17 | jupyter serverextension enable --py jupyter_notebook_gist 18 | jupyter nbextension install --py jupyter_notebook_gist 19 | jupyter nbextension enable --py jupyter_notebook_gist 20 | jupyter nbextension enable --py widgetsnbextension 21 | ``` 22 | 23 | The last step is needed to enable the `widgetsnbextension` extension that 24 | Jupyter-Notebook-Gist depends on. It may have been enabled before by a 25 | different extension. 26 | 27 | You may want to append ``--user`` to the commands above if you're getting 28 | configuration errors upon invoking them. 29 | 30 | To double-check if the extension was correctly installed run: 31 | 32 | ``` 33 | jupyter nbextension list 34 | jupyter serverextension list 35 | ``` 36 | 37 | To uninstall the extension run: 38 | 39 | ``` 40 | jupyter serverextension disable --py jupyter_notebook_gist 41 | jupyter nbextension disable --py jupyter_notebook_gist 42 | jupyter nbextension uninstall --py jupyter_notebook_gist 43 | pip uninstall jupyter-notebook-gist 44 | ``` 45 | 46 | ## Configuration 47 | 48 | After installing, edit your `jupyter_notebook_config.py` file to specify the 49 | GitHub client id and secret. 50 | 51 | If your `jupyter_notebook_config.py` file does not exist, you can create one by 52 | running `jupyter notebook --generate-config`. You can check the location of 53 | this file by running `jupyter --config-dir`. 54 | 55 | ```python 56 | c.NotebookGist.oauth_client_id = "my_client_id" # FIXME 57 | c.NotebookGist.oauth_client_secret = "my_client_secret" # FIXME 58 | ``` 59 | 60 | Replace the vars above with a working GitHub client id and secret. You can 61 | create one [here](https://github.com/settings/applications). 62 | 63 | Here's an [example of an OAuth application](https://cloud.githubusercontent.com/assets/969479/14916551/add90efc-0df0-11e6-8cfb-277754a48b66.png) 64 | created by @mreid-moz for testing. 65 | 66 | Then run `jupyter notebook` from the repo root. 67 | 68 | Alternatively you can also pass the GitHub client id and secret as command 69 | line parameters when you run the notebook (please fill the placeholders 70 | accordingly): 71 | 72 | ``` 73 | jupyter notebook --NotebookGist.oauth_client_id="" --NotebookGist.oauth_client_secret="" 74 | ``` 75 | 76 | ## Changelog 77 | 78 | ### Master 79 | 80 | - Buttons for loading gists are now available on the "tree" (file manager) page 81 | in Jupyter. 82 | 83 | - **IMPORTANT** Requires manual step to enable after running pip install 84 | (see installation docs)! 85 | 86 | To update: 87 | 88 | 1. Fully uninstall the extension first: 89 | 90 | ``` 91 | jupyter serverextension disable --py jupyter_notebook_gist 92 | jupyter nbextension disable --py jupyter_notebook_gist 93 | jupyter nbextension uninstall --py jupyter_notebook_gist 94 | pip uninstall jupyter-notebook-gist 95 | ``` 96 | 97 | 2. Follow the instructions above to reinstall 98 | 99 | ### 0.4.0 (2016-07-06) 100 | 101 | - Refactored config system to be able to configure it via CLI options or 102 | config values in `~/.jupyter/jupyter_notebook_config.py` 103 | 104 | - Fixed a bunch of Python packaging and code quality issues 105 | 106 | - Fixed a few issues in Python test suite 107 | 108 | - Set up continuous integration: https://travis-ci.org/mozilla/jupyter-notebook-gist 109 | 110 | - Set up code coverage reports: https://codecov.io/gh/mozilla/jupyter-notebook-gist 111 | 112 | - **IMPORTANT** Requires manual step to enable after running pip install 113 | (see installation docs)! 114 | 115 | To update: 116 | 117 | 1. Run `pip uninstall jupyter-notebook-gist` 118 | 2. Delete `gist.js` from your `nbextensions` folder. 119 | 3. Delete any references to `jupyter-notebook-gist.create_gist` in 120 | `jupyter_notebook_config.json` (in your .jupyter directory) 121 | 4. Delete any references to `gist` in `notebook.json` 122 | (in .jupyter/nbconfig) 123 | 5. Follow installation instructions to reinstall 124 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts = -v --flake8 --isort --cov-report=term-missing --cov=jupyter_notebook_gist --cov-config .coveragerc 3 | norecursedirs = *.egg .eggs dist build docs .tox 4 | flake8-ignore = E501 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | setup( 4 | name='jupyter-notebook-gist', 5 | use_scm_version={ 6 | 'version_scheme': 'post-release', 7 | 'local_scheme': 'dirty-tag' 8 | }, 9 | setup_requires=['setuptools_scm'], 10 | description='Create a gist from the Jupyter Notebook UI', 11 | author='Mozilla Firefox Data Platform', 12 | author_email='fx-data-platform@mozilla.com', 13 | packages=find_packages(where='src'), 14 | package_dir={'': 'src'}, 15 | include_package_data=True, 16 | license='MPL2', 17 | install_requires=[ 18 | 'ipython >= 4', 19 | 'notebook >= 4.3.1', 20 | 'jupyter', 21 | 'requests', 22 | 'six', 23 | 'widgetsnbextension', 24 | ], 25 | url='https://github.com/mozilla/jupyter-notebook-gist', 26 | zip_safe=False, 27 | ) 28 | -------------------------------------------------------------------------------- /src/jupyter_notebook_gist/__init__.py: -------------------------------------------------------------------------------- 1 | from pkg_resources import get_distribution, DistributionNotFound 2 | 3 | try: 4 | __version__ = get_distribution(__name__).version 5 | except DistributionNotFound: 6 | # package is not installed 7 | pass 8 | 9 | 10 | def _jupyter_nbextension_paths(): 11 | return [ 12 | { 13 | 'section': 'notebook', 14 | # the path is relative to the `jupyter_notebook_gist` directory 15 | 'src': 'static', 16 | # directory in the `nbextension/` namespace 17 | 'dest': 'jupyter-notebook-gist', 18 | # _also_ in the `nbextension/` namespace 19 | 'require': 'jupyter-notebook-gist/notebook-extension' 20 | }, 21 | { 22 | 'section': 'tree', 23 | 'src': 'static', 24 | 'dest': 'jupyter-notebook-gist', 25 | 'require': 'jupyter-notebook-gist/tree-extension' 26 | }, 27 | { 28 | 'section': 'common', 29 | 'src': 'static', 30 | 'dest': 'jupyter-notebook-gist', 31 | 'require': 'jupyter-notebook-gist/common' 32 | }, 33 | ] 34 | 35 | 36 | def _jupyter_server_extension_paths(): 37 | return [{ 38 | 'module': 'jupyter_notebook_gist', 39 | }] 40 | 41 | 42 | def load_jupyter_server_extension(nbapp): 43 | from notebook.utils import url_path_join 44 | 45 | from .config import NotebookGist 46 | from .handlers import GistHandler, DownloadNotebookHandler, LoadGistHandler 47 | 48 | # Extract our gist client details from the config: 49 | notebook_gist = NotebookGist( 50 | # add access to NotebookApp config, too 51 | parent=nbapp, 52 | # for convenient access to frontend settings 53 | config_manager=nbapp.config_manager, 54 | ) 55 | config = notebook_gist.config['NotebookGist'] 56 | params = { 57 | 'oauth_client_id': config['oauth_client_id'], 58 | 'oauth_client_secret': config['oauth_client_secret'], 59 | } 60 | url = nbapp.web_app.settings['base_url'] 61 | nbapp.web_app.add_handlers( 62 | r'.*', # match any host 63 | [ 64 | (url_path_join(url, '/create_gist'), GistHandler, params), 65 | (url_path_join(url, '/download_notebook'), 66 | DownloadNotebookHandler), 67 | (url_path_join(url, '/load_user_gists'), LoadGistHandler, params), 68 | ] 69 | ) 70 | -------------------------------------------------------------------------------- /src/jupyter_notebook_gist/config.py: -------------------------------------------------------------------------------- 1 | import six 2 | from traitlets.config import LoggingConfigurable 3 | from traitlets.traitlets import Unicode 4 | 5 | 6 | class NotebookGist(LoggingConfigurable): 7 | 8 | oauth_client_id = Unicode( 9 | '', 10 | help='The GitHub application OAUTH client ID', 11 | ).tag(config=True) 12 | 13 | oauth_client_secret = Unicode( 14 | '', 15 | help='The GitHub application OAUTH client secret', 16 | ).tag(config=True) 17 | 18 | def __init__(self, *args, **kwargs): 19 | self.config_manager = kwargs.pop('config_manager') 20 | super(NotebookGist, self).__init__(*args, **kwargs) 21 | # update the frontend settings with the currently passed 22 | # OAUTH client id 23 | client_id = self.config.NotebookGist.oauth_client_id 24 | if not isinstance(client_id, six.string_types): 25 | client_id = None 26 | self.config_manager.update('notebook', { 27 | 'oauth_client_id': client_id, 28 | }) 29 | -------------------------------------------------------------------------------- /src/jupyter_notebook_gist/handlers.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | import os 4 | import sys 5 | 6 | import requests 7 | import tornado 8 | from nbconvert.exporters.export import export_by_name 9 | from notebook.base.handlers import IPythonHandler 10 | from tornado.web import HTTPError 11 | 12 | GITHUB_API_ROOT = "https://api.github.com" 13 | 14 | PY3 = sys.version_info[0] == 3 15 | 16 | if PY3: 17 | string_types = (str,) 18 | else: 19 | string_types = (basestring,) # noqa 20 | 21 | 22 | request_session = requests.Session() 23 | 24 | 25 | def raise_error(msg): 26 | raise HTTPError(500, "ERROR: " + msg) 27 | 28 | 29 | def raise_github_error(msg): 30 | raise HTTPError(500, "ERROR: Github returned the following: " + msg) 31 | 32 | 33 | class BaseHandler(IPythonHandler): 34 | 35 | def initialize(self, oauth_client_id, oauth_client_secret): 36 | self.oauth_client_id = oauth_client_id 37 | self.oauth_client_secret = oauth_client_secret 38 | 39 | def request_access_token(self, access_code): 40 | "Request access token from GitHub" 41 | token_response = request_session.post( 42 | "https://github.com/login/oauth/access_token", 43 | data={ 44 | "client_id": self.oauth_client_id, 45 | "client_secret": self.oauth_client_secret, 46 | "code": access_code 47 | }, 48 | headers={"Accept": "application/json"}, 49 | ) 50 | return helper_request_access_token(token_response.json()) 51 | 52 | 53 | class GistHandler(BaseHandler): 54 | """Handler for saving and editing Gists. 55 | 56 | This handler will save out the notebook to GitHub gists in either a new 57 | Gist or it will create a new revision for a gist that already contains 58 | these two files. 59 | """ 60 | def get(self): 61 | 62 | # Extract access code 63 | access_code = extract_code_from_args(self.request.arguments) 64 | 65 | # Request access token from github 66 | access_token = self.request_access_token(access_code) 67 | 68 | # Extract notebook path 69 | nb_path = extract_notebook_path_from_args(self.request.arguments) 70 | 71 | # Extract file name 72 | filename, filename_no_ext = get_notebook_filename(nb_path) 73 | 74 | # Extract file contents given the path to the notebook 75 | notebook_output, python_output = get_notebook_contents(nb_path) 76 | 77 | # Prepare and our github request to create the new gist 78 | filename_with_py = filename_no_ext + ".py" 79 | gist_contents = { 80 | "description": filename_no_ext, 81 | "public": False, 82 | "files": { 83 | filename: {"filename": filename, "content": notebook_output}, 84 | filename_with_py: {"filename": filename_with_py, 85 | "content": python_output} 86 | } 87 | } 88 | 89 | # Get the authenticated user's matching gist (if available) 90 | match_id = find_existing_gist_by_name(filename, 91 | filename_with_py, 92 | access_token) 93 | 94 | # If no gist with this name exists yet, create a new gist 95 | if match_id is None: 96 | gist_response = create_new_gist(gist_contents, access_token) 97 | 98 | # If we have another gist with the same files, create a new revision 99 | # Note: The case where we have multiple gists with the files is handled 100 | # by find_existing_gist_by_name 101 | # This else catches the case where there is exactly 1 match 102 | else: 103 | gist_response = edit_existing_gist(gist_contents, 104 | match_id, 105 | access_token) 106 | 107 | gist_response_json = gist_response.json() 108 | verify_gist_response(gist_response_json) 109 | 110 | # If we get here, we are good and can redirect 111 | gist_url = gist_response_json.get("html_url", None) 112 | self.redirect(gist_url) 113 | 114 | 115 | class DownloadNotebookHandler(IPythonHandler): 116 | def post(self): 117 | # url and filename are sent in a JSON encoded blob 118 | post_data = tornado.escape.json_decode(self.request.body) 119 | 120 | nb_url = post_data['nb_url'] 121 | nb_name = base64.b64decode(post_data['nb_name']).decode('utf-8') 122 | force_download = post_data['force_download'] 123 | 124 | file_path = os.path.join(os.getcwd(), nb_name) 125 | 126 | if os.path.isfile(file_path): 127 | if not force_download: 128 | raise HTTPError(409, "ERROR: File already exists.") 129 | 130 | response = request_session.get(nb_url, stream=True) 131 | with open(file_path, 'wb') as fd: 132 | # TODO: check if this is a good chunk size 133 | for chunk in response.iter_content(1024): 134 | fd.write(chunk) 135 | 136 | self.write(nb_name) 137 | self.flush() 138 | 139 | 140 | class LoadGistHandler(BaseHandler): 141 | 142 | def get(self): 143 | 144 | # Extract access code 145 | access_code = extract_code_from_args(self.request.arguments) 146 | 147 | # Request access token from github 148 | access_token = self.request_access_token(access_code) 149 | 150 | github_headers = {"Accept": "application/json", 151 | "Authorization": "token " + access_token} 152 | 153 | response = request_session.get("https://api.github.com/gists", 154 | headers=github_headers) 155 | response_to_send = bytearray(response.text, 'utf-8') 156 | self.write("") 161 | 162 | 163 | def extract_code_from_args(args): 164 | """ 165 | Extracts the access code from the arguments dictionary (given back 166 | from github) 167 | """ 168 | if args is None: 169 | raise_error("Couldn't extract GitHub authentication code " 170 | "from response") 171 | 172 | # TODO: Is there a case where the length of the error will be < 0? 173 | error = args.get("error_description", None) 174 | if error is not None: 175 | if len(error) >= 0: 176 | raise_github_error(error) 177 | else: 178 | raise_error("Something went wrong") 179 | 180 | access_code = args.get("code", None) 181 | 182 | # access_code is supposed to be a list with 1 thing in it 183 | if not isinstance(access_code, list) or access_code[0] is None or \ 184 | len(access_code) != 1 or len(access_code[0]) <= 0: 185 | 186 | raise_error("Couldn't extract GitHub authentication code from " 187 | "response") 188 | 189 | # If we get here, everything was good - no errors 190 | access_code = access_code[0].decode('ascii') 191 | return access_code 192 | 193 | 194 | # Extracts the notebook path from the arguments dictionary (given back 195 | # from github) 196 | def extract_notebook_path_from_args(args): 197 | 198 | if args is None: 199 | raise_error("Couldn't extract notebook path from response") 200 | 201 | error = args.get("error_description", None) 202 | if error is not None: 203 | if len(error) >= 0: 204 | raise_github_error(error) 205 | 206 | path_bytes = args.get("nb_path", None) 207 | # path_bytes is supposed to be a list with 1 thing in it 208 | if not isinstance(path_bytes, list) or path_bytes[0] \ 209 | is None or len(path_bytes) != 1 or len(path_bytes[0]) <= 0: 210 | 211 | raise_error("Couldn't extract notebook path from response") 212 | 213 | # If we get here, everything was good - no errors 214 | nb_path = base64.b64decode(path_bytes[0]).decode('utf-8').lstrip("/") 215 | 216 | return nb_path 217 | 218 | 219 | def helper_request_access_token(token_args): 220 | token_error = token_args.get("error_description", None) 221 | if token_error is not None: 222 | raise_github_error(token_error) 223 | 224 | # Extract token and other info from github response 225 | access_token = token_args.get("access_token", None) 226 | token_type = token_args.get("token_type", None) 227 | scope = token_args.get("scope", None) 228 | if access_token is None or token_type is None or scope is None: 229 | raise_error("Couldn't extract needed info from GitHub access " 230 | "token response") 231 | 232 | # If we get here everything is good 233 | return access_token # do not care about scope or token_type 234 | 235 | 236 | def get_notebook_filename(nb_path): 237 | if not isinstance(nb_path, string_types) or len(nb_path) == 0: 238 | raise_error("Problem with notebook file name") 239 | 240 | # Extract file names given path to notebook 241 | filename = os.path.basename(nb_path) 242 | ext_start_ind = filename.rfind(".") 243 | 244 | # TODO: is it possible to have a notebook without an extension? 245 | if ext_start_ind == -1: 246 | filename_no_ext = filename 247 | else: 248 | filename_no_ext = filename[:ext_start_ind] 249 | 250 | return filename, filename_no_ext 251 | 252 | 253 | def get_notebook_contents(nb_path): 254 | if not isinstance(nb_path, string_types) or len(nb_path) == 0: 255 | raise_error("Couldn't export notebook contents") 256 | 257 | # Extract file contents given the path to the notebook 258 | try: 259 | notebook_output, _ = export_by_name("notebook", nb_path) 260 | python_output, _ = export_by_name("python", nb_path) 261 | except OSError: # python 2 does not support FileNotFoundError 262 | raise_error("Couldn't export notebook contents") 263 | 264 | return (notebook_output, python_output) 265 | 266 | 267 | def find_existing_gist_by_name(nb_filename, py_filename, access_token): 268 | github_headers = {"Accept": "application/json", 269 | "Authorization": "token " + access_token} 270 | 271 | response = request_session.get(GITHUB_API_ROOT + "/gists", 272 | headers=github_headers) 273 | gist_args = response.json() 274 | 275 | return helper_find_existing_gist_by_name(gist_args, nb_filename, 276 | py_filename) 277 | 278 | 279 | def helper_find_existing_gist_by_name(gist_args, nb_filename, py_filename): 280 | match_counter = 0 281 | match_id = None 282 | for gist in gist_args: 283 | gist_files = gist.get("files", None) 284 | if (gist_files is not None and nb_filename in gist_files and 285 | py_filename in gist_files): 286 | match_counter += 1 287 | if "id" in gist: 288 | match_id = gist["id"] 289 | 290 | # TODO: This probably shouldn't actually be an error 291 | # Instead, we should ask the user which gist they meant? 292 | if match_counter > 1: 293 | raise_error("You had multiple gists with the same name as this " 294 | "notebook. Aborting.") 295 | 296 | # If we are here we have either 0 or 1 gists that match. 297 | return match_id 298 | 299 | 300 | def create_new_gist(gist_contents, access_token): 301 | 302 | github_headers = {"Accept": "application/json", 303 | "Authorization": "token " + access_token} 304 | 305 | gist_response = request_session.post( 306 | GITHUB_API_ROOT + "/gists", 307 | data=json.dumps(gist_contents), 308 | headers=github_headers, 309 | ) 310 | return gist_response 311 | 312 | 313 | def edit_existing_gist(gist_contents, gist_id, access_token): 314 | github_headers = {"Accept": "application/json", 315 | "Authorization": "token " + access_token} 316 | 317 | gist_response = request_session.patch( 318 | GITHUB_API_ROOT + "/gists/" + gist_id, 319 | data=json.dumps(gist_contents), 320 | headers=github_headers, 321 | ) 322 | return gist_response 323 | 324 | 325 | def verify_gist_response(gist_response_json): 326 | 327 | if gist_response_json is None: 328 | raise_error("Couldn't get the URL for the gist that was just updated") 329 | 330 | update_gist_error = gist_response_json.get("error_description", None) 331 | if update_gist_error is not None: 332 | raise_github_error(update_gist_error) 333 | 334 | gist_url = gist_response_json.get("html_url", None) 335 | if gist_url is None: 336 | raise_error("Couldn't get the URL for the gist that was just updated") 337 | -------------------------------------------------------------------------------- /src/jupyter_notebook_gist/static/common.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'base/js/namespace', 3 | 'base/js/utils', 4 | 'moment', 5 | 'services/config' 6 | ], function(Jupyter, utils, moment, config) { 7 | function get_base_path() { 8 | var loc = window.location; 9 | var proto = loc.protocol; 10 | var host = loc.hostname; 11 | var port = loc.port; 12 | 13 | var base = proto + "//" + host; 14 | if (parseInt(port) != 80) { 15 | base += ":" + port; 16 | } 17 | return base; 18 | } 19 | 20 | function is_url_valid(url) { 21 | return /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url); 22 | } 23 | 24 | var github_redirect_uri = ( 25 | get_base_path() + 26 | utils.get_body_data("baseUrl") + 27 | "create_gist"); 28 | 29 | // Get the server side path to download to. 30 | var get_download_path = function() { 31 | if (Jupyter.hasOwnProperty('notebook')) { 32 | // On a notebook page 33 | return utils.url_path_split(Jupyter.notebook.notebook_path)[0]; 34 | } else if (Jupyter.hasOwnProperty('notebook_list')) { 35 | return Jupyter.notebook_list.notebook_path; 36 | } else { 37 | return ''; 38 | } 39 | } 40 | 41 | var load_from_url = function() { 42 | var url = prompt("Enter the URL to a Gist or a .ipynb."); 43 | if (url == "" || url == null) { 44 | // prompt() returns "" if empty value, or null 45 | // if user clicked cancel, want to abort in either case 46 | return; 47 | } 48 | if (!is_url_valid(url)) { 49 | alert('Invalid URL.'); 50 | return; 51 | } 52 | var parser = document.createElement('a'); 53 | parser.href = url; 54 | if (parser.hostname.indexOf('gist.github.com') > -1) { 55 | // this is a gist URL, extract the raw_url for the .ipynb file 56 | load_from_gist_url(url); 57 | } else if (url.indexOf('.ipynb', url.length - '.ipynb'.length) !== -1) { 58 | // URL is a raw .ipynb file 59 | var nb_pathname_parts = parser.pathname.split('/'); 60 | var filename = decodeURIComponent(nb_pathname_parts[nb_pathname_parts.length - 1]); 61 | download_nb_on_server(url, filename, false); 62 | } 63 | } 64 | 65 | var load_from_gist_url = function(url) { 66 | // this is a gist URL, extract the raw_url for the .ipynb file 67 | var gist_url_parts = url.split('/'); 68 | var gist_id = gist_url_parts[gist_url_parts.length-1]; 69 | 70 | var gist_api_url = "https://api.github.com/gists/" + gist_id; 71 | 72 | var xhr = new XMLHttpRequest(); 73 | xhr.onreadystatechange = function() { 74 | if (xhr.readyState == XMLHttpRequest.DONE) { 75 | if (xhr.status == 200) { 76 | var res = JSON.parse(xhr.responseText); 77 | for (var filename in res.files) { 78 | if (!res.files.hasOwnProperty(filename)) continue; 79 | if (filename.endsWith('.ipynb')) { 80 | download_nb_on_server(res.files[filename].raw_url, filename, false); 81 | } 82 | } 83 | console.log(res); 84 | } else if (xhr.status == 404) { 85 | alert("Gist not found") 86 | } else { 87 | alert("Couldn't load Gist.") 88 | } 89 | } 90 | } 91 | xhr.open("GET", gist_api_url, true); 92 | xhr.send(null); 93 | } 94 | 95 | var download_nb_on_server = function(url, name, force_download) { 96 | var nb_info = { 97 | nb_url: url, 98 | nb_name: window.btoa( 99 | utils.url_path_join(get_download_path(), name)), 100 | force_download: force_download 101 | } 102 | utils.ajax({ 103 | url: "/download_notebook", 104 | type: "POST", 105 | dataType: "json", 106 | data: JSON.stringify(nb_info) 107 | }).fail(function(xhr, textStatus) { 108 | if (xhr.status == 409) { 109 | // 409 Conflict 110 | // used if file already exists 111 | var newname = prompt( 112 | "File already exists. Please enter a new name.\n" + 113 | "Note: This may overwrite existing files.", 114 | name); 115 | if (newname == "" || newname == null) { 116 | // prompt() returns "" if empty value, or null 117 | // if user clicked cancel, want to abort in either case 118 | return; 119 | } 120 | download_nb_on_server(url, newname, true); 121 | } else if (xhr.status == 200) { 122 | window.open( 123 | utils.url_path_join( 124 | utils.get_body_data("baseUrl"), 125 | 'notebooks', 126 | encodeURIComponent(xhr.responseText))); 127 | } else if (xhr.status == 400) { 128 | alert("File did not download"); 129 | } 130 | }); 131 | } 132 | 133 | var load_public_user_gists = function() { 134 | // TODO: Figure out how to deal with page redirect when obtaining GitHub access code 135 | // For now, prompt user for their GitHub username to load their public gists 136 | var github_username = prompt("Please enter your GitHub username in order to retrieve your public gists."); 137 | if (github_username == "" || github_username == null) { 138 | // Do not send a request if user did not input anything 139 | return; 140 | }; 141 | 142 | var gist_api_url = "https://api.github.com/users/" + github_username + "/gists"; 143 | 144 | if (!is_url_valid(gist_api_url)) { 145 | alert('GitHub username is invalid.'); 146 | }; 147 | 148 | var xhr = new XMLHttpRequest(); 149 | xhr.open("GET", gist_api_url, true); 150 | xhr.setRequestHeader("Content-Type", "application/json"); 151 | xhr.onload = function(){ 152 | Jupyter.dialog.modal({ 153 | title: "Gists", 154 | body: format_user_gists(xhr.responseText), 155 | buttons: { 156 | "OK": {} 157 | } 158 | }); 159 | }; 160 | xhr.send(null); 161 | }; 162 | 163 | // Listen for the response message containing the user's gists 164 | // that is sent from the LoadGistHandler 165 | var auth_window; 166 | window.addEventListener('message', function(event) { 167 | if (event.origin != get_base_path()) return; 168 | if (auth_window === undefined) return; 169 | auth_window.close(); 170 | Jupyter.dialog.modal({ 171 | title: "All User Gists", 172 | body: format_user_gists(window.atob(event.data)), 173 | buttons: { 174 | "OK": {} 175 | } 176 | }) 177 | }); 178 | 179 | var load_all_user_gists = function () { 180 | var redirect_uri = ( 181 | get_base_path() + 182 | utils.get_body_data("baseUrl") + 183 | "load_user_gists"); 184 | get_client_id(function(client_id) { 185 | auth_window = window.open( 186 | "https://github.com/login/oauth/authorize?client_id=" + client_id + 187 | "&scope=gist&redirect_uri=" + redirect_uri, "", "width=550, height=500"); 188 | }); 189 | }; 190 | 191 | var format_user_gists = function(responseText) { 192 | var body = $('').attr({class: "table", id: "my_table"}); 193 | var head = $(''); 194 | var header = $('').addClass("row list_header"); 195 | header.append(""); 196 | header.append(""); 197 | header.append(""); 198 | header.append(""); 199 | head.append(header); 200 | body.append(head); 201 | var row, button, files, last_updated, pretty_date; 202 | var json_response = JSON.parse(responseText); 203 | // create flag to check if a notebook has been loaded 204 | var notebook_loaded = false; 205 | 206 | for (var i = 0; i < json_response.length; i++) { 207 | files = json_response[i].files; 208 | // Only load notebook gists 209 | if (!files[Object.keys(files)[0]].filename.endsWith('.ipynb')) continue; 210 | notebook_loaded = true; 211 | 212 | // Use same date formatting as SaveWidget's _render_checkpoint 213 | last_updated = moment(json_response[i].updated_at); 214 | var tdelta = Math.ceil(new Date() - last_updated); 215 | if (tdelta < utils.time.milliseconds.d) { 216 | // less than 24 hours old, use relative date 217 | pretty_date = last_updated.fromNow(); 218 | } else { 219 | // otherwise show calendar 220 | // at hh,mm,ss 221 | pretty_date = last_updated.calendar(); 222 | } 223 | 224 | // Create row containing gist information 225 | row = $('').addClass("list_item row"); 226 | row.append(""); 227 | row.append(""); 228 | row.append(""); 229 | // Create button to load notebook 230 | button_td = $('').addClass("list_item row"); 241 | row_message = $('
FilenameDescriptionLast UpdatedOpen Notebook
" + files[Object.keys(files)[0]].filename + "" + json_response[i].description + "" + pretty_date + "'); 231 | button = $('').addClass("btn btn-default btn-sm"); 232 | button.click({url: json_response[i].html_url}, load_gist_from_click); 233 | button.appendTo(button_td); 234 | row.append(button_td); 235 | body.append(row); 236 | }; 237 | 238 | // Inform user if no public notebooks were found 239 | if (!notebook_loaded) { 240 | row = $('
').attr("colspan", "4"); 242 | row_message.text('No public notebooks found.'); 243 | row.append(row_message); 244 | body.append(row); 245 | } 246 | 247 | return body; 248 | }; 249 | 250 | var load_gist_from_click = function(event) { 251 | var url = event.data.url; 252 | load_from_gist_url(url); 253 | }; 254 | 255 | var setup_info = function() { 256 | Jupyter.dialog.modal({ 257 | title: "Configuration Incomplete", 258 | body: "You haven't configured your GitHub Client ID in your jupyter_notebook_config.py file. Please set the Client ID and Secret before using this plugin. See the README for more info.", 259 | buttons: { 260 | "OK": {} 261 | }, 262 | sanitize: false 263 | }); 264 | } 265 | 266 | var get_client_id = function(callback) { 267 | var common_options = { 268 | base_url: utils.get_body_data("baseUrl"), 269 | notebook_path: utils.get_body_data("notebookPath"), 270 | }; 271 | var cfg = new config.ConfigSection('notebook', common_options); 272 | cfg.loaded.then(function() { 273 | callback(cfg.data.oauth_client_id); 274 | }); 275 | cfg.load(); 276 | } 277 | 278 | var is_valid_client_id = function(client_id) { 279 | if (client_id === "my_client_id" || client_id === null || client_id === undefined) { 280 | return false; 281 | } 282 | return true; 283 | } 284 | 285 | return { 286 | github_redirect_uri: github_redirect_uri, 287 | load_from_url: load_from_url, 288 | load_public_user_gists: load_public_user_gists, 289 | load_all_user_gists: load_all_user_gists, 290 | get_client_id: get_client_id, 291 | is_valid_client_id: is_valid_client_id, 292 | setup_info: setup_info 293 | }; 294 | }); 295 | -------------------------------------------------------------------------------- /src/jupyter_notebook_gist/static/notebook-extension.js: -------------------------------------------------------------------------------- 1 | 2 | define([ 3 | 'base/js/namespace', 4 | 'nbextensions/jupyter-notebook-gist/common' 5 | ], function (Jupyter, common) { 6 | var gist_notebook = function() { 7 | // Save the notebook and create a checkpoint to ensure that we create 8 | // the gist using the most up-to-date content 9 | Jupyter.notebook.save_checkpoint(); 10 | 11 | var github_client_id = Jupyter.notebook.config.data.oauth_client_id; 12 | // Get notebook path and encode it in base64 13 | // Characters like # get decoded by the github API and will mess up 14 | // getting the file path on the server if we use URI percent encoding, 15 | // so we use base64 instead 16 | var nb_path = window.btoa(Jupyter.notebook.base_url + Jupyter.notebook.notebook_path); 17 | 18 | // Start OAuth dialog 19 | window.open("https://github.com/login/oauth/authorize?client_id=" + github_client_id + 20 | "&scope=gist&redirect_uri=" + common.github_redirect_uri + 21 | "?nb_path=" + nb_path); 22 | } 23 | 24 | var create_gist_buttons = function () { 25 | if (!Jupyter.toolbar) { 26 | $([Jupyter.events]).on("app_initialized.NotebookApp", create_gist_buttons); 27 | return; 28 | } 29 | 30 | common.get_client_id(function(client_id) { 31 | if (!common.is_valid_client_id(client_id)) { 32 | Jupyter.toolbar.add_buttons_group([{ 33 | 'label': 'jupyter-notebook-gist setup', 34 | 'icon': 'fa-github', 35 | 'callback': common.setup_info, 36 | 'id': 'setup_info' 37 | }]); 38 | 39 | return; 40 | } 41 | 42 | if ($("#gist_notebook").length === 0) { 43 | Jupyter.toolbar.add_buttons_group([ 44 | { 45 | 'label' : 'save notebook as gist', 46 | 'icon' : 'fa-github', 47 | 'callback': gist_notebook, 48 | 'id' : 'gist_notebook' 49 | }, { 50 | 'label' : 'load notebook from URL', 51 | 'icon' : 'fa-link', 52 | 'callback': common.load_from_url, 53 | 'id' : 'load_notebook_from_url' 54 | }, { 55 | 'label' : 'load public user gists', 56 | 'icon' : 'fa-list-alt', 57 | 'callback': common.load_public_user_gists, 58 | 'id' : 'load_public_user_gists', 59 | }, { 60 | 'label' : 'load all user gists', 61 | 'icon' : 'fa-list', 62 | 'callback': common.load_all_user_gists, 63 | 'id' : 'load_all_user_gists', 64 | } 65 | ]); 66 | } 67 | }); 68 | }; 69 | 70 | var load_ipython_extension = function () { 71 | create_gist_buttons(); 72 | }; 73 | 74 | return { 75 | load_ipython_extension: load_ipython_extension 76 | }; 77 | }); 78 | -------------------------------------------------------------------------------- /src/jupyter_notebook_gist/static/tree-extension.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'nbextensions/jupyter-notebook-gist/common' 3 | ], function (common) { 4 | function add_toolbar_button(group, label, icon, callback, id) { 5 | group.append( 6 | $('