├── .gitattributes ├── .github ├── FUNDING.yml └── workflows │ └── release.yml ├── .gitignore ├── LICENSE ├── README.md ├── manifest.json ├── neo4j-graph-view ├── .gitignore ├── README.md ├── main.ts ├── package.json ├── resources │ ├── bloom_screenshot.jpg │ ├── browser_screenshot.png │ ├── cypher_querying.png │ ├── graphxr.gif │ ├── obsidian neo4j plugin.gif │ └── styled_screenshot.png ├── rollup.config.js ├── settings.ts ├── styles.css ├── tsconfig.json ├── versions.json └── visualization.ts ├── package-lock.json ├── setup.py └── smdc ├── __init__.py ├── args.py ├── convert.py ├── format ├── __init__.py ├── csv.py ├── cypher.py ├── format.py ├── neo4j.py ├── typed_list.py └── util.py ├── note.py ├── parse.py └── stream.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [HEmile] 2 | ko_fi: Emile 3 | custom: ["https://paypal.me/EvanKrieken"] 4 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Build obsidian plugin 2 | 3 | on: 4 | push: 5 | # Sequence of patterns matched against refs/tags 6 | tags: 7 | - '*' # Push events to matching any tag format, i.e. 1.0, 20.15.10 8 | 9 | env: 10 | PLUGIN_NAME: neo4j-graph-view # Change this to the name of your plugin-id folder 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Use Node.js 20 | uses: actions/setup-node@v1 21 | with: 22 | node-version: '14.x' # You might need to adjust this value to your own version 23 | - name: Build 24 | id: build 25 | run: | 26 | cd "neo4j-graph-view" 27 | npm install 28 | npm run build --if-present 29 | mkdir ${{ env.PLUGIN_NAME }} 30 | cp main.js manifest.json ${{ env.PLUGIN_NAME }} 31 | zip -r ${{ env.PLUGIN_NAME }}.zip ${{ env.PLUGIN_NAME }} 32 | ls 33 | echo "::set-output name=tag_name::$(git tag --sort version:refname | tail -n 1)" 34 | - name: Create Release 35 | id: create_release 36 | uses: actions/create-release@v1 37 | env: 38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | VERSION: ${{ github.ref }} 40 | with: 41 | tag_name: ${{ github.ref }} 42 | release_name: ${{ github.ref }} 43 | draft: false 44 | prerelease: false 45 | - name: Upload zip file 46 | id: upload-zip 47 | uses: actions/upload-release-asset@v1 48 | env: 49 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 50 | with: 51 | upload_url: ${{ steps.create_release.outputs.upload_url }} 52 | asset_path: neo4j-graph-view/${{ env.PLUGIN_NAME }}.zip 53 | asset_name: ${{ env.PLUGIN_NAME }}-${{ steps.build.outputs.tag_name }}.zip 54 | asset_content_type: application/zip 55 | - name: Upload main.js 56 | id: upload-main 57 | uses: actions/upload-release-asset@v1 58 | env: 59 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 60 | with: 61 | upload_url: ${{ steps.create_release.outputs.upload_url }} 62 | asset_path: neo4j-graph-view/main.js 63 | asset_name: main.js 64 | asset_content_type: text/javascript 65 | - name: Upload manifest.json 66 | id: upload-manifest 67 | uses: actions/upload-release-asset@v1 68 | env: 69 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 70 | with: 71 | upload_url: ${{ steps.create_release.outputs.upload_url }} 72 | asset_path: ./manifest.json 73 | asset_name: manifest.json 74 | asset_content_type: application/json 75 | - name: Upload styles.css 76 | id: upload-css 77 | uses: actions/upload-release-asset@v1 78 | env: 79 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 80 | with: 81 | upload_url: ${{ steps.create_release.outputs.upload_url }} 82 | asset_path: neo4j-graph-view/styles.css 83 | asset_name: styles.css 84 | asset_content_type: text/css -------------------------------------------------------------------------------- /.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 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # celery beat schedule file 95 | celerybeat-schedule 96 | 97 | # SageMath parsed files 98 | *.sage.py 99 | 100 | # Environments 101 | .env 102 | .venv 103 | env/ 104 | venv/ 105 | ENV/ 106 | env.bak/ 107 | venv.bak/ 108 | 109 | # Spyder project settings 110 | .spyderproject 111 | .spyproject 112 | 113 | # Rope project settings 114 | .ropeproject 115 | 116 | # mkdocs documentation 117 | /site 118 | 119 | # mypy 120 | .mypy_cache/ 121 | .dmypy.json 122 | dmypy.json 123 | 124 | # Pyre type checker 125 | .pyre/ 126 | 127 | # smd converter 128 | /markdown/ 129 | .idea/ 130 | out.cypher -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |

3 | Buy Me A Coffee donate button 4 | 5 | Downloads 7 | 8 | Github latest release 10 | 11 | Documentation 13 | 14 | chat on Discord 16 |

