Repository: zotero/translation-server Branch: master Commit: d88a8d538445 Files: 56 Total size: 183.8 KB Directory structure: gitextract_c6fz8f0f/ ├── .dockerignore ├── .eslintignore ├── .eslintrc ├── .github/ │ └── workflows/ │ └── ci.yml ├── .gitignore ├── .gitmodules ├── COPYING ├── Dockerfile ├── README.md ├── config/ │ ├── custom-environment-variables.json │ ├── default.json5 │ └── test.json ├── docker-entrypoint.sh ├── lambda_config.env-sample ├── lambda_deploy ├── lambda_local_test ├── lambda_local_test_event.json ├── lambda_package ├── lambda_template.yaml.j2 ├── package.json ├── src/ │ ├── args.js │ ├── cors.js │ ├── debug.js │ ├── exportEndpoint.js │ ├── formats.js │ ├── http.js │ ├── importEndpoint.js │ ├── lambda.js │ ├── proxy.js │ ├── searchEndpoint.js │ ├── server.js │ ├── testEndpoint.js │ ├── textSearch.js │ ├── translation/ │ │ ├── sandboxManager.js │ │ ├── translate.js │ │ └── translate_item.js │ ├── translators.js │ ├── utilities.js │ ├── webEndpoint.js │ ├── webSession.js │ └── zotero.js ├── test/ │ ├── data/ │ │ ├── bibtex_response.xml │ │ ├── loc_book1_response.xml │ │ └── pubmed_article1_response.xml │ ├── export_test.js │ ├── import_test.js │ ├── mocha.opts │ ├── search_test.js │ ├── setup.js │ ├── testTranslators/ │ │ └── testTranslators.js │ └── web_test.js ├── translate_export ├── translate_search ├── translate_url ├── translate_url_multiple └── translate_url_single ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ .git/ modules/translators/ Dockerfile docker-compose.* npm-debug.log node_modules/ ================================================ FILE: .eslintignore ================================================ connectorTypeSchemaData.js modules src/rdf/* ================================================ FILE: .eslintrc ================================================ { "env": { "es6": true, "node": true, "mocha": true }, "globals": { "Zotero": false }, "extends": [ "@zotero" ], "parserOptions": { "ecmaVersion": 2018 }, "rules": {} } ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: [push, pull_request] jobs: build: name: Test runs-on: ubuntu-latest timeout-minutes: 5 strategy: matrix: node-version: [20, 22, 24, 25] steps: - uses: actions/checkout@v2 - run: git submodule update --init --depth=1 modules/translate - run: git submodule update --init --depth=1 modules/utilities - run: git submodule update --init --depth=1 modules/zotero-schema - run: git submodule update --init --depth=1 modules/translators - name: Install Node ${{ matrix.node-version }} uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} - run: npm ci - run: npm test ================================================ FILE: .gitignore ================================================ node_modules config/production.json config/dev.json config/local.json lambda_config*.env ================================================ FILE: .gitmodules ================================================ [submodule "modules/translators"] path = modules/translators url = https://github.com/zotero/translators [submodule "modules/utilities"] path = modules/utilities url = https://github.com/zotero/utilities.git [submodule "modules/translate"] path = modules/translate url = https://github.com/zotero/translate.git [submodule "modules/zotero-schema"] path = modules/zotero-schema url = https://github.com/zotero/zotero-schema.git ================================================ FILE: COPYING ================================================ Zotero is Copyright © 2018-2021 Corporation for Digital Scholarship, Vienna, Virginia, USA http://digitalscholar.org Copyright © 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Roy Rosenzweig Center for History and New Media, George Mason University, Fairfax, Virginia, USA http://zotero.org The Corporation for Digital Scholarship distributes the Zotero source code under the GNU Affero General Public License, version 3 (AGPLv3). The full text of this license is given below. The Zotero name is a registered trademark of the Corporation for Digital Scholarship. See http://zotero.org/trademark for more information. Third-party copyright in this distribution is noted where applicable. All rights not expressly granted are reserved. ========================================================================= GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: Dockerfile ================================================ FROM node:lts # install npm dependencies WORKDIR /app COPY ./package.json /app/package.json RUN npm install # copy the code # (after dependencies installation) COPY . /app # Cloning zotero translators repository RUN git clone --depth=1 https://github.com/zotero/translators.git /app/modules/translators/ # run the application EXPOSE 1969 ENTRYPOINT [ "./docker-entrypoint.sh" ] ================================================ FILE: README.md ================================================ # Zotero Translation Server [![Build Status](https://img.shields.io/github/actions/workflow/status/zotero/translation-server/ci.yml?branch=master)](https://github.com/zotero/translation-server/actions) The Zotero translation server lets you use [Zotero translators](https://www.zotero.org/support/translators) without the Zotero client. ## Installation ### Running via Docker The easiest way to run a local instance of translation-server is via Docker. ``` docker pull zotero/translation-server docker run -d -p 1969:1969 --rm --name translation-server zotero/translation-server ``` This will pull the latest image [from Docker Hub](https://registry.hub.docker.com/r/zotero/translation-server) and run it as a background process on port 1969. Use `docker kill translation-server` to stop it. ### Running from source First, fetch the source code and install Node dependencies: 1. `git clone --recurse-submodules https://github.com/zotero/translation-server` 1. `cd translation-server` 1. `npm install` Once you've set up a local copy of the repo, you can run the server in various ways: #### Node.js `npm start` #### Docker (development) Build from the local repo and run in foreground: ``` docker build -t translation-server . docker run -ti -p 1969:1969 --rm translation-server ``` #### AWS Lambda translation-server can also run on AWS Lambda and be accessed through API Gateway. You will need the [AWS SAM CLI](https://docs.aws.amazon.com/lambda/latest/dg/sam-cli-requirements.html) to deploy the server. Copy and configure config file: ``` cp lambda_config.env-sample lambda_config.env ``` Test locally: ``` ./lambda_local_test lambda_config.env ``` Deploy: ``` ./lambda_deploy lambda_config.env ``` You can view the API Gateway endpoint in the Outputs section of the console output. ## User-Agent By default, translation-server uses a standard Chrome `User-Agent` string to maximize compatibility. This is fine for personal usage, but for a deployed service, it’s polite to customize `User-Agent` so that sites can identify requests and contact you in case of abuse. You can do this by setting the `USER_AGENT` environment variable: `USER_AGENT='my-custom-translation-server/2.0 (me@example.com)' npm start` If you find that regular requests are being blocked with a fully custom user-agent string, you can also add an identifier and contact information to the end of a standard browser UA string: ``` export USER_AGENT='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 my-custom-translation-server/2.0 (me@example.com)' npm start ``` ## Proxy Support You can configure translation-server to use a proxy server by setting the `HTTP_PROXY` and `HTTPS_PROXY` environment variables: `HTTP_PROXY=http://proxy.example.com:8080 HTTPS_PROXY=http://proxy.example.com:8080 npm start` If your proxy server uses a self-signed certificate, you can set `NODE_TLS_REJECT_UNAUTHORIZED=0` to force Node to ignore certificate errors. It’s also possible to opt out of proxying for specific hosts by using the `NO_PROXY` variable. See the [Node `request` library documentation](https://github.com/request/request#controlling-proxy-behaviour-using-environment-variables) for more details. ## Running tests `npm test` ## Endpoints ### Web Translation #### Retrieve metadata for a webpage: ``` $ curl -d 'https://www.nytimes.com/2018/06/11/technology/net-neutrality-repeal.html' \ -H 'Content-Type: text/plain' http://127.0.0.1:1969/web ``` Returns an array of translated items in Zotero API JSON format #### Retrieve metadata for a webpage with multiple results: ``` $ curl -d 'https://www.ncbi.nlm.nih.gov/pubmed/?term=crispr' \ -H 'Content-Type: text/plain' http://127.0.0.1:1969/web ``` Returns `300 Multiple Choices` with a JSON object: ``` { "url": "https://www.ncbi.nlm.nih.gov/pubmed/?term=crispr", "session": "9y5s0EW6m5GgLm0", "items": { "u30044970": { "title": "RNA Binding and HEPN-Nuclease Activation Are Decoupled in CRISPR-Cas13a." }, "u30044923": { "title": "Knockout of tnni1b in zebrafish causes defects in atrioventricular valve development via the inhibition of the myocardial wnt signaling pathway." }, // more results } } ``` To make a selection, delete unwanted results from the items object and POST the returned data back to the server as `application/json`. ### Search Translation Retrieve metadata from an identifier (DOI, ISBN, PMID, arXiv ID): ``` $ curl -d 10.2307/4486062 -H 'Content-Type: text/plain' http://127.0.0.1:1969/search ``` ### Export Translation Convert items in Zotero API JSON format to a [supported export format](https://github.com/zotero/translation-server/blob/master/src/formats.js) (RIS, BibTeX, etc.): ``` $ curl -d @items.json -H 'Content-Type: application/json' 'http://127.0.0.1:1969/export?format=bibtex' ``` ### Import Translation Convert items in any [import format](https://www.zotero.org/support/kb/importing_standardized_formats) to the Zotero API JSON format: ``` $ curl --data-binary @data.bib -H 'Content-Type: text/plain' http://127.0.0.1:1969/import ================================================ FILE: config/custom-environment-variables.json ================================================ { "translatorsDirectory": "TRANSLATORS_DIR" } ================================================ FILE: config/default.json5 ================================================ { "allowedOrigins": [], // CORS "blacklistedDomains": [], "deproxifyURLs": false, // Automatically try deproxified versions of URLs "identifierSearchLambda": "", // Identifier search Lambda function for text search "port": 1969, "host": "0.0.0.0", // host to listen on "httpMaxResponseSize": 10, // Max size of requested response to load; triggers 400 ResponseSize error when exceeded "textSearchTimeout": 5, "translators": { "CrossrefREST.email": "" // Pass an email to Crossref REST API to utilize the faster servers pool }, "trustProxyHeaders": false, // Trust X-Forwarded-For when logging requests "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36", "translatorsDirectory": "./modules/translators" } ================================================ FILE: config/test.json ================================================ { "testPort": 3456, "identifierSearchURL": "http://identifier-search/search?q=" } ================================================ FILE: docker-entrypoint.sh ================================================ #!/bin/bash # will be deprecated when https://github.com/zotero/translation-server/issues/1 will be released echo "-> Updating zotero translators" cd /app/modules/translators/ git pull --ff-only origin master cd /app/ exec npm start ================================================ FILE: lambda_config.env-sample ================================================ node_env=production deployment_bucket_name=deployment stack_name=TranslationServer main_function_name=translation-server identifier_search_function_name=identifier-search ================================================ FILE: lambda_deploy ================================================ #!/bin/bash -e dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" if [ -z $1 ]; then echo "Usage: $0 config.env" >&2 exit 1 fi set -a . "$dir/$1" set +a ./lambda_package j2 "$dir/lambda_template.yaml.j2" > "$dir/package/template.yaml" sam package --template-file "$dir/package/template.yaml" --s3-bucket $deployment_bucket_name --output-template-file "$dir/package/package.yaml" aws cloudformation deploy --template-file "$dir/package/package.yaml" --stack-name $stack_name --capabilities CAPABILITY_IAM aws cloudformation describe-stacks --stack-name $stack_name rm -rf "$dir/package" ================================================ FILE: lambda_local_test ================================================ #!/bin/bash -e dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" if [ -z $1 ]; then echo "Usage: $0 config.env" >&2 exit 1 fi set -a . "$dir/$1" set +a j2 "$dir/lambda_template.yaml.j2" > "$dir/lambda_template.yaml" sam local invoke Lambda --template "$dir/lambda_template.yaml" -e lambda_local_test_event.json rm "$dir/lambda_template.yaml" ================================================ FILE: lambda_local_test_event.json ================================================ { "body": "https://www.nytimes.com/2018/06/11/technology/net-neutrality-repeal.html", "resource": "/{proxy+}", "requestContext": { "resourceId": "123456", "apiId": "1234567890", "resourcePath": "/{proxy+}", "httpMethod": "POST", "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", "accountId": "123456789012", "identity": { "apiKey": null, "userArn": null, "cognitoAuthenticationType": null, "caller": null, "userAgent": "Custom User Agent String", "user": null, "cognitoIdentityPoolId": null, "cognitoIdentityId": null, "cognitoAuthenticationProvider": null, "sourceIp": "127.0.0.1", "accountId": null }, "stage": "prod" }, "queryStringParameters": { }, "headers": { "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", "Accept-Language": "en-US,en;q=0.8", "CloudFront-Is-Desktop-Viewer": "true", "CloudFront-Is-SmartTV-Viewer": "false", "CloudFront-Is-Mobile-Viewer": "false", "X-Forwarded-For": "127.0.0.1, 127.0.0.2", "CloudFront-Viewer-Country": "US", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Upgrade-Insecure-Requests": "1", "X-Forwarded-Port": "443", "Host": "1234567890.execute-api.us-east-1.amazonaws.com", "X-Forwarded-Proto": "https", "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", "CloudFront-Is-Tablet-Viewer": "false", "Cache-Control": "max-age=0", "User-Agent": "Custom User Agent String", "CloudFront-Forwarded-Proto": "https", "Accept-Encoding": "gzip, deflate, sdch", "Content-Type": "text/plain" }, "pathParameters": { "proxy": "web" }, "httpMethod": "POST", "stageVariables": { "baz": "qux" }, "path": "/web" } ================================================ FILE: lambda_package ================================================ rm -rf package mkdir package # Skip files that aren't required i.e. ".git" cp -R config package/ cp -R modules package/ cp -R node_modules package/ cp -R src package/ # Remove broken symlinks because "sam package" complains find -L package/ -maxdepth 10 -type l -delete ================================================ FILE: lambda_template.yaml.j2 ================================================ AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Description: >- Lambda-based translation-server to run Zotero translators ({{ node_env }}) Resources: # Lambda function Lambda: Type: 'AWS::Serverless::Function' Properties: FunctionName: {{ main_function_name }} CodeUri: ./ Handler: src/lambda.handler Runtime: nodejs14.x MemorySize: 2048 Timeout: 30 Policies: - LambdaInvokePolicy: FunctionName: {{ identifier_search_function_name }} Events: # API Gateway PostAPI: Type: Api Properties: # Proxy all POST requests to Lambda function Path: /{proxy+} Method: post OptionsAPI: Type: Api Properties: # Proxy all OPTIONS requests to Lambda function Path: /{proxy+} Method: options Environment: Variables: NODE_ENV: {{ node_env }} Outputs: API: Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/" ================================================ FILE: package.json ================================================ { "name": "translation-server", "version": "2.0.5", "description": "Zotero translation server", "license": "AGPL-3.0-only", "main": "index.js", "repository": { "type": "git", "url": "git+https://github.com/zotero/translation-server-v2" }, "dependencies": { "aws-sdk": "^2.1692.0", "config": "^4.1.1", "iconv-lite": "^0.4.24", "jsdom": "^29.0.1", "koa": "^2.15.3", "koa-bodyparser": "^4.4.1", "koa-route": "^3.2.0", "md5": "^2.3.0", "request": "^2.88.2", "request-promise-native": "^1.0.9", "serverless-http": "^2.7.0", "w3c-xmlserializer": "^5.0.0", "whatwg-encoding": "^3.1.1", "wicked-good-xpath": "git+https://git@github.com/zotero/wicked-good-xpath.git#1b88459", "xregexp": "^5.1.2", "yargs": "^12.0.2" }, "devDependencies": { "@zotero/eslint-config": "^1.0.8", "chai": "^4.1.2", "eslint": "^5.16.0", "mocha": "^5.2.0", "sinon": "^6.1.4", "supertest": "^3.1.0" }, "scripts": { "start": "node src/server.js", "start:debug": "node --inspect src/server.js", "test": "NODE_ENV=test ALLOW_CONFIG_MUTATIONS=1 node_modules/.bin/mocha test/*_test.js", "test:import": "DEBUG_LEVEL=0 NODE_ENV=test ALLOW_CONFIG_MUTATIONS=1 node_modules/.bin/mocha test/import_test.js" } } ================================================ FILE: src/args.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ 'use strict'; const { basename } = require('path'); const yargs = require('yargs'); module.exports = yargs .usage(`Usage: ${basename(process.argv[0])} [options]`) .wrap(78) .env('ZOTERO') .option('translator-tester', { alias: 't', type: 'boolean', default: false, describe: 'Serve the translator tester at /translatorTester' }) .help('help'); ================================================ FILE: src/cors.js ================================================ const config = require('config'); module.exports = async (ctx, next) => { headersSet = {}; function set(key, value) { ctx.set(key, value); headersSet[key] = value; } if (ctx.headers.origin) { let allowedOrigins = config.get('allowedOrigins').filter(x => x); let allAllowed = allowedOrigins.includes('*'); if (allAllowed || allowedOrigins.includes(ctx.headers.origin)) { set("Access-Control-Allow-Origin", allAllowed ? '*' : ctx.headers.origin); set("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); set("Access-Control-Allow-Headers", "Content-Type"); set("Access-Control-Expose-Headers", "Link"); } // Force a 200 on API Gateway ctx.body = ''; } try { await next(); } catch (e) { e.headers = Object.assign({}, e.headers, headersSet); throw e; } }; ================================================ FILE: src/debug.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ Zotero.Utilities = require('./utilities'); Zotero.Debug = new function () { var _console, _stackTrace, _store, _level, _lastTime, _output = []; var _slowTime = false; var _colorOutput = false; var _consoleViewer = false; var _consoleViewerQueue = []; var _consoleViewerListener; /** * Initialize debug logging */ this.init = function (enabled=true) { this.enabled = enabled; } this.log = function (message, level, maxDepth, stack) { if (!this.enabled) { return; } if (typeof message != 'string') { message = Zotero.Utilities.varDump(message, 0, maxDepth); } if (!level) { level = 3; } // If level above debug.level value, don't display if (level > _level) { return; } var deltaStr = ''; var deltaStrStore = ''; var delta = 0; var d = new Date(); if (_lastTime) { delta = d - _lastTime; } _lastTime = d; var slowPrefix = ""; var slowSuffix = ""; if (_slowTime && delta > _slowTime) { slowPrefix = "\x1b[31;40m"; slowSuffix = "\x1b[0m"; } delta = ("" + delta).padStart(7, "0"); deltaStr = "(" + slowPrefix + "+" + delta + slowSuffix + ")"; if (_store) { deltaStrStore = "(+" + delta + ")"; } if (stack === true) { stack = new Error().stack.substr('Error'.length); } if (stack) { message += '\n' + this.stackToString(stack); } var output = '(' + level + ')' + deltaStr + ': ' + message; console.log(output+"\n"); if (_store) { if (Math.random() < 1/1000) { // Remove initial lines if over limit var overage = this.count() - Zotero.Prefs.get('debug.store.limit'); if (overage > 0) { _output.splice(0, Math.abs(overage)); } } _output.push('(' + level + ')' + deltaStrStore + ': ' + message); } } this.get = Zotero.Promise.method(function(maxChars, maxLineLength) { var output = _output; var total = output.length; if (total == 0) { return ""; } if (maxLineLength) { for (var i=0, len=output.length; i maxLineLength) { output[i] = Zotero.Utilities.ellipsize(output[i], maxLineLength, false, true); } } } output = output.join('\n\n'); if (maxChars) { output = output.substr(maxChars * -1); // Cut at two newlines let matches = output.match(/^[\n]*\n\n/); if (matches) { output = output.substr(matches[0].length); } } return output; }); this.setStore = function (enable) { if (enable) { this.clear(); } _store = enable; this.updateEnabled(); this.storing = _store; } this.updateEnabled = function () { this.enabled = _console || _consoleViewer || _store; }; this.count = function () { return _output.length; } this.clear = function () { _output = []; } /** * Format a stack trace for output in the same way that Error.stack does * @param {Components.stack} stack * @param {Integer} [lines=5] Number of lines to format */ this.stackToString = function (stack, lines) { if (!lines) lines = 5; var str = ''; while(stack && lines--) { str += '\n ' + (stack.name || '') + '@' + stack.filename + ':' + stack.lineNumber; stack = stack.caller; } return this.filterStack(str).substr(1); }; /** * Strip Bluebird lines from a stack trace * * @param {String} stack */ this.filterStack = function (stack) { return stack.split(/\n/).filter(line => line.indexOf('zotero/bluebird') == -1).join('\n'); } } module.exports = Zotero.Debug; ================================================ FILE: src/exportEndpoint.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Corporation for Digital Scholarship Vienna, Virginia, USA https://www.zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const config = require('config'); const { FORMATS, CONTENT_TYPES } = require('./formats'); const Translate = require('./translation/translate'); var ExportEndpoint = module.exports = { handle: async function (ctx, next) { ctx.assert(ctx.is('json'), 415); var items = ctx.request.body; if (!items) { ctx.throw(400, "POST data not provided"); } var query = ctx.request.query; var translatorID; if (!query.format || !(translatorID = FORMATS[query.format])) { ctx.throw(400, "Invalid format specified"); } if (!items.length || !items[0].itemType) { ctx.throw(400, "Input must be an array of items as JSON"); } var translator = Zotero.Translators.get(translatorID); var legacy = Zotero.Utilities.semverCompare('4.0.27', translator.metadata.minVersion) > 0; // Emulate itemsToExportFormat as best as we can for (let item of items) { // There's no library, so all we have is a key if (!item.uri) { item.uri = item.key; delete item.key; } if (legacy) { // SQL instead of ISO 8601 if (item.dateAdded) item.dateAdded = Zotero.Date.isoToSQL(item.dateAdded); if (item.dateModified) item.dateAdded = Zotero.Date.isoToSQL(item.dateModified); if (item.accessDate) item.accessDate = Zotero.Date.isoToSQL(item.accessDate); } } var translate = new Translate.Export(); translate.setTranslator(translatorID); translate.setItems(items); try { await new Promise(function (resolve, reject) { translate.setHandler("done", function (obj, status) { if (!status) { reject(); } else { ctx.set('Content-Type', CONTENT_TYPES[query.format]); ctx.response.body = translate.string; resolve(); } }); translate.translate(); }); } catch (e) { ctx.throw( 500, "An error occurred during translation. Please check translation with the Zotero client.", { expose: true } ); } } }; ================================================ FILE: src/formats.js ================================================ /* eslint camelcase: "off" */ const FORMATS = { bibtex: "9cb70025-a888-4a29-a210-93ec52da40d4", biblatex: "b6e39b57-8942-4d11-8259-342c46ce395f", bookmarks: "4e7119e0-02be-4848-86ef-79a64185aad8", coins: "05d07af9-105a-4572-99f6-a8e231c0daef", csljson: "bc03b4fe-436d-4a1f-ba59-de4d2d7a63f7", csv: "25f4c5e2-d790-4daa-a667-797619c7e2f2", endnote_xml: "eb7059a4-35ec-4961-a915-3cf58eb9784b", evernote: "18dd188a-9afc-4cd6-8775-1980c3ce0fbf", mods: "0e2235e7-babf-413c-9acf-f27cce5f059c", rdf_bibliontology: "14763d25-8ba0-45df-8f52-b8d1108e7ac9", rdf_dc: "6e372642-ed9d-4934-b5d1-c11ac758ebb7", rdf_zotero: "14763d24-8ba0-45df-8f52-b8d1108e7ac9", refer: "881f60f2-0802-411a-9228-ce5f47b64c7d", refworks_tagged: "1a3506da-a303-4b0a-a1cd-f216e6138d86", ris: "32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7", tei: "032ae9b7-ab90-9205-a479-baf81f49184a", wikipedia: "3f50aaac-7acc-4350-acd0-59cb77faf620" }; const CONTENT_TYPES = { bibtex: "application/x-bibtex", biblatex: "application/x-bibtex", bookmarks: "text/html", coins: "text/html", csljson: "application/json", csv: "text/csv", endnote_xml: "text/xml", evernote: "text/xml", mods: "application/mods+xml", rdf_bibliontology: "application/rdf+xml", rdf_dc: "application/rdf+xml", rdf_zotero: "application/rdf+xml", refer: "application/x-research-info-systems", refworks_tagged: "text/plain", ris: "application/x-research-info-systems", tei: "text/xml", wikipedia: "text/x-wiki" }; module.exports = { FORMATS, CONTENT_TYPES }; ================================================ FILE: src/http.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2011 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ var config = require('config'); var request = require('request'); var iconv = require('iconv-lite'); var url = require('url'); var jsdom = require('jsdom'); var { JSDOM } = jsdom; var wgxpath = require('wicked-good-xpath'); var { MIMEType } = require("whatwg-mimetype"); // Use the same MIME type library as JSDOM /** * Functions for performing HTTP requests * @namespace */ Zotero.HTTP = new function() { this.StatusError = function(url, status, body) { this.message = `HTTP request to ${url} rejected with status ${status}`; this.status = status; this.responseText = body; }; this.StatusError.prototype = Object.create(Error.prototype); this.TimeoutError = function(ms) { this.message = `HTTP request has timed out after ${ms}ms`; }; this.TimeoutError.prototype = Object.create(Error.prototype); // Max size of requested response to load; triggers 400 ResponseSizeError when exceeded this.httpMaxResponseSize = ( config.has('httpMaxResponseSize') ? config.get('httpMaxResponseSize') : 10 ) * 1024 * 1024; this.ResponseSizeError = function(url) { this.message = `${url} response exceeds max size`; }; this.ResponseSizeError.prototype = Object.create(Error.prototype); this.UnsupportedFormatError = function (url, msg) { this.message = msg; }; this.UnsupportedFormatError.prototype = Object.create(Error.prototype); /** * Get a promise for a HTTP request * * @param {String} method The method of the request ("GET", "POST", "HEAD", or "OPTIONS") * @param {String} url URL to request * @param {Object} [options] Options for HTTP request:
    *
  • body - The body of a POST request
  • *
  • headers - Object of HTTP headers to send with the request
  • *
  • cookieSandbox - The sandbox from which cookies should be taken
  • *
  • debug - Log response text and status code
  • *
  • logBodyLength - Length of request body to log
  • *
  • timeout - Request timeout specified in milliseconds [default 15000]
  • *
  • responseType - The response type of the request from the XHR spec
  • *
  • responseTypeMap - A Map of remote content type ('application/x-bibtex') to * XHR response type ('text'). 'html' and 'xml' imply isHTML() and isXML() from * whatwg-mimetype. Use an empty string for the key to set a fallback response type; * otherwise unspecified content types are rejected.
  • *
  • successCodes - HTTP status codes that are considered successful, or FALSE to allow all
  • *
* @return {Promise} A promise resolved with an object containing the following XMLHttpRequest properties: * - responseText {String} * - getAllResponseHeaders {Function} * - getResponseHeader {Function} * - statusCode {Number} */ this.request = async function(method, requestURL, options = {}) { // Default options options = Object.assign({ body: null, headers: {}, cookieSandbox: request.jar(), debug: false, logBodyLength: 1024, timeout: 15000, responseType: '', successCodes: null, maxResponseSize: this.httpMaxResponseSize }, options); options.headers = Object.assign({ 'User-Agent': process.env.USER_AGENT || config.get('userAgent'), 'Accept': '*/*' }, options.headers); let logBody = ''; if (['GET', 'HEAD'].includes(method)) { if (options.body != null) { throw new Error(`HTTP ${method} cannot have a request body (${options.body})`) } } else if(options.body) { options.body = typeof options.body == 'string' ? options.body : JSON.stringify(options.body); if (!options.headers) options.headers = {}; if (!options.headers["Content-Type"]) { options.headers["Content-Type"] = "application/x-www-form-urlencoded"; } else if (options.headers["Content-Type"] == 'multipart/form-data') { // Allow XHR to set Content-Type with boundary for multipart/form-data delete options.headers["Content-Type"]; } logBody = `: ${options.body.substr(0, options.logBodyLength)}` + options.body.length > options.logBodyLength ? '...' : ''; // TODO: make sure below does its job in every API call instance // Don't display password or session id in console logBody = logBody.replace(/password":"[^"]+/, 'password":"********'); logBody = logBody.replace(/password=[^&]+/, 'password=********'); } Zotero.debug(`HTTP ${method} ${requestURL}${logBody}`); // Parse URL to escape it (e.g., Unicode characters) var parsedURL = new url.URL(requestURL); let {response, body} = await customRequest(method, parsedURL, options); if (options.debug) { Zotero.debug(`HTTP ${response.statusCode} response: ${body}`); } var result = { responseURL: response.request.uri.href, status: response.statusCode, getAllResponseHeaders: () => { return [...Object.entries(response.headers)].map(([k, v]) => `${k}: ${v}\r\n`).join(''); }, getResponseHeader: (header) => { return response.headers[header.toLowerCase()] || null; } }; var mimeType = new MIMEType(response.headers['content-type']); var responseType = getResponseType(response.headers['content-type'], options); result.type = responseType; if (responseType == 'document') { body = decodeContent(body, response.headers['content-type']); let dom = new JSDOM(body, { url: result.responseURL, // Inform JSDOM what content type it's parsing, // so it could reject unsupported content types contentType: response.headers['content-type'] }); wgxpath.install(dom.window, true); result.response = dom.window.document; // Follow meta redirects in HTML files if (mimeType.isHTML() || mimeType.essence == 'application/xhtml+xml') { let meta = result.response.querySelector('meta[http-equiv=refresh]'); if (meta && meta.getAttribute('content')) { let parts = meta.getAttribute('content').split(/;\s*url=/); // If there's a redirect to another URL in less than 15 seconds, // follow it if (parts.length == 2 && parseInt(parts[0]) <= 15) { let newURL = parts[1].trim().replace(/^'(.+)'/, '$1'); newURL = url.resolve(requestURL, newURL); Zotero.debug("Meta refresh to " + newURL); result = Zotero.HTTP.request(method, newURL, options); } } } } else if (responseType == 'json') { result.response = JSON.parse(body.toString()); } else if (responseType == 'text') { let charset = mimeType.parameters.get('charset'); // Treat unknown charset as utf-8 if (!charset) { charset = 'utf8'; } else if (!iconv.encodingExists(charset)) { Zotero.debug(`Unknown charset ${charset} -- decoding as UTF-8`); charset = 'utf8'; } body = iconv.decode(body, charset); result.response = body; result.responseText = body; } else { throw new Error("Invalid responseType"); } return result; }; /** * Load one or more documents * * This should stay in sync with the equivalent function in the client * * @param {String|String[]} urls - URL(s) of documents to load * @param {Function} processor - Callback to be executed for each document loaded * @param {CookieJar} [cookieSandbox] Cookie sandbox object * @return {Promise} - A promise for an array of results from the processor runs */ this.processDocuments = async function (urls, processor, options = {}) { // Handle old signature: urls, processor, onDone, onError if (arguments.length > 3) { Zotero.debug("Zotero.HTTP.processDocuments() now takes only 2 arguments -- update your code"); var onDone = arguments[3]; var onError = arguments[4]; } var cookieSandbox = options.cookieSandbox; var headers = options.headers; if (typeof urls == "string") urls = [urls]; var funcs = urls.map(url => () => { return Zotero.HTTP.request( "GET", url, { responseType: 'document', cookieSandbox, headers } ) .then((req) => { return processor(req.response, req.responseURL); }); }); // Run processes serially // TODO: Add some concurrency? var f; var results = []; while (f = funcs.shift()) { try { results.push(await f()); } catch (e) { if (onError) { onError(e); } throw e; } } // Deprecated if (onDone) { onDone(); } return results; } /** * Send an HTTP GET request * * @deprecated Use {@link Zotero.HTTP.request} * @param {String} url URL to request * @param {Function} onDone Callback to be executed upon request completion * @param {String} responseCharset * @param {CookieJar} cookieSandbox * @param {Object} headers HTTP headers to include with the request * @return {Boolean} True if the request was sent, or false if the browser is offline */ this.doGet = function(url, onDone, responseCharset, cookieSandbox, headers) { Zotero.debug('Zotero.HTTP.doGet is deprecated. Use Zotero.HTTP.request'); this.request('GET', url, {responseCharset, headers, cookieSandbox}) .then(onDone, function(e) { onDone({status: e.status, responseText: e.responseText}); }); return true; }; /** * Send an HTTP POST request * * @deprecated Use {@link Zotero.HTTP.request} * @param {String} url URL to request * @param {String|Object[]} body Request body * @param {Function} onDone Callback to be executed upon request completion * @param {String} headers Request HTTP headers * @param {String} responseCharset * @param {CookieJar} cookieSandbox * @return {Boolean} True if the request was sent, or false if the browser is offline */ this.doPost = function(url, body, onDone, headers, responseCharset, cookieSandbox) { Zotero.debug('Zotero.HTTP.doPost is deprecated. Use Zotero.HTTP.request'); this.request('POST', url, {body, responseCharset, headers, cookieSandbox}) .then(onDone, function(e) { onDone({status: e.status, responseText: e.responseText}); }); return true; }; } /** * A temporary workaround for JSDOM content decoding issues. * The code is adapted from jsdom/lib/api.js. All dependencies * are already used internally in JSDOM * * TODO: Remove this code when https://github.com/jsdom/jsdom/issues/2495 will be solved */ const sniffHTMLEncoding = require("html-encoding-sniffer"); const whatwgEncoding = require("whatwg-encoding"); function decodeContent(html, contentType) { let transportLayerEncodingLabel; if (contentType) { const mimeType = new MIMEType(contentType); transportLayerEncodingLabel = mimeType.parameters.get("charset"); } html = Buffer.from(html.buffer, html.byteOffset, html.byteLength); let encoding = sniffHTMLEncoding(html, {defaultEncoding: "UTF-8", transportLayerEncodingLabel}); html = whatwgEncoding.decode(html, encoding); return html; } /** * request.js doesn't support response size limitation, therefore * we have to do it manually * * @param {String} method * @param {String} requestURL * @param {Object} options * @return {Promise} response, body */ function customRequest(method, requestURL, options) { return new Promise(function (resolve, reject) { let response; // Make sure resolve/reject is called only once even if request.js // is emitting events when it shouldn't let returned = false; // Store buffers in array, because concatenation operation is is unbelievably slow let buffers = []; let bufferLength = 0; let req = request({ uri: requestURL, method, headers: options.headers, timeout: options.timeout, body: options.body, gzip: true, followAllRedirects: true, jar: options.cookieSandbox, encoding: null // Get body in a buffer }) .on('error', function (err) { if (returned) return; reject(err); }) .on('data', function (chunk) { if (returned) return; bufferLength += chunk.length; buffers.push(chunk); if (bufferLength > options.maxResponseSize) { req.abort(); returned = true; reject(new Zotero.HTTP.ResponseSizeError(requestURL)); } }) .on('response', function (res) { if (returned) return; response = res; if (!response.headers['content-type']) { returned = true; return reject(new Zotero.HTTP.UnsupportedFormatError(requestURL, 'Missing Content-Type header')); } // Check if the status code is allowed // Array of success codes given if (options.successCodes) { var success = options.successCodes.includes(response.statusCode); } // Explicit FALSE means allow any status code else if (options.successCodes === false) { var success = true; } // Otherwise, 2xx is success else { var success = response.statusCode >= 200 && response.statusCode < 300; } if (!success) { returned = true; return reject(new Zotero.HTTP.StatusError(requestURL, response.statusCode, response.body)); } // Check Content-Type before starting the download let supported = true; let mimeType = new MIMEType(response.headers['content-type']); if (options.responseType == 'document') { supported = mimeType.isHTML() || mimeType.isXML(); } else if (options.responseTypeMap) { let map = options.responseTypeMap; supported = (map.has('html') && mimeType.isHTML()) || (map.has('xml') && mimeType.isXML()) || map.has(mimeType.essence) // An empty string for a key allows unspecified types as text || map.has(''); } if (!supported) { req.abort(); returned = true; return reject(new Zotero.HTTP.UnsupportedFormatError( requestURL, response.headers['content-type'] + ' is not supported' )); } // Content-length doesn't always exists or it can be a length of a gzipped content, // but it's still worth to do the initial size check if ( response.headers['content-length'] !== undefined && response.headers['content-length'] > options.maxResponseSize ) { req.abort(); returned = true; reject(new Zotero.HTTP.ResponseSizeError(requestURL)); } }) .on('end', function () { if (returned) return; returned = true; resolve({response, body: Buffer.concat(buffers, bufferLength)}); }); }); }; function getResponseType(contentType, options) { var mimeType = new MIMEType(contentType); if (options.responseType) { return options.responseType; } if (options.responseTypeMap) { let map = options.responseTypeMap; if (map.has('html') && mimeType.isHTML()) { return map.get('html'); } if (map.has('xml') && mimeType.isXML()) { return map.get('xml'); } if (map.has(mimeType.essence)) { return map.get(mimeType.essence); } } return 'text'; } module.exports = Zotero.HTTP; ================================================ FILE: src/importEndpoint.js ================================================ 'use strict'; /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Corporation for Digital Scholarship Vienna, Virginia, USA https://www.zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const Translate = require('./translation/translate'); module.exports = { handle: async function (ctx, _next) { const translate = new Translate.Import(); translate.setString(ctx.request.body || ''); const translators = await translate.getTranslators(); if (translators.length === 0) { ctx.throw(500, 'No suitable translators found', { expose: true }); return; } translate.setTranslator(translators[0]); var items = await translate.translate({ libraryID: 1 }); ctx.set('Content-Type', 'application/json'); ctx.set('Zotero-Translator-ID', translators[0].translatorID); // Convert translator JSON to API JSON var newItems = []; items.forEach((item) => { newItems.push(...Zotero.Utilities.Item.itemToAPIJSON(item)); }); ctx.response.body = JSON.stringify(newItems, null, 2); } }; ================================================ FILE: src/lambda.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Center for History and New Media George Mason University, Fairfax, Virginia, USA https://www.zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const Koa = require('koa'); const _ = require('koa-route'); const bodyParser = require('koa-bodyparser'); const cors = require('./cors'); const serverless = require('serverless-http'); require('./zotero'); const Debug = require('./debug'); var Translators; // Translators module is cashed const SearchEndpoint = require('./searchEndpoint'); const WebEndpoint = require('./webEndpoint'); const ExportEndpoint = require('./exportEndpoint'); const ImportEndpoint = require('./importEndpoint'); const app = module.exports = new Koa(); app.use(function (ctx, next) { var msg = `${ctx.method} ${ctx.url} from ${ctx.request.ip} "${ctx.headers['user-agent']}"`; if (ctx.headers.origin) { msg += ` (${ctx.headers.origin})`; } Zotero.debug(msg); return next(); }); app.use(cors); app.use( bodyParser({ enableTypes: ['text', 'json'], jsonLimit: '5mb', textLimit: '3mb', }) ); app.use(_.post('/web', WebEndpoint.handle.bind(WebEndpoint))); app.use(_.post('/search', SearchEndpoint.handle.bind(SearchEndpoint))); app.use(_.post('/export', ExportEndpoint.handle.bind(ExportEndpoint))); app.use(_.post('/import', ImportEndpoint.handle.bind(ImportEndpoint))); Debug.init(1); const handler = serverless(app); module.exports.handler = async function (event, context) { if (!Translators) { Translators = require('./translators'); await Translators.init(); } var result = await handler(event, context); return result; }; ================================================ FILE: src/proxy.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2016 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ /** * Intercepts web requests to detect and redirect proxies. Loosely based on Zotero for Firefox proxy code. * * Zotero.Proxies.Detectors specifies detector functions/objects, which run asynchronously for every * request and add new proxies based on proxy specific rule match * * Zotero.Proxies.proxies defines a list of already known proxies (Zotero.Proxy), based on an URL match scheme. * * Each Zotero.Proxy holds a list of already recognized hosts (previously accessed via the proxy * by the user) and automatically redirects the requests to these hosts via the proxy. */ (function() { "use strict"; var url = require('url'); var TLDS = Zotero.requireTranslate('./tlds'); Zotero.Proxies = new function() { /** * Check the url for potential proxies and deproxify, providing a schema to build * a proxy object. * * @param URL * @returns {Object} Unproxied url to proxy object */ this.getPotentialProxies = function(URL) { var urlToProxy = {}; // If it's a known proxied URL just return it if (Zotero.Proxies.transparent) { for (var proxy of Zotero.Proxies.proxies) { if (proxy.regexp) { var m = proxy.regexp.exec(URL); if (m) { let proper = proxy.toProper(m); urlToProxy[proper] = proxy.toJSON(); return urlToProxy; } } } } urlToProxy[URL] = null; // if there is a subdomain that is also a TLD, also test against URI with the domain // dropped after the TLD // (i.e., www.nature.com.mutex.gmu.edu => www.nature.com) var m = /^(https?:\/\/)([^\/]+)/i.exec(URL); if (m) { // First, drop the 0- if it exists (this is an III invention) var host = m[2]; if (host.substr(0, 2) === "0-") host = host.substr(2); var hostnameParts = [host.split(".")]; if (m[1] == 'https://') { // try replacing hyphens with dots for https protocol // to account for EZProxy HttpsHypens mode hostnameParts.push(host.split('.')); hostnameParts[1].splice(0, 1, ...(hostnameParts[1][0].replace(/-/g, '.').split('.'))); } for (let i=0; i < hostnameParts.length; i++) { let parts = hostnameParts[i]; // If hostnameParts has two entries, then the second one is with replaced hyphens let dotsToHyphens = i == 1; // skip the lowest level subdomain, domain and TLD for (let j=1; j=0; i--) { var param = this.parameters[i]; re = re.replace(Zotero_Proxy_schemeParameterRegexps[param], "$1"+Zotero_Proxy_schemeParameters[param]); } this.regexp = new RegExp(re); } /** * Converts a proxied URL to an unproxied URL using this proxy * * @param m {Array} The match from running this proxy's regexp against a URL spec * @type String */ Zotero.Proxy.prototype.toProper = function(m) { if (!Array.isArray(m)) { let match = this.regexp.exec(m); if (!match) { return m } else { m = match; } } let hostIdx = this.parameters.indexOf("%h"); let scheme = m[0].indexOf('https') == 0 ? 'https://' : 'http://'; if (hostIdx != -1) { var properURL = scheme+m[hostIdx+1]+"/"; } else { var properURL = scheme+this.hosts[0]+"/"; } // Replace `-` with `.` in https to support EZProxy HttpsHyphens. // Potentially troublesome with domains that contain dashes if (this.dotsToHyphens || (this.dotsToHyphens == undefined && scheme == "https://") || !properURL.includes('.')) { properURL = properURL.replace(/-/g, '.'); } if (this.indices["%p"]) { properURL += m[this.parameters.indexOf("%p")+1]; } else { var dir = m[this.parameters.indexOf("%d")+1]; var file = m[this.parameters.indexOf("%f")+1]; if (dir !== "") properURL += dir+"/"; properURL += file; } return properURL; } /** * Converts an unproxied URL to a proxied URL using this proxy * * @param {Object|String} uri The URI corresponding to the unproxied URL * @type String */ Zotero.Proxy.prototype.toProxy = function(uri) { if (typeof uri == "string") { uri = url.parse(uri); // If there's no path it is set to null, but we need // at least an empty string to avoid doing many checks uri.path = uri.path || ''; } if (this.regexp.exec(uri.href) || Zotero.Proxies._isBlacklisted(uri.host)) { return uri.href; } var proxyURL = this.scheme; for(var i=this.parameters.length-1; i>=0; i--) { var param = this.parameters[i]; var value = ""; if (param == "%h") { value = (this.dotsToHyphens && uri.protocol == 'https:') ? uri.host.replace(/\./g, '-') : uri.host; } else if (param == "%p") { value = uri.path.substr(1); } else if (param == "%d") { value = uri.path.substr(0, uri.path.lastIndexOf("/")); } else if (param == "%f") { value = uri.path.substr(uri.path.lastIndexOf("/")+1) } proxyURL = proxyURL.substr(0, this.indices[param])+value+proxyURL.substr(this.indices[param]+2); } if (proxyURL.includes('://')) { return proxyURL; } return uri.protocol + '//' + proxyURL; } /** * Generate a display name for the proxy (e.g., "proxy.example.edu (HTTPS)") * * @return {String} */ Zotero.Proxy.prototype.toDisplayName = function () { try { var parts = this.scheme.match(/^(?:(?:[^:]+):\/\/)?([^\/]+)/); var domain = parts[1] // Include part after %h, if it's present .split('%h').pop() // Trim leading punctuation after the %h .match(/\W(.+)/)[1]; return domain; } catch (e) { Zotero.logError(`Invalid proxy ${this.scheme}: ${e}`); return this.scheme; } } module.exports = {Proxies: Zotero.Proxies, Proxy: Zotero.Proxy}; })(); ================================================ FILE: src/searchEndpoint.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Corporation for Digital Scholarship Vienna, Virginia, USA https://www.zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const config = require('config'); const Translate = require('./translation/translate'); const TextSearch = require('./textSearch'); var SearchEndpoint = module.exports = { handle: async function (ctx, next) { ctx.assert(ctx.is('text'), 415); var data = ctx.request.body; if (!data) { ctx.throw(400, "POST data not provided\n"); } // Look for DOI, ISBN, etc. var identifiers = Zotero.Utilities.extractIdentifiers(data); // Use PMID only if it's the only text in the query, with or without a pmid: prefix if (identifiers.length && identifiers[0].PMID && identifiers[0].PMID !== data.replace(/^\s*(?:pmid:)?([0-9]+)\s*$/, '$1')) { identifiers = []; } // Text search if (!identifiers.length) { await TextSearch.handle(ctx, next); return; } await this.handleIdentifier(ctx, identifiers[0]); }, handleIdentifier: async function (ctx, identifier) { // Identifier try { var translate = new Translate.Search(); translate.setIdentifier(identifier); let translators = await translate.getTranslators(); if (!translators.length) { ctx.throw(501, "No translators available", { expose: true }); } translate.setTranslator(translators); var items = await translate.translate({ libraryID: false }); } catch (e) { if (e == translate.ERROR_NO_RESULTS) { ctx.throw(501, e, { expose: true }); } Zotero.debug(e, 1); ctx.throw( 500, "An error occurred during translation. " + "Please check translation with the Zotero client.", { expose: true } ); } // Translation can return multiple items (e.g., a parent item and notes pointing to it), // so we have to return an array with keyed items var newItems = []; items.forEach(item => { newItems.push(...Zotero.Utilities.Item.itemToAPIJSON(item)); }); ctx.response.body = newItems; } }; ================================================ FILE: src/server.js ================================================ /* eslint no-process-env: "off" */ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Center for History and New Media George Mason University, Fairfax, Virginia, USA https://www.zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const process = require('process'); const config = require('config'); const Koa = require('koa'); const _ = require('koa-route'); const bodyParser = require('koa-bodyparser'); const cors = require('./cors'); // Prevent UnhandledPromiseRejection crash in Node 15, though this shouldn't be necessary process.on('unhandledRejection', (reason, promise) => { Zotero.debug('Unhandled rejection: ' + (reason.stack || reason), 1) }); require('./zotero'); const Debug = require('./debug'); const Translators = require('./translators'); const SearchEndpoint = require('./searchEndpoint'); const WebEndpoint = require('./webEndpoint'); const ExportEndpoint = require('./exportEndpoint'); const ImportEndpoint = require('./importEndpoint'); const app = module.exports = new Koa(); if (config.get('trustProxyHeaders')) { app.proxy = true; } app.use(function (ctx, next) { var msg = `${ctx.method} ${ctx.url} from ${ctx.request.ip} "${ctx.headers['user-agent']}"`; if (ctx.headers.origin) { msg += ` (${ctx.headers.origin})`; } Zotero.debug(msg); return next(); }); app.use(cors); app.use( bodyParser({ enableTypes: ['text', 'json'], jsonLimit: '5mb', textLimit: '5mb', }) ); app.use(_.post('/web', WebEndpoint.handle.bind(WebEndpoint))); app.use(_.post('/search', SearchEndpoint.handle.bind(SearchEndpoint))); app.use(_.post('/export', ExportEndpoint.handle.bind(ExportEndpoint))); app.use(_.post('/import', ImportEndpoint.handle.bind(ImportEndpoint))); Debug.init(process.env.DEBUG_LEVEL ? parseInt(process.env.DEBUG_LEVEL) : 1); Translators.init() .then(function () { // Don't start server in test mode, since it's handled by supertest if (process.env.NODE_ENV == 'test') return; var port = config.get('port'); var host = config.get('host'); app.listen(port, host); Debug.log(`Listening on ${host}:${port}`); }); ================================================ FILE: src/testEndpoint.js ================================================ var fs = require('fs'); var path = require('path'); var TestEndpoint = { handlePlain: async function (ctx, _next) { ctx.response.body = 'TestHello'; }, handleSingle: async function (ctx, _next) { var title = ctx.headers['accept-language'] == 'fr' ? 'Titre' : 'Title'; ctx.response.body = ` ${title} Body `; }, handleMultiple: async function (ctx, _next) { ctx.response.body = '' + '' + '' + '' + ''; }, handleRedirect: async function (ctx, _next) { ctx.redirect('/test/single'); }, handleBibTeX: async function (ctx, _next) { ctx.set('Content-Type', 'application/x-bibtex'); ctx.response.body = fs .readFileSync(path.join(__dirname, '../test/data/bibtex_response.xml')) .toString(); }, invalidContentType: async function (ctx, _next) { ctx.set('Content-Type', 'image/jpeg'); ctx.response.body = ''; }, missingContentType: async function (ctx, _next) { ctx.response.body = null; } }; module.exports = TestEndpoint; ================================================ FILE: src/textSearch.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Center for History and New Media George Mason University, Fairfax, Virginia, USA https://www.zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const config = require('config'); const XRegExp = require('xregexp'); const md5 = require('md5'); const AWS = require('aws-sdk'); const Lambda = new AWS.Lambda({apiVersion: '2015-03-31'}); module.exports = { /** * Handle text search * * @return {Promise} */ handle: async function (ctx, next) { // If identifier-search is disabled in the request or unavailable, return 501 if (ctx.request.query.text === '0' || !config.has('identifierSearchLambda') || !config.get("identifierSearchLambda")) { ctx.throw(501, "No identifiers found", { expose: true }); } var data = ctx.request.body; var result = await search( data, ctx.query && ctx.query.start ); // Throw selection if two or more items are found, or the selection flag is marked if (result.items.length >= 2 || result.items.length >= 1 && result.select) { let newItems = {}; for (let item of result.items) { let DOI = item.DOI; let ISBN = item.ISBN; if (!DOI && item.extra) { let m = item.extra.match(/DOI: (.*)/); if (m) DOI = m[1]; } if (!ISBN && item.extra) { let m = item.extra.match(/ISBN: (.*)/); if (m) ISBN = m[1]; } let identifier; // DOI has a priority over ISBN for items that have both if (DOI) { identifier = DOI; } else if (item.ISBN) { identifier = ISBN.split(' ')[0]; } newItems[identifier] = { itemType: item.itemType, title: item.title, description: formatDescription(item), }; } // If there were more results, include a link to the next result set if (result.next) { ctx.set('Link', `; rel="next"`); } ctx.response.status = 300; // // TODO: Differentiate from web request 300 // ctx.response.body = newItems; return; } if (result.items.length === 1) { ctx.response.body = Zotero.Utilities.Item.itemToAPIJSON(result.items[0]); return; } ctx.response.body = []; }, // Expose for stubbing in tests queryLambda: async function (query) { let params = { FunctionName: config.get('identifierSearchLambda'), InvocationType: 'RequestResponse', Payload: JSON.stringify({query}) }; let result = await Lambda.invoke(params).promise(); if (result.FunctionError) { throw new Error('Lambda error: ' + result.Payload); } identifiers = JSON.parse(result.Payload); return identifiers; } }; async function search(query, start) { const timeout = config.get('textSearchTimeout') * 1000; const startTime = new Date(); const numResults = 3; let identifiers; let moreResults = false; try { identifiers = await module.exports.queryLambda(query); // If passed a start= parameter, skip ahead let startPos = 0; if (start) { for (let i = 0; i < identifiers.length; i++) { if (identifierToToken(identifiers[i]) == start) { startPos = i + 1; break; } } } if (identifiers.length > startPos + numResults + 1) { moreResults = true; } identifiers = identifiers.slice(startPos); } catch(e) { Zotero.debug(e, 1); return {select: false, items: []}; } let items = []; let nextLastIdentifier = null; for (let identifier of identifiers) { let translate = new Zotero.Translate.Search(); try { translate.setIdentifier(identifier); let translators = await translate.getTranslators(); if (!translators.length) { if (new Date() > startTime.getTime() + timeout) { break; } continue; } translate.setTranslator(translators); let newItems = await translate.translate({ libraryID: false }); if (newItems.length) { let seq = getLongestCommonSequence(newItems[0].title, query); if (seq.length >= 6 && seq.split(' ').length >= 2) { items.push(newItems[0]); // Keep track of last identifier if we're limiting results if (moreResults) { nextLastIdentifier = identifier; } if (items.length == numResults) { break; } } } } catch (e) { if (e !== translate.ERROR_NO_RESULTS) { Zotero.debug(e, 1); } } if (new Date() > startTime.getTime() + timeout) { break; } } return { // Force item selection, even for a single item select: true, items, next: nextLastIdentifier ? identifierToToken(nextLastIdentifier) : null }; // // Query Crossref and LoC/GBV in parallel to respond faster to the client // let [crossrefItems, libraryItems] = await Promise.all([queryCrossref(query), queryLibraries(query)]); // // // Subtract book reviews from Crossref // crossrefItems = subtractCrossrefItems(crossrefItems, libraryItems); // // let items = crossrefItems.concat(libraryItems); // // // Filter out too fuzzy items, by comparing item title (and other metadata) against query // return await filterResults(items, query); } function formatDescription(item) { let parts = []; let authors = []; for (let creator of item.creators) { if (creator.creatorType === 'author' && creator.lastName) { authors.push(creator.lastName); if (authors.length === 3) break; } } if(authors.length) parts.push(authors.join(', ')); if (item.date) { let m = item.date.toString().match(/[0-9]{4}/); if (m) parts.push(m[0]); } if(item.publicationTitle) { parts.push(item.publicationTitle); } else if(item.publisher) { parts.push(item.publisher); } return parts.join(' \u2013 '); } function subtractCrossrefItems(crossrefItems, libraryItems) { let items = []; for(let crossrefItem of crossrefItems) { // Keep books and book sections if(['book', 'bookSection'].includes(crossrefItem.itemType)) { items.push(crossrefItem); continue; } let crossrefTitle = crossrefItem.title; // Remove all tags crossrefTitle = crossrefTitle.replace(/<\/?\w+[^<>]*>/gi, ''); crossrefTitle = crossrefTitle.replace(/:/g, ' '); // Normalize title, split to words, filter out empty array elements crossrefTitle = normalize(crossrefTitle).split(' ').filter(x => x).join(' '); let found = false; for(let libraryItem of libraryItems) { let libraryTitle = libraryItem.title; // Remove all tags libraryTitle = libraryTitle.replace(/<\/?\w+[^<>]*>/gi, ''); libraryTitle = libraryTitle.replace(/:/g, ' '); // Normalize title, split to words, filter out empty array elements libraryTitle = normalize(libraryTitle).split(' ').filter(x => x).join(' '); if(crossrefTitle.includes(libraryTitle)) { found = true; break; } } if(!found) { items.push(crossrefItem); } } return items; } async function queryCrossref(query) { let items = []; try { let translate = new Zotero.Translate.Search(); // Crossref REST translate.setTranslator("0a61e167-de9a-4f93-a68a-628b48855909"); translate.setSearch({query}); items = await translate.translate({libraryID: false}); } catch (e) { Zotero.debug(e, 2); } return items; } /** * Queries LoC and if that fails, queries GBV */ async function queryLibraries(query) { let items = []; try { let translate = new Zotero.Translate.Search(); // Library of Congress ISBN translate.setTranslator("c070e5a2-4bfd-44bb-9b3c-4be20c50d0d9"); translate.setSearch({query}); items = await translate.translate({libraryID: false}); } catch (e) { Zotero.debug(e, 2); try { let translate = new Zotero.Translate.Search(); // Gemeinsamer Bibliotheksverbund ISBN translate.setTranslator("de0eef58-cb39-4410-ada0-6b39f43383f9"); translate.setSearch({query}); items = await translate.translate({libraryID: false}); } catch (e) { Zotero.debug(e, 2); } } return items; } /** * Decomposes all accents and ligatures, * filters out symbols that aren't space or alphanumeric, * and lowercases alphabetic symbols. */ function normalize(text) { let rx = XRegExp('[^\\pL 0-9]', 'g'); text = XRegExp.replace(text, rx, ''); text = text.normalize('NFKD'); text = XRegExp.replace(text, rx, ''); text = text.toLowerCase(); return text; } /** * Checks if a given word equals to any of the authors' names */ function hasAuthor(authors, word) { return authors.some(author => { return (author.firstName && normalize(author.firstName).split(' ').includes(word)) || (author.lastName && normalize(author.lastName).split(' ').includes(word)); }); } /** * Tries to find the longest common words sequence between * item title and query text. Query text must include title (or part of it) * from the beginning. If there are leftover query words, it tries to * validate them against item metadata (currently only authors and year) */ async function filterResults(items, query) { let filteredItems = []; let select = false; // Normalize query, split to words, filter out empty array elements let queryWords = normalize(query).split(' ').filter(x => x); for (let item of items) { let DOI = item.DOI; let ISBN = item.ISBN; if (!DOI && item.extra) { let m = item.extra.match(/DOI: (.*)/); if (m) DOI = m[1]; } if (!ISBN && item.extra) { let m = item.extra.match(/ISBN: (.*)/); if (m) ISBN = m[1]; } if (!DOI && !ISBN) continue; let title = item.title; // Remove all tags title = title.replace(/<\/?\w+[^<>]*>/gi, ''); title = title.replace(/:/g, ' '); // Normalize title, split to words, filter out empty array elements let titleWords = normalize(title).split(' ').filter(x => x); let longestFrom = 0; let longestLen = 0; // Finds the longest common words sequence between query text and item.title for (let i = 0; i < queryWords.length; i++) { for (let j = queryWords.length; j > 0; j--) { let a = queryWords.slice(i, j); for (let k = 0; k < titleWords.length - a.length + 1; k++) { let b = titleWords.slice(k, a.length + k); if (a.length && b.length && a.join(' ') === b.join(' ')) { if (a.length > longestLen) { longestFrom = i; longestLen = b.length; } } } } } // At least two common words sequence must be found between query and title if (longestLen < 1) continue; // Longest common sequence of words let foundPart = queryWords.slice(longestFrom, longestLen); // Remaining words let rems = queryWords.slice(0, longestFrom); rems = rems.concat(queryWords.slice(longestLen)); // If at least one remaining word is left, it tries to compare it against item metadata. // Otherwise the whole query text is found in the title, and we have a full match if (rems.length) { let foundAuthor = false; let needYear = false; let foundYear = false; // Still remaining words let rems2 = []; for (let rem of rems) { // Ignore words if (['the', 'a', 'an'].indexOf(rem) >= 0) continue; // If the remaining word has at least 2 chars and exists in metadata authors if (rem.length >= 2 && hasAuthor(item.creators, rem)) { foundAuthor = true; continue; } // If the remaining word is a 4 digit number (year) if (/^[0-9]{4}$/.test(rem)) { needYear = true; if (item.date) { // If the remaining word exists in the item date let m = item.date.toString().match(/[0-9]{4}/); if (m && m[0] === rem) { foundYear = true; continue; } } } // Push the word that is still remaining rems2.push(rem); } // If a year exists in the query, but is not matched to the item date if (needYear && !foundYear) continue; // If there are still remaining words and none of authors are found if (rems2.length && !foundAuthor) continue; } // If the query part that was found in title is shorter than 30 symbols if (foundPart.join(' ').length < 30) select = true; filteredItems.push({ matchedLen: foundPart.join(' ').length, titleLen: titleWords.join(' ').length, item }); } // Sort results by matched text length // and how close the matched text length is to title length filteredItems.sort(function (a, b) { if (b.matchedLen < a.matchedLen) return -1; if (b.matchedLen > a.matchedLen) return 1; return Math.abs(a.matchedLen - a.titleLen) - Math.abs(b.matchedLen - b.titleLen); }); filteredItems = filteredItems.map(item => item.item); return {select, items: filteredItems}; } function getLongestCommonSequence(title, query) { title = title.replace(/<\/?\w+[^<>]*>/gi, ''); title = title.replace(/:/g, ' '); query = query.replace(/:/g, ' '); // Normalize, split to words and filter out empty array elements let titleWords = normalize(title).split(' ').filter(x => x); let queryWords = normalize(query).split(' ').filter(x => x); let longestFrom = 0; let longestLen = 0; // Finds the longest common words sequence between query text and item.title for (let i = 0; i < queryWords.length; i++) { for (let j = queryWords.length; j > 0; j--) { let a = queryWords.slice(i, j); for (let k = 0; k < titleWords.length - a.length + 1; k++) { let b = titleWords.slice(k, a.length + k); if (a.length && b.length && a.join(' ') === b.join(' ')) { if (a.length > longestLen) { longestFrom = i; longestLen = b.length; } } } } } return queryWords.slice(longestFrom, longestFrom + longestLen).join(' '); } function identifierToToken(identifier) { return md5(JSON.stringify(identifier)); } ================================================ FILE: src/translation/sandboxManager.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ /** * @class Manages the translator sandbox * @param {Translate} translate * @param {String|window} sandboxLocation */ var SandboxManager = function(sandboxLocation) { this.sandbox = { "Zotero":{}, Promise, }; }; SandboxManager.prototype = { /** * Evaluates code in the sandbox * @param {String} code Code to evaluate * @param {String[]} functions Functions to import into the sandbox (rather than leaving * as inner functions) */ eval: function(code, functions) { // delete functions to import for (var i in functions) { delete this.sandbox[functions[i]]; } // Prepend sandbox properties within eval environment (what a mess (1)) for (var prop in this.sandbox) { code = 'var ' + prop + ' = this.sandbox.' + prop + ';' + code; } // Import inner functions back into the sandbox for (var i in functions) { // TODO: Omit in translate.js? if (functions[i] == 'detectExport') continue; try { code += 'this.sandbox.' + functions[i] + ' = ' + functions[i] + ';'; } catch (e) { } } // Eval in a closure (function() { eval(code); }).call(this); }, /** * Imports an object into the sandbox * * @param {Object} object Object to be imported (under Zotero) * @param {Boolean} passTranslateAsFirstArgument Whether the translate instance should be passed * as the first argument to the function. */ importObject: function(object, passAsFirstArgument, attachTo) { if(!attachTo) attachTo = this.sandbox.Zotero; for(var key in (object.__exposedProps__ ? object.__exposedProps__ : object)) { if(Function.prototype[key]) continue; if(typeof object[key] === "function" || typeof object[key] === "object") { // magic closures attachTo[key] = new function() { var fn = object[key]; return function() { var args = (passAsFirstArgument ? [passAsFirstArgument] : []); for(var i=0; i. ***** END LICENSE BLOCK ***** */ Zotero.Translate = Zotero.requireTranslate('./translation/translate'); Zotero.Translate = {...Zotero.Translate, SandboxManager: require('./sandboxManager'), ...require('./translate_item') }; Zotero.Translate.ItemSaver.prototype.saveItems = async function (jsonItems, attachmentCallback, itemsDoneCallback) { this.items = (this.items || []).concat(jsonItems) return jsonItems } // Translation architecture shims and monkey-patches var wgxpath = require('wicked-good-xpath'); global.XPathResult = wgxpath.XPathResultType; var jsdom = require('jsdom'); var { JSDOM } = jsdom; var serializeNode = require("w3c-xmlserializer"); // Shim innerText for JSDOM, see https://github.com/jsdom/jsdom/issues/1245 // JSDOM interfaces are recreated per instance, so we use the beforeParse hook // to apply shims once per instance (not on every window access). function shimInnerText(window) { Object.defineProperty(window.Attr.prototype, 'innerText', { get() { return this.textContent; }, set(value) { this.textContent = value; }, configurable: true, }); Object.defineProperty(window.Node.prototype, 'innerText', { get() { // innerText in the browser is more sophisticated, but this removes most unwanted content // https://github.com/jsdom/jsdom/issues/1245#issuecomment-584677454 let el = this.cloneNode(true); el.querySelectorAll('script, style').forEach(s => s.remove()); return el.textContent; }, set(value) { this.textContent = value; }, configurable: true, }); } // Wrap JSDOM constructor to inject innerText shim via beforeParse for all instances jsdom.JSDOM = class extends JSDOM { constructor(input, options = {}) { var originalBeforeParse = options.beforeParse; options.beforeParse = function (window) { shimInnerText(window); if (originalBeforeParse) { originalBeforeParse(window); } }; super(input, options); } }; JSDOM = jsdom.JSDOM; var dom = new JSDOM(''); wgxpath.install(dom.window, true); global.DOMParser = dom.window.DOMParser; global.XMLSerializer = class XMLSerializer { serializeToString(node) { return serializeNode(node); } }; module.exports = Zotero.Translate; ================================================ FILE: src/translation/translate_item.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2011 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ ItemSaver = function(libraryID, attachmentMode, forceTagType) {}; ItemSaver.ATTACHMENT_MODE_IGNORE = 0; ItemSaver.ATTACHMENT_MODE_DOWNLOAD = 1; ItemSaver.ATTACHMENT_MODE_FILE = 2; // We don't define a real itemSaver here because Zotero.Translate will always be run in object-only // mode, but we do define a saveCollection no-op. ItemSaver.prototype.saveCollection = function() {}; ItemGetter = function() { this._itemsLeft = null; this._collectionsLeft = null; this._itemID = 1; }; ItemGetter.prototype = { "setItems":function(items) { this._itemsLeft = items; this.numItems = this._itemsLeft.length; }, /** * Retrieves the next available item */ "nextItem":function() { if(!this._itemsLeft.length) return false; var item = this._itemsLeft.shift(); if (this.legacy) { item = Zotero.Utilities.Item.itemToLegacyExportFormat(item); } if (!item.attachments) { item.attachments = []; } if (!item.notes) { item.notes = []; } // convert single field creators to format expected by export if(item.creators) { for(var i=0; i. ***** END LICENSE BLOCK ***** */ // Enumeration of types of translators var TRANSLATOR_TYPES = {"import":1, "export":2, "web":4, "search":8}; const fs = require('fs'); const path = require('path'); var Translators = Zotero.requireTranslate('./translators'); /** * Singleton to handle loading and caching of translators * @namespace */ Translators = Object.assign(Translators, new function() { var _cache, _translators; var _initialized = false; const infoRe = /^\s*{[\S\s]*?}\s*?[\r\n]/; /** * Initializes translator cache, loading all translators into memory * @param {Zotero.Translators[]} [translators] List of translators. If not specified, they will be * retrieved from storage. */ this.init = async function(translators) { if(!translators) { translators = await this.load(); } _cache = {"import":[], "export":[], "web":[], "search":[]}; _translators = {}; _initialized = true; // Build caches for(var i=0; i b.priority) { return 1; } else if (a.priority < b.priority) { return -1; } } for(var type in _cache) { _cache[type].sort(cmp); } Zotero.debug(`Translators initialized with ${translators.length} loaded`); }; this.load = async function() { var translatorsDirPath = path.resolve(path.resolve(__dirname, '..'), Zotero.Prefs.get("translatorsDirectory")); if(!await new Promise(resolve => fs.access(translatorsDirPath, (err) => resolve(!err)))) { throw new Error("Translators directory "+translatorsDirPath+" is not "+ "accessible. Please set this correctly in config.js.\n") } var translatorFilePaths = await new Promise((resolve, reject) => fs.readdir(translatorsDirPath, (err, files) => err ? reject(err) : resolve(files))); var translators = []; for (let filePath of translatorFilePaths) { if (filePath[0] === '.' || filePath.substr(filePath.length-3) !== ".js") continue; filePath = path.resolve(translatorsDirPath, filePath); var data = await new Promise((resolve, reject) => fs.readFile(filePath, "utf8", (err, data) => err ? reject(err) : resolve(data))); // Strip off byte order mark, if one exists if(data[0] === "\uFEFF") data = data.substr(1); // We assume lastUpdated is at the end to avoid running the regexp on more than necessary var lastUpdatedIndex = data.indexOf('"lastUpdated"'); if (lastUpdatedIndex == -1) { Zotero.debug("Invalid or missing translator metadata JSON object in " + filename); continue; } // Add 50 characters to clear lastUpdated timestamp and final "}" var header = data.substr(0, lastUpdatedIndex + 50); var m = infoRe.exec(header); if (!m) { Zotero.debug("Invalid or missing translator metadata JSON object in " + filename); continue; } var metadataString = m[0]; try { var info = JSON.parse(metadataString); } catch(e) { Zotero.debug("Invalid or missing translator metadata JSON object in " + filename); continue; } info.code = data; // We don't ever want to reload from disk again (and don't have the code to do that either) info.cacheCode = true; translators.push(info); } return translators; }; /** * Gets the translator that corresponds to a given ID * * @param {String} id The ID of the translator */ this.get = function (id) { if (!_initialized) { throw new Error("Trying to retrieve a translator without initalizing translator store"); } var translator = _translators[id]; if (!translator) { return false; } return translator; }; /** * Gets all translators for a specific type of translation * @param {String} type The type of translators to get (import, export, web, or search) * @param {Boolean} [debugMode] Whether to assume debugging mode. If true, code is included for * unsupported translators, and code originally retrieved from the * repo is re-retrieved from Zotero Standalone. */ this.getAllForType = async function (type, debugMode) { if(!_initialized) Zotero.Translators.init() var translators = _cache[type].slice(0); var codeGetter = new Zotero.Translators.CodeGetter(translators, debugMode); return codeGetter.getAll().then(function() { return translators; }); }; this.getCodeForTranslator = Zotero.Promise.method(function (translator) { if (translator.code) { return translator.code; } else { throw new Error(`Code for translator ${translator.translatorID} is missing`); } }); /** * Gets web translators for a specific location * @param {String} uri The URI for which to look for translators * @return {Promise} - A promise for a 2-item array containing an array of translators and * an array of functions for converting URLs from proper to proxied forms */ this.getWebTranslatorsForLocation = async function (URI, rootURI) { var isFrame = URI !== rootURI; if(!_initialized) Zotero.Translators.init(); var allTranslators = _cache["web"]; var potentialTranslators = []; var proxies = []; var rootSearchURIs = Zotero.Proxies.getPotentialProxies(rootURI); var frameSearchURIs = isFrame ? Zotero.Proxies.getPotentialProxies(URI) : rootSearchURIs; Zotero.debug("Translators: Looking for translators for "+Object.keys(frameSearchURIs).join(', ')); for(var i=0; i. Utilities based in part on code taken from Piggy Bank 2.1.1 (BSD-licensed) ***** END LICENSE BLOCK ***** */ var Zotero = require('./zotero'); Zotero.OpenURL = Zotero.requireUtilities('./openurl'); Zotero.Date = Zotero.requireUtilities('./date'); Zotero.Utilities = Zotero.requireUtilities('./utilities'); Zotero.Utilities = {...Zotero.Utilities, XRegExp: Zotero.requireUtilities('xregexp-all'), Item: Zotero.requireUtilities('./utilities_item') }; // Due to how Utilities.Translate is constructed from the of // Utilities, we cannot define it above in the object with the rest Zotero.Utilities.Translate = Zotero.requireTranslate('./utilities_translate'); var addZoteroUnicodeData = Zotero.requireUtilities('xregexp-unicode-zotero'); addZoteroUnicodeData(Zotero.Utilities.XRegExp); Zotero.Schema = Zotero.requireUtilities('./schema.js'); Zotero.Schema.init(require('../modules/zotero-schema/schema.json')); module.exports = Zotero.Utilities; ================================================ FILE: src/webEndpoint.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Corporation for Digital Scholarship Vienna, Virginia, USA https://www.zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const WebSession = require('./webSession'); // Timeout for select requests, in seconds const SELECT_TIMEOUT = 60; const sessionsWaitingForSelection = {}; var requestsSinceGC = 0; var WebEndpoint = module.exports = { handle: async function (ctx, next) { ctx.assert(ctx.is('text/plain') || ctx.is('json'), 415); setTimeout(() => { gc(); }); var data = ctx.request.body; if (!data) { ctx.throw(400, "POST data not provided\n"); } // If follow-up URL request, retrieve session and update context var query; var session; if (typeof data == 'object') { let sessionID = data.session; if (!sessionID) { ctx.throw(400, "'session' not provided"); } session = sessionsWaitingForSelection[sessionID]; if (session) { delete sessionsWaitingForSelection[sessionID]; session.ctx = ctx; session.next = next; session.data = data; } else { let single = !!ctx.request.query.single; session = new WebSession(ctx, next, data.url, { single }); } } else { // From https://stackoverflow.com/a/3809435, modified to allow up to 9-char TLDs and IP addresses let urlRE = /^(https?:\/\/)?([-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,9}\b|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|\b)){4})(\S*)$/i; if (!data.match(urlRE)) { ctx.throw(400, "URL not provided"); } // Prepend 'http://' if not provided if (!data.startsWith('http')) { data = 'http://' + data; } let single = !!ctx.request.query.single; session = new WebSession(ctx, next, data, { single }); } await session.handleURL(); if (ctx.response.status == 300) { if(typeof data == 'object') { // Select item if this was an item selection query session.data = data; await session.handleURL(); } else { // Store session if returning multiple choices sessionsWaitingForSelection[session.id] = session; } } } }; /** * Perform garbage collection every 10 requests */ function gc() { if ((++requestsSinceGC) == 10) { for (let i in sessionsWaitingForSelection) { let session = sessionsWaitingForSelection[i]; if (session.started && Date.now() >= session.started + SELECT_TIMEOUT * 1000) { delete sessionsWaitingForSelection[i]; } } requestsSinceGC = 0; } } ================================================ FILE: src/webSession.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Corporation for Digital Scholarship Vienna, Virginia, USA https://www.zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const config = require('config'); const urlLib = require('url'); const { CONTENT_TYPES } = require('./formats'); const Translate = require('./translation/translate'); const TLDS = Zotero.requireTranslate('./tlds'); const HTTP = require('./http'); const Translators = require('./translators'); const ImportEndpoint = require('./importEndpoint'); const SearchEndpoint = require('./searchEndpoint'); const { jar: cookieJar } = require('request'); const SERVER_TRANSLATION_TIMEOUT = 30; const FORWARDED_HEADERS = ['Accept-Language']; var WebSession = module.exports = function (ctx, next, data, options) { this.ctx = ctx; this.next = next; this.data = data; this.options = options; }; /** * @return {Promise} */ WebSession.prototype.handleURL = async function () { if (typeof this.data == 'object') { await this.selectDone(); return; } var url = this.data; // Forward supported headers var headers = {}; for (let header of FORWARDED_HEADERS) { let lc = header.toLowerCase(); if (this.ctx.headers[lc]) { headers[header] = this.ctx.headers[lc]; } } try { var parsedURL = urlLib.parse(url); } catch (e) { this.ctx.throw(400, "Invalid URL provided\n"); } // Check domain var m = url.match(/https?:\/\/([^/]+)/); if (m) { let domain = m[1]; let blacklisted = config.get("blacklistedDomains") .some(x => x && new RegExp(x).test(domain)); if (blacklisted) { let doi = this.cleanDOIFromURL(url); if (!doi) { this.ctx.throw(500, "An error occurred retrieving the document\n"); } await SearchEndpoint.handleIdentifier(this.ctx, { DOI: doi }); return; } } var responseTypeMap = new Map([ ['html', 'document'], ['application/xhtml+xml', 'document'], ['text/plain', 'text'] ]); // Force all import content types to text for (let type in CONTENT_TYPES) { let contentType = CONTENT_TYPES[type]; if (contentType == 'text/html') continue; if (responseTypeMap.has(contentType)) continue; responseTypeMap.set(contentType, 'text'); } var urlsToTry = config.get('deproxifyURLs') ? this.deproxifyURL(url) : [url]; for (let i = 0; i < urlsToTry.length; i++) { let url = urlsToTry[i]; if (urlsToTry.length > 1) { Zotero.debug("Trying " + url); } /*let runningInstance; if ((runningInstance = Zotero.Server.Translation.waitingForSelection[data.sessionid]) && data.items) { // Already waiting for a items response, so just pass this there runningInstance._cookieSandbox.setTimeout(SERVER_TRANSLATION_TIMEOUT*1000, runningInstance.timeout.bind(runningInstance)); runningInstance.sendResponse = sendResponseCallback; runningInstance.selectDone(data.items); break; }*/ // New request this._cookieSandbox = cookieJar(); let resolve; let reject; let promise = new Promise(function () { resolve = arguments[0]; reject = arguments[1]; }); let translate = new Translate.Web(); let translatePromise; translate.setHandler("translators", async function (translate, translators) { // Force single-page saving if (this.options.single) { translators = translators.filter(t => t.itemType != 'multiple'); } try { translatePromise = this.translate(translate, translators); await translatePromise; resolve(); } catch (e) { reject(e); } }.bind(this)); translate.setHandler("select", (translate, items, callback) => { try { this.select( url, translate, items, callback, translatePromise ); } catch (e) { Zotero.debug(e, 1); reject(e); // Resolve the translate promise callback([]); return; } resolve(); }); translate.setCookieSandbox(this._cookieSandbox); translate.setRequestHeaders(headers); try { let req = await Zotero.HTTP.request( "GET", url, { responseTypeMap, cookieSandbox: this._cookieSandbox, headers } ); if (req.type === 'document') { translate.setDocument(req.response); // This could be optimized by only running detect on secondary translators // if the first fails, but for now just run detect on all translate.getTranslators(true); } else { Zotero.debug(`Handling ${req.getResponseHeader('content-type')} as import`); this.ctx.request.body = req.response; await ImportEndpoint.handle(this.ctx); return; } return promise; } catch (e) { Zotero.debug(e, 1); if (e instanceof Zotero.HTTP.StatusError && e.status == 404) { this.ctx.throw(400, "Remote page not found"); } let doi = this.cleanDOIFromURL(url); if (doi) { Zotero.debug(`Error translating page -- continuing with DOI ${doi} from URL`); await SearchEndpoint.handleIdentifier(this.ctx, { DOI: doi }); return; } if (e instanceof Zotero.HTTP.ResponseSizeError) { this.ctx.throw(400, "Response exceeds max size"); } if (e instanceof Zotero.HTTP.UnsupportedFormatError) { this.ctx.throw(400, "The remote document is not in a supported format"); } // No more URLs to try if (i == urlsToTry.length - 1) { this.ctx.throw(500, "An error occurred retrieving the document"); } } } }; /** * Called when translators are available to perform translation * * @return {Promise} */ WebSession.prototype.translate = async function (translate, translators) { // No matching translators if (!translators.length) { Zotero.debug("No translators found -- saving as a webpage"); this.saveWebpage(translate); return; } var translator; var items; while (translator = translators.shift()) { translate.setTranslator(translator); try { items = await translate.translate({ libraryID: false }); break; } catch (e) { Zotero.debug("Translation using " + translator.label + " failed", 1); Zotero.debug(e, 1); // If no more translators, save as webpage if (!translators.length) { this.saveWebpage(translate); return; } // Try next translator } } //this._cookieSandbox.clearTimeout(); // Check for DOI in URL if no results if (!items.length) { let doi = this.cleanDOIFromURL(translate.location); if (doi) { Zotero.debug(`No results -- continuing with DOI ${doi} from URL`); await SearchEndpoint.handleIdentifier(this.ctx, { DOI: doi }); return; } } var json = []; for (let item of items) { json.push(...Zotero.Utilities.Item.itemToAPIJSON(item)); } this.ctx.response.status = 200; this.ctx.response.body = json; }; /** * TEMP: Remove once there's a generic webpage translator * * @return {undefined} */ WebSession.prototype.saveWebpage = function (translate) { let head = translate.document.documentElement.querySelector('head'); if (!head) { // XXX better status code? this.ctx.throw(501, "No translators available\n"); } // TEMP: Return basic webpage item for HTML let description = head.querySelector('meta[name=description]'); if (description) { description = description.getAttribute('content'); } let data = { itemType: "webpage", url: translate.document.location.href, title: translate.document.title, abstractNote: description, accessDate: Zotero.Date.dateToISO(new Date()) }; this.ctx.response.body = Zotero.Utilities.Item.itemToAPIJSON(data); }; /** * Called if multiple items are available for selection from the translator */ WebSession.prototype.select = function (url, translate, items, callback, promise) { // Fix for translators that return item list as array rather than object if (Array.isArray(items)) { let newItems = {}; for (let i = 0; i < items.length; i++) { newItems[i] = items[i]; } items = newItems; } // If translator returns objects with 'title' and 'checked' properties (e.g., PubMed), // extract title for (let i in items) { if (items[i].title) { items[i] = items[i].title; } } this.id = Zotero.Utilities.randomString(15); this.started = Date.now(); this.url = url; this.translate = translate; this.items = items; this.selectCallback = callback; this.translatePromise = promise; // Send "Multiple Choices" HTTP response //this._cookieSandbox.clearTimeout(); this.ctx.response.status = 300; this.ctx.response.body = { url, session: this.id, items }; }; /** * Called when items have been selected by the client */ WebSession.prototype.selectDone = function () { var url = this.data.url; var selectedItems = this.data.items; if (this.url != url) { this.ctx.throw(409, "'url' does not match URL in session"); } if (!selectedItems) { this.ctx.throw(400, "'items' not provided"); } // Make sure items are actually available var haveItems = false; for (let i in selectedItems) { if (this.items[i] === undefined || this.items[i] !== selectedItems[i]) { this.selectCallback([]); this.ctx.throw(409, "Items specified do not match items available"); } haveItems = true; } // Make sure at least one item was specified if (!haveItems) { this.selectCallback([]); this.ctx.throw(400, "No items specified"); } // Run select callback this.selectCallback(selectedItems); // The original translate promise in this.translate() from the first request is stalled while // waiting for item select from the client. When the follow-up request comes in, the new ctx // object is swapped in by the endpoint code, and the select callback above allows the // translate promise to complete and the translated items to be assigned to the new ctx // response body. return this.translatePromise; }; /** * Called if the request timed out before it could complete */ /*WebSession.prototype.timeout = function() { this.sendResponse(504, "text/plain", "Translation timed out.\n"); };*/ /** * Try to determine whether the passed URL looks like a proxied URL based on TLDs in the * middle of the domain and return a list of likely URLs, starting with the longest domain * and ending with the original one * * E.g., https://www-example-co-uk.mutex.gmu.edu -> * * [ * 'https://www.example.co.uk', * 'https://www.example.co', * 'https://www-example-co-uk.mutex.gmu.edu', * ] * * Based on Zotero.Proxies.getPotentialProxies() */ WebSession.prototype.deproxifyURL = function (url) { var urlToProxy = { [url]: null }; // if there is a subdomain that is also a TLD, also test against URI with the domain // dropped after the TLD // (i.e., www.nature.com.mutex.gmu.edu => www.nature.com) var m = /^(https?:\/\/)([^\/]+)/i.exec(url); if (m) { // First, drop the 0- if it exists (this is an III invention) var host = m[2]; if (host.substr(0, 2) === "0-") host = host.substr(2); var hostnameParts = [host.split(".")]; if (m[1] == 'https://') { // try replacing hyphens with dots for https protocol // to account for EZProxy HttpsHypens mode hostnameParts.push(host.split('.')); hostnameParts[1].splice(0, 1, ...(hostnameParts[1][0].replace(/-/g, '.').split('.'))); } for (let i=0; i < hostnameParts.length; i++) { let parts = hostnameParts[i]; // If hostnameParts has two entries, then the second one is with replaced hyphens let dotsToHyphens = i == 1; // skip the lowest level subdomain, domain and TLD for (let j=1; j b.length - a.length); urls.push(urls.shift()); return urls; }; WebSession.prototype.cleanDOIFromURL = function (url) { let doi = Zotero.Utilities.cleanDOI(decodeURIComponent(url)); if (doi) { // Stop at query string, ampersand, or hash doi = doi.replace(/[?&#].*/, ''); } return doi || null; }; ================================================ FILE: src/zotero.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ const path = require('path'); const config = require('config'); const fs = require('fs'); var Zotero = global.Zotero = module.exports = new function() { this.isNode = true; this.isServer = true; this.locale = 'en-US'; this.version = "5.0.97"; /** * Debug logging function * * Uses prefs e.z.debug.log and e.z.debug.level (restart required) * * Defaults to log level 3 if level not provided */ this.debug = function(message, level) { Zotero.Debug.log(message, level); } /** * Log a JS error to the Mozilla JS error console. * @param {Exception} err */ this.logError = function(err) { // Firefox uses this Zotero.debug(err); } this.setTimeout = setTimeout; } // TODO: Pref store Zotero.Prefs = new function(){ var tempStore = {}; this.get = function(pref) { if (tempStore.hasOwnProperty(pref)) return tempStore[pref]; if (config.has(pref)) return config.get(pref); }; /** * @param pref * @param value */ this.set = function(pref, value) { tempStore[pref] = value; }; /** * @param pref */ this.clear = function(pref) { delete tempStore[pref]; } } /** * A custom require function to import modules from the translate submodule * @param {String} modulePath * @returns {*} */ Zotero.requireTranslate = function(modulePath) { return require(path.resolve(__dirname, '../modules/translate/src/', modulePath)); } Zotero.requireUtilities = function(modulePath) { return require(path.resolve(__dirname, '../modules/utilities/', modulePath)); } Zotero.Promise = Zotero.requireTranslate('./promise'); Zotero.Debug = Zotero.requireTranslate('./debug'); Zotero.Translators = require('./translators'); Zotero.Utilities = require('./utilities'); Zotero.Date = Zotero.requireUtilities('./date'); Zotero.Date.init(Zotero.requireUtilities('./resource/dateFormats.json')) Zotero.OpenURL = Zotero.requireUtilities('./openurl'); Zotero.Translator = Zotero.requireTranslate('./translator'); Zotero.Translate = require('./translation/translate'); Zotero.Proxies = require('./proxy').Proxies; Zotero.Proxy = require('./proxy').Proxy; var $rdf = Zotero.requireTranslate('./rdf/init'); if(Zotero.RDF) { Zotero.RDF.AJAW = $rdf; } else { Zotero.RDF = {AJAW:$rdf}; } Zotero = Object.assign(Zotero, Zotero.requireUtilities('./cachedTypes')); Zotero.setTypeSchema(Zotero.requireUtilities('./resource/zoteroTypeSchemaData')); ================================================ FILE: test/data/bibtex_response.xml ================================================ @article{Bar19, author = "Foo Bar", title = "Title", journal = "Journal", volume = 123, year = 2019, pages = "123--125"} ================================================ FILE: test/data/loc_book1_response.xml ================================================ 1.11xml 01691cam a2200361 a 4500 16725802 20120514113518.0 110407s2011 mdua b 001 0 eng 7 cbc orignew 1 ecip 20 y-gencatlg acquire 2 shelf copies policy default xh09 2011-04-07 xh09 2011-04-07 to Dewey rd14 2011-04-07 xn02 2011-12-13 1 copy rec'd., to CIP ver. rf10 2012-02-27 Z-CipVer. telework to BCDD xn05 2012-05-14 copy 2 added 2011009234 015994368 Uk 1421402831 (hardcover : alk. paper) 9781421402833 (hardcover : alk. paper) (OCoLC)ocn711959730 DLC DLC YDX YDXCP BWX CDX IXA UKMGB ZCU DLC pcc e-fr--- TX719 .T253 2011 641.5944 22 Takats, Sean, 1974- The expert cook in enlightenment France / Sean Takats. Baltimore : Johns Hopkins University Press, 2011. x, 203 p. : ill. ; 24 cm. The Johns Hopkins University studies in historical and political science, 129th series ; 2 Includes bibliographical references (p.[179]-196) and index. Defining the cook -- Corrupting spaces -- Pots and pens -- Theorizing the kitchen -- The servant of medicine -- Conclusion. Cooking, French History 18th century. Cooking France History 18th century. Cooks France History 18th century. France Social life and customs 18th century. Johns Hopkins University studies in historical and political science ; 129th ser., 2. 11.1bath.ISBN=^97814214028331xml ================================================ FILE: test/data/pubmed_article1_response.xml ================================================ 30571677 2018 12 20
1553-7358 14 12 2018 Dec PLoS computational biology PLoS Comput. Biol. Ten simple rules for documenting scientific software. e1006561 10.1371/journal.pcbi.1006561 Lee Benjamin D BD http://orcid.org/0000-0002-7133-8397 School of Engineering and Applied Sciences, Harvard University, Cambridge, Massachusetts, United States of America. eng Editorial 2018 12 20
United States PLoS Comput Biol 101238922 1553-734X The author has declared that no competing interests exist.
2018 12 21 6 0 2018 12 21 6 0 2018 12 21 6 0 epublish 30571677 10.1371/journal.pcbi.1006561 PCOMPBIOL-D-18-01117
================================================ FILE: test/export_test.js ================================================ /* global assert:false, request:false */ var { JSDOM } = require('jsdom'); const dom = new JSDOM(''); const DOMParser = dom.window.DOMParser; describe("/export", function () { var json = [{"key":"Q5VYZIG2","version":0,"itemType":"newspaperArticle","creators":[{"firstName":"Keith","lastName":"Collins","creatorType":"author"}],"tags":[{"tag":"Net Neutrality","type":1},{"tag":"Pai, Ajit","type":1},{"tag":"Federal Communications Commission","type":1},{"tag":"Regulation and Deregulation of Industry","type":1},{"tag":"Computers and the Internet","type":1}],"title":"Net Neutrality Has Officially Been Repealed. Here’s How That Could Affect You.","section":"Technology","url":"https://www.nytimes.com/2018/06/11/technology/net-neutrality-repeal.html","abstractNote":"Net Neutrality rules that required internet service providers to offer equal access to all web content are no longer in effect as of Monday.","language":"en-US","libraryCatalog":"NYTimes.com","accessDate":"2018-08-21T08:23:37Z","date":"2018-06-11","publicationTitle":"The New York Times","ISSN":"0362-4331"}]; var jsonMinimal = [{ key: "JZMIXKUW", version: 0, itemType: "webpage", url: "http://example.com/", title: "Example", accessDate: "2019-01-14T20:18:11Z"}] it("should export to BibTeX (full)", async function () { var response = await request() .post('/export?format=bibtex') .send(json) .expect(200); assert.isTrue(response.text.trim().startsWith('@article')); }); it("should export to BibTeX (minimal)", async function () { var response = await request() .post('/export?format=bibtex') .send(jsonMinimal) .expect(200); assert.isTrue(response.text.trim().startsWith('@misc')); }); it("should set BibTeX access date", async function () { var response = await request() .post('/export?format=bibtex') .send(jsonMinimal) .expect(200); assert.match(response.text, /urldate = {2019-01-14}/); }); it("should export to RIS (full)", async function () { var response = await request() .post('/export?format=ris') .send(json) .expect(200); assert.isTrue(response.text.startsWith('TY - NEWS')); }); it("should export to RIS (minimal)", async function () { var response = await request() .post('/export?format=ris') .send(jsonMinimal) .expect(200); console.log(response.text); assert.isTrue(response.text.startsWith('TY - ELEC')); }); it("should export COinS (full)", async function () { var response = await request() .post('/export?format=coins') .send(json) .expect(200) .expect('Content-Type', 'text/html'); assert.isTrue(response.text.startsWith(" Zotero.Utilities.Item.itemToAPIJSON(item))), // normalize and flatten results found: response.body, }; for (const ef of ['expected', 'found']) { for (const item of items[ef]) { // inline attached notes -- notes are exported as separate items with a parentItem, but the parentItem is going to be different every time the test is ran if (!item.notes) { item.notes = items[ef] .filter(note => (note.itemType === 'note' && note.parentItem === item.key)) .map(note => ({ note: note.note, itemType: note.itemType})); } } // remove notes now inlined items[ef] = items[ef].filter(item => (item.itemType !== 'note' || !item.parentItem)); for (const item of items[ef]) { // remove purely administrative fields -- must be done in 2nd run because the key/parentItem are required in the 1st run for inlining notes delete item.key; delete item.version; delete item.parentItem; // remove empty array to simplify comparison if (Array.isArray(item.tags) && !item.tags.length) { delete item.tags; } // sort tags for stable comparison if (item.tags) { item.tags.sort((a, b) => `${a.type}::${a.tag}`.localeCompare(`${b.type}::${b.tag}`)); } } } assert.deepEqual(items.expected, items.found); }); } function parseJSON(name, json, source) { try { return JSON.parse(json); } catch (err) { it(`should import ${name}`, function () { const m = err.message.match(/(.*) at position ([0-9]+)$/); if (m) { const pos = parseInt(m[2]); const line = source.substring(0, source.indexOf(json) + pos).split('\n').length; const column = pos - json.lastIndexOf('\n', pos); throw new Error(`${m[1]} around line ${line}, column ${column}`); } throw err; }); } return null; } (process.env.IMPORT_TESTS ? describe : describe.skip)("/import", function () { const translators = path.join(__dirname, '../modules/translators'); for (const translator of fs.readdirSync(translators)) { if (!translator.endsWith('.js')) continue; const name = translator.replace(/\.js$/, ''); const code = fs.readFileSync(path.join(translators, translator), 'utf-8'); const marker = code.indexOf('/** BEGIN TEST CASES **/'); if (marker === -1) continue; const header = parseJSON(name, code.replace(/\n}\n[\s\S]*/, '}'), code); if (!header) continue; const start = code.indexOf('[', marker); const end = code.lastIndexOf(']') + 1; const cases = parseJSON(name, code.substring(Math.max(start, marker), Math.max(end, start, marker)), code); if (!cases) continue; let caseNo = 0; for (const test of cases) { caseNo += 1; if (test.type !== 'import') continue; addTest(`${name} # ${caseNo}`, header.translatorID, test.input, test.items); } } }); ================================================ FILE: test/mocha.opts ================================================ --file test/setup.js ================================================ FILE: test/search_test.js ================================================ /* global assert:false, request:false, sinon:false */ const config = require('config'); const HTTP = require('../src/http'); const TextSearch = require('../src/textSearch'); const path = require('path'); const fs = require('fs'); const urlParse = require('url'); describe("/search", function () { var bookISBN1 = '9781421402833'; var bookTitle1 = 'The expert cook in enlightenment France'; var articlePMID1 = '30571677'; var articleTitle1 = 'Ten simple rules for documenting scientific software'; beforeEach(() => { var origHTTPRequest = HTTP.request.bind(HTTP); sinon.stub(HTTP, 'request').callsFake(async function (method, url, options) { if (url.startsWith('http://127.0.0.1')) { return origHTTPRequest(method, url, options); } Zotero.debug("Mocking request"); if (url.startsWith('https://www.crossref.org')) { return { status: 200, responseText: '' + '' + 'Either ISSN or Journal title or Proceedings title must be supplied.' + '' }; } // Mock Library of Congress ISBN lookup if (url.startsWith('https://lx2.loc.gov')) { var xml = fs.readFileSync( path.join(__dirname, 'data', 'loc_book1_response.xml'), { encoding: 'utf-8' } ); return { status: 200, responseText: xml }; } if (url.startsWith('https://eutils.ncbi.nlm.nih.gov')) { let xml = fs.readFileSync( path.join(__dirname, 'data', 'pubmed_article1_response.xml'), { encoding: 'utf-8' } ); return { status: 200, responseText: xml }; } Zotero.debug("Unhandled request"); throw new Error("Unhandled request"); }); // Mock identifier-search Lambda call var origQueryLambda = TextSearch.queryLambda.bind(TextSearch); sinon.stub(TextSearch, 'queryLambda').callsFake(function (query) { if (query == bookTitle1.toLowerCase()) { return Promise.resolve([{"ISBN":bookISBN1}]); } return origQueryLambda(query); }); }); afterEach(() => { HTTP.request.restore(); TextSearch.queryLambda.restore(); }); it("should perform a text search", async function () { config.identifierSearchLambda = 'IdentifierSearch'; var response = await request() .post('/search') .set('Content-Type', 'text/plain') .send(bookTitle1.toLowerCase()); assert.equal(response.statusCode, 300); var json = response.body; assert.lengthOf(Object.keys(json), 1); assert.equal(json[bookISBN1].itemType, 'book'); assert.equal(json[bookISBN1].title, bookTitle1); }); it("should translate an ISBN", async function () { var response = await request() .post('/search') .set('Content-Type', 'text/plain') .send(bookISBN1); assert.equal(response.statusCode, 200); var json = response.body; assert.lengthOf(json, 2); assert.equal(json[0].itemType, 'book'); assert.equal(json[0].title, bookTitle1); // This note contains keywords that should probably be tags assert.equal(json[1].itemType, 'note'); assert.equal(json[1].parentItem, json[0].key); }); it("should translate a PMID", async function () { var response = await request() .post('/search') .set('Content-Type', 'text/plain') .send(articlePMID1); assert.equal(response.statusCode, 200); var json = response.body; assert.lengthOf(json, 1); assert.equal(json[0].itemType, 'journalArticle'); assert.equal(json[0].title, articleTitle1); }); it("should translate a PMID with 'pmid:' prefix", async function () { var response = await request() .post('/search') .set('Content-Type', 'text/plain') .send('pmid:' + articlePMID1); assert.equal(response.statusCode, 200); var json = response.body; assert.lengthOf(json, 1); assert.equal(json[0].itemType, 'journalArticle'); assert.equal(json[0].title, articleTitle1); }); }); ================================================ FILE: test/setup.js ================================================ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "bodyParser" }] */ const config = require('config'); const request = require('supertest'); const chai = require('chai'); global.sinon = require('sinon'); const app = require('../src/server'); const Koa = require('koa'); const _ = require('koa-route'); const bodyParser = require('koa-bodyparser'); const TestEndpoint = require('../src/testEndpoint'); // Globals that are available to every test global.assert = chai.assert; global.request = function () { return request(app.callback()) }; global.testURL = `http://127.0.0.1:${config.get('testPort')}/test/`; // Serve sample pages for tests const testApp = new Koa(); testApp.use(_.get('/test/plain', TestEndpoint.handlePlain)); testApp.use(_.get('/test/single', TestEndpoint.handleSingle)); testApp.use(_.get('/test/multiple', TestEndpoint.handleMultiple)); testApp.use(_.get('/test/redirect', TestEndpoint.handleRedirect)); testApp.use(_.get('/test/bibtex', TestEndpoint.handleBibTeX)); testApp.use(_.get('/test/invalidContentType', TestEndpoint.invalidContentType)); testApp.use(_.get('/test/missingContentType', TestEndpoint.missingContentType)); var testServer = testApp.listen(config.get('testPort')); before(async function () { // Wait for translator initialization await Promise.delay(500); }); after(function () { testServer.close(); }); ================================================ FILE: test/testTranslators/testTranslators.js ================================================ /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2018 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see . ***** END LICENSE BLOCK ***** */ 'use strict'; process.on('unhandledRejection', (err, p) => { console.error(err); }); require('../../src/zotero'); require('../../src/translation/translate'); require('../../src/http'); const { basename } = require('path'); const yargs = require('yargs'); const fs = require('fs').promises; const { jar: cookieJar } = require('request'); const {TranslatorTester} = require('../../modules/translate/testTranslators/translatorTester.js'); let options = yargs .usage(`Usage: ${basename(process.argv[0])} [options]`) .wrap(78) .option('output', { type: 'string', alias: 'o', describe: 'Path to the output file for translation results' }) .option('cross-origin', { type: 'boolean', default: true, describe: 'Enable cross-origin HTTP requests in translators' }) .option('num-concurrent-tests', { type: 'number', default: 10 }) .option('grep', { type: 'string', alias: 'g', describe: 'Only test translators with matching labels or ids' }) .option('browser', { type: 'string', alias: 'b', default: 'v', describe: "The browser flag" }) .argv; // For debugging specific translators by label let regexp = options.g && new RegExp(options.g); const TEST_TYPES = ["web", "import", "export", "search"]; var results = []; // NOTE: We need to attach a cookie sandbox to the translate instances to make websites with // cookie forgetting browser/scrapper protection happy when calling HTTP.processDocuments(). // Thus we're overriding the translate instance constructing method and attaching a cookie jar Zotero.Translate.newInstance = function(type) { let translate = new Zotero.Translate[type.substr(0, 1).toUpperCase()+type.substr(1).toLowerCase()]; if (translate.setCookieSandbox) { translate.setCookieSandbox(cookieJar()); } return translate; } if (!options.crossOrigin) { // Monkey patching translator http methods to disallow cross-origin requests let throwIfDifferentOrigins = function(origin, url) { let a = new URL(origin), b = new URL(url); if (a.origin != b.origin) { throw new Error(`Cross origin request from ${origin} to ${url} not allowed`); } } let doGet = Zotero.Utilities.Translate.prototype.doGet; let doPost = Zotero.Utilities.Translate.prototype.doPost; Zotero.Utilities.Translate.prototype.doGet = function(urls) { if (!this._translate.location) return; if(typeof(urls) == "string") { var url = urls; } else { var url = arguments[0].shift(); } throwIfDifferentOrigins(this._translate.location, url); return doGet.apply(this, arguments); } Zotero.Utilities.Translate.prototype.doPost = function() { if (!this._translate.location) return; throwIfDifferentOrigins(this._translate.location, arguments[0]); return doPost.apply(this, arguments); } } /** * Runs a specific set of tests */ async function runTesters(translators, type) { for (let translator of translators) { let tester = new TranslatorTester(translator, type, (_, t)=> console.log(t + '\n')); await new Promise(resolve => { tester.runTests(function() { try { if(tester.pending.length) return; // Done translating, so serialize test results let result = tester.serialize(); results.push(result); resolve(result); } catch(e) { Zotero.debug(e); Zotero.logError(e); resolve(); } }) }); } return; } (async function() { Zotero.Debug.init(0); await Zotero.Translators.init(); for (let type of TEST_TYPES) { let translators = await Zotero.Translators.getAllForType(type, true); try { // Concurrent async via iterators magic // https://stackoverflow.com/a/51020535 if (regexp) { translators = translators.filter(t => regexp.test(t.label) || regexp.test(t.translatorID)); } let iterator = translators.values(); let promises = new Array(options.numConcurrentTests).fill(iterator).map(t => runTesters(t, type)); await Promise.all(promises); } catch(e) { Zotero.debug(e); Zotero.logError(e); } } results.sort(function(a, b) { var atype = TEST_TYPES.indexOf(a.type); var btype = TEST_TYPES.indexOf(b.type); if (atype != btype) return atype-btype; else return a.label.localeCompare(b.label); }) let result = { browser: options.browser, version: Zotero.version, results: results }; if (options.o) { await fs.writeFile(options.o, JSON.stringify(result, null, '\t')); } // If any tests failed, return non-0 exit code let retVal = 0; if (results.some(r => r.failed.length || r.unknown.length)) { retVal = 1; } process.exit(retVal); })(); ================================================ FILE: test/web_test.js ================================================ /* global assert:false, request:false, testURL:false */ describe("/web", function () { it("should translate a generic webpage", async function () { var url = testURL + 'plain'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 200); var json = response.body; assert.lengthOf(json, 1); assert.equal(json[0].itemType, 'webpage'); assert.equal(json[0].title, 'Test'); }); it("should translate a webpage with embedded metadata", async function () { var url = testURL + 'single'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 200); var json = response.body; assert.lengthOf(json, 1); assert.equal(json[0].itemType, 'journalArticle'); assert.equal(json[0].title, 'Title'); }); it("should return multiple results and perform follow-up translation", async function () { var url = testURL + 'multiple'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 300); var json = response.body; assert.equal(json.url, url); assert.property(json, 'session'); assert.deepEqual(json.items, { 0: 'A', 1: 'B', 2: 'C' }); delete json.items[1]; response = await request() .post('/web') .send(json); assert.equal(response.statusCode, 200); json = response.body; assert.lengthOf(json, 2); assert.equal(json[0].title, 'A'); assert.equal(json[1].title, 'C'); }); // Simulate a request to a different server without the cached session id it("should return multiple results and perform follow-up translation with unknown session id", async function () { var url = testURL + 'multiple'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 300); var json = response.body; assert.equal(json.url, url); assert.property(json, 'session'); assert.deepEqual(json.items, { 0: 'A', 1: 'B', 2: 'C' }); delete json.items[1]; // Change the session id json.session[0] = json.session[0] == 'a' ? 'b' : 'a'; response = await request() .post('/web') .send(json); assert.equal(response.statusCode, 200); json = response.body; assert.lengthOf(json, 2); assert.equal(json[0].title, 'A'); assert.equal(json[1].title, 'C'); }); it("should follow a redirect and use the final URL for translation", async function () { var url = testURL + 'redirect'; var finalURL = testURL + 'single'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 200); var json = response.body; assert.lengthOf(json, 1); assert.equal(json[0].itemType, 'journalArticle'); assert.equal(json[0].title, 'Title'); assert.equal(json[0].url, finalURL); }); it("should translate a remote BibTeX file", async function () { var url = testURL + 'bibtex'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 200); var json = response.body; assert.lengthOf(json, 1); assert.equal(json[0].itemType, 'journalArticle'); assert.equal(json[0].title, 'Title'); }); it("should return 400 if a page returns a 404", async function () { var url = testURL + '404'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 400); assert.equal(response.text, 'Remote page not found'); }); // Note: This doesn't test subsequent requests during translation it("should forward the Accept-Language header in the initial request", async function () { var url = testURL + 'single'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .set('Accept-Language', 'fr') .send(url); assert.equal(response.statusCode, 200); var json = response.body; assert.lengthOf(json, 1); assert.equal(json[0].itemType, 'journalArticle'); assert.equal(json[0].title, 'Titre'); }); it("should reject non-HTML/XML upstream content types", async function () { var url = testURL + 'invalidContentType'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 400); assert.equal(response.text, "The remote document is not in a supported format"); }); it("should reject missing upstream Content-Type header", async function () { var url = testURL + 'missingContentType'; var response = await request() .post('/web') .set('Content-Type', 'text/plain') .send(url); assert.equal(response.statusCode, 400); assert.equal(response.text, "The remote document is not in a supported format"); }); }); ================================================ FILE: translate_export ================================================ #!/bin/bash format="$1" if [ -z "$1" ]; then echo "Usage: $0 format" exit 1 fi json='[{"key":"Q5VYZIG2","version":0,"itemType":"newspaperArticle","creators":[{"firstName":"Keith","lastName":"Collins","creatorType":"author"}],"tags":[{"tag":"Net Neutrality","type":1},{"tag":"Pai, Ajit","type":1},{"tag":"Federal Communications Commission","type":1},{"tag":"Regulation and Deregulation of Industry","type":1},{"tag":"Computers and the Internet","type":1}],"title":"Net Neutrality Has Officially Been Repealed. Here’s How That Could Affect You.","section":"Technology","url":"https://www.nytimes.com/2018/06/11/technology/net-neutrality-repeal.html","abstractNote":"Net Neutrality rules that required internet service providers to offer equal access to all web content are no longer in effect as of Monday.","language":"en-US","libraryCatalog":"NYTimes.com","accessDate":"2018-08-21T08:23:37Z","date":"2018-06-11","publicationTitle":"The New York Times","ISSN":"0362-4331"}]' curl -v -d "$json" -H "Content-Type: application/json" "127.0.0.1:1969/export?format=$format" ================================================ FILE: translate_search ================================================ #!/bin/bash URL="$1" if [ -z "$1" ]; then echo "Usage: $0 identifier-or-phrase" exit 1 fi curl -v -d "$URL" -H "Content-Type: text/plain" 127.0.0.1:1969/search ================================================ FILE: translate_url ================================================ #!/bin/bash URL="$1" if [ -z "$1" ]; then echo "Usage: $0 URL" exit 1 fi curl -v -d "$URL" -H "Content-Type: text/plain" 127.0.0.1:1969/web ================================================ FILE: translate_url_multiple ================================================ #!/bin/bash URL="$1" if [ -z "$1" ]; then echo "Usage: $0 URL" exit 1 fi curl -v -d "$URL" -H "Content-Type: text/plain" 127.0.0.1:1969/web | jq '{ url: .url, session: .session, items: .items | to_entries | [.[0]] | from_entries }' | curl -v -d @- -H "Content-Type: application/json" 127.0.0.1:1969/web ================================================ FILE: translate_url_single ================================================ #!/bin/bash URL="$1" if [ -z "$1" ]; then echo "Usage: $0 URL" exit 1 fi curl -v -d "$URL" -H 'Content-Type: text/plain' '127.0.0.1:1969/web?single=1'