17 | 18 | ANNOUNCEMENT: This plugin has been rewritten with new name Juggl. It no longer requires Neo4j and Python, and has a lot more features than Neo4j graph view. 19 | You can install this new plugin from the Obsidian community plugins settings! 20 | Note that the Neo4j Graph View plugin will be removed from the community plugins soon. 21 | 22 | ## Neo4j Graph View 23 | ![](https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/main/neo4j-graph-view/resources/styled_screenshot.png) 24 | 25 | Documentation at https://juggl.io/Neo4j+Graph+View/Neo4j+Graph+View+Plugin. 26 | 27 | Join the new Discord server to discuss the plugin: https://discord.gg/sAmSGpaPgM 28 | 29 | Adds a new and much more functional graph view to Obsidian. It does so by connecting 30 | to a [Neo4j](https://neo4j.com/) database. Features: 31 | - Selectively style nodes and edges by tags, folders and link types 32 | - Selective expansion and hiding of nodes 33 | - View images within the graph 34 | - [Cypher](https://neo4j.com/developer/cypher/) querying 35 | - Typed links using `- linkType [[note 1]], [[note 2|alias]]` 36 | - Hierarchical layout 37 | 38 | Next up: 39 | - [x] Remove the need to install Neo4j and Python 40 | - [ ] Different and more stable front end 41 | - [x] Standardize style sheet using CSS instead of JSON 42 | 43 | A [Roadmap](https://juggl.io/Roadmap) with planned features is also available. 44 | 45 | ![](https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/main/neo4j-graph-view/resources/obsidian%20neo4j%20plugin.gif) 46 | 47 | ### Installation 48 | Detailed installation instructions is at https://juggl.io/Neo4j+Graph+View/Installation+of+Neo4j+Graph+View+Plugin 49 | 1. Make sure you have [Python 3.6+](https://www.python.org/downloads/) installed. It needs the system-installed Python. Make sure to add Python to PATH! 50 | 2. Make sure you have [Neo4j desktop](https://neo4j.com/download/) installed 51 | 4. Create a new database in Neo4j desktop and start it. Record the password you use! 52 | 5. In the settings of the plugin, enter the password. Then run the restart command. 53 | 54 | If installing Python seems daunting, you can wait a couple of weeks. The goal is to port that code to Javascript. 55 | 56 | ### Use 57 | Detailed getting started guide is at https://juggl.io/Neo4j+Graph+View/Using+the+Neo4j+Graph+View 58 | 59 | On an open note, use the command "Neo4j Graph View: Open local graph of note". You can run commands using ctrl/cmd+p. Alternatively, you can bind this command to a hotkey in the settings. 60 | 61 | The settings contains several options, such as coloring based on folders and a hierarchical layout. 62 | 63 | #### Cypher Querying 64 | Create code blocks with language `cypher`. In this code block, create your Cypher query. Then, when the cursor is on this 65 | code block, use the Obsidian command 'Neo4j Graph View: Execute Cypher query'. Example: 66 | 67 | ![](https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/main/neo4j-graph-view/resources/cypher_querying.png) 68 | 69 | 70 | ### Possible problems 71 | All changes made in obsidian should be automatically reflected in Neo4j, but this is still very buggy. 72 | 73 | If you are running into issues, see https://juggl.io/Neo4j+Graph+View/Installation+of+Neo4j+Graph+View+Plugin#troubleshooting 74 | ### Semantics 75 | The plugin collects all notes with extension .md in the input directory (default: `markdown/`). Each note is interpreted as follows: 76 | - Interprets tags as entity types 77 | - Interprets YAML frontmatter as entity properties 78 | - Interprets wikilinks as links with type `inline`, and adds content 79 | - Lines of the format `"- linkType [[note 1]], [[note 2|alias]]"` creates links with type `linkType` from the current note to `note 1` and `note 2`. 80 | - The name of the note is stored in the property `name` 81 | - The content of the note (everything except YAML frontmatter and typed links) is stored in the property `content` 82 | - Links to notes that do not exist yet are created without any types. 83 | 84 | 85 | ## Other visualization and querying options 86 | Another use case for this plugin is to use your Obsidian vault in one of the many apps in the Neo4j desktop 87 | Graph Apps Store. Using with this plugin active will automatically connect it to your vault. Here are some suggestions: 88 | ### Neo4j Bloom 89 | [Neo4j bloom](https://neo4j.com/product/bloom/) is very powerful graph visualization software. Compared to the embedded 90 | graph view in Obsidian, it offers much more freedom in customization. 91 | 92 | ![](https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/main/neo4j-graph-view/resources/bloom_screenshot.jpg) 93 | 94 | 95 | ### GraphXR 96 | [GraphXR](https://www.kineviz.com/) is a 3D graph view, which looks quite gorgeous! 97 | 98 | ![](https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/main/neo4j-graph-view/resources/graphxr.gif) 99 | 100 | 101 | ### Neo4j Browser 102 | A query browser that uses the Cypher language to query your vault. Can be used for advanced queries or data anlysis of 103 | your vault. 104 | 105 | ![](https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/main/neo4j-graph-view/resources/browser_screenshot.png) 106 | 107 | 108 | ## Python code: Semantic Markdown to Neo4j 109 | This Obsidian plugin uses the Python package `semantic-markdown-converter`, which is also in this repo. 110 | It creates an active data stream from a folder of Markdown notes to a Neo4j database. 111 | For documentation, see https://juggl.io/Neo4j+Graph+View/Semantic+Markdown+Converter 112 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "neo4j-graph-view", 3 | "name": "Neo4j Graph View", 4 | "version": "0.2.6", 5 | "minAppVersion": "0.9.16", 6 | "description": "An Obsidian plugin for advanced graph visualization and querying using Neo4j.", 7 | "author": "Emile", 8 | "authorUrl": "https://twitter.com/emilevankrieken", 9 | "isDesktopOnly": true 10 | } 11 | -------------------------------------------------------------------------------- /neo4j-graph-view/.gitignore: -------------------------------------------------------------------------------- 1 | # Intellij 2 | *.iml 3 | .idea 4 | 5 | # npm 6 | node_modules 7 | package-lock.json 8 | 9 | # build 10 | main.js 11 | *.js.map -------------------------------------------------------------------------------- /neo4j-graph-view/README.md: -------------------------------------------------------------------------------- 1 | ## Neo4j Graph View 2 | ![](resources/obsidian%20neo4j%20plugin.gif) 3 | 4 | Adds a new and much more functional graph view to Obsidian. It does so by connecting 5 | to a [Neo4j](https://neo4j.com/) database. Features: 6 | - Color nodes by tags 7 | - Selective expansion and hiding of nodes 8 | - Typed links using `- linkType [[note 1]], [[note 2|alias]]` 9 | - Hierarchical layout 10 | 11 | ### Installation 12 | 1. Make sure you have python 3.6+ installed 13 | 2. Make sure you have [Neo4j desktop](https://neo4j.com/download/) installed 14 | 4. Create a new database in Neo4j desktop and start it. Record the password you use! 15 | 5. In the settings of the plugin, enter the password. Then run the restart command. 16 | 17 | ### Use 18 | On an open node, use the command "Neo4j Graph View: Open local graph of note". 19 | - Click on a node to open it in the Markdown view 20 | - Double-click on a node to expand its neighbors 21 | - Shift-drag in the graph view to select nodes 22 | - Use E to expand the neighbors of all selected nodes 23 | - Use H or Backspace to hide all selected nodes from the view 24 | - Use I (invert) to select all nodes that are not currently selected 25 | - Use A to select all nodes 26 | - All notes visited are added to the graph 27 | 28 | 29 | ### Possible problems 30 | All changes made in obsidian should be automatically reflected in Neo4j, but this is still very buggy. There also seem 31 | to be problems with duplicate nodes in the graph. 32 | 33 | ### Semantics 34 | This collects all notes with extension .md in the input directory (default: `markdown/`). Each note is interpreted as follows: 35 | - Interprets tags as entity types 36 | - Interprets YAML frontmatter as entity properties 37 | - Interprets wikilinks as links with type `inline`, and adds content 38 | - Lines of the format `"- linkType [[note 1]], [[note 2|alias]]"` creates links with type `linkType` from the current note to `note 1` and `note 2`. 39 | - The name of the note is stored in the property `name` 40 | - The content of the note (everything except YAML frontmatter and typed links) is stored in the property `content` 41 | - Links to notes that do not exist yet are created without any types. 42 | 43 | This uses a very simple syntax for typed links. There is no agreed-upon Markdown syntax for this as of yet. 44 | If you are interested in using a different syntax than the list format `"- linkType [[note 1]], [[note 2|alias]]"`, 45 | please submit an issue. 46 | -------------------------------------------------------------------------------- /neo4j-graph-view/main.ts: -------------------------------------------------------------------------------- 1 | import { 2 | FileSystemAdapter, 3 | MarkdownView, MenuItem, normalizePath, 4 | Notice, 5 | Plugin, Scope, TAbstractFile, TFile, 6 | WorkspaceLeaf 7 | } from 'obsidian'; 8 | import {INeo4jViewSettings, Neo4jViewSettingTab, DefaultNeo4jViewSettings} from "./settings"; 9 | import {exec, ChildProcess, spawn} from 'child_process'; 10 | import {promisify} from "util"; 11 | import {PythonShell} from "python-shell"; 12 | import {NV_VIEW_TYPE, NeoVisView, MD_VIEW_TYPE, PROP_VAULT} from "./visualization"; 13 | // import 'express'; 14 | import {IncomingMessage, Server, ServerResponse} from "http"; 15 | import {Editor} from "codemirror"; 16 | import {start} from "repl"; 17 | import {Neo4jError} from "neo4j-driver"; 18 | import {IdType} from "vis-network"; 19 | 20 | // I got this from https://github.com/SilentVoid13/Templater/blob/master/src/fuzzy_suggester.ts 21 | const exec_promise = promisify(exec); 22 | 23 | const STATUS_OFFLINE = "Neo4j stream offline"; 24 | 25 | const DEVELOP_MODE = false; 26 | 27 | export default class Neo4jViewPlugin extends Plugin { 28 | settings: INeo4jViewSettings; 29 | stream_process: PythonShell; 30 | path: string; 31 | statusBar: HTMLElement; 32 | neovisView: NeoVisView; 33 | imgServer: Server; 34 | 35 | async onload() { 36 | let noticeText = "WARNING: Neo4j Graph View is deprecated and replaced by the new Obsidian plugin Juggl." 37 | new Notice(noticeText); 38 | console.log(noticeText); 39 | if (this.app.vault.adapter instanceof FileSystemAdapter) { 40 | this.path = this.app.vault.adapter.getBasePath(); 41 | } 42 | 43 | this.settings = Object.assign(DefaultNeo4jViewSettings, await this.loadData());//(await this.loadData()) || DefaultNeo4jViewSettings; 44 | this.statusBar = this.addStatusBarItem(); 45 | this.statusBar.setText(STATUS_OFFLINE); 46 | 47 | // this.registerView(NV_VIEW_TYPE, (leaf: WorkspaceLeaf) => this.neovisView=new NeoVisView(leaf, this.app.workspace.activeLeaf?.getDisplayText(), this)) 48 | 49 | this.addCommand({ 50 | id: 'restart-stream', 51 | name: 'Restart Neo4j stream', 52 | callback: () => { 53 | console.log('Restarting stream'); 54 | this.restart(); 55 | }, 56 | }); 57 | 58 | this.addCommand({ 59 | id: 'stop-stream', 60 | name: 'Stop Neo4j stream', 61 | callback: () => { 62 | this.shutdown(); 63 | }, 64 | }); 65 | 66 | // this.addCommand({ 67 | // id: 'open-bloom-link', 68 | // name: 'Open note in Neo4j Bloom', 69 | // callback: () => { 70 | // if (!this.stream_process) { 71 | // new Notice("Cannot open in Neo4j Bloom as neo4j stream is not active.") 72 | // } 73 | // let active_view = this.app.workspace.getActiveViewOfType(MarkdownView); 74 | // if (active_view == null) { 75 | // return; 76 | // } 77 | // let name = active_view.getDisplayText(); 78 | // // active_view.getState(). 79 | // 80 | // console.log(encodeURI("neo4j://graphapps/neo4j-bloom?search=SMD_no_tags with name " + name)); 81 | // open(encodeURI("neo4j://graphapps/neo4j-bloom?search=SMD_no_tags with name " + name)); 82 | // // require("electron").shell.openExternal("www.google.com"); 83 | // }, 84 | // }); 85 | 86 | this.addCommand({ 87 | id: 'open-vis', 88 | name: 'Open local graph of note', 89 | callback: () => { 90 | let active_view = this.app.workspace.getActiveViewOfType(MarkdownView); 91 | if (active_view == null) { 92 | return; 93 | } 94 | let name = active_view.getDisplayText(); 95 | this.openLocalGraph(name); 96 | }, 97 | }); 98 | 99 | this.addCommand({ 100 | id: 'execute-query', 101 | name: 'Execute Cypher query', 102 | callback: () => { 103 | if (!this.stream_process) { 104 | new Notice("Cannot open local graph as neo4j stream is not active.") 105 | return; 106 | } 107 | this.executeQuery(); 108 | }, 109 | }); 110 | 111 | this.addSettingTab(new Neo4jViewSettingTab(this.app, this)); 112 | 113 | this.app.workspace.on("file-menu", ((menu, file: TFile) => { 114 | menu.addItem((item) =>{ 115 | item.setTitle("Open Neo4j Graph View").setIcon("dot-network") 116 | .onClick(evt => { 117 | if (file.extension === "md") { 118 | this.openLocalGraph(file.basename); 119 | } 120 | else { 121 | this.openLocalGraph(file.name); 122 | } 123 | }); 124 | }) 125 | })); 126 | 127 | 128 | await this.initialize(); 129 | 130 | 131 | } 132 | 133 | public getFileFromAbsolutePath(abs_path: string): TAbstractFile { 134 | const path = require('path'); 135 | const relPath = path.relative(this.path, abs_path); 136 | return this.app.vault.getAbstractFileByPath(relPath); 137 | } 138 | 139 | public async openFile(file: TFile) { 140 | const md_leaves = this.app.workspace.getLeavesOfType(MD_VIEW_TYPE).concat(this.app.workspace.getLeavesOfType('image')); 141 | // this.app.workspace.iterateAllLeaves(leaf => console.log(leaf.view.getViewType())); 142 | if (md_leaves.length > 0) { 143 | await md_leaves[0].openFile(file); 144 | } 145 | else { 146 | await this.app.workspace.getLeaf(true).openFile(file); 147 | } 148 | } 149 | 150 | public async restart() { 151 | new Notice("Restarting Neo4j stream."); 152 | await this.shutdown(); 153 | await this.initialize(); 154 | } 155 | 156 | public async initialize() { 157 | console.log('Initializing Neo4j stream'); 158 | try { 159 | let out = await exec_promise("pip3 install --upgrade pip " + 160 | "--user ", {timeout: 10000000}); 161 | 162 | if (this.settings.debug) { 163 | console.log(out.stdout); 164 | } 165 | console.log(out.stderr); 166 | let {stdout, stderr} = await exec_promise("pip3 install --upgrade semantic-markdown-converter " + 167 | "--no-warn-script-location " + 168 | (DEVELOP_MODE ? "--index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple " : "") + 169 | "--user ", {timeout: 10000000}); 170 | if (this.settings.debug) { 171 | console.log(stdout); 172 | } 173 | console.log(stderr); 174 | } 175 | catch (e) { 176 | console.log("Error during updating semantic markdown: \n", e); 177 | new Notice("Error during updating semantic markdown. Check the console for crash report."); 178 | } 179 | let options = { 180 | args: ['--input', this.path, 181 | '--password', this.settings.password, 182 | '--typed_links_prefix', this.settings.typed_link_prefix, 183 | '--community', this.settings.community] 184 | .concat(this.settings.debug ? ["--debug"] : []) 185 | .concat(this.settings.convert_markdown ? ["--convert_markdown"] : []) 186 | }; 187 | try { 188 | // @ts-ignore 189 | this.stream_process = PythonShell.runString("from smdc.stream import main;" + 190 | "main();", options, function(err, results) { 191 | if (err) throw err; 192 | console.log('Neo4j stream killed'); 193 | }); 194 | let plugin = this; 195 | process.on("exit", function() { 196 | plugin.shutdown(); 197 | }) 198 | let statusbar = this.statusBar; 199 | let settings = this.settings; 200 | this.stream_process.on('message', function (message) { 201 | // received a message sent from the Python script (a simple "print" statement) 202 | if (message === 'Stream is active!') { 203 | console.log(message); 204 | new Notice("Neo4j stream online!"); 205 | statusbar.setText("Neo4j stream online"); 206 | } 207 | else if (message === 'invalid user credentials') { 208 | console.log(message); 209 | new Notice('Please provide a password in the Neo4j Graph View settings'); 210 | statusbar.setText(STATUS_OFFLINE); 211 | } 212 | else if (message === 'no connection to db') { 213 | console.log(message); 214 | new Notice("No connection to Neo4j database. Please start Neo4j Database in Neo4j Desktop"); 215 | statusbar.setText(STATUS_OFFLINE); 216 | } 217 | else if (/^onSMD/.test(message)) { 218 | if (settings.debug) {console.log(message)} 219 | console.log("handling event"); 220 | const parts = message.split("/"); 221 | const leaves = plugin.app.workspace.getLeavesOfType(NV_VIEW_TYPE); 222 | const name = parts[1]; 223 | leaves.forEach((leaf) =>{ 224 | let view = leaf.view as NeoVisView; 225 | if (parts[0] === "onSMDModifyEvent") { 226 | if (view.expandedNodes.includes(name)) { 227 | view.updateWithCypher(plugin.localNeighborhoodCypher(name)); 228 | } 229 | else { 230 | view.updateWithCypher(plugin.nodeCypher(name)); 231 | } 232 | } 233 | else if (parts[0] === "onSMDMovedEvent") { 234 | let new_name = parts[2]; 235 | if (view.expandedNodes.includes(name)) { 236 | view.updateWithCypher(plugin.localNeighborhoodCypher(new_name)); 237 | view.expandedNodes.remove(name); 238 | view.expandedNodes.push(new_name); 239 | } 240 | else { 241 | view.updateWithCypher(plugin.nodeCypher(new_name)); 242 | } 243 | } 244 | else if (parts[0] === "onSMDDeletedEvent") { 245 | // TODO: Maybe automatically update to dangling link by running an update query. 246 | view.deleteNode(parts[1]); 247 | // view.updateStyle(); 248 | } 249 | else if (parts[0] === "onSMDRelDeletedEvent") { 250 | parts.slice(1).forEach((id: IdType) => { 251 | view.deleteEdge(id); 252 | }) 253 | } 254 | }); 255 | } 256 | else if (settings.debug) { 257 | console.log(message); 258 | } 259 | }); 260 | 261 | new Notice("Initializing Neo4j stream."); 262 | this.statusBar.setText('Initializing Neo4j stream'); 263 | } 264 | catch(error) { 265 | console.log("Error during initialization of semantic markdown: \n", error); 266 | new Notice("Error during initialization of the Neo4j stream. Check the console for crash report."); 267 | } 268 | this.httpServer(); 269 | } 270 | 271 | async httpServer() { 272 | let path = require('path'); 273 | let http = require('http'); 274 | let fs = require('fs'); 275 | 276 | let dir = path.join(this.path); 277 | 278 | let mime = { 279 | gif: 'image/gif', 280 | jpg: 'image/jpeg', 281 | png: 'image/png', 282 | svg: 'image/svg+xml', 283 | }; 284 | let settings = this.settings; 285 | this.imgServer = http.createServer(function (req: IncomingMessage, res: ServerResponse) { 286 | 287 | let reqpath = req.url.toString().split('?')[0]; 288 | if (req.method !== 'GET') { 289 | res.statusCode = 501; 290 | res.setHeader('Content-Type', 'text/plain'); 291 | return res.end('Method not implemented'); 292 | } 293 | let file = path.join(dir, decodeURI(reqpath.replace(/\/$/, '/index.html'))); 294 | if (settings.debug) { 295 | console.log("entering query"); 296 | console.log(req); 297 | console.log(file); 298 | } 299 | if (file.indexOf(dir + path.sep) !== 0) { 300 | res.statusCode = 403; 301 | res.setHeader('Content-Type', 'text/plain'); 302 | return res.end('Forbidden'); 303 | } 304 | // @ts-ignore 305 | let type = mime[path.extname(file).slice(1)]; 306 | let s = fs.createReadStream(file); 307 | s.on('open', function () { 308 | res.setHeader('Content-Type', type); 309 | s.pipe(res); 310 | }); 311 | s.on('error', function () { 312 | res.setHeader('Content-Type', 'text/plain'); 313 | res.statusCode = 404; 314 | res.end('Not found'); 315 | }); 316 | }); 317 | try { 318 | let port = this.settings.imgServerPort; 319 | this.imgServer.listen(port, function () { 320 | console.log('Image server listening on http://localhost:' + port + '/'); 321 | }); 322 | } 323 | catch (e){ 324 | console.log(e); 325 | new Notice("Neo4j: Couldn't start image server, see console"); 326 | } 327 | } 328 | 329 | openLocalGraph(name: string) { 330 | if (!this.stream_process) { 331 | new Notice("Cannot open local graph as neo4j stream is not active.") 332 | return; 333 | } 334 | 335 | const leaf = this.app.workspace.splitActiveLeaf(this.settings.splitDirection); 336 | const query = this.localNeighborhoodCypher(name); 337 | const neovisView = new NeoVisView(leaf, query, this); 338 | leaf.open(neovisView); 339 | neovisView.expandedNodes.push(name); 340 | } 341 | 342 | getLinesOffsetToGoal(start: number, goal: string, step = 1, cm: Editor): number { 343 | // Code taken from https://github.com/mrjackphil/obsidian-text-expand/blob/0.6.4/main.ts 344 | const lineCount = cm.lineCount(); 345 | let offset = 0; 346 | 347 | while (!isNaN(start + offset) && start + offset < lineCount && start + offset >= 0) { 348 | const result = goal === cm.getLine(start + offset); 349 | if (result) { 350 | return offset; 351 | } 352 | offset += step; 353 | } 354 | 355 | return start; 356 | } 357 | 358 | getContentBetweenLines(fromLineNum: number, startLine: string, endLine: string, cm: Editor) { 359 | // Code taken from https://github.com/mrjackphil/obsidian-text-expand/blob/0.6.4/main.ts 360 | const topOffset = this.getLinesOffsetToGoal(fromLineNum, startLine, -1, cm); 361 | const botOffset = this.getLinesOffsetToGoal(fromLineNum, endLine, 1, cm); 362 | 363 | const topLine = fromLineNum + topOffset + 1; 364 | const botLine = fromLineNum + botOffset - 1; 365 | 366 | if (!(cm.getLine(topLine - 1) === startLine && cm.getLine(botLine + 1) === endLine)) { 367 | return ""; 368 | } 369 | 370 | return cm.getRange({line: topLine || fromLineNum, ch: 0}, 371 | {line: botLine || fromLineNum, ch: cm.getLine(botLine)?.length }); 372 | } 373 | 374 | nodeCypher(label: string): string { 375 | return "MATCH (n) WHERE n.name=\"" + label + 376 | "\" AND n." + PROP_VAULT + "=\"" + this.app.vault.getName() + 377 | "\" RETURN n" 378 | } 379 | 380 | localNeighborhoodCypher(label:string): string { 381 | return "MATCH (n {name: \"" + label + 382 | "\", " + PROP_VAULT + ":\"" + this.app.vault.getName() + 383 | "\"}) OPTIONAL MATCH (n)-[r]-(m) RETURN n,r,m" 384 | } 385 | 386 | executeQuery() { 387 | // Code taken from https://github.com/mrjackphil/obsidian-text-expand/blob/0.6.4/main.ts 388 | const currentView = this.app.workspace.activeLeaf.view; 389 | 390 | if (!(currentView instanceof MarkdownView)) { 391 | return; 392 | } 393 | 394 | const cmDoc = currentView.sourceMode.cmEditor; 395 | const curNum = cmDoc.getCursor().line; 396 | const query = this.getContentBetweenLines(curNum, '```cypher', '```', cmDoc); 397 | if (query.length > 0) { 398 | const leaf = this.app.workspace.splitActiveLeaf(this.settings.splitDirection); 399 | try { 400 | const neovisView = new NeoVisView(leaf, query, this); 401 | leaf.open(neovisView); 402 | } 403 | catch(e) { 404 | if (e instanceof Neo4jError) { 405 | new Notice("Invalid cypher query. Check console for more info."); 406 | } 407 | else { 408 | throw e; 409 | } 410 | } 411 | } 412 | } 413 | 414 | public async shutdown() { 415 | if(this.stream_process) { 416 | new Notice("Stopping Neo4j stream"); 417 | this.stream_process.kill(); 418 | this.statusBar.setText("Neo4j stream offline"); 419 | this.stream_process = null; 420 | this.imgServer.close(); 421 | this.imgServer = null; 422 | } 423 | } 424 | 425 | async onunload() { 426 | console.log('Unloading Neo4j Graph View plugin'); 427 | await this.shutdown(); 428 | } 429 | 430 | } 431 | 432 | -------------------------------------------------------------------------------- /neo4j-graph-view/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "neovis-graph-visualization", 3 | "version": "0.9.12", 4 | "description": "An Obsidian plugin for advanced graph visualization and querying using Neovis.js.", 5 | "main": "main.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/HEmile/semantic-markdown-converter.git" 9 | }, 10 | "scripts": { 11 | "dev": "rollup --config rollup.config.js -w", 12 | "build": "rollup --config rollup.config.js" 13 | }, 14 | "keywords": [], 15 | "author": "", 16 | "license": "MIT", 17 | "devDependencies": { 18 | "@egjs/hammerjs": "^2.0.17", 19 | "@rollup/plugin-commonjs": "^15.1.0", 20 | "@rollup/plugin-node-resolve": "^9.0.0", 21 | "@rollup/plugin-typescript": "^6.0.0", 22 | "@types/node": "^14.14.2", 23 | "component-emitter": "^1.3.0", 24 | "hammerjs": "^2.0.8", 25 | "keycharm": "^0.2.0", 26 | "moment": "^2.29.1", 27 | "obsidian": "https://github.com/obsidianmd/obsidian-api/tarball/master", 28 | "rollup": "^2.32.1", 29 | "timsort": "^0.3.0", 30 | "tslib": "^2.0.3", 31 | "typescript": "^4.0.3", 32 | "uuid": "^8.3.2", 33 | "vis-data": "^6.6.1", 34 | "vis-util": "^4.3.4" 35 | }, 36 | "dependencies": { 37 | "@rollup/plugin-json": "^4.1.0", 38 | "child_process": "^1.0.2", 39 | "neovis.js": "^1.6.0", 40 | "open": "^7.3.0", 41 | "python-shell": "^2.0.3" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /neo4j-graph-view/resources/bloom_screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/77afd66a1167ca2ed825ae000b463084745033d2/neo4j-graph-view/resources/bloom_screenshot.jpg -------------------------------------------------------------------------------- /neo4j-graph-view/resources/browser_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/77afd66a1167ca2ed825ae000b463084745033d2/neo4j-graph-view/resources/browser_screenshot.png -------------------------------------------------------------------------------- /neo4j-graph-view/resources/cypher_querying.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/77afd66a1167ca2ed825ae000b463084745033d2/neo4j-graph-view/resources/cypher_querying.png -------------------------------------------------------------------------------- /neo4j-graph-view/resources/graphxr.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/77afd66a1167ca2ed825ae000b463084745033d2/neo4j-graph-view/resources/graphxr.gif -------------------------------------------------------------------------------- /neo4j-graph-view/resources/obsidian neo4j plugin.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/77afd66a1167ca2ed825ae000b463084745033d2/neo4j-graph-view/resources/obsidian neo4j plugin.gif -------------------------------------------------------------------------------- /neo4j-graph-view/resources/styled_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HEmile/obsidian-neo4j-graph-view/77afd66a1167ca2ed825ae000b463084745033d2/neo4j-graph-view/resources/styled_screenshot.png -------------------------------------------------------------------------------- /neo4j-graph-view/rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from '@rollup/plugin-typescript'; 2 | import {nodeResolve} from '@rollup/plugin-node-resolve'; 3 | import commonjs from '@rollup/plugin-commonjs'; 4 | // import json from '@rollup/plugin-json'; 5 | 6 | export default { 7 | input: 'main.ts', 8 | output: { 9 | dir: '.', 10 | sourcemap: 'inline', 11 | format: 'cjs', 12 | exports: 'default' 13 | }, 14 | external: ['obsidian'], 15 | plugins: [ 16 | typescript(), 17 | nodeResolve({browser: true}), 18 | commonjs(), 19 | // json(), 20 | ] 21 | }; -------------------------------------------------------------------------------- /neo4j-graph-view/settings.ts: -------------------------------------------------------------------------------- 1 | import {App, Notice, PluginSettingTab, Setting, SplitDirection} from "obsidian"; 2 | 3 | import Neo4jViewPlugin from './main'; 4 | import {EdgeOptions, NodeOptions} from "vis-network"; 5 | import {NeoVisView, NV_VIEW_TYPE} from "./visualization"; 6 | 7 | export interface INeo4jViewSettings { 8 | index_content: boolean; 9 | auto_expand: boolean; 10 | auto_add_nodes: boolean; 11 | community: string; 12 | hierarchical: boolean; 13 | convert_markdown: boolean; 14 | show_arrows: boolean; 15 | inlineContext: boolean; 16 | password: string; 17 | typed_link_prefix: string; 18 | splitDirection: SplitDirection; // 'horizontal'; 19 | imgServerPort: number; 20 | debug: boolean; 21 | nodeSettings: string; 22 | edgeSettings: string; 23 | } 24 | 25 | export const DefaultNodeSettings: NodeOptions = { 26 | size: 9, 27 | font: { 28 | size: 12, 29 | strokeWidth: 1 30 | }, 31 | borderWidth: 0, 32 | widthConstraint: {maximum: 200}, 33 | } 34 | 35 | export const DefaultEdgeSettings: EdgeOptions = { 36 | font: { 37 | size: 12, 38 | strokeWidth: 2 39 | }, 40 | width: 0.5, 41 | } 42 | 43 | export const DefaultNeo4jViewSettings: INeo4jViewSettings = { 44 | auto_add_nodes: true, 45 | auto_expand: false, 46 | hierarchical: false, 47 | index_content: false, 48 | convert_markdown: true, 49 | community: "tags", 50 | password: "", 51 | show_arrows: true, 52 | inlineContext: false, 53 | splitDirection: 'horizontal', 54 | typed_link_prefix: '-', 55 | imgServerPort: 3837, 56 | debug: false, 57 | nodeSettings: JSON.stringify({ 58 | "defaultStyle": DefaultNodeSettings, 59 | "exampleTag": { 60 | size: 20, 61 | color: "yellow" 62 | }, 63 | "image": { 64 | size: 40, 65 | font: { 66 | size: 0 67 | } 68 | }, 69 | }), 70 | edgeSettings: JSON.stringify({ 71 | "defaultStyle": DefaultEdgeSettings, 72 | }) 73 | } 74 | 75 | 76 | 77 | export class Neo4jViewSettingTab extends PluginSettingTab { 78 | plugin: Neo4jViewPlugin; 79 | constructor(app: App, plugin: Neo4jViewPlugin) { 80 | super(app, plugin); 81 | this.plugin = plugin; 82 | } 83 | 84 | display(): void { 85 | let {containerEl} = this; 86 | containerEl.empty(); 87 | 88 | containerEl.createEl('h3'); 89 | containerEl.createEl('h3', {text: 'Neo4j Graph View'}); 90 | 91 | let doc_link = document.createElement("a"); 92 | doc_link.href = "https://juggl.io/Neo4j+Graph+View/Neo4j+Graph+View+Plugin"; 93 | doc_link.target = '_blank'; 94 | doc_link.innerHTML = 'the documentation'; 95 | 96 | let discord_link = document.createElement("a"); 97 | discord_link.href = "https://discord.gg/sAmSGpaPgM"; 98 | discord_link.target = '_blank'; 99 | discord_link.innerHTML = 'the Discord server'; 100 | 101 | let juggl_link = document.createElement("a"); 102 | juggl_link.href = "https://juggl.io/"; 103 | juggl_link.target = '_blank'; 104 | juggl_link.innerHTML = 'Juggl'; 105 | 106 | let introPar = document.createElement("p"); 107 | introPar.innerHTML = "WARNING: Neo4j Graph View is deprecated and will not receive any more updates. " + 108 | "It will be removed from the community plugins soon. It is replaced by " + juggl_link.outerHTML + ".
" + 109 | "Check out " + doc_link.outerHTML + " for installation help and a getting started guide.
" + 110 | "Join " + discord_link.outerHTML + " for nice discussion and additional help." 111 | 112 | containerEl.appendChild(introPar); 113 | 114 | new Setting(containerEl) 115 | .setName("Neo4j database password") 116 | .setDesc("The password of your neo4j graph database. WARNING: This is stored in plaintext in your vault. " + 117 | "Don't use sensitive passwords here!") 118 | .addText(text => { 119 | text.setPlaceholder("") 120 | .setValue(this.plugin.settings.password) 121 | .onChange((new_folder) => { 122 | this.plugin.settings.password = new_folder; 123 | this.plugin.saveData(this.plugin.settings); 124 | }).inputEl.setAttribute("type", "password") 125 | }); 126 | 127 | containerEl.createEl('h3'); 128 | containerEl.createEl('h3', {text: 'Appearance'}); 129 | 130 | new Setting(containerEl) 131 | .setName("Color-coding") 132 | .setDesc("What property to choose for coloring the nodes in the graph. Requires a server restart.") 133 | .addDropdown(dropdown => dropdown 134 | .addOption('tags','Tags') 135 | .addOption('folders','Folders') 136 | .addOption('none','No color-coding') 137 | .setValue(this.plugin.settings.community) 138 | .onChange((value) => { 139 | this.plugin.settings.community = value; 140 | this.plugin.saveData(this.plugin.settings); 141 | })); 142 | 143 | 144 | new Setting(containerEl) 145 | .setName("Hierarchical layout") 146 | .setDesc("Use the hierarchical graph layout instead of the normal one.") 147 | .addToggle(toggle => { 148 | toggle.setValue(this.plugin.settings.hierarchical) 149 | .onChange((new_value) => { 150 | this.plugin.settings.hierarchical = new_value; 151 | this.plugin.saveData(this.plugin.settings); 152 | }) 153 | }); 154 | 155 | new Setting(containerEl) 156 | .setName("Show arrows") 157 | .setDesc("Show arrows on edges.") 158 | .addToggle(toggle => { 159 | toggle.setValue(this.plugin.settings.show_arrows) 160 | .onChange((new_value) => { 161 | this.plugin.settings.show_arrows = new_value; 162 | this.plugin.saveData(this.plugin.settings); 163 | }) 164 | }); 165 | new Setting(containerEl) 166 | .setName("Show context on inline links") 167 | .setDesc("Shows the paragraph where an inline link is in on the edge.") 168 | .addToggle(toggle => { 169 | toggle.setValue(this.plugin.settings.inlineContext) 170 | .onChange((new_value) => { 171 | this.plugin.settings.inlineContext = new_value; 172 | this.plugin.saveData(this.plugin.settings); 173 | }) 174 | }); 175 | containerEl.createEl('h4'); 176 | containerEl.createEl('h4', {text: 'Node Styling'}); 177 | 178 | const div = document.createElement("div"); 179 | div.className = "neovis_setting"; 180 | this.containerEl.children[this.containerEl.children.length - 1].appendChild(div); 181 | div.setAttr("style", "height: 100%; width:100%"); 182 | 183 | let input = div.createEl("textarea"); 184 | input.placeholder = JSON.stringify(DefaultNodeSettings); 185 | input.value = this.plugin.settings.nodeSettings; 186 | input.onchange = (ev) => { 187 | this.plugin.settings.nodeSettings = input.value; 188 | this.plugin.saveData(this.plugin.settings); 189 | let leaves = this.plugin.app.workspace.getLeavesOfType(NV_VIEW_TYPE); 190 | leaves.forEach((leaf) =>{ 191 | (leaf.view as NeoVisView).updateStyle(); 192 | }); 193 | }; 194 | input.setAttr("style", "height: 300px; width: 100%; " + 195 | "-webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;"); 196 | 197 | let temp_link = document.createElement("a"); 198 | temp_link.href = "https://publish.obsidian.md/semantic-obsidian/Node+styling"; 199 | temp_link.target = '_blank'; 200 | temp_link.innerHTML ='this link'; 201 | 202 | let par = document.createElement("p"); 203 | par.innerHTML = "Styling of nodes in .json format.
" + 204 | "Use {\"defaultStyle\": {}} for the default styling of nodes. " + 205 | "Use {\"image\": {}} to style images. Use {\"SMD_dangling\": {}} to style dangling notes.
" + 206 | "When color-coding is set to Folders, use the path to the folder for this key. " + 207 | "Use {\"/\" for the root folder.
" + 208 | "See " + temp_link.outerHTML + " for help with styling nodes. " 209 | 210 | containerEl.appendChild(par); 211 | 212 | containerEl.createEl('h4'); 213 | containerEl.createEl('h4', {text: 'Edge Styling'}); 214 | 215 | const div2 = document.createElement("div"); 216 | div2.className = "neovis_setting2"; 217 | this.containerEl.children[this.containerEl.children.length - 1].appendChild(div2); 218 | div2.setAttr("style", "height: 100%; width:100%"); 219 | 220 | let input2 = div2.createEl("textarea"); 221 | input2.placeholder = JSON.stringify(DefaultEdgeSettings); 222 | input2.value = this.plugin.settings.edgeSettings; 223 | input2.onchange = (ev) => { 224 | this.plugin.settings.edgeSettings = input2.value; 225 | this.plugin.saveData(this.plugin.settings); 226 | let leaves = this.plugin.app.workspace.getLeavesOfType(NV_VIEW_TYPE); 227 | leaves.forEach((leaf) =>{ 228 | (leaf.view as NeoVisView).updateStyle(); 229 | }); 230 | }; 231 | input2.setAttr("style", "height: 300px; width: 100%; " + 232 | "-webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;"); 233 | 234 | let temp_link2 = document.createElement("a"); 235 | temp_link2.href = "https://publish.obsidian.md/semantic-obsidian/Edge+styling"; 236 | temp_link2.target = '_blank'; 237 | temp_link2.innerHTML = 'this link'; 238 | 239 | let par2 = document.createElement("p"); 240 | par2.innerHTML = "Styling of edges is done in .json format.
" + 241 | "The first key determines what types of links to apply this style to. " + 242 | "Use {\"defaultStyle\": {}} for the default styling of edges, and {\"inline\":{} } for the styling of untyped links. " + 243 | "See " + temp_link2.outerHTML + " for help with styling edges." 244 | 245 | containerEl.appendChild(par2); 246 | 247 | 248 | containerEl.createEl('h3'); 249 | containerEl.createEl('h3', {text: 'Advanced'}); 250 | 251 | new Setting(containerEl) 252 | .setName("Automatic expand") 253 | .setDesc("This will automatically expand the neighbourhood around any nodes clicked on or added to the graph. " + 254 | "This normally only happens when pressing E or when double-clicking.") 255 | .addToggle(toggle => { 256 | toggle.setValue(this.plugin.settings.auto_expand) 257 | .onChange((new_value) => { 258 | this.plugin.settings.auto_expand = new_value; 259 | this.plugin.saveData(this.plugin.settings); 260 | }) 261 | }); 262 | new Setting(containerEl) 263 | .setName("Automatically add nodes") 264 | .setDesc("This will automatically add nodes to the graph whenever a note is opened.") 265 | .addToggle(toggle => { 266 | toggle.setValue(this.plugin.settings.auto_add_nodes) 267 | .onChange((new_value) => { 268 | this.plugin.settings.auto_add_nodes = new_value; 269 | this.plugin.saveData(this.plugin.settings); 270 | }) 271 | }); 272 | 273 | new Setting(containerEl) 274 | .setName("Convert Markdown") 275 | .setDesc("If true, the server will convert the content of notes to HTML. This can slow the server. " + 276 | "Turn it off to increase server performance at the cost of not having proper previews on hovering in the graph. ") 277 | .addToggle(toggle => { 278 | toggle.setValue(this.plugin.settings.convert_markdown) 279 | .onChange((new_value) => { 280 | this.plugin.settings.convert_markdown = new_value; 281 | this.plugin.saveData(this.plugin.settings); 282 | }) 283 | }); 284 | 285 | new Setting(containerEl) 286 | .setName("Index note content") 287 | .setDesc("This will full-text index the content of notes. " + 288 | "This allows searching within notes using the Neo4j Bloom search bar. However, it could decrease performance.") 289 | .addToggle(toggle => { 290 | toggle.setValue(this.plugin.settings.index_content) 291 | .onChange((new_value) => { 292 | this.plugin.settings.index_content = new_value; 293 | this.plugin.saveData(this.plugin.settings); 294 | }) 295 | }); 296 | 297 | new Setting(containerEl) 298 | .setName("Typed links prefix") 299 | .setDesc("Prefix to use for typed links. Default is '-'. Requires a server restart.") 300 | .addText(text => { 301 | text.setPlaceholder("") 302 | .setValue(this.plugin.settings.typed_link_prefix) 303 | .onChange((new_folder) => { 304 | this.plugin.settings.typed_link_prefix = new_folder; 305 | this.plugin.saveData(this.plugin.settings); 306 | }) 307 | }); 308 | 309 | new Setting(containerEl) 310 | .setName("Image server port") 311 | .setDesc("Set the port of the image server. If you use multiple vaults, these need to be set differently. Default 3000.") 312 | .addText(text => { 313 | text.setValue(this.plugin.settings.imgServerPort + '') 314 | .setPlaceholder('3000') 315 | .onChange((new_value) => { 316 | this.plugin.settings.imgServerPort = parseInt(new_value.trim()); 317 | this.plugin.saveData(this.plugin.settings); 318 | }) 319 | }); 320 | 321 | new Setting(containerEl) 322 | .setName("Debug") 323 | .setDesc("Enable debug mode. Prints a lot of stuff in the developers console. Requires a server restart.") 324 | .addToggle(toggle => { 325 | toggle.setValue(this.plugin.settings.debug) 326 | .onChange((new_value) => { 327 | this.plugin.settings.debug = new_value; 328 | this.plugin.saveData(this.plugin.settings); 329 | }) 330 | }); 331 | 332 | 333 | } 334 | } -------------------------------------------------------------------------------- /neo4j-graph-view/styles.css: -------------------------------------------------------------------------------- 1 | div.vis-tooltip { 2 | white-space: pre-line; 3 | font-family: inherit; 4 | font-size: inherit; 5 | width: fit-content; 6 | max-width: 500px; 7 | border: 0; 8 | padding: 15px; 9 | background-color: white; 10 | } 11 | 12 | div.neovis_setting { 13 | width: content-box; 14 | } 15 | -------------------------------------------------------------------------------- /neo4j-graph-view/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "inlineSourceMap": true, 5 | "inlineSources": true, 6 | "module": "ESNext", 7 | "target": "es5", 8 | "allowJs": true, 9 | "noImplicitAny": true, 10 | "moduleResolution": "node", 11 | "importHelpers": true, 12 | "lib": [ 13 | "dom", 14 | "es5", 15 | "scripthost", 16 | "es2015" 17 | ] 18 | }, 19 | "include": [ 20 | "**/*.ts" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /neo4j-graph-view/versions.json: -------------------------------------------------------------------------------- 1 | { 2 | "1.0.1": "0.9.12", 3 | "1.0.0": "0.9.7" 4 | } 5 | -------------------------------------------------------------------------------- /neo4j-graph-view/visualization.ts: -------------------------------------------------------------------------------- 1 | import {IEdge, INode, IRelationshipConfig, NEOVIS_DEFAULT_CONFIG} from "neovis.js"; 2 | import NeoVis from 'neovis.js'; 3 | import {INeo4jViewSettings} from "./settings"; 4 | import {EventRef, ItemView, MarkdownView, Menu, normalizePath, TFile, Vault, Workspace, WorkspaceLeaf} from "obsidian"; 5 | import Neo4jViewPlugin from "./main"; 6 | import {Relationship, Node} from "neo4j-driver"; 7 | import {Data, IdType, Network, NodeOptions} from "vis-network"; 8 | 9 | export const NV_VIEW_TYPE = "neovis"; 10 | export const MD_VIEW_TYPE = 'markdown'; 11 | 12 | export const PROP_VAULT = "SMD_vault" 13 | export const PROP_PATH = "SMD_path" 14 | export const PROP_COMMUNITY = "SMD_community" 15 | 16 | let VIEW_COUNTER = 0; 17 | 18 | export class NeoVisView extends ItemView{ 19 | 20 | workspace: Workspace; 21 | listeners: EventRef[]; 22 | settings: INeo4jViewSettings; 23 | initial_query: string; 24 | vault: Vault; 25 | plugin: Neo4jViewPlugin; 26 | viz: NeoVis; 27 | network: Network; 28 | hasClickListener = false; 29 | rebuildRelations = true; 30 | selectName: string = undefined; 31 | expandedNodes: string[] = []; 32 | nodes: Record; 33 | edges: Record; 34 | 35 | constructor(leaf: WorkspaceLeaf, initial_query: string, plugin: Neo4jViewPlugin) { 36 | super(leaf); 37 | this.settings = plugin.settings; 38 | this.workspace = this.app.workspace; 39 | this.initial_query = initial_query; 40 | this.vault = this.app.vault; 41 | this.plugin = plugin; 42 | } 43 | 44 | async onOpen() { 45 | const div = document.createElement("div"); 46 | div.id = "neovis_id" + VIEW_COUNTER; 47 | VIEW_COUNTER += 1; 48 | this.containerEl.children[1].appendChild(div); 49 | div.setAttr("style", "height: 100%; width:100%"); 50 | // console.log(this.containerEl); 51 | const config = { 52 | container_id: div.id, 53 | server_url: "bolt://localhost:7687", 54 | server_user: "neo4j", 55 | server_password: this.settings.password, 56 | arrows: this.settings.show_arrows, 57 | hierarchical: this.settings.hierarchical, 58 | labels: { 59 | [NEOVIS_DEFAULT_CONFIG]: { 60 | "caption": "name", 61 | //"size": this.settings.node_size, 62 | "community": PROP_COMMUNITY, 63 | "title_properties": [ 64 | "aliases", 65 | "content" 66 | ], 67 | } 68 | }, 69 | relationships: { 70 | "inline": { 71 | "thickness": "weight", 72 | "caption": this.settings.inlineContext ? "context": false, 73 | "title_properties": [ 74 | "parsedContext" 75 | ] 76 | }, 77 | [NEOVIS_DEFAULT_CONFIG]: { 78 | "thickness": "defaultThicknessProperty", 79 | "caption": true 80 | } 81 | }, 82 | initial_cypher: this.initial_query 83 | }; 84 | this.viz = new NeoVis(config); 85 | this.viz.registerOnEvent("completed", (e)=>{ 86 | if (!this.hasClickListener) { 87 | // @ts-ignore 88 | this.network = this.viz["_network"] as Network; 89 | // @ts-ignore 90 | this.nodes = this.viz._nodes; 91 | // @ts-ignore 92 | this.edges = this.viz._edges; 93 | // Register on click event 94 | this.network.on("click", (event) => { 95 | if (event.nodes.length > 0) { 96 | this.onClickNode(this.findNode(event.nodes[0])); 97 | } 98 | else if (event.edges.length == 1) { 99 | this.onClickEdge(this.findEdge(event.edges[0])); 100 | } 101 | }); 102 | this.network.on("doubleClick", (event) => { 103 | if (event.nodes.length > 0) { 104 | this.onDoubleClickNode(this.findNodeRaw(event.nodes[0])); 105 | } 106 | }); 107 | this.network.on("oncontext", (event) => { 108 | // Thanks Liam for sharing how to do context menus 109 | const fileMenu = new Menu(this.plugin.app); // Creates empty file menu 110 | let nodeId = this.network.getNodeAt(event.pointer.DOM); 111 | 112 | if (!(nodeId === undefined)) { 113 | let node = this.findNode(nodeId); 114 | let file = this.getFileFromNode(node); 115 | if (!(file === undefined)) { 116 | // hook for plugins to populate menu with "file-aware" menu items 117 | this.app.workspace.trigger("file-menu", fileMenu, file, "my-context-menu", null); 118 | } 119 | } 120 | fileMenu.addItem((item) =>{ 121 | item.setTitle("Expand selection (E)").setIcon("dot-network") 122 | .onClick(evt => { 123 | this.expandSelection(); 124 | }); 125 | }); 126 | fileMenu.addItem((item) =>{ 127 | item.setTitle("Hide selection (H)").setIcon("dot-network") 128 | .onClick(evt => { 129 | this.hideSelection(); 130 | }); 131 | }); 132 | fileMenu.addItem((item) =>{ 133 | item.setTitle("Invert selection (I)").setIcon("dot-network") 134 | .onClick(evt => { 135 | this.invertSelection(); 136 | }); 137 | }); 138 | fileMenu.addItem((item) =>{ 139 | item.setTitle("Select all (A)").setIcon("dot-network") 140 | .onClick(evt => { 141 | this.hideSelection(); 142 | }); 143 | }); 144 | let domRect = this.containerEl.getBoundingClientRect(); 145 | // console.log("DOM", event.pointer.DOM); 146 | // console.log("Canvas", event.pointer.canvas); 147 | // console.log("offset", domRect.left, domRect.top) 148 | // console.log("DOM offset", { x: event.pointer.DOM.x + domRect.left, y: event.pointer.DOM.y + domRect.top }); 149 | // console.log("Canvas offset", { x: event.pointer.canvas.x + domRect.left, y: event.pointer.canvas.y + domRect.top }); 150 | // Actually open the menu 151 | fileMenu.showAtPosition({ x: event.pointer.DOM.x + domRect.left, y: event.pointer.DOM.y + domRect.top }); 152 | }) 153 | this.hasClickListener = true; 154 | } 155 | if (this.rebuildRelations) { 156 | let inQuery = this.getInQuery(this.viz.nodes.getIds()); 157 | let query = "MATCH (n)-[r]-(m) WHERE n." + PROP_VAULT + "= \"" + this.vault.getName() + "\" AND n.name " + inQuery 158 | + " AND m." + PROP_VAULT + "= \"" + this.vault.getName() + "\" AND m.name " + inQuery + 159 | " RETURN r"; 160 | this.viz.updateWithCypher(query); 161 | this.rebuildRelations = false; 162 | } 163 | this.updateStyle(); 164 | if (!(this.selectName=== undefined)) { 165 | this.viz.nodes.forEach(node => { 166 | if (node.label === this.selectName) { 167 | this.network.setSelection({nodes: [node.id], edges: []}); 168 | this.selectName = undefined; 169 | } 170 | }) 171 | } 172 | if (this.settings.debug) { 173 | // @ts-ignore 174 | console.log(this.nodes); 175 | // @ts-ignore 176 | console.log(this.edges); 177 | } 178 | }); 179 | this.load(); 180 | this.viz.render(); 181 | 182 | // Register on file open event 183 | this.workspace.on("file-open", (file) => { 184 | if (file && this.settings.auto_add_nodes) { 185 | const name = file.basename; 186 | //todo: Select node 187 | if (this.settings.auto_expand) { 188 | this.updateWithCypher(this.plugin.localNeighborhoodCypher(name)); 189 | } 190 | else { 191 | this.updateWithCypher(this.plugin.nodeCypher(name)); 192 | } 193 | this.selectName = name; 194 | } 195 | }); 196 | 197 | // Register keypress event 198 | this.containerEl.addEventListener("keydown", (evt) => { 199 | if (evt.key === "e"){ 200 | this.expandSelection(); 201 | } 202 | else if (evt.key === "h" || evt.key === "Backspace"){ 203 | this.hideSelection(); 204 | } 205 | else if (evt.key === "i") { 206 | this.invertSelection(); 207 | } 208 | else if (evt.key === "a") { 209 | this.selectAll(); 210 | } 211 | }); 212 | } 213 | 214 | findNodeRaw(id: IdType): Node { 215 | // @ts-ignore 216 | return this.viz.nodes.get(id)?.raw as Node; 217 | } 218 | 219 | findNode(id: IdType): INode { 220 | return this.viz.nodes.get(id) as INode; 221 | } 222 | 223 | findEdge(id: IdType): Relationship { 224 | // @ts-ignore 225 | return this.viz.edges.get(id)?.raw as Relationship; 226 | } 227 | 228 | updateWithCypher(cypher: string) { 229 | if (this.settings.debug) { 230 | console.log(cypher); 231 | } 232 | this.viz.updateWithCypher(cypher); 233 | this.rebuildRelations = true; 234 | } 235 | 236 | getFileFromNode(node: INode) { 237 | // @ts-ignore 238 | let label = node.raw.properties["name"]; 239 | return this.app.metadataCache.getFirstLinkpathDest(label, ''); 240 | } 241 | 242 | updateStyle() { 243 | let nodeOptions = JSON.parse(this.settings.nodeSettings); 244 | this.viz.nodes.forEach((node) => { 245 | let nodeId = this.network.findNode(node.id); 246 | 247 | let specificOptions: NodeOptions[] = []; 248 | let file = this.getFileFromNode(node); 249 | if (this.settings.community === "tags") { 250 | node.raw.labels.forEach((label) => { 251 | if (label in nodeOptions) { 252 | specificOptions.push(nodeOptions[label]); 253 | } 254 | }); 255 | } 256 | else if (this.settings.community === "folders" && !(file === undefined)) { 257 | // @ts-ignore 258 | const path = file.parent.path; 259 | if (path in nodeOptions) { 260 | specificOptions.push(nodeOptions[path]); 261 | } 262 | } 263 | // Style images 264 | if (/(\.png|\.jpg|\.jpeg|\.gif|\.svg)$/.test(node.label) && !(file === undefined)) { 265 | specificOptions.push({shape: "image", image: "http://localhost:" + 266 | this.settings.imgServerPort + "/" 267 | + encodeURI(file.path)}); 268 | if ("image" in nodeOptions) { 269 | specificOptions.push(nodeOptions["image"]); 270 | } 271 | } 272 | // @ts-ignore 273 | let node_sth = this.network.body.nodes[nodeId]; 274 | if (!(node_sth === undefined)) { 275 | node_sth.setOptions(Object.assign({}, nodeOptions["defaultStyle"], ...specificOptions)); 276 | } else if(this.settings.debug) { 277 | console.log(node); 278 | } 279 | }); 280 | let edgeOptions = JSON.parse(this.settings.edgeSettings); 281 | this.viz.edges.forEach((edge) => { 282 | // @ts-ignore 283 | let edge_sth = this.network.body.edges[edge.id]; 284 | let type = edge.raw.type; 285 | let specificOptions = type in edgeOptions ? [edgeOptions[type]] : []; 286 | if (!(edge_sth === undefined)) { 287 | edge_sth.setOptions(Object.assign({}, edgeOptions["defaultStyle"], ...specificOptions)); 288 | } else if (this.settings.debug) { 289 | console.log(edge); 290 | } 291 | }); 292 | } 293 | 294 | async onClickNode(node: INode) { 295 | const file = this.getFileFromNode(node); 296 | // @ts-ignore 297 | let label = node.raw.properties["name"]; 298 | if (file) { 299 | await this.plugin.openFile(file); 300 | } 301 | else { 302 | // Create dangling file 303 | // TODO: Add default folder 304 | // @ts-ignore 305 | const filename = label + ".md"; 306 | const createdFile = await this.vault.create(filename, ''); 307 | await this.plugin.openFile(createdFile); 308 | } 309 | if (this.settings.auto_expand) { 310 | await this.updateWithCypher(this.plugin.localNeighborhoodCypher(label)); 311 | } 312 | } 313 | 314 | async onDoubleClickNode(node: Node) { 315 | // @ts-ignore 316 | const label = node.properties["name"]; 317 | this.expandedNodes.push(label); 318 | await this.updateWithCypher(this.plugin.localNeighborhoodCypher(label)); 319 | } 320 | 321 | async onClickEdge(edge: Object) { 322 | // @ts-ignore 323 | // if (!edge.raw) { 324 | // return; 325 | // } 326 | // // @ts-ignore 327 | // const rel = edge.raw as Relationship; 328 | // console.log(edge); 329 | // // @ts-ignore 330 | // const file = rel.properties["context"]; 331 | // const node = this.viz.nodes.get(rel.start.high); 332 | // const label = node.label; 333 | 334 | // TODO: Figure out how to open a node at the context point 335 | // this.workspace.openLinkText() 336 | 337 | } 338 | 339 | getInQuery(nodes: IdType[]): string { 340 | let query = "IN [" 341 | let first = true; 342 | for (let id of nodes) { 343 | // @ts-ignore 344 | const title = this.findNodeRaw(id).properties["name"] as string; 345 | if (!first) { 346 | query += ", "; 347 | } 348 | query += "\"" + title + "\""; 349 | first = false; 350 | } 351 | query += "]" 352 | return query; 353 | } 354 | 355 | async expandSelection() { 356 | let selected_nodes = this.network.getSelectedNodes(); 357 | if (selected_nodes.length === 0) { 358 | return; 359 | } 360 | let query = "MATCH (n)-[r]-(m) WHERE n." + PROP_VAULT + "= \"" + this.vault.getName() + "\" AND n.name "; 361 | query += this.getInQuery(selected_nodes); 362 | query += " RETURN r,m"; 363 | let expandedNodes = this.expandedNodes; 364 | selected_nodes.forEach(id => { 365 | // @ts-ignore 366 | const title = this.findNodeRaw(id).properties["name"] as string; 367 | if (!expandedNodes.includes(title)) { 368 | expandedNodes.push(title); 369 | } 370 | }); 371 | this.updateWithCypher(query); 372 | } 373 | 374 | deleteNode(id: IdType) { 375 | // console.log(this.viz.nodes); 376 | // @ts-ignore 377 | 378 | let node = this.findNode(id) || this.nodes[id]; 379 | if (node === undefined) { 380 | return; 381 | } 382 | // @ts-ignore 383 | const title = node.raw.properties["name"] as string; 384 | if (this.expandedNodes.includes(title)) { 385 | this.expandedNodes.remove(title); 386 | } 387 | let expandedNodes = this.expandedNodes; 388 | this.network.getConnectedNodes(id).forEach((value: any) => { 389 | this.findNodeRaw(value); 390 | // @ts-ignore 391 | const n_title = this.findNodeRaw(value).properties["name"] as string; 392 | if (expandedNodes.includes(n_title)) { 393 | expandedNodes.remove(n_title); 394 | } 395 | }); 396 | 397 | let edges_to_remove: IEdge[] = []; 398 | this.viz.edges.forEach((edge) => { 399 | if (edge.from === id || edge.to === id) { 400 | edges_to_remove.push(edge); 401 | } 402 | }); 403 | edges_to_remove.forEach(edge => { 404 | this.viz.edges.remove(edge); 405 | }); 406 | 407 | this.viz.nodes.remove(id); 408 | 409 | let keys_to_remove = []; 410 | for (let key in this.edges) { 411 | let edge = this.edges[key]; 412 | if (edge.to === id || edge.from === id) { 413 | keys_to_remove.push(key); 414 | } 415 | } 416 | keys_to_remove.forEach((key) => { 417 | // @ts-ignore 418 | delete this.edges[key]; 419 | }); 420 | 421 | delete this.nodes[id as number]; 422 | } 423 | 424 | deleteEdge(id: IdType) { 425 | let edge = this.edges[id]; 426 | if (edge === undefined) { 427 | return; 428 | } 429 | 430 | let nodes = [edge.from, edge.to]; 431 | 432 | this.viz.edges.remove(edge); 433 | 434 | delete this.edges[id]; 435 | 436 | // TODO: Check if the node deletion is using the right rule 437 | // Current rule: The connected nodes are not expanded, and also have no other edges. 438 | nodes.forEach(node_id => { 439 | let node = this.findNodeRaw(node_id); 440 | // @ts-ignore 441 | if (!this.expandedNodes.contains(node.properties["name"]) 442 | && this.network.getConnectedEdges(node_id).length === 0) { 443 | this.deleteNode(node_id); 444 | } 445 | }); 446 | } 447 | 448 | async hideSelection() { 449 | if (this.network.getSelectedNodes().length === 0) { 450 | return; 451 | } 452 | // Update expanded nodes. Make sure to not automatically expand nodes of which a neighbor was hidden. 453 | // Otherwise, one would have to keep hiding nodes. 454 | this.network.getSelectedNodes().forEach(id => { 455 | this.deleteNode(id); 456 | }); 457 | // this.network.deleteSelected(); 458 | 459 | // This super hacky code is used because neovis.js doesn't like me removing nodes from the graph. 460 | // Essentially, whenever it'd execute a new query, it'd re-add all hidden nodes! 461 | // This resets the state of NeoVis so that it only acts as an interface with neo4j instead of also keeping 462 | // track of the data. 463 | // @ts-ignore 464 | // let data = {nodes: this.viz.nodes, edges: this.viz.edges} as Data; 465 | // this.viz.clearNetwork(); 466 | // this.network.setData(data); 467 | this.updateStyle(); 468 | } 469 | 470 | invertSelection() { 471 | let selectedNodes = this.network.getSelectedNodes(); 472 | let network = this.network; 473 | let inversion = this.viz.nodes.get({filter: function(item){ 474 | return !selectedNodes.contains(item.id) && network.findNode(item.id).length > 0; 475 | }}).map((item) => item.id); 476 | this.network.setSelection({nodes: inversion, edges: []}) 477 | } 478 | 479 | 480 | selectAll() { 481 | this.network.unselectAll(); 482 | this.invertSelection(); 483 | } 484 | 485 | async checkAndUpdate() { 486 | try { 487 | if(await this.checkActiveLeaf()) { 488 | await this.update(); 489 | } 490 | } catch (error) { 491 | console.error(error) 492 | } 493 | } 494 | 495 | async update(){ 496 | this.load(); 497 | } 498 | 499 | async checkActiveLeaf() { 500 | return false; 501 | } 502 | 503 | getDisplayText(): string { 504 | return "Neo4j Graph"; 505 | } 506 | 507 | getViewType(): string { 508 | return NV_VIEW_TYPE; 509 | } 510 | 511 | 512 | } -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "requires": true, 3 | "lockfileVersion": 1, 4 | "dependencies": { 5 | "is-docker": { 6 | "version": "2.1.1", 7 | "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.1.1.tgz", 8 | "integrity": "sha512-ZOoqiXfEwtGknTiuDEy8pN2CfE3TxMHprvNer1mXiqwkOT77Rw3YVrUQ52EqAOU3QAWDQ+bQdx7HJzrv7LS2Hw==" 9 | }, 10 | "is-wsl": { 11 | "version": "2.2.0", 12 | "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", 13 | "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", 14 | "requires": { 15 | "is-docker": "^2.0.0" 16 | } 17 | }, 18 | "open": { 19 | "version": "7.3.0", 20 | "resolved": "https://registry.npmjs.org/open/-/open-7.3.0.tgz", 21 | "integrity": "sha512-mgLwQIx2F/ye9SmbrUkurZCnkoXyXyu9EbHtJZrICjVAJfyMArdHp3KkixGdZx1ZHFPNIwl0DDM1dFFqXbTLZw==", 22 | "requires": { 23 | "is-docker": "^2.0.0", 24 | "is-wsl": "^2.1.1" 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | with open("README.md", "r", encoding="utf-8") as fh: 4 | long_description = fh.read() 5 | 6 | 7 | setup(name='semantic-markdown-converter', 8 | version='0.5.9', 9 | description='Converts different typed link formats in Markdown into each other and to external formats. Supports Obsidian Neo4j plugin.', 10 | long_description=long_description, 11 | long_description_content_type="text/markdown", 12 | url='https://github.com/HEmile/semantic-markdown-converter', 13 | packages=find_packages(), 14 | install_requires=['pyyaml', 'tqdm', 'py2neo', 'watchdog>=1.0.2', 15 | 'markdown', 'mdx-wikilink-plus'], 16 | entry_points={ 17 | 'console_scripts': ['smdc=smdc.convert:main', 'smds=smdc.stream:main'] 18 | }, 19 | classifiers=[ 20 | "Programming Language :: Python :: 3", 21 | "License :: OSI Approved :: MIT License", 22 | "Operating System :: OS Independent", 23 | ], 24 | author='Emile van Krieken', 25 | author_email='emilevankrieken@live.nl', 26 | license='MIT', 27 | zip_safe=False, 28 | python_requires='>=3.6',) -------------------------------------------------------------------------------- /smdc/__init__.py: -------------------------------------------------------------------------------- 1 | DEBUG = False 2 | from .note import Note, Relationship 3 | from .args import convert_args, server_args 4 | from smdc.format import FORMAT_TYPES 5 | from .convert import convert 6 | from .parse import parse_folder, parse_note, note_name, obsidian_url 7 | from .stream import stream, main 8 | 9 | -------------------------------------------------------------------------------- /smdc/args.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from pathlib import Path 3 | 4 | import smdc 5 | 6 | def _mutual_args(parser): 7 | parser.add_argument('--input', metavar='i', type=str, default=".", 8 | help='directory with markdown files') 9 | parser.add_argument('--input_format', metavar='f', type=str, default="typed_list", 10 | help='format of inputs') 11 | parser.add_argument('--extension', metavar='e', type=str, default=".md", 12 | help='extension of markdown files') 13 | parser.add_argument('--retaindb', action="store_true", default=False) 14 | parser.add_argument('--password', metavar='p', type=str, default="") 15 | parser.add_argument("--vault_name", metavar='n', type=str, default=None, help="Defaults to input directory name") 16 | parser.add_argument("--batch_size", metavar='b', type=int, default=75, help="Batch size for sending to neo4j") 17 | parser.add_argument("--debug", action="store_true", help="Debug mode") 18 | parser.add_argument("--index_content", action="store_true", help="Use to index the content in neo4j. Can highly impact performance") 19 | parser.add_argument("--typed_links_prefix", metavar='t', type=str, default="-") 20 | parser.add_argument('--community', metavar='c', type=str, default="tags", help="Options: {tags, folders, none}. Used for color coding in Obsidian plugin.") 21 | parser.add_argument('--convert_markdown', action="store_true", help="Converts content property to HTML. Takes quite a bit longer on startup. ") 22 | parser.add_argument('-r', action="store_false", default=True) 23 | 24 | def server_args(): 25 | parser = argparse.ArgumentParser( 26 | description='Stream changes in Obsidian vaults to active neo4j server.') 27 | _mutual_args(parser) 28 | args = parser.parse_args() 29 | if not args.vault_name: 30 | args.vault_name = Path(args.input).name 31 | if args.debug: 32 | smdc.DEBUG = True 33 | print(args) 34 | return args 35 | 36 | def convert_args(): 37 | parser = argparse.ArgumentParser( 38 | description='Convert different typed links representations of Markdown into other formats.') 39 | _mutual_args(parser) 40 | parser.add_argument('--output_format', metavar='r', type=str, default="neo4j", 41 | help='format of inputs') 42 | parser.add_argument('--output', metavar='o', type=str, default="out", 43 | help='directory for output files') 44 | args = parser.parse_args() 45 | if not args.vault_name: 46 | args.vault_name = Path(args.input).name 47 | if args.debug: 48 | smdc.DEBUG = True 49 | print(args) 50 | return args 51 | -------------------------------------------------------------------------------- /smdc/convert.py: -------------------------------------------------------------------------------- 1 | import smdc.parse as parse 2 | from smdc import convert_args 3 | from smdc.format import FORMAT_TYPES 4 | 5 | 6 | def convert(args): 7 | notes = parse.parse_folder(FORMAT_TYPES[args.input_format], args) 8 | return FORMAT_TYPES[args.output_format].write(notes, args) 9 | 10 | 11 | def main(): 12 | args = convert_args() 13 | convert(args) 14 | 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /smdc/format/__init__.py: -------------------------------------------------------------------------------- 1 | from .format import Format 2 | from .typed_list import TypedList 3 | from .cypher import Cypher 4 | from .neo4j import Neo4j 5 | FORMAT_TYPES = {"typed_list": TypedList(), "cypher": Cypher(), "neo4j": Neo4j()} -------------------------------------------------------------------------------- /smdc/format/csv.py: -------------------------------------------------------------------------------- 1 | from smdc.format import Format 2 | from smdc.note import Note, Relationship 3 | import io 4 | import os 5 | from smdc.format.util import escape_quotes 6 | 7 | 8 | class CSV(Format): 9 | 10 | def parse(self, file: io.TextIOWrapper, name, parsed_notes: [Note]) -> Note: 11 | raise NotImplementedError 12 | 13 | def write(self, file, parsed_notes: [Note]): 14 | # First create all nodes in the graph before doing the relationships, so they all exist. 15 | with open(file + '.csv', 'w') as f: 16 | 17 | for name, note in parsed_notes.items(): 18 | 19 | line = "CREATE (" 20 | if note.tags: 21 | line += ":" + ":".join(note.tags) 22 | line += " { name: '" + escape_quotes(name) + "', content: '" + escape_quotes(note.content) + "'" 23 | for property, value in note.properties.items(): 24 | line += ", " + property + ": '" + escape_quotes(str(value)) + "'" 25 | line += "});" + os.linesep 26 | f.write(line) 27 | 28 | for name, note in parsed_notes.items(): 29 | f.write("MATCH (a)" + os.linesep + "WHERE a.name == '" + escape_quotes(name) + "'" + os.linesep) 30 | i = 0 31 | for trgt, rels in note.out_rels.items(): 32 | f.write( 33 | "MATCH (b" + str(i) + ")" + os.linesep + "WHERE b" + str(i) + ".name == '" + 34 | escape_quotes(trgt) + "'" + os.linesep) 35 | for rel in rels: 36 | f.write("CREATE (a)-[r:" + rel.type + "]->(b" + str(i) + ")" + os.linesep) 37 | i += 1 38 | f.write(";" + os.linesep) 39 | 40 | -------------------------------------------------------------------------------- /smdc/format/cypher.py: -------------------------------------------------------------------------------- 1 | from smdc.format import Format 2 | from smdc.note import Note, Relationship 3 | import io 4 | import os 5 | from smdc.format.util import escape_quotes 6 | 7 | 8 | def escape_cypher(string): 9 | # r = escape_quotes(string) 10 | # Note: CYPHER doesn't allow putting semicolons in text, for some reason. This is lossy! 11 | # r = r.replace(";", ",") 12 | r = string.replace("\\u", "\\\\u") 13 | if r and r[-1] == '\\': 14 | r += ' ' 15 | return r 16 | 17 | def to_cyper(parsed_notes: [Note]): 18 | lines = [] 19 | # First create all nodes in the graph before doing the relationships, so they all exist. 20 | for name, note in parsed_notes.items(): 21 | line = "CREATE (" 22 | if note.tags: 23 | line += ":" + ":".join(note.tags) + " {" 24 | properties = [] 25 | for property, value in note.properties.items(): 26 | properties.append(property + ": '" + escape_cypher(str(value)) + "'") 27 | line += ", ".join(properties) 28 | line += "});" 29 | lines.append(line) 30 | 31 | notes_in_cypher = set(parsed_notes.keys()) 32 | 33 | for name, note in parsed_notes.items(): 34 | if not note.out_rels.keys(): 35 | continue 36 | match_a = "MATCH (a)" + os.linesep + "WHERE a.name = '" + escape_cypher(name) + "'" + os.linesep 37 | for trgt, rels in note.out_rels.items(): 38 | if trgt not in notes_in_cypher: 39 | lines.append("CREATE ({name:'" + escape_cypher(trgt) + "'});") 40 | notes_in_cypher.add(trgt) 41 | match_b = "MATCH (b)" + os.linesep + "WHERE b.name = '" + \ 42 | escape_cypher(trgt) + "'" + os.linesep 43 | for rel in rels: 44 | line = "CREATE (a)-[:" + rel.type + " {" 45 | properties = [] 46 | for property, value in rel.properties.items(): 47 | properties.append(property + ": '" + escape_cypher(str(value)) + "'") 48 | line += ", ".join(properties) 49 | line += "}]->(b);" 50 | lines.append(match_a + match_b + line) 51 | return lines 52 | 53 | class Cypher(Format): 54 | 55 | def parse(self, file: io.TextIOWrapper, name, parsed_notes: [Note]) -> Note: 56 | raise NotImplementedError 57 | 58 | def write(self, parsed_notes: [Note], args): 59 | lines = to_cyper(parsed_notes) 60 | with open(args.output + '.cypher', 'w', encoding='utf-8') as f: 61 | f.writelines(os.linesep.join(lines)) 62 | 63 | 64 | -------------------------------------------------------------------------------- /smdc/format/format.py: -------------------------------------------------------------------------------- 1 | import abc 2 | from smdc.note import Note 3 | import io 4 | 5 | class Format(abc.ABC): 6 | 7 | @abc.abstractmethod 8 | def parse(self, file: io.TextIOWrapper, name: str, parsed_notes: [Note], args) -> Note: 9 | ... 10 | 11 | @abc.abstractmethod 12 | def write(self, parsed_notes: [Note], args): 13 | ... -------------------------------------------------------------------------------- /smdc/format/neo4j.py: -------------------------------------------------------------------------------- 1 | from py2neo.client import ConnectionUnavailable 2 | 3 | from smdc.format import Format 4 | from smdc.note import Note 5 | import io 6 | from smdc.format.cypher import escape_cypher 7 | from smdc.parse import obsidian_url, PROP_VAULT, PROP_PATH 8 | from py2neo import Graph, Node, Relationship, Subgraph 9 | from py2neo.database.work import ClientError 10 | from pathlib import Path 11 | import tqdm 12 | 13 | CAT_DANGLING = "SMD_dangling" 14 | CAT_NO_TAGS = "SMD_no_tags" 15 | 16 | PROP_COMMUNITY = "SMD_community" 17 | INDEX_PROPS = ['name', 'aliases'] 18 | 19 | def get_community(note: Note, communities: [str], community_type: str): 20 | if community_type == "tags": 21 | if note.tags: 22 | community = escape_cypher(note.tags[0]) 23 | else: 24 | community = CAT_NO_TAGS 25 | elif community_type == "folders": 26 | community = str(Path(note.properties[PROP_PATH]).parent) 27 | if community not in communities: 28 | communities.append(community) 29 | return communities.index(community) 30 | 31 | def node_from_note(note: Note, all_tags: [str], all_communities: [str], community_type: str) -> Node: 32 | tags = [CAT_NO_TAGS] 33 | if note.tags: 34 | tags = list(map(escape_cypher, note.tags)) 35 | for tag in tags: 36 | if tag not in all_tags: 37 | all_tags.append(tag) 38 | properties = {} 39 | for property, value in note.properties.items(): 40 | properties[property] = escape_cypher(str(value)) 41 | properties[PROP_COMMUNITY] = get_community(note, all_communities, community_type) 42 | return Node(*tags, **properties) 43 | 44 | def add_rels_between_nodes(rels, src_node, trgt_node, subgraph: [Relationship]): 45 | # Adds all relations between src node and trgt node as described in rels to subgraph 46 | for rel in rels: 47 | properties = {} 48 | for property, value in rel.properties.items(): 49 | properties[property] = escape_cypher(str(value)) 50 | subgraph.append(Relationship(src_node, escape_cypher(rel.type), trgt_node, **properties)) 51 | 52 | 53 | def create_index(graph, tag): 54 | try: 55 | for prop in INDEX_PROPS: 56 | graph.run(f"CREATE INDEX index_{prop}_{tag} IF NOT EXISTS FOR (n:{tag}) ON (n.{prop})") 57 | graph.run(f"CREATE INDEX index_name_vault IF NOT EXISTS for (n:{tag}) ON (n.{prop})") 58 | except ClientError as e: 59 | print(e) 60 | print(f"Warning: Could not create index for {tag}", flush=True) 61 | 62 | def create_dangling(name:str, vault_name:str, all_communities: [str]) -> Node: 63 | n = Node(CAT_DANGLING, name=escape_cypher(name), community=all_communities.index(CAT_DANGLING), 64 | obsidian_url=escape_cypher(obsidian_url(name, vault_name))) 65 | n[PROP_VAULT] = vault_name 66 | return n 67 | 68 | class Neo4j(Format): 69 | 70 | def parse(self, file: io.TextIOWrapper, name, parsed_notes: [Note], args) -> Note: 71 | raise NotImplementedError 72 | 73 | def write(self, parsed_notes: [Note], args): 74 | try: 75 | g = Graph(password=args.password) 76 | except ClientError as e: 77 | print("invalid user credentials", flush=True) 78 | raise e 79 | except ConnectionUnavailable as e: 80 | print("no connection to db", flush=True) 81 | raise e 82 | tx = g.begin() 83 | if not args.retaindb: 84 | print("Clearing neo4j database") 85 | tx.run(f"MATCH (n) WHERE n.{PROP_VAULT}='{args.vault_name}' DETACH DELETE n") 86 | 87 | nodes = {} 88 | print("Converting nodes", flush=True) 89 | all_tags = [CAT_DANGLING, CAT_NO_TAGS] 90 | all_communities = all_tags if args.community == "tags" else [CAT_DANGLING] 91 | # First create all nodes in the graph before doing the relationships, so they all exist. 92 | for name, note in tqdm.tqdm(parsed_notes.items()): 93 | node = node_from_note(note, all_tags, all_communities, args.community) 94 | nodes[name] = node 95 | 96 | if nodes: 97 | print("Transferring nodes to graph", flush=True) 98 | tx.create(Subgraph(nodes=nodes.values())) 99 | 100 | rels_to_create = [] 101 | nodes_to_create = [] 102 | print("Creating relationships", flush=True) 103 | i = 1 104 | for name, note in tqdm.tqdm(parsed_notes.items()): 105 | if not note.out_rels.keys(): 106 | continue 107 | src_node = nodes[name] 108 | for trgt, rels in note.out_rels.items(): 109 | if trgt not in nodes: 110 | nodes[trgt] = create_dangling(trgt, args.vault_name, all_communities) 111 | nodes_to_create.append(nodes[trgt]) 112 | trgt_node = nodes[trgt] 113 | add_rels_between_nodes(rels, src_node, trgt_node, rels_to_create) 114 | # Send batches to server. Greatly speeds up conversion. 115 | if i % args.batch_size == 0: 116 | tx.create(Subgraph(nodes=nodes_to_create, relationships=rels_to_create)) 117 | rels_to_create = [] 118 | nodes_to_create = [] 119 | i += 1 120 | if rels_to_create or nodes_to_create: 121 | tx.create(Subgraph(nodes=nodes_to_create, relationships=rels_to_create)) 122 | print("Committing data", flush=True) 123 | tx.commit() 124 | 125 | print("Creating index", flush=True) 126 | # TODO: Schema inference for auto-indexing? 127 | for tag in tqdm.tqdm(all_tags): 128 | create_index(g, tag) 129 | try: 130 | g.run("CALL db.index.fulltext.drop(\"SMDnameAlias\")") 131 | except ClientError: 132 | pass 133 | try: 134 | g.run("CALL db.index.fulltext.drop(\"SMDcontent\")") 135 | except ClientError: 136 | pass 137 | if all_tags: 138 | g.run("CALL db.index.fulltext.createNodeIndex(\"SMDnameAlias\", [\"" + "\", \"".join(all_tags) + "\"], [\"name\", \"aliases\"])") 139 | if args.index_content: 140 | g.run("CALL db.index.fulltext.createNodeIndex(\"SMDcontent\", [\"" + "\", \"".join(all_tags) + "\"], [\"content\"])") 141 | return g, all_tags, all_communities 142 | 143 | 144 | -------------------------------------------------------------------------------- /smdc/format/typed_list.py: -------------------------------------------------------------------------------- 1 | from smdc.format import Format 2 | from smdc.note import Note, Relationship 3 | import io 4 | import os 5 | from smdc.format.util import parse_yaml_header, get_tags_from_line, get_wikilinks_from_line, parse_wikilink, \ 6 | PUNCTUATION, markdownToHtml 7 | 8 | 9 | class TypedList(Format): 10 | 11 | def parse_word(self, line, index, breaks=[' ', os.linesep, ',']): 12 | if index >= len(line): 13 | return index 14 | for j in range(index, len(line)): 15 | if line[j] in breaks: 16 | return j 17 | 18 | return j + 1 19 | 20 | def move_index(self, line, index): 21 | if index >= len(line): 22 | return index 23 | for j in range(index, len(line)): 24 | if line[j] != ' ': 25 | return j 26 | 27 | return j 28 | 29 | def parse(self, file: io.TextIOWrapper, name, parsed_notes: [Note], args) -> Note: 30 | line = file.readline() 31 | parsed_yaml = None 32 | # Find YAML header, or continue 33 | while line: 34 | if line.strip(): 35 | if line == '---' + os.linesep: 36 | try: 37 | parsed_yaml = parse_yaml_header(file) 38 | except Exception as e: 39 | print(e) 40 | break 41 | line = file.readline() 42 | 43 | content = [] 44 | relations = {} 45 | tags = [] 46 | while line: 47 | if line.startswith(f"{args.typed_links_prefix} ") and len(line) > 2: 48 | is_rel = True 49 | index = self.parse_word(line, 2, breaks=PUNCTUATION) 50 | type = line[2:index] 51 | if len(type) != 0: 52 | index = self.move_index(line, index + 1) 53 | words = [] 54 | while index < len(line) - 2: 55 | new_index = self.parse_word(line, index) 56 | words.append(line[index:new_index]) 57 | index = self.move_index(line, new_index + 1) 58 | year = None 59 | trgts = [] 60 | active_trgt = None 61 | for i, word in enumerate(words): 62 | if word[:2] == "[[": 63 | if active_trgt: 64 | is_rel = False 65 | break 66 | if word[-2:] == "]]": 67 | trgts.append(parse_wikilink(word[2:-2], name)) 68 | else: 69 | active_trgt = word[2:] 70 | continue 71 | elif word[-2:] == "]]": 72 | if not active_trgt: 73 | is_rel = False 74 | break 75 | trgts.append(parse_wikilink(active_trgt + " " + word[:-2], name)) 76 | active_trgt = None 77 | continue 78 | if i == 0 and type in ['publishedIn', 'at']: 79 | year = word 80 | elif active_trgt: 81 | active_trgt += " " + word 82 | else: 83 | is_rel = False 84 | break 85 | if is_rel: 86 | for trgt in trgts: 87 | properties = {} 88 | if year: 89 | properties["year"] = year 90 | rel = Relationship(type, properties) 91 | if trgt in relations: 92 | relations[trgt].append(rel) 93 | else: 94 | relations[trgt] = [rel] 95 | line = file.readline() 96 | continue 97 | content.append(line) 98 | for tag in get_tags_from_line(line): 99 | if tag not in tags: 100 | tags.append(tag) 101 | # TODO: Save aliases as Relation property 102 | for wikilink in get_wikilinks_from_line(line, name): 103 | rel = Relationship("inline", 104 | properties={"context": line, 105 | "parsedContext": markdownToHtml(line) if args.convert_markdown else ""}) 106 | if wikilink in relations: 107 | relations[wikilink].append(rel) 108 | else: 109 | relations[wikilink] = [rel] 110 | line = file.readline() 111 | raw_content = markdownToHtml("".join(content)) if args.convert_markdown else "".join(content) 112 | return Note(name, tags, raw_content, out_rels=relations, properties=parsed_yaml if parsed_yaml else {}) 113 | 114 | def write(self, file, parsed_notes: [Note]): 115 | raise NotImplementedError -------------------------------------------------------------------------------- /smdc/format/util.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | import os 3 | import markdown 4 | from markdown.extensions import Extension 5 | from markdown.preprocessors import Preprocessor 6 | import re 7 | 8 | def parse_yaml_header(file): 9 | lines = [] 10 | line = file.readline() 11 | while line != "---" + os.linesep and line: 12 | lines.append(line) 13 | line = file.readline() 14 | 15 | return yaml.safe_load("".join(lines)) 16 | 17 | 18 | class HashtagExtension(Extension): 19 | # Code based on https://github.com/Kongaloosh/python-markdown-hashtag-extension/blob/master/markdown_hashtags/markdown_hashtag_extension.py 20 | # Used to extract tags from markdown 21 | def extendMarkdown(self, md): 22 | """ Add FencedBlockPreprocessor to the Markdown instance. """ 23 | md.registerExtension(self) 24 | md.preprocessors.register(HashtagPreprocessor(md), 'hashtag', 10) # After HTML Pre Processor 25 | 26 | 27 | class HashtagPreprocessor(Preprocessor): 28 | ALBUM_GROUP_RE = re.compile( 29 | r"""(?:(?<=\s)|^)#(\w*[A-Za-z_]+\w*)""" 30 | ) 31 | 32 | def __init__(self, md): 33 | super(HashtagPreprocessor, self).__init__(md) 34 | 35 | def run(self, lines): 36 | """ Match and store Fenced Code Blocks in the HtmlStash. """ 37 | HASHTAG_WRAP = ''' #{0}''' 38 | text = "\n".join(lines) 39 | while True: 40 | hashtag = '' 41 | m = self.ALBUM_GROUP_RE.search(text) 42 | if m: 43 | hashtag += HASHTAG_WRAP.format(m.group()[1:]) 44 | placeholder = self.markdown.htmlStash.store(hashtag) 45 | text = '%s %s %s' % (text[:m.start()], placeholder, text[m.end():]) 46 | else: 47 | break 48 | return text.split('\n') 49 | 50 | 51 | # def makeExtension(*args, **kwargs): 52 | # return HashtagExtension(*args, **kwargs) 53 | 54 | def markdownToHtml(md_text): 55 | return markdown.markdown(md_text, extensions=['mdx_wikilink_plus','fenced_code', 56 | 'footnotes', 'tables', HashtagExtension()], 57 | extension_configs={ 58 | 'mdx_wikilink_plus': { 59 | 'html_class': 'internal-link', 60 | 'url_whitespace': ' ' 61 | } 62 | }) 63 | 64 | PUNCTUATION = ["#", "$", "!", ".", ",", "?", "/", ":", ";", "`", " ", "-", "+", "=", "|", os.linesep] + [str(i) for i in range(0, 10)] 65 | 66 | 67 | def get_tags_from_line(line) -> [str]: 68 | pos_tags = [i for i, char in enumerate(line) if char == '#'] 69 | tags = [] 70 | for i in pos_tags: 71 | if i == 0 or line[i - 1] == ' ': 72 | index = next((index for index, c in enumerate(line[i+1:]) if c in PUNCTUATION), -1) 73 | if index == -1: 74 | tags.append(line[i+1:]) 75 | else: 76 | tag = line[i + 1:index + i + 1] 77 | if len(tag) > 0: 78 | tags.append(tag) 79 | return tags 80 | 81 | def parse_wikilink(between_brackets:str, note_title: str) -> str: 82 | first_arg = between_brackets.split("|")[0] 83 | if len(first_arg) != 0: 84 | title = first_arg.split("#")[0] 85 | if len(title) == 0: 86 | # Wikilinks like [[#header]] refer to itself 87 | return note_title 88 | else: 89 | # Wikilinks like [[title#header]] 90 | return title 91 | return "" 92 | 93 | def get_wikilinks_from_line(line, note_title) -> [str]: 94 | result = re.findall('\[\[(.*?)\]\]', line) 95 | if result: 96 | r = [] 97 | for wikilink in result: 98 | title = parse_wikilink(wikilink, note_title) 99 | if title: 100 | r.append(title) 101 | return r 102 | return [] 103 | 104 | def escape_quotes(string) -> str: 105 | r1 = string.replace("\\\'", "\\\\\'") 106 | r1 = r1.replace("'", "\\\'") 107 | return r1.replace('\"', "\\\"") 108 | -------------------------------------------------------------------------------- /smdc/note.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | class Relationship: 4 | def __init__(self, type: str, properties={}): 5 | self.type = type 6 | self.properties = properties 7 | 8 | def __str__(self): 9 | return self.type + self.properties.__str__() 10 | 11 | 12 | class Note: 13 | 14 | def __init__(self, name:str, tags: [str], content:str, properties={}, out_rels={}, in_rels={}): 15 | self.tags = tags 16 | self.out_rels = out_rels 17 | self.in_rels = in_rels 18 | self.properties = properties 19 | self.properties['name'] = name 20 | self.properties['content'] = content 21 | 22 | 23 | def add_out_rel(self, to:str, rel:Relationship): 24 | if to in self.out_rels: 25 | self.out_rels[to].append(rel) 26 | else: 27 | self.out_rels[to] = [rel] 28 | 29 | def add_in_rel(self, src: str, rel: Relationship): 30 | if src in self.in_rels: 31 | self.in_rels[src].append(rel) 32 | else: 33 | self.in_rels[src] = [rel] 34 | 35 | @property 36 | def name(self): 37 | return self.properties['name'] 38 | 39 | @property 40 | def content(self): 41 | return self.properties['content'] 42 | 43 | def __str__(self): 44 | return self.name + os.linesep + self.tags.__str__() + os.linesep + self.content + os.linesep + self.out_rels.__str__() 45 | -------------------------------------------------------------------------------- /smdc/parse.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from smdc.format import Format 3 | from tqdm import tqdm 4 | import os 5 | from urllib.parse import quote 6 | 7 | PROP_OBSIDIAN_URL = "obsidian_url" 8 | PROP_PATH = "SMD_path" 9 | PROP_VAULT = "SMD_vault" 10 | 11 | def note_name(path, extension=".md"): 12 | return os.path.basename(path)[:-len(extension)] 13 | 14 | def obsidian_url(name:str, vault:str) -> str: 15 | return "obsidian://open?vault=" + quote(vault) + "&file=" + quote(name) + ".md" 16 | 17 | def parse_note(format: Format, note_path, args): 18 | name = note_name(note_path) 19 | with open(Path(note_path), 'r', encoding='utf-8') as f: 20 | # TODO: This isn't passing parsed notes right now. But this isn't currently used. 21 | note = format.parse(f, name, [], args) 22 | # Assign automatic properties for handling data and plugins 23 | note.properties[PROP_OBSIDIAN_URL] = obsidian_url(name, args.vault_name) 24 | note.properties[PROP_PATH] = note_path 25 | note.properties[PROP_VAULT] = args.vault_name 26 | return note 27 | 28 | def parse_folder(format: Format, args): 29 | notes_path = args.input 30 | note_extension = args.extension 31 | vault_name = args.vault_name 32 | if args.r: 33 | iterate = Path(notes_path).rglob("*" + note_extension) 34 | else: 35 | iterate = Path(notes_path).glob("*" + note_extension) 36 | all_files = list(iterate) 37 | parsed_notes = {} 38 | print("Parsing notes", flush=True) 39 | for path in tqdm(all_files): 40 | with open(path, mode='r', encoding='utf-8') as f: 41 | name = note_name(path, note_extension) 42 | try: 43 | note = format.parse(f, name, parsed_notes, args) 44 | note.properties[PROP_OBSIDIAN_URL] = obsidian_url(name, vault_name) 45 | note.properties[PROP_PATH] = path 46 | note.properties[PROP_VAULT] = vault_name 47 | parsed_notes[name] = note 48 | except Exception as e: 49 | print(e) 50 | print("Exception raised during parsing " + str(path) + ". Skipping this note! Please report this.", flush=True) 51 | print("Finished parsing notes", flush=True) 52 | return parsed_notes 53 | 54 | -------------------------------------------------------------------------------- /smdc/stream.py: -------------------------------------------------------------------------------- 1 | from smdc import server_args, convert, parse_note, FORMAT_TYPES, Note, note_name, obsidian_url 2 | from watchdog.events import PatternMatchingEventHandler 3 | from watchdog.observers import Observer 4 | import time 5 | from py2neo import Node, Subgraph, Relationship, Graph 6 | from py2neo.data import walk 7 | from smdc.format.neo4j import node_from_note, add_rels_between_nodes, CAT_DANGLING, CAT_NO_TAGS, create_index, \ 8 | create_dangling, PROP_COMMUNITY, get_community 9 | from smdc.format.cypher import escape_cypher 10 | from pathlib import Path 11 | import smdc 12 | from smdc.parse import PROP_VAULT, PROP_PATH 13 | 14 | 15 | def wrapper(fn): 16 | def _return(event): 17 | try: 18 | fn(event) 19 | except BaseException as e: 20 | print(e) 21 | return _return 22 | 23 | 24 | 25 | class SMDSEventHandler(): 26 | def __init__(self, graph: Graph, tags: [str], communities: [str], args): 27 | self.graph = graph 28 | self.nodes = graph.nodes 29 | self.relationships = graph.relationships 30 | self.args = args 31 | self.input_format = FORMAT_TYPES[args.input_format] 32 | self.vault_name = args.vault_name 33 | self.index_content = args.index_content 34 | self.tags = tags 35 | self.communities = communities 36 | 37 | def _clear_outgoing(self, node: Node): 38 | rels = self.relationships.match([node, None]) 39 | if len(rels) > 0: 40 | self.graph.separate(Subgraph(relationships=rels)) 41 | 42 | def _process_node_on_graph(self, note: Note): 43 | if smdc.DEBUG: 44 | print(note, flush=True) 45 | in_graph = self.nodes.match(**{'name': note.name, PROP_VAULT: self.vault_name}) 46 | if len(in_graph) == 0: 47 | # Create new node 48 | node = node_from_note(note, self.tags, self.communities, self.args.community) 49 | if smdc.DEBUG: 50 | print("creating") 51 | print(node, flush=True) 52 | self.graph.create(node) 53 | return 54 | # Update 55 | node = in_graph.first() 56 | if smdc.DEBUG: 57 | print("updating") 58 | print(node, flush=True) 59 | # Update labels 60 | node.clear_labels() 61 | note_tags = [CAT_NO_TAGS] 62 | if note.tags: 63 | note_tags = list(map(escape_cypher, note.tags)) 64 | node.update_labels(note_tags) 65 | for tag in note_tags: 66 | if tag not in self.tags: 67 | create_index(self.graph, tag) 68 | self.tags.append(tag) 69 | # Update properties 70 | node.clear() 71 | escaped_properties = {} 72 | for key, value in note.properties.items(): 73 | escaped_properties[key] = escape_cypher(str(value)) 74 | escaped_properties[PROP_COMMUNITY] = get_community(note, self.communities, self.args.community) 75 | node.update(escaped_properties) 76 | self.graph.push(node) 77 | 78 | # # Delete active relations 79 | # self._clear_outgoing(node) 80 | 81 | # Insert up-to-date relations 82 | rels_to_create = [] 83 | nodes_to_create = [] 84 | not_matched_active_rels = list(map(lambda r: r.identity, self.relationships.match([node, None]))) 85 | for trgt, rels in note.out_rels.items(): 86 | trgt_node = self.nodes.match(**{'name': trgt, PROP_VAULT: self.vault_name}) 87 | if len(trgt_node) == 0: 88 | trgt_node = create_dangling(trgt, self.vault_name, self.tags) 89 | nodes_to_create.append(trgt_node) 90 | else: 91 | trgt_node = trgt_node.first() 92 | # Possibly refactor this with 93 | for i, rel in enumerate(rels): 94 | properties = {} 95 | for property, value in rel.properties.items(): 96 | properties[property] = escape_cypher(str(value)) 97 | rel_type = escape_cypher(rel.type) 98 | found_rel = False 99 | active_rels = list(filter(lambda r: r.identity in not_matched_active_rels, 100 | self.relationships.match([node, None]))) 101 | # Update instead of removing makes sure the relationship has a persistent id 102 | for active_rel in active_rels: 103 | walks = list(walk(active_rel)) 104 | if type(active_rel).__name__ == rel_type and walks[2] == trgt_node: 105 | # Maybe this can leave dangling properties? But that'' an edge case. Not sure how to clear properties. 106 | active_rel.clear() 107 | active_rel.update(properties) 108 | self.graph.push(active_rel) 109 | found_rel = True 110 | not_matched_active_rels.remove(active_rel.identity) 111 | break 112 | if not found_rel: 113 | rels_to_create.append(Relationship(node, rel_type, trgt_node, **properties)) 114 | 115 | if rels_to_create or nodes_to_create: 116 | self.graph.create(Subgraph(nodes=nodes_to_create, relationships=rels_to_create)) 117 | if len(not_matched_active_rels) > 0: 118 | rels = list(filter(lambda r: r.identity in not_matched_active_rels, 119 | self.relationships.match([node, None]))) 120 | if len(rels) > 0: 121 | self.graph.separate(Subgraph(relationships=rels)) 122 | print("onSMDRelDeletedEvent/" + "/".join(map(str, not_matched_active_rels))) 123 | 124 | def _print_debug_rel(self, node, relationship): 125 | print(len(list(self.relationships.match([node, None])))) 126 | l = list(walk(relationship)) 127 | print(l[0].identity, l[0]["name"]) 128 | print(l[1]) 129 | print(l[2].identity, l[2]["name"]) 130 | 131 | def on_created(self): 132 | def _on_created(event): 133 | if smdc.DEBUG: 134 | print("On created", event.src_path, flush=True) 135 | # TODO: What if this name already exists in the vault? Does it make sense to override old data? 136 | note = parse_note(self.input_format, event.src_path, self.args) 137 | self._process_node_on_graph(note) 138 | return wrapper(_on_created) 139 | 140 | def on_deleted(self): 141 | def _on_deleted(event): 142 | if smdc.DEBUG: 143 | print("On deleted", event.src_path, flush=True) 144 | name = note_name(event.src_path) 145 | node = self.nodes.match(name=name).first() 146 | node_id = node.identity 147 | in_rels = self.relationships.match([None, node]) 148 | if len(in_rels) > 0: 149 | # If there are still active incoming links, keep the node as a reference 150 | node.clear() 151 | node.clear_labels() 152 | node.add_label(CAT_DANGLING) 153 | node.name = escape_cypher(name) 154 | node.obsidian_url = escape_cypher(obsidian_url(name, self.vault_name)) 155 | self._clear_outgoing(node) 156 | else: 157 | self.graph.delete(node) 158 | print(f"onSMDDeletedEvent/{node_id}", flush=True) 159 | return wrapper(_on_deleted) 160 | 161 | def on_modified(self): 162 | def _on_modified(event): 163 | if smdc.DEBUG: 164 | print("On modified", event.src_path, flush=True) 165 | note = parse_note(self.input_format, event.src_path, self.args) 166 | self._process_node_on_graph(note) 167 | print(f"onSMDModifyEvent/{note.name}", flush=True) 168 | return wrapper(_on_modified) 169 | 170 | def on_moved(self): 171 | def _on_moved(event): 172 | if smdc.DEBUG: 173 | print("On moved", event.src_path, event.dest_path, flush=True) 174 | old_name = note_name(event.src_path) 175 | node = self.nodes.match(name=old_name).first() 176 | new_name = note_name(event.dest_path) 177 | # TODO: What if this name already exists in the vault? 178 | node['name'] = new_name 179 | node['obsidian_url'] = obsidian_url(new_name, self.vault_name) 180 | node[PROP_PATH] = event.dest_path 181 | self.graph.push(node) 182 | print(f"onSMDMovedEvent/{old_name}/{new_name}", flush=True) 183 | return wrapper(_on_moved) 184 | 185 | def stream(graph, tags, communities, args): 186 | # Code credit: http://thepythoncorner.com/dev/how-to-create-a-watchdog-in-python-to-look-for-filesystem-changes/ 187 | event_handler = PatternMatchingEventHandler(patterns=["*.md"], case_sensitive=True) 188 | 189 | smds_event_handler = SMDSEventHandler(graph, tags, communities, args) 190 | event_handler.on_created = smds_event_handler.on_created() 191 | event_handler.on_deleted = smds_event_handler.on_deleted() 192 | event_handler.on_modified = smds_event_handler.on_modified() 193 | event_handler.on_moved = smds_event_handler.on_moved() 194 | 195 | observer = Observer() 196 | path = Path(args.input) 197 | if smdc.DEBUG: 198 | print(path.absolute(), flush=True) 199 | observer.schedule(event_handler, path=Path(args.input), recursive=args.r) 200 | 201 | observer.start() 202 | 203 | try: 204 | print("Stream is active!", flush=True) 205 | import sys 206 | sys.stdout.flush() 207 | while True: 208 | # TODO: Catch when connection to neo4j server is down. 209 | time.sleep(1) 210 | except KeyboardInterrupt: 211 | observer.stop() 212 | observer.join() 213 | 214 | def main(): 215 | args = server_args() 216 | args.output_format = 'neo4j' 217 | # Initialize the database 218 | graph, tags, communities = convert(args) 219 | # return 220 | # Start the server 221 | stream(graph, tags, communities, args) 222 | 223 | 224 | if __name__ == "__main__": 225 | main() 226 | --------------------------------------------------------------------------------