├── .coveragerc
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── MANIFEST.in
├── README.rst
├── ckanext
├── __init__.py
└── extractor
│ ├── __init__.py
│ ├── config.py
│ ├── fanstatic
│ └── .gitignore
│ ├── i18n
│ └── ckanext-extractor.pot
│ ├── interfaces.py
│ ├── lib.py
│ ├── logic
│ ├── __init__.py
│ ├── action.py
│ ├── auth.py
│ ├── helpers.py
│ └── schema.py
│ ├── model.py
│ ├── paster.py
│ ├── plugin.py
│ ├── public
│ └── .gitignore
│ ├── tasks.py
│ ├── templates
│ └── .gitignore
│ └── tests
│ ├── __init__.py
│ ├── helpers.py
│ ├── logic
│ ├── __init__.py
│ └── test_action.py
│ ├── test.pdf
│ ├── test_interfaces.py
│ ├── test_lib.py
│ ├── test_plugin.py
│ └── test_tasks.py
├── dev-requirements.txt
├── requirements.txt
├── runtests.sh
├── setup.cfg
├── setup.py
├── test-local.ini.example
├── test.ini
└── travis
├── build.bash
├── run.bash
├── solr
├── ckan-2.6
│ ├── schema.xml
│ └── solrconfig.xml
├── ckan-2.7
│ ├── schema.xml
│ └── solrconfig.xml
├── ckan-2.8
│ ├── schema.xml
│ └── solrconfig.xml
├── ckan-master
│ ├── schema.xml
│ └── solrconfig.xml
└── solrconfig.xml
└── test-local.ini
/.coveragerc:
--------------------------------------------------------------------------------
1 | [report]
2 | omit =
3 | */site-packages/*
4 | */python?.?/*
5 | ckan/*
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /test-local.ini
2 | /README.html
3 |
4 | .ropeproject
5 | node_modules
6 | bower_components
7 |
8 | # Byte-compiled / optimized / DLL files
9 | __pycache__/
10 | *.py[cod]
11 |
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | env/
18 | build/
19 | develop-eggs/
20 | dist/
21 | sdist/
22 | *.egg-info/
23 | .installed.cfg
24 | *.egg
25 |
26 | # PyInstaller
27 | # Usually these files are written by a python script from a template
28 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
29 | *.manifest
30 | *.spec
31 |
32 | # Installer logs
33 | pip-log.txt
34 | pip-delete-this-directory.txt
35 |
36 | # Unit test / coverage reports
37 | htmlcov/
38 | .tox/
39 | .coverage
40 | .cache
41 | nosetests.xml
42 | coverage.xml
43 |
44 | # Sphinx documentation
45 | docs/_build/
46 |
47 | # Vim
48 | .*.swp
49 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 |
3 | sudo: required
4 |
5 | python:
6 | - "2.7"
7 |
8 | services:
9 | - postgresql
10 | - redis-server
11 |
12 | addons:
13 | postgresql: "9.4"
14 |
15 | env:
16 | - CKANVERSION=master
17 | - CKANVERSION=2.8
18 | - CKANVERSION=2.7
19 | - CKANVERSION=2.6
20 |
21 | install: bash travis/build.bash
22 |
23 | script: bash travis/run.bash
24 |
25 | after_success: coveralls
26 |
27 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log for ckanext-extractor
2 |
3 | The format of this file is based on [Keep a Changelog], and this
4 | project uses [Semantic Versioning].
5 |
6 |
7 | ## [Unreleased]
8 |
9 | ### Fixed
10 |
11 | - Improved the update of the search index after extraction (reported by
12 | [@jbothma](https://github.com/stadt-karlsruhe/ckanext-extractor/issues/16))
13 |
14 |
15 | ## [0.4.0] (2018-01-29)
16 |
17 | ### Changed
18 |
19 | - Moved from CKAN's deprecated, Celery-based background task system to the
20 | [new system](http://docs.ckan.org/en/latest/maintaining/background-tasks.html)
21 | introduced in CKAN 2.7. Users of CKAN 2.6 and older need to install
22 | [ckanext-rq](https://github.com/ckan/ckanext-rq). See the README for details
23 | ([#9](https://github.com/stadt-karlsruhe/ckanext-extractor/issues/9))
24 |
25 | ### Fixed
26 |
27 | - Handling of multiple values for the same metadata field (reported by
28 | [@gjackson12](https://github.com/stadt-karlsruhe/ckanext-extractor/issues/11))
29 |
30 |
31 | ## [0.3.1] (2017-11-22)
32 |
33 | ### Fixed
34 |
35 | - Don't validate package dicts when re-indexing them (reported and contributed
36 | by [@wardi](https://github.com/stadt-karlsruhe/ckanext-extractor/pull/6))
37 |
38 | - Fixed a crash when trying to extract from a resource in a private dataset.
39 | Private datasets are now ignored. (reported by
40 | [@gjackson12](https://github.com/stadt-karlsruhe/ckanext-extractor/issues/8))
41 |
42 |
43 | ## [0.3.0] (2017-05-10)
44 |
45 | ### Added
46 |
47 | - `IExtractorRequest` interface for adjusting the download request (contributed
48 | by [@metaodi](https://github.com/stadt-karlsruhe/ckanext-extractor/pull/5))
49 |
50 | ### Changed
51 |
52 | - Moved change log to a separate file
53 |
54 | ### Fixed
55 |
56 | - Improved handling of errors when downloading resource data (reported by
57 | [@phisqb](https://github.com/stadt-karlsruhe/ckanext-extractor/issues/4))
58 |
59 |
60 | ## [0.2.0] (2016-10-19)
61 |
62 | ### Added
63 |
64 | - `IExtractorPostprocessor` interface for postprocessing extraction results
65 |
66 | ### Fixed
67 |
68 | - Fixed logging problems in `paster` commands
69 |
70 |
71 | ## 0.1.0 (2016-06-14)
72 |
73 | - First release
74 |
75 |
76 | [Keep a Changelog]: http://keepachangelog.com
77 | [Semantic Versioning]: http://semver.org/
78 |
79 | [Unreleased]: https://github.com/stadt-karlsruhe/ckanext-extractor/compare/v0.4.0...master
80 | [0.4.0]: https://github.com/stadt-karlsruhe/ckanext-extractor/compare/v0.3.1...v0.4.0
81 | [0.3.1]: https://github.com/stadt-karlsruhe/ckanext-extractor/compare/v0.3.0...v0.3.1
82 | [0.3.0]: https://github.com/stadt-karlsruhe/ckanext-extractor/compare/v0.2.0...v0.3.0
83 | [0.2.0]: https://github.com/stadt-karlsruhe/ckanext-extractor/compare/v0.1.0...v0.2.0
84 |
85 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.rst
2 | include requirements.txt
3 | recursive-include ckanext/extractor *.html *.json *.js *.less *.css *.mo
4 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | ckanext-extractor
2 | #################
3 |
4 | .. image:: https://travis-ci.org/stadt-karlsruhe/ckanext-extractor.svg?branch=master
5 | :target: https://travis-ci.org/stadt-karlsruhe/ckanext-extractor
6 |
7 | .. image:: https://coveralls.io/repos/github/stadt-karlsruhe/ckanext-extractor/badge.svg?branch=master
8 | :target: https://coveralls.io/github/stadt-karlsruhe/ckanext-extractor
9 |
10 | A CKAN_ extension for automatically extracting text and metadata from datasets.
11 |
12 | *ckanext-extractor* automatically extracts text and metadata from your
13 | resources and adds them to the search index so that they can be used to find
14 | your data.
15 |
16 | .. _CKAN: https://www.ckan.org
17 |
18 |
19 | Requirements
20 | ============
21 | *ckanext-extractor* has been developed and tested with CKAN 2.6 and later.
22 | Other versions may or may not work.
23 |
24 | Since *ckanext-extractor* relies on the background job system introduced in
25 | CKAN 2.7, users of earlier CKAN versions need to also install ckanext-rq_.
26 |
27 | .. _ckanext-rq: https://github.com/ckan/ckanext-rq
28 |
29 |
30 | Installation
31 | ============
32 | **Note:** The following steps assume a standard CKAN source installation.
33 |
34 | Install Python Package
35 | ----------------------
36 | Activate your CKAN virtualenv::
37 |
38 | . /usr/lib/ckan/default/bin/activate
39 |
40 | Install the latest development version of *ckanext-extractor* and its
41 | dependencies::
42 |
43 | cd /usr/lib/ckan/default
44 | pip install -e git+https://github.com/stadt-karlsruhe/ckanext-extractor#egg=ckanext-extractor
45 | pip install -r src/ckanext-extractor/requirements.txt
46 |
47 | On a production system you'll probably want to pin a certain `release version`_
48 | of *ckanext-extractor* instead::
49 |
50 | pip install -e git+https://github.com/stadt-karlsruhe/ckanext-extractor@v0.4.0#egg=ckanext-extractor
51 |
52 | .. _release version: https://github.com/stadt-karlsruhe/ckanext-extractor/releases
53 |
54 | Configure CKAN
55 | --------------
56 | Open your CKAN configuration file (e.g. ``/etc/ckan/default/production.ini``)
57 | and add ``extractor`` to the list of plugins::
58 |
59 | ckan.plugins = ... extractor
60 |
61 | Initialize the database::
62 |
63 | paster --plugin=ckanext-extractor init -c /etc/ckan/default/production.ini
64 |
65 |
66 | Start Background Worker
67 | -----------------------
68 | *ckanext-extractor* uses background jobs to perform the extraction
69 | asynchronously so that they do not block the web server. You therefore need to
70 | make sure that a CKAN background worker is running::
71 |
72 | paster --plugin=ckan jobs worker --config=/etc/ckan/default/production.ini
73 |
74 | See the `CKAN documentation`_ for more information on background jobs and for
75 | tips on how to run workers in production environments.
76 |
77 | .. _`CKAN documentation`: http://docs.ckan.org/en/latest/maintaining/background-tasks.html
78 |
79 |
80 | Configure Solr
81 | --------------
82 | For the actual extraction CKAN's Apache Solr server is used. However, the
83 | necessary Solr plugins are deactivated by default. To enable them, find your
84 | main Solr configuration file (usually ``/etc/solr/conf/solrconfig.xml``) and
85 | add/uncomment the following lines::
86 |
87 |
88 |
89 |
90 | **Note:** The Solr packages on Ubuntu are broken_ and do not contain the
91 | necessary files. You can simply download an `official release`_ of the same
92 | version, unpack it to a suitable location (without installing it) and adjust
93 | the ``dir`` arguments in the configuration lines above accordingly. For
94 | example, if you have unpacked the files to ``/var/lib/apache-solr``, then you
95 | would need to put the following lines into ``solrconfig.xml``::
96 |
97 |
98 |
99 |
100 | .. _broken: https://bugs.launchpad.net/ubuntu/+source/lucene-solr/+bug/1565637
101 | .. _`official release`: http://archive.apache.org/dist/lucene/solr
102 |
103 | Once the text and metadata have been extracted they need to be added to the
104 | Solr index, which requires appropriate Solr fields. To set them up add the
105 | following lines to your Solr schema configuration (usually
106 | ``/etc/solr/conf/schema.xml``)::
107 |
108 | # Directly before the line that says ""
109 |
110 |
111 | # Directly before the line that says ""
112 |
113 |
114 | Make sure to restart Solr after you have applied the changes. For example, if
115 | you're using Jetty as an application server for Solr, then
116 |
117 | ::
118 |
119 | sudo service jetty restart
120 |
121 |
122 | Restart CKAN
123 | ------------
124 | Finally, restart your CKAN server::
125 |
126 | sudo service apache2 restart
127 |
128 |
129 | Test your Installation
130 | ----------------------
131 | The installation is now complete. To verify that everything is working open the
132 | URL ``/api/3/action/extractor_list``, e.g. via
133 |
134 | ::
135 |
136 | wget -qO - http://localhost/api/3/action/extractor_list
137 |
138 | The output should look like this (in particular, ``success`` should be ``true``)::
139 |
140 | {"help": "http://localhost/api/3/action/help_show?name=extractor_list", "success": true, "result": []}
141 |
142 |
143 | You're Done!
144 | ------------
145 | Your installation of *ckanext-extractor* is now complete, and new/updated
146 | resources will have their metadata automatically indexed. You may want to
147 | adapt the configuration to your needs, see below for details. Once that is
148 | done you may also want to extract metadata from your existing resources::
149 |
150 | . /usr/lib/ckan/default/bin/activate
151 | paster --plugin=ckanext-extractor extract all -c /etc/ckan/default/production.ini
152 |
153 | This and other ``paster`` administration commands are explained below in more
154 | detail.
155 |
156 |
157 | Configuration
158 | =============
159 | *ckanext-extractor* can be configured via the usual CKAN configuration file (e.g.
160 | ``/etc/ckan/default/production.ini``). You must restart your CKAN server after
161 | updating the configuration.
162 |
163 | Formats for Extraction
164 | ----------------------
165 | While Solr can extract text and metadata from many file formats not all of
166 | them might be of interest to you. You can therefore configure for which formats
167 | extraction is performed via the ``ckanext.extractor.indexed_formats`` option. It
168 | takes a list of space-separated formats, where the format is the one specified
169 | in a resource's CKAN metadata (and not the file extension or MIME type)::
170 |
171 | ckanext.extractor.indexed_formats = pdf txt
172 |
173 | Formats are case-insensitive. You can use wildcards (``*`` and ``?``) to match
174 | multiple formats. To extract data from all formats simply set
175 |
176 | ::
177 |
178 | ckanext.extractor.indexed_formats = *
179 |
180 | By default, extraction is only enabled for the PDF format::
181 |
182 | ckanext.extractor.indexed_formats = pdf
183 |
184 | Fields for Indexing
185 | -------------------
186 | Once text and metadata have been extracted they can be added to the search
187 | index. Again, Solr supports more metadata fields than one usually needs. You
188 | can therefore configure which fields are indexed via the
189 | ``ckanext.extractor.indexed_fields`` option. It takes a space-separated list of
190 | field names::
191 |
192 | ckanext.extractor.indexed_fields = fulltext author
193 |
194 | The full text of a document is available via the ``fulltext`` field. Field names
195 | are case-insensitive. You can use wildcards (``*`` and ``?``) to match multiple
196 | field names. To index all fields simply set
197 |
198 | ::
199 |
200 | ckanext.extractor.indexed_fields = *
201 |
202 | By default, only the full text of a document is indexed::
203 |
204 | ckanext.extractor.indexed_fields = fulltext
205 |
206 | **Note:** *ckanext-extractor* normalizes the field names reported by Solr by
207 | replacing underscores (``_``) with hyphens (``-``). In addition, multiple
208 | values for the same field in the same document are collapsed into a single
209 | value.
210 |
211 |
212 | Paster Commands
213 | ===============
214 | In general, *ckanext-extractor* works automatically: whenever a new resource is
215 | created or an existing resource changes, its metadata is extracted and indexed.
216 | However, for administration purposes, metadata can also be managed from the
217 | command line using the paster_ tool.
218 |
219 | .. _paster: http://docs.ckan.org/en/latest/maintaining/paster.html
220 |
221 | **Note:** You have to activate your virtualenv before you can use these
222 | commands::
223 |
224 | . /usr/lib/ckan/default/bin/activate
225 |
226 | The general form for a paster command is
227 |
228 | ::
229 |
230 | paster --plugin=ckanext-extractor COMMAND ARGUMENTS --config=/etc/ckan/default/production.ini
231 |
232 | Replace ``COMMAND`` and ``ARGUMENTS`` as described below. For example::
233 |
234 | paster --plugin=ckanext-extractor extract all --config=/etc/ckan/default/production.ini
235 |
236 |
237 | - ``delete (all | ID [ID [...]])``: Delete metadata. You can specify one or
238 | more resource IDs or a single ``all`` argument (in which case all metadata is
239 | deleted).
240 |
241 | - ``extract [--force] (all | ID [ID [...]])``: Extract metadata. You can
242 | specify one or more resource IDs or a single ``all`` argument (in which case
243 | metadata is extracted from all resources with appropriate formats). An
244 | optional ``--force`` argument can be used to force extraction even if the
245 | resource is unchanged, or if another extraction job already has been
246 | scheduled for that resource.
247 |
248 | Note that this command only schedules the necessary extraction background
249 | tasks. A background jobs worker has to be running for the extraction to
250 | actually happen.
251 |
252 | - ``init``: Initialize the database tables for *ckanext-extractor*. You only
253 | need to use this once (during the installation).
254 |
255 | - ``list``: List the IDs of all resources for which metadata has been
256 | extracted.
257 |
258 | - ``show (all | ID [ID [...]])``: Show extracted metadata. You can specify one
259 | or more resource IDs or a single ``all`` argument (in which case all metadata
260 | is shown).
261 |
262 |
263 | API
264 | ===
265 | Metadata can be managed via the standard `CKAN API`_. Unless noted otherwise
266 | all commands are only available via POST requests to authenticated users.
267 |
268 | .. _`CKAN API`: http://docs.ckan.org/en/latest/api/index.html
269 |
270 | ``extractor_delete``
271 | --------------------
272 | Delete metadata.
273 |
274 | Only available to administrators.
275 |
276 | Parameters:
277 |
278 | :id: ID of the resource for which metadata should be deleted.
279 |
280 |
281 | ``extractor_extract``
282 | ---------------------
283 | Extract metadata.
284 |
285 | This function schedules a background task for extracting metadata from a
286 | resource.
287 |
288 | Only available to administrators.
289 |
290 | Parameters:
291 |
292 | :id: ID of the resource for which metadata should be extracted.
293 |
294 | :force: Optional boolean flag to force extraction even if the resource is
295 | unchanged, or if an extraction task has already been scheduled for that
296 | resource.
297 |
298 | Returns a dict with the following entries:
299 |
300 | :status: A string describing the state of the metadata. This can be one of the
301 | following:
302 |
303 | :new: if no metadata for the resource existed before
304 |
305 | :update: if metadata existed but is going to be updated
306 |
307 | :unchanged: if metadata existed but won't get updated (for example because
308 | the resource's URL did not change since the last extraction)
309 |
310 | :inprogress: if a background extraction task for this resource is already
311 | in progress
312 |
313 | :ignored: if the resource format is configured to be ignored
314 |
315 | Note that if ``force`` is true then an extraction job will be scheduled
316 | regardless of the status reported, unless that state is ``ignored``.
317 |
318 | :task_id: The ID of the background task. If ``state`` is ``new`` or ``update``
319 | then this is the ID of a newly created task. If ``state`` is ``inprogress``
320 | then it's the ID of the existing task. Otherwise it is ``null``.
321 |
322 | If ``force`` is true then this is the ID of the new extraction task.
323 |
324 | ``extractor_list``
325 | ------------------
326 | List resources with metadata.
327 |
328 | Returns a list with the IDs of all resources for which metadata has been
329 | extracted.
330 |
331 | Available to all (even anonymous) users via GET and POST.
332 |
333 | ``extractor_show``
334 | ------------------
335 | Show the metadata for a resource.
336 |
337 | Parameters:
338 |
339 | :id: ID of the resource for which metadata should be extracted.
340 |
341 | Returns a dict with the resource's metadata and information about the last
342 | extraction.
343 |
344 | Available to all (even anonymous) users via GET and POST.
345 |
346 |
347 | Postprocessing Extraction Results
348 | =================================
349 | The ``ckanext.extractor.interfaces.IExtractorPostprocessor`` interface can be
350 | used to hook into the extraction process. It allows you to postprocess
351 | extraction results and to automatically trigger actions that use the extraction
352 | results for other purposes.
353 |
354 | The interface offers 3 hooks:
355 |
356 | - ``extractor_after_extract(resource_dict, extracted)`` is called right after
357 | the extraction before the extracted metadata ``extracted`` is filtered and
358 | stored. You can modify ``extracted`` (in-place) and the changes will end up
359 | in the database.
360 |
361 | - ``extractor_after_save(resource_dict, metadata_dict)`` is called after the
362 | metadata has been filtered and stored in the database but before it is
363 | indexed. ``metadata_dict`` is a dict-representation of a
364 | ``ckanext.extractor.model.ResourceMetadata`` instance and contains both the
365 | extracted metadata and information about the extraction process
366 | (meta-metadata, so to speak).
367 |
368 | - ``extractor_after_index(resource_dict, metadata_dict)`` is called at the very
369 | end of the extraction process, after the metadata has been extracted,
370 | filtered, stored and indexed.
371 |
372 |
373 | Adjusting the download request
374 | ==============================
375 | The ``ckanext.extractor.interfaces.IExtractorRequest`` interface can be used to
376 | modify the HTTP request made for downloading a resource file for extraction. A
377 | typical use case would be to add custom authentication headers required by the
378 | remote server which are normally provided by the user's browser.
379 |
380 | The interface offers 1 hook:
381 |
382 | - ``extractor_before_request(request)`` is called before a request is sent to
383 | download a resource file for extraction. The ``request`` parameter is a
384 | ``PreparedRequest`` object `from the requests library
385 | `_.
386 |
387 |
388 | Development
389 | ===========
390 |
391 | ::
392 |
393 | . /usr/lib/ckan/default/bin/activate
394 | git clone https://github.com/stadt-karlsruhe/ckanext-extractor.git
395 | cd ckanext-extractor
396 | python setup.py develop
397 | pip install -r dev-requirements.txt
398 |
399 |
400 | Running the Tests
401 | -----------------
402 | To run the tests, activate your CKAN virtualenv and do::
403 |
404 | ./runtests.sh
405 |
406 | Any additional arguments are passed on to ``nosetests``.
407 |
408 |
409 | Change Log
410 | ==========
411 | See the file `CHANGELOG.md`.
412 |
413 |
414 | License
415 | =======
416 | Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
417 |
418 | Distributed under the GNU Affero General Public License. See the file
419 | ``LICENSE`` for details.
420 |
421 |
--------------------------------------------------------------------------------
/ckanext/__init__.py:
--------------------------------------------------------------------------------
1 | # this is a namespace package
2 | try:
3 | import pkg_resources
4 | pkg_resources.declare_namespace(__name__)
5 | except ImportError:
6 | import pkgutil
7 | __path__ = pkgutil.extend_path(__path__, __name__)
8 |
--------------------------------------------------------------------------------
/ckanext/extractor/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | __version__ = '0.4.0'
23 |
24 |
--------------------------------------------------------------------------------
/ckanext/extractor/config.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | from fnmatch import fnmatch
23 | import logging.config
24 | import os.path
25 | from string import lower
26 |
27 | import paste.deploy
28 | from paste.registry import Registry
29 | from pylons import config, translator
30 |
31 | from ckan.plugins import toolkit
32 | from ckan.config.environment import load_environment
33 | from ckan.lib.cli import MockTranslator
34 |
35 |
36 | DEFAULTS = {
37 | 'ckanext.extractor.indexed_formats': 'pdf',
38 | 'ckanext.extractor.indexed_fields': 'fulltext',
39 | }
40 |
41 | TRANSFORMATIONS = {
42 | 'ckanext.extractor.indexed_formats': [lower, toolkit.aslist],
43 | 'ckanext.extractor.indexed_fields': [lower, toolkit.aslist],
44 | }
45 |
46 |
47 | def get(setting):
48 | """
49 | Get configuration setting.
50 |
51 | ``setting`` is the setting without the ``ckanext.extractor.``
52 | prefix.
53 |
54 | Handles defaults and transformations.
55 | """
56 | setting = 'ckanext.extractor.' + setting
57 | value = config.get(setting, DEFAULTS[setting])
58 | for transformation in TRANSFORMATIONS[setting]:
59 | value = transformation(value)
60 | return value
61 |
62 |
63 | # Adapted from ckanext-archiver
64 | def load_config(ini_path):
65 | """
66 | Load CKAN configuration.
67 | """
68 | ini_path = os.path.abspath(ini_path)
69 | logging.config.fileConfig(ini_path, disable_existing_loggers=False)
70 | conf = paste.deploy.appconfig('config:' + ini_path)
71 | load_environment(conf.global_conf, conf.local_conf)
72 | _register_translator()
73 |
74 |
75 | # Adapted from ckanext-archiver
76 | def _register_translator():
77 | """
78 | Register a translator in this thread.
79 | """
80 | global registry
81 | try:
82 | registry
83 | except NameError:
84 | registry = Registry()
85 | registry.prepare()
86 | global translator_obj
87 | try:
88 | translator_obj
89 | except NameError:
90 | translator_obj = MockTranslator()
91 | registry.register(translator, translator_obj)
92 |
93 |
94 | def _any_match(s, patterns):
95 | """
96 | Check if a string matches at least one pattern.
97 | """
98 | return any(fnmatch(s, pattern) for pattern in patterns)
99 |
100 |
101 | def is_field_indexed(field):
102 | """
103 | Check if a metadata field is configured to be indexed.
104 | """
105 | return _any_match(field.lower(), get('indexed_fields'))
106 |
107 |
108 | def is_format_indexed(format):
109 | """
110 | Check if a resource format is configured to be indexed.
111 | """
112 | return _any_match(format.lower(), get('indexed_formats'))
113 |
114 |
--------------------------------------------------------------------------------
/ckanext/extractor/fanstatic/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stadt-karlsruhe/ckanext-extractor/1d49dd615493db21ce0004b40f2ae0bb68f3869f/ckanext/extractor/fanstatic/.gitignore
--------------------------------------------------------------------------------
/ckanext/extractor/i18n/ckanext-extractor.pot:
--------------------------------------------------------------------------------
1 | # Translations template for ckanext-extractor.
2 | # Copyright (C) 2016 ORGANIZATION
3 | # This file is distributed under the same license as the ckanext-extractor
4 | # project.
5 | # FIRST AUTHOR , 2016.
6 | #
7 | #, fuzzy
8 | msgid ""
9 | msgstr ""
10 | "Project-Id-Version: ckanext-extractor 0.0.1\n"
11 | "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
12 | "POT-Creation-Date: 2016-04-25 12:20+0200\n"
13 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
14 | "Last-Translator: FULL NAME \n"
15 | "Language-Team: LANGUAGE \n"
16 | "MIME-Version: 1.0\n"
17 | "Content-Type: text/plain; charset=utf-8\n"
18 | "Content-Transfer-Encoding: 8bit\n"
19 | "Generated-By: Babel 0.9.6\n"
20 |
21 | #: ckanext/extractor/logic/action.py:28
22 | msgid "No metadata found for resource '{resource}'."
23 | msgstr ""
24 |
25 |
--------------------------------------------------------------------------------
/ckanext/extractor/interfaces.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | from ckan import plugins
23 |
24 |
25 | class IExtractorPostprocessor(plugins.Interface):
26 | '''
27 | Postprocess extracted metadata.
28 |
29 | This interfaces provides hooks for postprocess resource metadata
30 | after its extraction. They can be used to modify the metadata before
31 | it is stored or to automatically trigger actions that use the
32 | extraction results for other purposes.
33 |
34 | Note that none of the hooks are called if an exception ocurred
35 | during the extraction.
36 | '''
37 | def extractor_after_extract(self, resource_dict, extracted):
38 | '''
39 | Postprocess metadata after extraction.
40 |
41 | Called directly after metadata has been extracted and
42 | normalized. ``extracted`` is a dict containing the metadata.
43 |
44 | Implementations can modify ``extracted`` in place, the return
45 | value of the function is ignored.
46 |
47 | Note that filtering of metadata according to
48 | ``ckanext.extractor.indexed_fields`` is done after this function
49 | is called.
50 | '''
51 |
52 | def extractor_after_save(self, resource_dict, metadata_dict):
53 | '''
54 | Postprocess metadata after it has been saved.
55 |
56 | Called after metadata has been extracted and saved in the
57 | database.
58 |
59 | ``metadata_dict`` is a dict-representation of the resource's
60 | ``ckanext.extractor.model.ResourceMetadata`` instance. Changes
61 | to ``metadata_dict`` and the return value of the function are
62 | ignored.
63 |
64 | Note: When this function is called the fields have been filtered
65 | according to ``ckanext.extractor.indexed_fields``, but the
66 | extracted metadata hasn't been indexed, yet.
67 | '''
68 |
69 | def extractor_after_index(self, resource_dict, metadata_dict):
70 | '''
71 | Postprocess metadata after it has been indexed.
72 |
73 | Called after the package of the resource whose metadata has been
74 | extracted has been re-indexed after the extraction.
75 |
76 | ``resource_dict`` and ``metadata_dict`` are dict-representations
77 | of the resource and the metadata, respectively. Changes to them
78 | and the return value of the function are ignored.
79 |
80 | Note: When this function is called the fields have been filtered
81 | according to ``ckanext.extractor.indexed_fields``.
82 | '''
83 |
84 |
85 | class IExtractorRequest(plugins.Interface):
86 | '''
87 | Alter HTTP download requests.
88 |
89 | This interface allows you to modify the HTTP request for downloading
90 | a resource file, e.g. if the remote server requires certain
91 | authentication headers.
92 | '''
93 | def extractor_before_request(self, request):
94 | '''
95 | Alter a HTTP download request.
96 |
97 | ``request`` is a ``PreparedRequest`` object.
98 |
99 | This function must return a ``PreparedRequest`` object, which
100 | can either be the original request after it has been modified or
101 | a completely new one.
102 |
103 | Details can be found in the `requests documentation
104 | `_.
105 | '''
106 | return request
107 |
--------------------------------------------------------------------------------
/ckanext/extractor/lib.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import datetime
23 | import tempfile
24 |
25 | from ckan.plugins import PluginImplementations
26 | from .interfaces import IExtractorRequest
27 |
28 | from pylons import config
29 | import pysolr
30 | from requests import Request, Session
31 |
32 |
33 | def download_and_extract(resource_url):
34 | """
35 | Download resource and extract metadata using Solr.
36 |
37 | The extracted metadata is cleaned and returned.
38 | """
39 | session = Session()
40 | request = Request('GET', resource_url).prepare()
41 | for plugin in PluginImplementations(IExtractorRequest):
42 | request = plugin.extractor_before_request(request)
43 | with tempfile.NamedTemporaryFile() as f:
44 | r = session.send(request, stream=True)
45 | r.raise_for_status()
46 | for chunk in r.iter_content(chunk_size=1024):
47 | f.write(chunk)
48 | f.flush()
49 | f.seek(0)
50 | data = pysolr.Solr(config['solr_url']).extract(f, extractFormat='text')
51 | data['metadata']['fulltext'] = data['contents']
52 | return dict(clean_metadatum(*x) for x in data['metadata'].iteritems())
53 |
54 |
55 | def clean_metadatum(key, value):
56 | """
57 | Clean an extracted metadatum.
58 |
59 | Takes a key/value pair and returns it in cleaned form.
60 | """
61 | if isinstance(value, list) and len(value) == 1:
62 | # Flatten 1-element lists
63 | value = value[0]
64 | key = key.lower().replace('_', '-')
65 | return key, value
66 |
67 |
--------------------------------------------------------------------------------
/ckanext/extractor/logic/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stadt-karlsruhe/ckanext-extractor/1d49dd615493db21ce0004b40f2ae0bb68f3869f/ckanext/extractor/logic/__init__.py
--------------------------------------------------------------------------------
/ckanext/extractor/logic/action.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import logging
23 |
24 | import ckan.plugins.toolkit as toolkit
25 | from ckan.logic import validate
26 | from pylons import config
27 | from sqlalchemy.orm.exc import NoResultFound
28 |
29 | from . import schema
30 | from .helpers import check_access
31 | from ..model import ResourceMetadata, ResourceMetadatum
32 | from ..config import is_format_indexed
33 | from ..tasks import extract
34 |
35 | try:
36 | enqueue_job = toolkit.enqueue_job
37 | except AttributeError:
38 | # CKAN 2.6 or older
39 | from ckanext.rq.jobs import enqueue as enqueue_job
40 |
41 |
42 | log = logging.getLogger(__name__)
43 |
44 |
45 | def _get_metadata(resource_id):
46 | try:
47 | return ResourceMetadata.one(resource_id=resource_id)
48 | except NoResultFound:
49 | raise toolkit.ObjectNotFound(
50 | toolkit._("No metadata found for resource '{resource}'.").format(
51 | resource=resource_id))
52 |
53 |
54 | @check_access('extractor_delete')
55 | @validate(schema.extractor_delete)
56 | def extractor_delete(context, data_dict):
57 | """
58 | Delete the metadata for a resource.
59 |
60 | :param string id: The ID or the name of the resource
61 | """
62 | log.debug('extractor_delete {}'.format(data_dict['id']))
63 | metadata = _get_metadata(data_dict['id'])
64 | metadata.delete().commit()
65 |
66 |
67 | @check_access('extractor_extract')
68 | @validate(schema.extractor_extract)
69 | def extractor_extract(context, data_dict):
70 | """
71 | Extract and store metadata for a resource.
72 |
73 | Metadata extraction is done in an asynchronous background job, so
74 | this function may return before extraction is complete.
75 |
76 | :param string id: The ID or name of the resource
77 |
78 | :param boolean force: Extract metadata even if the resource hasn't
79 | changed, or if an extraction task is already scheduled for the
80 | resource (optional).
81 |
82 | :rtype: A dict with the following keys:
83 |
84 | :status: A string describing the state of the metadata. This
85 | can be one of the following:
86 |
87 | :new: if no metadata for the resource existed before
88 |
89 | :update: if metadata existed but is going to be updated
90 |
91 | :unchanged: if metadata existed but won't get updated
92 | (for example because the resource's URL did not
93 | change since the last extraction)
94 |
95 | :inprogress: if a background extraction task for this
96 | resource is already in progress
97 |
98 | :ignored: if the resource format is configured to be
99 | ignored
100 |
101 | Note that if ``force`` is true then an extraction job will
102 | be scheduled regardless of the status reported, unless that
103 | status is ``ignored``.
104 |
105 | :task_id: The ID of the background task. If ``state`` is ``new``
106 | or ``update`` then this is the ID of a newly created task.
107 | If ``state`` is ``inprogress`` then it's the ID of the
108 | existing task. Otherwise it is ``null``.
109 |
110 | If ``force`` is true then this is the ID of the new
111 | extraction task.
112 |
113 | """
114 | log.debug('extractor_extract {}'.format(data_dict['id']))
115 | force = data_dict.get('force', False)
116 | resource = toolkit.get_action('resource_show')(context, data_dict)
117 | task_id = None
118 | metadata = None
119 | try:
120 | metadata = ResourceMetadata.one(resource_id=resource['id'])
121 | if metadata.task_id:
122 | status = 'inprogress'
123 | task_id = metadata.task_id
124 | elif not is_format_indexed(resource['format']):
125 | metadata.delete()
126 | metadata.commit()
127 | metadata = None
128 | status = 'ignored'
129 | elif (metadata.last_url != resource['url']
130 | or metadata.last_format != resource['format']):
131 | status = 'update'
132 | else:
133 | status = 'unchanged'
134 | except NoResultFound:
135 | if is_format_indexed(resource['format']):
136 | status = 'new'
137 | else:
138 | status = 'ignored'
139 | if status in ('new', 'update') or (status != 'ignored' and force):
140 | args = (config['__file__'], resource)
141 | title = 'Metadata extraction for resource {}'.format(resource['id'])
142 | if metadata is None:
143 | metadata = ResourceMetadata.create(resource_id=resource['id'])
144 | job = enqueue_job(extract, args, title=title)
145 | task_id = metadata.task_id = job.id
146 | metadata.save()
147 | return {
148 | 'status': status,
149 | 'task_id': task_id,
150 | }
151 |
152 |
153 | @toolkit.side_effect_free
154 | @check_access('extractor_list')
155 | @validate(schema.extractor_list)
156 | def extractor_list(context, data_dict):
157 | """
158 | List resources that have metadata.
159 |
160 | Returns a list with the IDs of the resources which have metadata
161 | associated with them.
162 |
163 | :rtype: list
164 | """
165 | log.debug('extractor_list')
166 | return [m.resource_id for m in ResourceMetadata.filter_by(task_id=None)]
167 |
168 |
169 | @toolkit.side_effect_free
170 | @check_access('extractor_show')
171 | @validate(schema.extractor_show)
172 | def extractor_show(context, data_dict):
173 | """
174 | Show the stored metadata for a resource.
175 |
176 | :param string id: The ID or name of the resource
177 |
178 | :rtype: dict
179 | """
180 | log.debug('extractor_show {}'.format(data_dict['id']))
181 | metadata = _get_metadata(data_dict['id'])
182 | result = metadata.as_dict()
183 | result['meta'] = dict(metadata.meta)
184 | return result
185 |
186 |
--------------------------------------------------------------------------------
/ckanext/extractor/logic/auth.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import logging
23 |
24 | import ckan.plugins.toolkit as toolkit
25 |
26 |
27 | log = logging.getLogger(__name__)
28 |
29 |
30 | def _only_sysadmins(context, datadict):
31 | return {'success': False}
32 |
33 |
34 | @toolkit.auth_allow_anonymous_access
35 | def _everybody(context, datadict):
36 | return {'success': True}
37 |
38 |
39 | extractor_delete = _only_sysadmins
40 | extractor_extract = _only_sysadmins
41 | extractor_list = _everybody
42 | extractor_show = _everybody
43 |
44 |
--------------------------------------------------------------------------------
/ckanext/extractor/logic/helpers.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import functools
23 | import logging
24 |
25 | from ckan.plugins import toolkit
26 |
27 |
28 | log = logging.getLogger(__name__)
29 |
30 |
31 | def check_access(auth_func_name):
32 | """
33 | Decorator for API function authorization.
34 |
35 | Calls the auth function of the given name to make sure that the
36 | user is authorized to execute the function.
37 | """
38 | def decorator(f):
39 | @functools.wraps(f)
40 | def wrapped(context, data_dict):
41 | toolkit.check_access(auth_func_name, context, data_dict)
42 | return f(context, data_dict)
43 | return wrapped
44 | return decorator
45 |
46 |
--------------------------------------------------------------------------------
/ckanext/extractor/logic/schema.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | from inspect import getmembers
23 | import logging
24 |
25 | from ckan.lib.navl.validators import ignore_missing, not_empty
26 | from ckan.logic.schema import default_pagination_schema
27 | from ckan.logic.validators import boolean_validator
28 |
29 |
30 | log = logging.getLogger(__name__)
31 |
32 |
33 | class _Schema(object):
34 | """
35 | Pseudo-class for composable schema definitions.
36 |
37 | Creating an instance of this class will return a dict with the
38 | class' variables instead of a real instance. This allows you to
39 | define composable schemas via inheritance::
40 |
41 | class Schema1(_Schema):
42 | field1 = [not_empty, unicode]
43 |
44 | class Schema2(Schema1):
45 | field2 = [ignore_missing, unicode]
46 |
47 | print(Schema2())
48 | # {
49 | # 'field1': [not_empty, unicode],
50 | # 'field2': [ignore_missing, unicode]
51 | # }
52 | """
53 | def __new__(cls):
54 | return {key: value for key, value in getmembers(cls) if not
55 | key.startswith('__')}
56 |
57 |
58 | class _MandatoryID(_Schema):
59 | id = [not_empty, unicode]
60 |
61 | extractor_delete = _MandatoryID
62 |
63 | class extractor_extract(_MandatoryID):
64 | force = [ignore_missing, boolean_validator]
65 |
66 | extractor_list = default_pagination_schema
67 | extractor_show = _MandatoryID
68 |
69 |
--------------------------------------------------------------------------------
/ckanext/extractor/model.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | """
21 | Data model.
22 |
23 | The metadata fields extracted by Solr/Tika vary from one filetype to
24 | another. Therefore a flexible way of storing a resource's metadata is
25 | required instead of a fixed set of columns. We achieve this using a
26 | separate table in which we store both the name and the value of each
27 | individual metadatum. Using SQLAlchemy's ``association_proxy`` and
28 | ``attribute_mapped_collection`` that table is then accessed in a dict-
29 | like fashion using the ``ResourceMetadata`` class. This means that you
30 | will probably never need to use the ``ResourceMetadatum`` class.
31 |
32 | In addition to the resource metadata, the class ``ResourceMetadata``
33 | also stores information about the extraction process.
34 | """
35 |
36 | from __future__ import absolute_import, print_function, unicode_literals
37 |
38 | import logging
39 |
40 | from sqlalchemy import Column, ForeignKey, Table, types
41 | from sqlalchemy.ext.associationproxy import association_proxy
42 | from sqlalchemy.orm import relationship
43 | from sqlalchemy.orm.collections import attribute_mapped_collection
44 |
45 | from ckan.model.domain_object import DomainObject
46 | from ckan.model.meta import mapper, metadata
47 |
48 |
49 | log = logging.getLogger(__name__)
50 |
51 | resource_metadatum_table = None
52 | RESOURCE_METADATUM_TABLE_NAME = 'ckanext_extractor_resource_metadatum'
53 |
54 | resource_metadata_table = None
55 | RESOURCE_METADATA_TABLE_NAME = 'ckanext_extractor_resource_metadata'
56 |
57 |
58 | class BaseObject(DomainObject):
59 | """
60 | Base class for data models.
61 | """
62 | @classmethod
63 | def filter_by(cls, **kwargs):
64 | return cls.Session.query(cls).filter_by(**kwargs)
65 |
66 | @classmethod
67 | def one(cls, **kwargs):
68 | return cls.filter_by(**kwargs).one()
69 |
70 | @classmethod
71 | def create(cls, **kwargs):
72 | instance = cls(**kwargs)
73 | cls.Session.add(instance)
74 | cls.Session.commit()
75 | return instance
76 |
77 | def delete(self):
78 | super(BaseObject, self).delete()
79 | return self
80 |
81 |
82 | def setup():
83 | """
84 | Set up ORM.
85 |
86 | Does not create any database tables, see :py:func:`create_tables`
87 | for that.
88 | """
89 | global resource_metadata_table
90 | if resource_metadata_table is None:
91 | log.debug('Defining resource metadata table')
92 | resource_metadata_table = Table(
93 | RESOURCE_METADATA_TABLE_NAME,
94 | metadata,
95 | Column('resource_id', types.UnicodeText, ForeignKey('resource.id',
96 | ondelete='CASCADE', onupdate='CASCADE'), nullable=False,
97 | primary_key=True),
98 | Column('last_extracted', types.DateTime),
99 | Column('last_url', types.UnicodeText),
100 | Column('last_format', types.UnicodeText),
101 | Column('task_id', types.UnicodeText)
102 | )
103 | mapper(
104 | ResourceMetadata,
105 | resource_metadata_table,
106 | properties={
107 | '_meta': relationship(ResourceMetadatum, collection_class=
108 | attribute_mapped_collection('key'),
109 | cascade='all, delete, delete-orphan'),
110 | }
111 | )
112 | else:
113 | log.debug('Resource metadata table already defined')
114 | global resource_metadatum_table
115 | if resource_metadatum_table is None:
116 | log.debug('Defining resource metadatum table')
117 | resource_metadatum_table = Table(
118 | RESOURCE_METADATUM_TABLE_NAME,
119 | metadata,
120 | Column('id', types.Integer, nullable=False, primary_key=True),
121 | Column('resource_id', types.UnicodeText, ForeignKey(
122 | RESOURCE_METADATA_TABLE_NAME + '.resource_id',
123 | ondelete='CASCADE', onupdate='CASCADE'), nullable=False),
124 | Column('key', types.UnicodeText, nullable=False),
125 | Column('value', types.UnicodeText)
126 | )
127 | mapper(ResourceMetadatum, resource_metadatum_table)
128 | else:
129 | log.debug('Resource metadatum table already defined')
130 |
131 |
132 | def create_tables():
133 | """
134 | Create database tables.
135 | """
136 | setup()
137 | if not resource_metadata_table.exists():
138 | log.info('Creating resource metadata table')
139 | resource_metadata_table.create()
140 | else:
141 | log.info('Resource metadata table already exists')
142 | if not resource_metadatum_table.exists():
143 | log.info('Creating resource metadatum table')
144 | resource_metadatum_table.create()
145 | else:
146 | log.info('Resource metadatum table already exists')
147 |
148 |
149 | class ResourceMetadatum(BaseObject):
150 | """
151 | A single metadatum of a resource (e.g. ``fulltext``) and its value.
152 | """
153 | def __init__(self, key, value=None):
154 | self.key = key
155 | self.value = value
156 |
157 |
158 | class ResourceMetadata(BaseObject):
159 | """
160 | A resource's metadata and information about their extraction.
161 | """
162 | meta = association_proxy('_meta', 'value')
163 |
164 | def as_dict(self):
165 | d = super(ResourceMetadata, self).as_dict()
166 | # DomainObject.as_dict doesn't include association proxies
167 | d['meta'] = dict(self.meta)
168 | return d
169 |
170 |
--------------------------------------------------------------------------------
/ckanext/extractor/paster.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import sys
23 |
24 | from sqlalchemy import inspect
25 |
26 | from ckan.lib.cli import CkanCommand
27 |
28 | # Do not import modules for CKAN or ckanext-extractor here (unless you know
29 | # what you're doing), since their loggers won't work if imported before the
30 | # CKAN configuration has been loaded.
31 |
32 |
33 | def _error(msg):
34 | sys.exit('ERROR: ' + msg)
35 |
36 |
37 | def _compress(s, n=50):
38 | s = unicode(s)
39 | if len(s) < n:
40 | return s
41 | else:
42 | return s[:n/2] + ' ... ' + s[-n/2:]
43 |
44 |
45 | class ExtractorCommand(CkanCommand):
46 | """
47 | Base class for ckanext.extractor Paster commands.
48 | """
49 | def _get_ids(self, only_with_metadata=False):
50 | """
51 | Get list of resource IDs from command line arguments.
52 |
53 | Returns the specific IDs listed or all IDs if ``all`` was passed.
54 |
55 | If ``only_with_metadata`` is true and ``all`` was passed then only
56 | IDs of resources which have metadata are returned.
57 | """
58 | from ckan.plugins import toolkit
59 | if len(self.args) < 1:
60 | _error('Missing argument. Specify one or more resource IDs '
61 | + 'or "all".')
62 | if len(self.args) == 1 and self.args[0].lower() == 'all':
63 | if only_with_metadata:
64 | return sorted(toolkit.get_action('extractor_list')({}, {}))
65 | else:
66 | from ckan.model import Resource
67 | return sorted(r.id for r in Resource.active())
68 | else:
69 | return self.args[:]
70 |
71 |
72 | class DeleteCommand(ExtractorCommand):
73 | """
74 | Delete metadata
75 |
76 | delete (all | ID [ID [...]])
77 | """
78 | max_args = None
79 | min_args = 1
80 | usage = __doc__
81 | summary = __doc__.strip().split('\n')[0]
82 |
83 | def command(self):
84 | self._load_config()
85 | from ckan.plugins import toolkit
86 | delete = toolkit.get_action('extractor_delete')
87 | for id in self._get_ids(True):
88 | print(id)
89 | delete({}, {'id': id})
90 |
91 |
92 | class ExtractCommand(ExtractorCommand):
93 | """
94 | Extract metadata
95 |
96 | extract [--force] (all | ID [ID [...]])
97 |
98 | If --force is given then extraction is performed even if the
99 | the resource hasn't changed or another extraction task for the
100 | resource is already in progress.
101 |
102 | Note that a background jobs worker must be running, this command
103 | only schedules the necessary background tasks.
104 | """
105 | max_args = None
106 | min_args = None
107 | usage = __doc__
108 | summary = __doc__.strip().split('\n')[0]
109 |
110 | def __init__(self, name):
111 | super(ExtractCommand, self).__init__(name)
112 | self.parser.add_option('--force', default=False,
113 | help='Force extraction',
114 | action='store_true')
115 |
116 | def command(self):
117 | self._load_config()
118 | from ckan.plugins import toolkit
119 | extract = toolkit.get_action('extractor_extract')
120 | for id in self._get_ids():
121 | print(id + ': ', end='')
122 | result = extract({}, {'id': id, 'force': self.options.force})
123 | status = result['status']
124 | if result['task_id']:
125 | status += ' (task {})'.format(result['task_id'])
126 | print(status)
127 |
128 |
129 | class InitCommand(ExtractorCommand):
130 | """
131 | Initialize database tables.
132 | """
133 | max_args = 0
134 | min_args = 0
135 | usage = __doc__
136 | summary = __doc__.strip().split('\n')[0]
137 |
138 | def command(self):
139 | self._load_config()
140 | from .model import create_tables
141 | create_tables()
142 |
143 |
144 | class ListCommand(ExtractorCommand):
145 | """
146 | List resources with metadata
147 | """
148 | max_args = 0
149 | min_args = 0
150 | usage = __doc__
151 | summary = __doc__.strip().split('\n')[0]
152 |
153 | def command(self):
154 | self._load_config()
155 | from ckan.plugins import toolkit
156 | result = toolkit.get_action('extractor_list')({}, {})
157 | print('\n'.join(sorted(result)))
158 |
159 |
160 | class ShowCommand(ExtractorCommand):
161 | """
162 | Show metadata
163 |
164 | show (all | ID [ID [...]])
165 | """
166 | max_args = None
167 | min_args = 1
168 | usage = __doc__
169 | summary = __doc__.strip().split('\n')[0]
170 |
171 | def command(self):
172 | self._load_config()
173 | from ckan.plugins import toolkit
174 | from ckan.logic import NotFound
175 | show = toolkit.get_action('extractor_show')
176 | ids = self._get_ids(True)
177 | for i, id in enumerate(ids):
178 | try:
179 | result = show({}, {'id': id})
180 | except NotFound as e:
181 | print(e)
182 | continue
183 | print('{}:'.format(id))
184 | for key in sorted(result):
185 | if key in ('resource_id', 'meta'):
186 | continue
187 | print(' {}: {!r}'.format(key, result[key]))
188 | print(' meta:')
189 | meta = result['meta']
190 | for key in sorted(meta):
191 | print(' {}: {!r}'.format(key, _compress(meta[key])))
192 | if i < len(ids) - 1:
193 | print('')
194 |
195 |
--------------------------------------------------------------------------------
/ckanext/extractor/plugin.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import collections
23 | import json
24 | import logging
25 |
26 | from ckan import plugins
27 | from ckan.logic import NotFound
28 | from ckan.plugins import toolkit
29 |
30 | from .config import is_field_indexed, is_format_indexed
31 | from .logic import action, auth
32 | from . import model
33 |
34 |
35 | log = logging.getLogger(__name__)
36 | get_action = toolkit.get_action
37 |
38 |
39 | # Template for the Solr field names
40 | SOLR_FIELD = 'ckanext-extractor_{id}_{key}'
41 |
42 |
43 | def _is_resource(obj):
44 | """
45 | Check if a dict describes a resource.
46 |
47 | This is a very simple, duck-typing style test that only checks
48 | whether the dict contains an ``package_id`` entry.
49 | """
50 | return 'package_id' in obj
51 |
52 |
53 | class ExtractorPlugin(plugins.SingletonPlugin):
54 | plugins.implements(plugins.IConfigurer)
55 | plugins.implements(plugins.IPackageController, inherit=True)
56 | plugins.implements(plugins.IResourceController, inherit=True)
57 | plugins.implements(plugins.IActions)
58 | plugins.implements(plugins.IAuthFunctions)
59 | plugins.implements(plugins.IConfigurable)
60 |
61 | #
62 | # IConfigurer
63 | #
64 |
65 | def update_config(self, config):
66 | toolkit.add_template_directory(config, 'templates')
67 | toolkit.add_public_directory(config, 'public')
68 | toolkit.add_resource('fanstatic', 'extractor')
69 |
70 | #
71 | # IConfigurable
72 | #
73 |
74 | def configure(self, config):
75 | model.setup()
76 |
77 | #
78 | # IPackageController / IResourceController
79 | #
80 |
81 | def after_create(self, context, obj):
82 | if _is_resource(obj):
83 | ctx = dict(context, ignore_auth=True)
84 | get_action('extractor_extract')(ctx, obj)
85 |
86 | def after_update(self, context, obj):
87 | if _is_resource(obj):
88 | ctx = dict(context, ignore_auth=True)
89 | get_action('extractor_extract')(ctx, obj)
90 | else:
91 | # If a previously private package became public then we need to
92 | # extract all its resources. However, we don't have the old
93 | # package dict (there's no `before_update` in IPackageController),
94 | # so we simply re-extract all resources if for any updated public
95 | # dataset. If the resources didn't change then this won't add much
96 | # overhead.
97 | #
98 | # If, on the other hand, the package is private then we prune all
99 | # the metadata for all its resources to avoid leaking information
100 | # via the `extractor_list` and `extractor_show` action functions.
101 | if obj.get('private', True):
102 | for res_dict in obj.get('resources', []):
103 | try:
104 | ctx = dict(context, ignore_auth=True)
105 | get_action('extractor_delete')(ctx, res_dict)
106 | except toolkit.ObjectNotFound:
107 | pass
108 | else:
109 | for res_dict in obj.get('resources', []):
110 | ctx = dict(context, ignore_auth=True)
111 | get_action('extractor_extract')(ctx, res_dict)
112 |
113 | #
114 | # IResourceController
115 | #
116 |
117 | def before_delete(self, context, res_dict, res_dicts):
118 | ctx = dict(context, ignore_auth=True)
119 | try:
120 | get_action('extractor_delete')(ctx, res_dict)
121 | except NotFound:
122 | # Resource didn't have any metadata
123 | pass
124 |
125 | #
126 | # IPackageController
127 | #
128 |
129 | def before_index(self, pkg_dict):
130 | data_dict = json.loads(pkg_dict['data_dict'])
131 | for resource in data_dict['resources']:
132 | if not is_format_indexed(resource['format']):
133 | continue
134 | try:
135 | metadata = get_action('extractor_show')({}, resource)
136 | except NotFound:
137 | continue
138 | for key, value in metadata['meta'].iteritems():
139 | if is_field_indexed(key):
140 | field = SOLR_FIELD.format(id=resource['id'], key=key)
141 | pkg_dict[field] = value
142 | return pkg_dict
143 |
144 | #
145 | # IActions
146 | #
147 |
148 | def get_actions(self):
149 | return {
150 | 'extractor_delete': action.extractor_delete,
151 | 'extractor_extract': action.extractor_extract,
152 | 'extractor_list': action.extractor_list,
153 | 'extractor_show': action.extractor_show,
154 | }
155 |
156 | #
157 | # IAuthFunctions
158 | #
159 |
160 | def get_auth_functions(self):
161 | return {
162 | 'extractor_delete': auth.extractor_delete,
163 | 'extractor_extract': auth.extractor_extract,
164 | 'extractor_list': auth.extractor_list,
165 | 'extractor_show': auth.extractor_show,
166 | }
167 |
168 |
--------------------------------------------------------------------------------
/ckanext/extractor/public/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stadt-karlsruhe/ckanext-extractor/1d49dd615493db21ce0004b40f2ae0bb68f3869f/ckanext/extractor/public/.gitignore
--------------------------------------------------------------------------------
/ckanext/extractor/tasks.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import datetime
23 | import logging
24 | import tempfile
25 |
26 | from sqlalchemy.orm.exc import NoResultFound
27 | from requests.exceptions import RequestException
28 |
29 | from ckan.lib import search
30 | from ckan.plugins import PluginImplementations, toolkit
31 |
32 | from .config import is_field_indexed, load_config
33 | from .model import ResourceMetadata, ResourceMetadatum
34 | from .lib import download_and_extract
35 | from .interfaces import IExtractorPostprocessor
36 |
37 |
38 | log = logging.getLogger(__name__)
39 |
40 |
41 | def extract(ini_path, res_dict):
42 | """
43 | Download resource, extract and store metadata.
44 |
45 | The extracted metadata is stored in the database.
46 |
47 | Note that this task does check whether the resource exists in the
48 | database, whether the resource's format is indexed or whether there
49 | is an existing task working on the resource's metadata. This is the
50 | responsibility of the caller.
51 |
52 | The task does check which metadata fields are configured to be
53 | indexed and only stores those in the database.
54 |
55 | Any previously stored metadata for the resource is cleared.
56 | """
57 | load_config(ini_path)
58 |
59 | # Get package data before doing any hard work so that we can fail
60 | # early if the package is private.
61 | try:
62 | toolkit.get_action('package_show')({'validate': False},
63 | {'id': res_dict['package_id']})
64 | except toolkit.NotAuthorized:
65 | log.debug(('Not extracting resource {} since it belongs to the ' +
66 | 'private dataset {}.').format(res_dict['id'],
67 | res_dict['package_id']))
68 | return
69 |
70 | try:
71 | metadata = ResourceMetadata.one(resource_id=res_dict['id'])
72 | except NoResultFound:
73 | metadata = ResourceMetadata.create(resource_id=res_dict['id'])
74 | try:
75 | metadata.last_url = res_dict['url']
76 | metadata.last_format = res_dict['format']
77 | metadata.last_extracted = datetime.datetime.now()
78 | metadata.meta.clear()
79 | extracted = download_and_extract(res_dict['url'])
80 | for plugin in PluginImplementations(IExtractorPostprocessor):
81 | plugin.extractor_after_extract(res_dict, extracted)
82 | for key, value in extracted.iteritems():
83 | if not is_field_indexed(key):
84 | continue
85 |
86 | # Some documents contain multiple values for the same field. This
87 | # is not supported in our database model, hence we collapse these
88 | # into a single value.
89 | if isinstance(value, list):
90 | log.debug('Collapsing multiple values for metadata field ' +
91 | '"{}" in resource {} into a single value.'.format(key,
92 | res_dict['id']))
93 | value = ', '.join(value)
94 |
95 | metadata.meta[key] = value
96 | except RequestException as e:
97 | log.warn('Failed to download resource data from "{}": {}'.format(
98 | res_dict['url'], e.message))
99 | finally:
100 | metadata.task_id = None
101 | metadata.save()
102 |
103 | for plugin in PluginImplementations(IExtractorPostprocessor):
104 | plugin.extractor_after_save(res_dict, metadata.as_dict())
105 |
106 | # We need to update the search index for the package here. Note that
107 | # we cannot rely on the automatic update that happens when a resource
108 | # is changed, since our extraction task runs asynchronously and may
109 | # be finished only when the automatic index update has already run.
110 | search.rebuild(package_id=res_dict['package_id'])
111 |
112 | for plugin in PluginImplementations(IExtractorPostprocessor):
113 | plugin.extractor_after_index(res_dict, metadata.as_dict())
114 |
115 |
--------------------------------------------------------------------------------
/ckanext/extractor/templates/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stadt-karlsruhe/ckanext-extractor/1d49dd615493db21ce0004b40f2ae0bb68f3869f/ckanext/extractor/templates/.gitignore
--------------------------------------------------------------------------------
/ckanext/extractor/tests/__init__.py:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/ckanext/extractor/tests/helpers.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import contextlib
23 | import datetime
24 | import os.path
25 | import re
26 | from SimpleHTTPServer import SimpleHTTPRequestHandler
27 | from SocketServer import TCPServer
28 | from threading import Thread
29 | import time
30 |
31 | import mock
32 | from nose.tools import assert_raises, assert_true, assert_false
33 | from sqlalchemy.orm.exc import NoResultFound
34 |
35 | from ckan.logic import NotAuthorized, ValidationError
36 | from ckan.tests.helpers import call_action
37 |
38 | from ..model import ResourceMetadata, ResourceMetadatum
39 |
40 |
41 | def assert_equal(actual, expected, msg=''):
42 | """
43 | Assert that two values are equal.
44 |
45 | Like ``nose.tools.assert_equal`` but upon mismatch also displays the
46 | expected and actual values even if a message is given.
47 | """
48 | if actual == expected:
49 | return
50 | diff_msg = 'Got {!r} but expected {!r}.'.format(actual, expected)
51 | raise AssertionError((msg + ' ' + diff_msg).strip())
52 |
53 |
54 | def fake_process(res_dict):
55 | """
56 | Mark resource metadata as processed by removing its task ID.
57 | """
58 | metadata = get_metadata(res_dict)
59 | metadata.task_id = None
60 | metadata.last_url = res_dict['url']
61 | metadata.last_format = res_dict['format']
62 | metadata.save()
63 |
64 |
65 | def assert_no_metadata(res_dict):
66 | """
67 | Assert that no metadata are stored for a resource.
68 | """
69 | if ResourceMetadata.filter_by(resource_id=res_dict['id']).count() > 0:
70 | raise AssertionError(('Found unexcepted metadata for resource '
71 | + '"{id}".').format(id=res_dict['id']))
72 | if ResourceMetadatum.filter_by(resource_id=res_dict['id']).count() > 0:
73 | raise AssertionError(('Found unexcepted metadatum for resource '
74 | + '"{id}".').format(id=res_dict['id']))
75 |
76 |
77 | def assert_metadata(res_dict):
78 | """
79 | Assert that metadata is stored for a resource.
80 | """
81 | try:
82 | get_metadata(res_dict)
83 | except NoResultFound:
84 | raise AssertionError('No metadata found for resource "{id}".'.format(
85 | id=res_dict['id']))
86 |
87 |
88 | def get_metadata(res_dict):
89 | """
90 | Shortcut to get metadata for a resource.
91 | """
92 | return ResourceMetadata.one(resource_id=res_dict['id'])
93 |
94 |
95 | def call_action_with_auth(action, context=None, **kwargs):
96 | """
97 | Call an action with authorization checks.
98 |
99 | Like ``ckan.tests.helpers.call_action``, but authorization are
100 | not bypassed.
101 | """
102 | if context is None:
103 | context = {}
104 | context['ignore_auth'] = False
105 | return call_action(action, context, **kwargs)
106 |
107 |
108 | def assert_authorized(user_dict, action, msg, **kwargs):
109 | """
110 | Assert that a user is authorized to perform an action.
111 |
112 | Raises an ``AssertionError`` if access was denied.
113 | """
114 | context = {'user': user_dict['name']}
115 | try:
116 | call_action_with_auth(action, context, **kwargs)
117 | except NotAuthorized:
118 | raise AssertionError(msg)
119 |
120 |
121 | def assert_not_authorized(user_dict, action, msg, **kwargs):
122 | """
123 | Assert that a user is not authorized to perform an action.
124 |
125 | Raises an ``AssertionError`` if access was granted.
126 | """
127 | context = {'user': user_dict['name']}
128 | try:
129 | call_action_with_auth(action, context, **kwargs)
130 | except NotAuthorized:
131 | return
132 | raise AssertionError(msg)
133 |
134 |
135 | def assert_anonymous_access(action, **kwargs):
136 | """
137 | Assert that an action can be called anonymously.
138 | """
139 | context = {'user': ''}
140 | try:
141 | call_action_with_auth(action, context, **kwargs)
142 | except NotAuthorized:
143 | raise AssertionError('"{}" cannot be called anonymously.'.format(
144 | action))
145 |
146 |
147 | def assert_no_anonymous_access(action, **kwargs):
148 | """
149 | Assert that an action cannot be called anonymously.
150 | """
151 | context = {'user': ''}
152 | try:
153 | call_action_with_auth(action, context, **kwargs)
154 | except NotAuthorized:
155 | return
156 | raise AssertionError('"{}" can be called anonymously.'.format(action))
157 |
158 |
159 | def assert_validation_fails(action, msg=None, **kwargs):
160 | """
161 | Assert that an action call doesn't validate.
162 | """
163 | try:
164 | call_action(action, **kwargs)
165 | except ValidationError:
166 | return
167 | if msg is None:
168 | msg = ('Validation succeeded unexpectedly for action "{action}" with '
169 | + 'input {input!r}.').format(action=action, input=kwargs)
170 | raise AssertionError(msg)
171 |
172 |
173 | class AddressReuseServer(TCPServer):
174 | allow_reuse_address = True
175 |
176 |
177 | class HTTPRequestHandler(SimpleHTTPRequestHandler):
178 | """
179 | Serves files from a given directory instead of current directory.
180 | """
181 | def __init__(self, dir, *args, **kwargs):
182 | self.dir = os.path.abspath(dir)
183 | SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
184 |
185 | def translate_path(self, path):
186 | return os.path.join(self.dir, path.lstrip('/'))
187 |
188 |
189 | class SimpleServer(Thread):
190 | """
191 | HTTP server that serves a directory in a separate thread.
192 |
193 | If ``dir`` is not given the current directory is used.
194 | """
195 | def __init__(self, dir=None, port=8000):
196 | super(SimpleServer, self).__init__()
197 | if dir is None:
198 | dir = os.getcwd()
199 |
200 | def factory(*args, **kwargs):
201 | return HTTPRequestHandler(dir, *args, **kwargs)
202 |
203 | self.httpd = AddressReuseServer(("", port), factory)
204 |
205 | def run(self):
206 | try:
207 | self.httpd.serve_forever()
208 | finally:
209 | self.httpd.server_close()
210 |
211 | def stop(self):
212 | self.httpd.shutdown()
213 |
214 |
215 | def assert_time_span(start, stop=None, min=None, max=None):
216 | """
217 | Assert validity of a time span.
218 |
219 | ``start`` and ``stop`` are ``datetime.datetime`` instances. If
220 | ``stop`` is not given the current date and time is used.
221 |
222 | The length of the time span between ``start`` and ``stopped`` is
223 | computed (in seconds). If ``min`` (``max``) is given and larger
224 | (smaller) than the time span then an ``AssertionError`` is raised.
225 | """
226 | if stop is None:
227 | stop = datetime.datetime.now()
228 | span = (stop - start).total_seconds()
229 | if (min is not None) and (min > span):
230 | msg = 'Time span {span}s is too small (must be >={min}s).'.format(
231 | span=span, min=min)
232 | raise AssertionError(msg)
233 | if (max is not None) and (max < span):
234 | msg = 'Time span {span}s is too large (must be <={max}s).'.format(
235 | span=span, max=max)
236 | raise AssertionError(max)
237 |
238 |
239 | def is_package_found(query, pkg_id):
240 | """
241 | Check if a package is found via a query.
242 | """
243 | result = call_action('package_search', q=query)
244 | return any(pkg['id'] == pkg_id for pkg in result['results'])
245 |
246 |
247 | def assert_package_found(query, id, msg=None):
248 | """
249 | Assert that a package is found via a query.
250 | """
251 | assert_true(is_package_found(query, id), msg)
252 |
253 |
254 | def assert_package_not_found(query, id, msg=None):
255 | """
256 | Assert that a package is not found via a query.
257 | """
258 | assert_false(is_package_found(query, id), msg)
259 |
260 |
261 | try:
262 | from ckan.tests.helpers import recorded_logs
263 | except ImportError:
264 | import collections
265 | import logging
266 |
267 | # Copied from CKAN 2.7
268 | @contextlib.contextmanager
269 | def recorded_logs(logger=None, level=logging.DEBUG,
270 | override_disabled=True, override_global_level=True):
271 | u'''
272 | Context manager for recording log messages.
273 |
274 | :param logger: The logger to record messages from. Can either be a
275 | :py:class:`logging.Logger` instance or a string with the
276 | logger's name. Defaults to the root logger.
277 |
278 | :param int level: Temporary log level for the target logger while
279 | the context manager is active. Pass ``None`` if you don't want
280 | the level to be changed. The level is automatically reset to its
281 | original value when the context manager is left.
282 |
283 | :param bool override_disabled: A logger can be disabled by setting
284 | its ``disabled`` attribute. By default, this context manager
285 | sets that attribute to ``False`` at the beginning of its
286 | execution and resets it when the context manager is left. Set
287 | ``override_disabled`` to ``False`` to keep the current value
288 | of the attribute.
289 |
290 | :param bool override_global_level: The ``logging.disable`` function
291 | allows one to install a global minimum log level that takes
292 | precedence over a logger's own level. By default, this context
293 | manager makes sure that the global limit is at most ``level``,
294 | and reduces it if necessary during its execution. Set
295 | ``override_global_level`` to ``False`` to keep the global limit.
296 |
297 | :returns: A recording log handler that listens to ``logger`` during
298 | the execution of the context manager.
299 | :rtype: :py:class:`RecordingLogHandler`
300 |
301 | Example::
302 |
303 | import logging
304 |
305 | logger = logging.getLogger(__name__)
306 |
307 | with recorded_logs(logger) as logs:
308 | logger.info(u'Hello, world!')
309 |
310 | logs.assert_log(u'info', u'world')
311 | '''
312 | if logger is None:
313 | logger = logging.getLogger()
314 | elif not isinstance(logger, logging.Logger):
315 | logger = logging.getLogger(logger)
316 | handler = RecordingLogHandler()
317 | old_level = logger.level
318 | manager_level = logger.manager.disable
319 | disabled = logger.disabled
320 | logger.addHandler(handler)
321 | try:
322 | if level is not None:
323 | logger.setLevel(level)
324 | if override_disabled:
325 | logger.disabled = False
326 | if override_global_level:
327 | if (level is None) and (manager_level > old_level):
328 | logger.manager.disable = old_level
329 | elif (level is not None) and (manager_level > level):
330 | logger.manager.disable = level
331 | yield handler
332 | finally:
333 | logger.handlers.remove(handler)
334 | logger.setLevel(old_level)
335 | logger.disabled = disabled
336 | logger.manager.disable = manager_level
337 |
338 |
339 | # Copied from CKAN 2.7
340 | class RecordingLogHandler(logging.Handler):
341 | u'''
342 | Log handler that records log messages for later inspection.
343 |
344 | You can inspect the recorded messages via the ``messages`` attribute
345 | (a dict that maps log levels to lists of messages) or by using
346 | ``assert_log``.
347 |
348 | This class is rarely useful on its own, instead use
349 | :py:func:`recorded_logs` to temporarily record log messages.
350 | '''
351 | def __init__(self, *args, **kwargs):
352 | super(RecordingLogHandler, self).__init__(*args, **kwargs)
353 | self.clear()
354 |
355 | def emit(self, record):
356 | self.messages[record.levelname.lower()].append(record.getMessage())
357 |
358 | def assert_log(self, level, pattern, msg=None):
359 | u'''
360 | Assert that a certain message has been logged.
361 |
362 | :param string pattern: A regex which the message has to match.
363 | The match is done using ``re.search``.
364 |
365 | :param string level: The message level (``'debug'``, ...).
366 |
367 | :param string msg: Optional failure message in case the expected
368 | log message was not logged.
369 |
370 | :raises AssertionError: If the expected message was not logged.
371 | '''
372 | compiled_pattern = re.compile(pattern)
373 | for log_msg in self.messages[level]:
374 | if compiled_pattern.search(log_msg):
375 | return
376 | if not msg:
377 | if self.messages[level]:
378 | lines = u'\n '.join(self.messages[level])
379 | msg = (u'Pattern "{}" was not found in the log messages for '
380 | + u'level "{}":\n {}').format(pattern, level, lines)
381 | else:
382 | msg = (u'Pattern "{}" was not found in the log messages for '
383 | + u'level "{}" (no messages were recorded for that '
384 | + u'level).').format(pattern, level)
385 | raise AssertionError(msg)
386 |
387 | def clear(self):
388 | u'''
389 | Clear all captured log messages.
390 | '''
391 | self.messages = collections.defaultdict(list)
392 |
393 |
--------------------------------------------------------------------------------
/ckanext/extractor/tests/logic/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stadt-karlsruhe/ckanext-extractor/1d49dd615493db21ce0004b40f2ae0bb68f3869f/ckanext/extractor/tests/logic/__init__.py
--------------------------------------------------------------------------------
/ckanext/extractor/tests/logic/test_action.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import uuid
23 |
24 | import mock
25 | from nose.tools import assert_false, assert_raises, assert_true
26 |
27 | from ckan.logic import NotFound
28 | from ckan.model import Resource
29 | from ckan.tests.helpers import call_action, FunctionalTestBase
30 | from ckan.tests import factories
31 |
32 | from ...model import ResourceMetadata
33 | from ..helpers import (assert_anonymous_access, assert_authorized, assert_equal,
34 | assert_no_anonymous_access, assert_no_metadata,
35 | assert_not_authorized, get_metadata, fake_process,
36 | assert_validation_fails)
37 |
38 |
39 | def enqueue_job(*args, **kwargs):
40 | return mock.Mock(id=str(uuid.uuid4()))
41 |
42 |
43 | class TestExtractorList(FunctionalTestBase):
44 |
45 | def test_extractor_list_empty(self):
46 | """
47 | extractor_list when no metadata exist.
48 | """
49 | assert_equal(call_action('extractor_list'), [])
50 |
51 | def test_extractor_list_inprogress(self):
52 | """
53 | extractor_list does not list metadata that is in progress.
54 | """
55 | factories.Resource(format='pdf')
56 | assert_equal(call_action('extractor_list'), [])
57 |
58 | def test_extractor_list_some(self):
59 | """
60 | extractor_list when some metadata exist.
61 | """
62 | res_dict = factories.Resource(format='pdf')
63 | fake_process(res_dict)
64 | assert_equal(call_action('extractor_list'), [res_dict['id']])
65 |
66 | def test_extractor_list_auth(self):
67 | """
68 | Authorization for extractor_show.
69 | """
70 | assert_authorized(factories.User(), 'extractor_list',
71 | "Normal user wasn't allowed to extractor_list")
72 | assert_anonymous_access('extractor_list')
73 |
74 |
75 | @mock.patch('ckanext.extractor.logic.action.enqueue_job',
76 | side_effect=enqueue_job)
77 | class TestExtractorExtract(FunctionalTestBase):
78 |
79 | def test_extractor_extract_new_indexed(self, enqueue_job):
80 | """
81 | extractor_extract for a new resource with indexed format.
82 | """
83 | res_dict = factories.Resource(format='pdf')
84 | get_metadata(res_dict).delete().commit()
85 | enqueue_job.reset_mock()
86 | result = call_action('extractor_extract', id=res_dict['id'])
87 | assert_equal(result['status'], 'new', 'Wrong state')
88 | assert_false(result['task_id'] is None, 'Missing task ID')
89 | assert_equal(result['task_id'], get_metadata(res_dict).task_id,
90 | 'Task IDs differ.')
91 | assert_equal(enqueue_job.call_count, 1,
92 | 'Wrong number of extraction tasks.')
93 |
94 | def test_extractor_extract_new_ignored(self, enqueue_job):
95 | """
96 | extractor_extract for a new resource with ignored format.
97 | """
98 | res_dict = factories.Resource(format='foo')
99 | result = call_action('extractor_extract', id=res_dict['id'])
100 | assert_equal(result['status'], 'ignored', 'Wrong state')
101 | assert_true(result['task_id'] is None, 'Unexpected task ID')
102 | assert_equal(enqueue_job.call_count, 0,
103 | 'Wrong number of extraction tasks.')
104 |
105 | def test_extractor_extract_unchanged(self, enqueue_job):
106 | """
107 | extractor_extract for a resource with unchanged format and URL.
108 | """
109 | res_dict = factories.Resource(format='pdf')
110 | enqueue_job.reset_mock()
111 | fake_process(res_dict)
112 | result = call_action('extractor_extract', id=res_dict['id'])
113 | assert_equal(result['status'], 'unchanged', 'Wrong state')
114 | assert_true(result['task_id'] is None, 'Unexpected task ID')
115 | assert_equal(result['task_id'], get_metadata(res_dict).task_id,
116 | 'Task IDs differ.')
117 | assert_equal(enqueue_job.call_count, 0,
118 | 'Wrong number of extraction tasks.')
119 |
120 | def test_extractor_extract_update_indexed_format(self, enqueue_job):
121 | """
122 | extractor_extract for a resource with updated, indexed format.
123 | """
124 | res_dict = factories.Resource(format='pdf')
125 | enqueue_job.reset_mock()
126 | fake_process(res_dict)
127 |
128 | resource = Resource.get(res_dict['id'])
129 | resource.format = 'doc'
130 | resource.save()
131 |
132 | result = call_action('extractor_extract', id=res_dict['id'])
133 | assert_equal(result['status'], 'update', 'Wrong state')
134 | assert_false(result['task_id'] is None, 'Missing task ID')
135 | assert_equal(result['task_id'], get_metadata(res_dict).task_id,
136 | 'Task IDs differ.')
137 | assert_equal(enqueue_job.call_count, 1,
138 | 'Wrong number of extraction tasks.')
139 |
140 | def test_extractor_extract_update_ignored_format(self, enqueue_job):
141 | """
142 | extractor_extract for a resource with updated, ignored format.
143 | """
144 | res_dict = factories.Resource(format='pdf')
145 | enqueue_job.reset_mock()
146 | fake_process(res_dict)
147 |
148 | resource = Resource.get(res_dict['id'])
149 | resource.format = 'foo'
150 | resource.save()
151 |
152 | result = call_action('extractor_extract', id=res_dict['id'])
153 | assert_equal(result['status'], 'ignored', 'Wrong state')
154 | assert_true(result['task_id'] is None, 'Unexpected task ID')
155 | assert_equal(enqueue_job.call_count, 0,
156 | 'Wrong number of extraction tasks.')
157 | assert_no_metadata(res_dict)
158 |
159 | def test_extractor_extract_inprogress(self, enqueue_job):
160 | """
161 | extractor_extract for a resource that's already being extracted.
162 | """
163 | res_dict = factories.Resource(format='pdf')
164 | enqueue_job.reset_mock()
165 | old_task_id = get_metadata(res_dict).task_id
166 | result = call_action('extractor_extract', id=res_dict['id'])
167 | assert_equal(result['status'], 'inprogress', 'Wrong state')
168 | assert_equal(result['task_id'], old_task_id, 'Task IDs differ.')
169 | assert_equal(enqueue_job.call_count, 0,
170 | 'Wrong number of extraction tasks.')
171 |
172 | def test_extractor_extract_unexisting(self, enqueue_job):
173 | """
174 | extractor_extract for a resource that does not exist.
175 | """
176 | assert_raises(
177 | NotFound, lambda: call_action('extractor_extract',
178 | id='does-not-exist'))
179 |
180 | def test_extractor_extract_auth(self, enqueue_job):
181 | """
182 | Authorization for extractor_extract.
183 | """
184 | res_dict = factories.Resource(format='pdf')
185 | assert_not_authorized(factories.User(), 'extractor_extract',
186 | 'Normal user was allowed to extractor_extract',
187 | id=res_dict['id'])
188 | assert_no_anonymous_access('extractor_extract', id=res_dict['id'])
189 | assert_authorized(factories.Sysadmin(), 'extractor_extract',
190 | "Sysadmin wasn't allowed to extractor_extract",
191 | id=res_dict['id'])
192 |
193 | def test_extractor_extract_validation(self, enqueue_job):
194 | """
195 | Input validation for extractor_extract.
196 | """
197 | assert_validation_fails('extractor_extract', 'ID was not required.')
198 | assert_validation_fails('extractor_extract',
199 | 'Wrong force type was accepted',
200 | force='maybe')
201 |
202 | def test_extractor_extract_force_ignored_format(self, enqueue_job):
203 | """
204 | Forcing extractor_extract with ignored format.
205 | """
206 | res_dict = factories.Resource(format='foo')
207 | result = call_action('extractor_extract', id=res_dict['id'],
208 | force=True)
209 | assert_equal(result['status'], 'ignored', 'Wrong state')
210 | assert_true(result['task_id'] is None, 'Unexpected task ID')
211 | assert_equal(enqueue_job.call_count, 0,
212 | 'Wrong number of extraction tasks.')
213 |
214 | def test_extractor_extract_force_unchanged(self, enqueue_job):
215 | """
216 | Forcing extractor_extract with unchanged resource.
217 | """
218 | res_dict = factories.Resource(format='pdf')
219 | enqueue_job.reset_mock()
220 | fake_process(res_dict)
221 | result = call_action('extractor_extract', id=res_dict['id'],
222 | force=True)
223 | assert_equal(result['status'], 'unchanged', 'Wrong state')
224 | assert_false(result['task_id'] is None, 'Missing task ID')
225 | assert_equal(result['task_id'], get_metadata(res_dict).task_id,
226 | 'Task IDs differ.')
227 | assert_equal(enqueue_job.call_count, 1,
228 | 'Wrong number of extraction tasks.')
229 |
230 | def test_extractor_extract_force_inprogress(self, enqueue_job):
231 | """
232 | Forcing extractor_extract with existing task.
233 | """
234 | res_dict = factories.Resource(format='pdf')
235 | enqueue_job.reset_mock()
236 | old_task_id = get_metadata(res_dict).task_id
237 |
238 | result = call_action('extractor_extract', id=res_dict['id'],
239 | force=True)
240 | assert_equal(result['status'], 'inprogress', 'Wrong state')
241 | assert_false(result['task_id'] is None, 'Missing task ID')
242 | assert_equal(result['task_id'], get_metadata(res_dict).task_id,
243 | 'Task IDs differ.')
244 | assert_false(result['task_id'] == old_task_id,
245 | 'Task ID was not updated.')
246 | assert_equal(enqueue_job.call_count, 1,
247 | 'Wrong number of extraction tasks.')
248 |
249 |
250 | @mock.patch('ckanext.extractor.logic.action.enqueue_job',
251 | return_value=mock.Mock(id='test-id'))
252 | class TestExtractorShow(FunctionalTestBase):
253 |
254 | def test_extractor_show_unexisting(self, enqueue_job):
255 | """
256 | extractor_show for a resource that does not exist.
257 | """
258 | assert_raises(
259 | NotFound, lambda: call_action('extractor_show',
260 | id='does-not-exist'))
261 |
262 | def test_extractor_show_inprogress(self, enqueue_job):
263 | """
264 | extractor_show for metadata that is in progress.
265 | """
266 | res_dict = factories.Resource(format='pdf')
267 | result = call_action('extractor_show', id=res_dict['id'])
268 | assert_equal(result['task_id'], 'test-id', 'Wrong task ID.')
269 |
270 | def test_extractor_show_normal(self, enqueue_job):
271 | """
272 | extractor_show for normal metadata.
273 | """
274 | res_dict = factories.Resource(format='pdf')
275 | fake_process(res_dict)
276 | metadata = get_metadata(res_dict)
277 | metadata.meta['fulltext'] = 'foobar'
278 | metadata.meta['author'] = 'John Doe'
279 | metadata.save()
280 | result = call_action('extractor_show', id=res_dict['id'])
281 | assert_equal(result['meta']['fulltext'], 'foobar', 'Wrong fulltext.')
282 | assert_equal(result['meta']['author'], 'John Doe', 'Wrong author.')
283 | assert_equal(result['resource_id'], res_dict['id'],
284 | 'Wrong resource ID.')
285 | assert_true(result['task_id'] is None, 'Unexpected task ID.')
286 |
287 | def test_extractor_show_auth(self, enqueue_job):
288 | """
289 | Authorization for extractor_show.
290 | """
291 | res_dict = factories.Resource(format='pdf')
292 | assert_authorized(factories.User(), 'extractor_show',
293 | "Normal user wasn't allowed to extractor_show",
294 | id=res_dict['id'])
295 | assert_anonymous_access('extractor_show', id=res_dict['id'])
296 |
297 | def test_extractor_show_validation(self, enqueue_job):
298 | """
299 | Input validation for extractor_show.
300 | """
301 | assert_validation_fails('extractor_show',
302 | 'ID was not required.')
303 |
304 |
305 | @mock.patch('ckanext.extractor.logic.action.enqueue_job',
306 | side_effect=enqueue_job)
307 | class TestExtractorDelete(FunctionalTestBase):
308 |
309 | def test_extractor_delete_unexisting(self, enqueue_job):
310 | """
311 | extractor_delete for a resource that does not exist.
312 | """
313 | assert_raises(
314 | NotFound, lambda: call_action('extractor_delete',
315 | id='does-not-exist'))
316 |
317 | def test_extractor_delete_normal(self, enqueue_job):
318 | """
319 | extractor_delete for a normal resource.
320 | """
321 | res_dict = factories.Resource(format='pdf')
322 | fake_process(res_dict)
323 | call_action('extractor_delete', id=res_dict['id'])
324 | assert_no_metadata(res_dict)
325 |
326 | def test_extractor_delete_auth(self, enqueue_job):
327 | """
328 | Authorization for extractor_delete.
329 | """
330 | res_dict = factories.Resource(format='pdf')
331 | assert_not_authorized(factories.User(), 'extractor_delete',
332 | 'Normal user was allowed to extractor_delete',
333 | id=res_dict['id'])
334 | assert_no_anonymous_access('extractor_delete', id=res_dict['id'])
335 | assert_authorized(factories.Sysadmin(), 'extractor_delete',
336 | "Sysadmin wasn't allowed to extractor_delete",
337 | id=res_dict['id'])
338 |
339 | def test_extractor_delete_validation(self, enqueue_job):
340 | """
341 | Input validation for extractor_delete.
342 | """
343 | assert_validation_fails('extractor_delete', 'ID was not required.')
344 |
345 |
--------------------------------------------------------------------------------
/ckanext/extractor/tests/test.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stadt-karlsruhe/ckanext-extractor/1d49dd615493db21ce0004b40f2ae0bb68f3869f/ckanext/extractor/tests/test.pdf
--------------------------------------------------------------------------------
/ckanext/extractor/tests/test_interfaces.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | from collections import defaultdict
23 | import functools
24 | import requests
25 |
26 | import mock
27 | from pylons import config
28 |
29 | from ckan.tests import factories, helpers
30 | from ckan.plugins import implements, SingletonPlugin, PluginImplementations
31 |
32 | from ..interfaces import IExtractorPostprocessor, IExtractorRequest
33 | from ..tasks import extract
34 | from .helpers import (assert_equal, get_metadata, assert_package_found,
35 | assert_package_not_found)
36 | from nose.tools import assert_true
37 |
38 |
39 | RES_DICT = {
40 | 'url': 'https://does-not-matter',
41 | 'format': 'PDF',
42 | }
43 |
44 | METADATA = {
45 | 'fulltext': 'foobar',
46 | 'author': 'john_doe',
47 | 'created': 'yesterday',
48 | }
49 |
50 |
51 | def filter_metadata(d):
52 | keys = config['ckanext.extractor.indexed_fields'].split()
53 | return dict((key, value) for key, value in d.iteritems() if key in keys)
54 |
55 |
56 | class MockPostprocessor(SingletonPlugin):
57 |
58 | def __init__(self):
59 | SingletonPlugin.__init__(self)
60 | self.called = 0
61 |
62 |
63 | class MockAfterExtractPostprocessor(MockPostprocessor):
64 | implements(IExtractorPostprocessor, inherit=True)
65 |
66 | def extractor_after_extract(self, res_dict, extracted):
67 | self.called += 1
68 | for key, value in RES_DICT.iteritems():
69 | assert_equal(value, res_dict[key])
70 | assert_equal(extracted, METADATA)
71 | extracted['fulltext'] = 'i can change this'
72 |
73 |
74 | class MockAfterSavePostprocessor(MockPostprocessor):
75 | implements(IExtractorPostprocessor, inherit=True)
76 |
77 | def extractor_after_save(self, res_dict, metadata_dict):
78 | self.called += 1
79 | for key, value in RES_DICT.iteritems():
80 | assert_equal(value, res_dict[key])
81 | assert_equal(metadata_dict['meta'], filter_metadata(METADATA))
82 | assert_package_not_found(METADATA['fulltext'], res_dict['package_id'])
83 |
84 |
85 | class MockAfterIndexPostprocessor(MockPostprocessor):
86 | implements(IExtractorPostprocessor, inherit=True)
87 |
88 | def extractor_after_index(self, res_dict, metadata_dict):
89 | self.called += 1
90 | for key, value in RES_DICT.iteritems():
91 | assert_equal(value, res_dict[key])
92 | assert_equal(metadata_dict['meta'], filter_metadata(METADATA))
93 | assert_package_found(METADATA['fulltext'], res_dict['package_id'])
94 |
95 |
96 | class MockBeforeRequest(MockPostprocessor):
97 | implements(IExtractorRequest, inherit=True)
98 |
99 | def extractor_before_request(self, request):
100 | self.called += 1
101 | assert_true(isinstance(request, requests.PreparedRequest))
102 | request.url = 'http://test-url.example.com/file.pdf'
103 | return request
104 |
105 |
106 | MockPostprocessor().disable()
107 | MockAfterExtractPostprocessor().disable()
108 | MockAfterSavePostprocessor().disable()
109 | MockAfterIndexPostprocessor().disable()
110 | MockBeforeRequest().disable()
111 |
112 |
113 | def with_plugin(cls):
114 | '''
115 | Activate a plugin during a function's execution.
116 | '''
117 | def decorator(f):
118 | plugin = cls()
119 | @functools.wraps(f)
120 | def wrapped(*args, **kwargs):
121 | plugin.activate()
122 | try:
123 | plugin.enable()
124 | args = list(args) + [plugin]
125 | return f(*args, **kwargs)
126 | finally:
127 | plugin.disable()
128 | return wrapped
129 | return decorator
130 |
131 |
132 | @mock.patch('ckanext.extractor.tasks.load_config')
133 | @mock.patch('ckanext.extractor.tasks.download_and_extract',
134 | side_effect=lambda _: METADATA.copy())
135 | class TestIExtractorPostprocessor(object):
136 |
137 | @with_plugin(MockAfterExtractPostprocessor)
138 | def test_after_extract(self, download_and_extract, load_config, plugin):
139 | res_dict = factories.Resource(**RES_DICT)
140 | get_metadata(res_dict).delete().commit()
141 | extract(config['__file__'], res_dict)
142 | assert_equal(plugin.called, 1)
143 | metadata = get_metadata(res_dict)
144 | assert_equal(metadata.meta['fulltext'], 'i can change this')
145 |
146 | @with_plugin(MockAfterSavePostprocessor)
147 | def test_after_save(self, download_and_extract, load_config, plugin):
148 | res_dict = factories.Resource(**RES_DICT)
149 | get_metadata(res_dict).delete().commit()
150 | extract(config['__file__'], res_dict)
151 | assert_equal(plugin.called, 1)
152 |
153 | @with_plugin(MockAfterIndexPostprocessor)
154 | def test_after_index(self, download_and_extract, load_config, plugin):
155 | res_dict = factories.Resource(**RES_DICT)
156 | get_metadata(res_dict).delete().commit()
157 | extract(config['__file__'], res_dict)
158 | assert_equal(plugin.called, 1)
159 |
160 | @mock.patch('ckanext.extractor.tasks.load_config')
161 | @mock.patch('ckanext.extractor.tasks.toolkit')
162 | @mock.patch('ckanext.extractor.tasks.search')
163 | @mock.patch('ckanext.extractor.lib.pysolr.Solr')
164 | @mock.patch('ckanext.extractor.lib.Session')
165 | class TestIExtractorRequest(object):
166 |
167 | def setup(self):
168 | self.res_dict = factories.Resource(**RES_DICT)
169 |
170 | @with_plugin(MockBeforeRequest)
171 | def test_before_request(self, session, solr, search, toolkit, load_config, plugin):
172 | extract(config['__file__'], self.res_dict)
173 | assert_equal(plugin.called, 1)
174 | assert_true(session.called)
175 |
176 | name, args, kwargs = session.mock_calls[1]
177 | assert_equal(name, '().send')
178 | assert_equal(args[0].url, 'http://test-url.example.com/file.pdf')
179 |
--------------------------------------------------------------------------------
/ckanext/extractor/tests/test_lib.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import os.path
23 |
24 | from nose.tools import assert_true
25 |
26 | from ..lib import clean_metadatum, download_and_extract
27 | from .helpers import assert_equal, SimpleServer
28 |
29 |
30 | class TestDownloadAndExtract(object):
31 |
32 | PORT = 8000
33 |
34 | def __init__(self):
35 | self.server = SimpleServer(os.path.dirname(__file__), self.PORT)
36 |
37 | def setup(self):
38 | self.server.start()
39 |
40 | def teardown(self):
41 | self.server.stop()
42 |
43 | def test_download_and_extract(self):
44 | pdf_url = 'http://localhost:{port}/test.pdf'.format(port=self.PORT)
45 | metadata = download_and_extract(pdf_url)
46 | assert_true('Foobarium' in metadata['fulltext'], 'Incorrect fulltext.')
47 | assert_equal(metadata['content-type'], 'application/pdf')
48 |
49 |
50 | def test_clean_metadatum():
51 | assert_equal(clean_metadatum('X_y', ['X_y']), ('x-y', 'X_y'))
52 |
53 |
--------------------------------------------------------------------------------
/ckanext/extractor/tests/test_plugin.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import datetime
23 |
24 | import mock
25 | from sqlalchemy.orm.exc import NoResultFound
26 |
27 | from ckan.model import Package
28 | from ckan.lib.search import index_for
29 | from ckan.tests import factories, helpers
30 |
31 | from .helpers import (assert_equal, get_metadata, assert_metadata,
32 | assert_no_metadata, assert_package_found,
33 | assert_package_not_found)
34 | from ..model import ResourceMetadata
35 | from ..plugin import ExtractorPlugin
36 |
37 |
38 | RES_DICT = {
39 | 'url': 'does-not-matter',
40 | 'format': 'pdf',
41 | }
42 |
43 | METADATA = {
44 | 'fulltext': 'foobar',
45 | 'author': 'john_doe',
46 | 'created': 'yesterday',
47 | }
48 |
49 |
50 | def enqueue_job(name, args, **opts):
51 | res_dict = args[1]
52 | try:
53 | metadata = get_metadata(res_dict)
54 | except NoResultFound:
55 | metadata = ResourceMetadata.create(resource_id=res_dict['id'])
56 | metadata.last_format = res_dict['format']
57 | metadata.last_url = res_dict['url']
58 | metadata.last_extracted = datetime.datetime.now()
59 | metadata.task_id = None
60 | metadata.meta.update(METADATA)
61 | metadata.save()
62 | pkg_dict = helpers.call_action('package_show', id=res_dict['package_id'])
63 | index_for('package').update_dict(pkg_dict)
64 | return mock.Mock(id=None)
65 |
66 |
67 | @mock.patch('ckanext.extractor.logic.action.enqueue_job',
68 | side_effect=enqueue_job)
69 | class TestHooks(helpers.FunctionalTestBase):
70 | """
71 | Test that extraction and indexing happens automatically.
72 | """
73 | def test_extraction_upon_resource_creation(self, enqueue_job):
74 | """
75 | Metadata is extracted and indexed after resource creation.
76 | """
77 | factories.Resource(**RES_DICT)
78 | assert_equal(enqueue_job.call_count, 1,
79 | 'Wrong number of extraction tasks.')
80 |
81 | def test_extraction_upon_resource_update(self, enqueue_job):
82 | """
83 | Metadata is extracted and indexed after resource update.
84 | """
85 | res_dict = factories.Resource(**RES_DICT)
86 | enqueue_job.reset_mock()
87 | res_dict['format'] = 'doc' # Change format to trigger new extraction
88 | helpers.call_action('resource_update', **res_dict)
89 | assert_equal(enqueue_job.call_count, 1,
90 | 'Wrong number of extraction tasks.')
91 |
92 | def test_deletion_upon_resource_deletion(self, enqueue_job):
93 | """
94 | Metadata is removed when a resource is deleted.
95 | """
96 | res_dict = factories.Resource(**RES_DICT)
97 | assert_package_found(METADATA['fulltext'], res_dict['package_id'],
98 | 'Metadata not added to index.')
99 | assert_package_found(METADATA['author'], res_dict['package_id'],
100 | 'Metadata not added to index.')
101 | helpers.call_action('resource_delete', **res_dict)
102 | assert_package_not_found(METADATA['fulltext'], res_dict['package_id'],
103 | 'Metadata not removed from index.')
104 | assert_package_not_found(METADATA['author'], res_dict['package_id'],
105 | 'Metadata not removed from index.')
106 | assert_no_metadata(res_dict)
107 |
108 | def test_resource_deletion_with_no_metadata(self, enqueue_job):
109 | """
110 | A resource that doesn't have metadata can be removed.
111 | """
112 | res_dict = factories.Resource(url='foo', format='not-indexed')
113 | helpers.call_action('resource_delete', {'ignore_auth': True}, **res_dict)
114 |
115 | def test_extraction_after_public_dataset_update(self, enqueue_job):
116 | """
117 | If a public dataset is updated then its resources are extracted.
118 | """
119 | pkg_dict = factories.Dataset()
120 | res_dict = factories.Resource(package_id=pkg_dict['id'], **RES_DICT)
121 | pkg_dict = helpers.call_action('package_show', id=pkg_dict['id'])
122 | helpers.call_action('extractor_delete', id=res_dict['id'])
123 | enqueue_job.reset_mock()
124 | helpers.call_action('package_update', **pkg_dict)
125 | assert_equal(enqueue_job.call_count, 1,
126 | 'Wrong number of extraction tasks.')
127 |
128 | def test_deletion_after_private_dataset_update(self, enqueue_job):
129 | """
130 | If a private dataset is updated its resources' metadata is removed.
131 | """
132 | user = factories.Sysadmin()
133 | org_dict = factories.Organization()
134 | pkg_dict = factories.Dataset(owner_org=org_dict['id'])
135 | res_dict = factories.Resource(package_id=pkg_dict['id'], **RES_DICT)
136 | pkg_dict = helpers.call_action('package_show', id=pkg_dict['id'])
137 | pkg_dict['private'] = True
138 | assert_metadata(res_dict)
139 | helpers.call_action('package_update', {'user': user['id']}, **pkg_dict)
140 | assert_no_metadata(res_dict)
141 |
142 |
--------------------------------------------------------------------------------
/ckanext/extractor/tests/test_tasks.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published
8 | # by the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 |
20 | from __future__ import absolute_import, print_function, unicode_literals
21 |
22 | import datetime
23 | import logging
24 | import re
25 |
26 | import mock
27 | from pylons import config
28 | from nose.tools import assert_false, assert_true
29 | from requests.exceptions import RequestException
30 |
31 | from ckan.lib import search
32 | from ckan.plugins import toolkit
33 | from ckan.tests import factories
34 | from ckan.tests.helpers import FunctionalTestBase
35 |
36 | from ..tasks import extract
37 | from .helpers import (assert_equal, assert_time_span, get_metadata,
38 | assert_package_found, assert_package_not_found,
39 | recorded_logs)
40 |
41 |
42 | RES_DICT = {
43 | 'url': 'does-not-matter',
44 | 'format': 'pdf',
45 | }
46 |
47 | METADATA = {
48 | 'fulltext': 'foobar',
49 | 'author': 'john_doe',
50 | 'created': 'yesterday',
51 | }
52 |
53 |
54 | @mock.patch('ckanext.extractor.tasks.download_and_extract',
55 | return_value=METADATA)
56 | @mock.patch('ckanext.extractor.tasks.load_config')
57 | class TestMetadataExtractTask(FunctionalTestBase):
58 |
59 | def test_new(self, lc_mock, dae_mock):
60 | """
61 | Metadata extraction without previous metadata.
62 | """
63 | res_dict = factories.Resource(**RES_DICT)
64 | get_metadata(res_dict).delete().commit()
65 | extract(config['__file__'], res_dict)
66 | metadata = get_metadata(res_dict)
67 | assert_equal(metadata.meta['fulltext'], METADATA['fulltext'],
68 | 'Wrong fulltext.')
69 | assert_equal(metadata.meta['author'], METADATA['author'],
70 | 'Wrong author.')
71 | assert_false('created' in metadata.meta,
72 | '"created" field was not ignored.')
73 | assert_equal(metadata.last_format, res_dict['format'],
74 | 'Wrong last_format')
75 | assert_equal(metadata.last_url, res_dict['url'], 'Wrong last_url.')
76 | assert_true(metadata.task_id is None, 'Unexpected task ID.')
77 | assert_time_span(metadata.last_extracted, max=5)
78 | assert_package_found(METADATA['fulltext'], res_dict['package_id'],
79 | 'Metadata not indexed.')
80 | assert_package_found(METADATA['author'], res_dict['package_id'],
81 | 'Metadata not indexed.')
82 | assert_package_not_found(METADATA['created'], res_dict['package_id'],
83 | 'Wrong metadata indexed.')
84 |
85 | def test_update(self, lc_mock, dae_mock):
86 | """
87 | Metadata extraction of indexed format with previous metadata.
88 | """
89 | res_dict = factories.Resource(**RES_DICT)
90 | metadata = get_metadata(res_dict)
91 | metadata.meta['fulltext'] = 'old fulltext'
92 | metadata.meta['author'] = 'old author'
93 | metadata.meta['updated'] = 'should be removed'
94 | metadata.meta['last_extracted'] = datetime.datetime(2000, 1, 1)
95 | metadata.last_format = 'old format'
96 | metadata.last_url = 'old url'
97 | metadata.save()
98 | extract(config['__file__'], res_dict)
99 | metadata = get_metadata(res_dict)
100 | assert_equal(metadata.meta['fulltext'], METADATA['fulltext'],
101 | 'Wrong fulltext.')
102 | assert_equal(metadata.meta['author'], METADATA['author'],
103 | 'Wrong author.')
104 | assert_false('created' in metadata.meta,
105 | '"created" field was not ignored.')
106 | assert_false('updated' in metadata.meta,
107 | '"updated" field was not removed.')
108 | assert_equal(metadata.last_format, res_dict['format'],
109 | 'Wrong last_format')
110 | assert_equal(metadata.last_url, res_dict['url'], 'Wrong last_url.')
111 | assert_true(metadata.task_id is None, 'Unexpected task ID.')
112 | assert_time_span(metadata.last_extracted, max=5)
113 | assert_package_found(METADATA['fulltext'], res_dict['package_id'],
114 | 'Metadata not indexed.')
115 | assert_package_found(METADATA['author'], res_dict['package_id'],
116 | 'Metadata not indexed.')
117 | assert_package_not_found(METADATA['created'], res_dict['package_id'],
118 | 'Wrong metadata indexed.')
119 |
120 | def test_download_errors(self, lc_mock, dae_mock):
121 | """
122 | Handling of errors during resource downloading.
123 | """
124 | dae_mock.side_effect = RequestException('OH NOES')
125 | res_dict = factories.Resource(**RES_DICT)
126 | with recorded_logs() as logs:
127 | extract(config['__file__'], res_dict)
128 | logs.assert_log('warning', re.escape(res_dict['url']))
129 | logs.assert_log('warning', 'OH NOES')
130 |
131 | def test_extraction_from_private_dataset(self, lc_mock, dae_mock):
132 | """
133 | Handling of resources in private datasets.
134 | """
135 | # See https://github.com/stadt-karlsruhe/ckanext-extractor/issues/8
136 | org_dict = factories.Organization()
137 | pkg_dict = factories.Dataset(private=True, owner_org=org_dict['id'])
138 | res_dict = factories.Resource(package_id=pkg_dict['id'], **RES_DICT)
139 | with recorded_logs() as logs:
140 | extract(config['__file__'], res_dict)
141 | logs.assert_log('debug', 'private')
142 | dae_mock.assert_not_called()
143 |
144 | def test_multiple_values_for_the_same_field(self, lc_mock, dae_mock):
145 | """
146 | Handling of multiple values for the same metadata field.
147 | """
148 | # See https://github.com/stadt-karlsruhe/ckanext-extractor/issues/11
149 | dae_mock.return_value = {
150 | 'fulltext': 'foobar',
151 | 'author': ['john_doe', 'jane_doe'],
152 | }
153 | res_dict = factories.Resource(**RES_DICT)
154 | with recorded_logs() as logs:
155 | extract(config['__file__'], res_dict)
156 | logs.assert_log('debug', 'Collapsing.*author')
157 | metadata = get_metadata(res_dict)
158 | assert_equal(metadata.meta['author'], 'john_doe, jane_doe')
159 |
160 | def test_package_update_race_condition(self, lc_mock, dae_mock):
161 | """
162 | Handling of package updates during extraction.
163 | """
164 | res_dict = factories.Resource(**RES_DICT)
165 | sysadmin = factories.Sysadmin()
166 |
167 | def download_and_extract(*args, **kwargs):
168 | # Simulate a change to the package by another party during
169 | # the download and extraction process.
170 | toolkit.get_action('package_patch')({'user': sysadmin['name']},
171 | {'id': res_dict['package_id'],
172 | 'title': 'A changed title'})
173 | return {'fulltext': 'foobar'}
174 |
175 | dae_mock.side_effect = download_and_extract
176 | extract(config['__file__'], res_dict)
177 |
178 | # Make sure that the changed package metadata is kept and indexed
179 | pkg_dict = toolkit.get_action('package_show')(
180 | {}, {'id': res_dict['package_id']})
181 | assert_equal(pkg_dict['title'], 'A changed title')
182 | indexed_pkg_dict = search.show(res_dict['package_id'])
183 | assert_equal(indexed_pkg_dict['title'], 'A changed title')
184 |
185 |
--------------------------------------------------------------------------------
/dev-requirements.txt:
--------------------------------------------------------------------------------
1 | nose==1.3.7
2 | mock==1.0.1
3 |
4 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pysolr>=3.4.0
2 | requests>=2.7.0
3 |
4 |
--------------------------------------------------------------------------------
/runtests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # Run the tests for ckanext-extractor.
4 | #
5 | # Any arguments are forwarded to nosetests.
6 |
7 | # Create database tables if necessary
8 | paster --plugin=ckanext-extractor init -c test.ini
9 |
10 | # Run tests
11 | nosetests --ckan \
12 | --with-pylons=test.ini \
13 | --with-coverage \
14 | --cover-package=ckanext.extractor \
15 | --cover-erase \
16 | --cover-inclusive \
17 | $@
18 |
19 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [extract_messages]
2 | keywords = translate isPlural
3 | add_comments = TRANSLATORS:
4 | output_file = ckanext/extractor/i18n/ckanext-extractor.pot
5 | width = 80
6 |
7 | [init_catalog]
8 | domain = ckanext-extractor
9 | input_file = ckanext/extractor/i18n/ckanext-extractor.pot
10 | output_dir = ckanext/extractor/i18n
11 |
12 | [update_catalog]
13 | domain = ckanext-extractor
14 | input_file = ckanext/extractor/i18n/ckanext-extractor.pot
15 | output_dir = ckanext/extractor/i18n
16 | previous = true
17 |
18 | [compile_catalog]
19 | domain = ckanext-extractor
20 | directory = ckanext/extractor/i18n
21 | statistics = true
22 |
23 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright (C) 2016-2018 Stadt Karlsruhe (www.karlsruhe.de)
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published
7 | # by the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 |
19 | from setuptools import setup, find_packages
20 | import codecs
21 | import os.path
22 | import re
23 |
24 |
25 | HERE = os.path.abspath(os.path.dirname(__file__))
26 |
27 | # Get the long description from the README
28 | with codecs.open(os.path.join(HERE, 'README.rst'), encoding='utf-8') as f:
29 | long_description = f.read()
30 |
31 | # Extract version
32 | INIT_PY = os.path.join(HERE, 'ckanext', 'extractor', '__init__.py')
33 | version = None
34 | with codecs.open(INIT_PY) as f:
35 | for line in f:
36 | m = re.match(r'__version__\s*=\s*[\'"](.*)[\'"]', line)
37 | if m:
38 | version = m.groups()[0]
39 | break
40 | if version is None:
41 | raise RuntimeError('Could not extract version from "{}".'.format(INIT_PY))
42 |
43 | setup(
44 | name='''ckanext-extractor''',
45 |
46 | # Versions should comply with PEP440. For a discussion on single-sourcing
47 | # the version across setup.py and the project code, see
48 | # http://packaging.python.org/en/latest/tutorial.html#version
49 | version=version,
50 |
51 | description='''A full text and metadata extractor for CKAN''',
52 | long_description=long_description,
53 |
54 | # The project's main homepage.
55 | url='https://github.com/stadt-karlsruhe/ckanext-extractor',
56 |
57 | # Author details
58 | author='''Stadt Karlsruhe''',
59 | author_email='''transparenz@karlsruhe.de''',
60 |
61 | # Choose your license
62 | license='AGPL',
63 |
64 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
65 | classifiers=[
66 | # How mature is this project? Common values are
67 | # 3 - Alpha
68 | # 4 - Beta
69 | # 5 - Production/Stable
70 | 'Development Status :: 4 - Beta',
71 |
72 | # Pick your license as you wish (should match "license" above)
73 | 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
74 |
75 | # Specify the Python versions you support here. In particular, ensure
76 | # that you indicate whether you support Python 2, Python 3 or both.
77 | 'Programming Language :: Python :: 2.7',
78 | ],
79 |
80 |
81 | # What does your project relate to?
82 | keywords='''CKAN metadata meta data extraction fulltext full text search
83 | solr tika index''',
84 |
85 | # You can just specify the packages manually here if your project is
86 | # simple. Or you can use find_packages().
87 | packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
88 | namespace_packages=['ckanext'],
89 |
90 | # List run-time dependencies here. These will be installed by pip when your
91 | # project is installed. For an analysis of "install_requires" vs pip's
92 | # requirements files see:
93 | # https://packaging.python.org/en/latest/technical.html#install-requires-vs-requirements-files
94 | install_requires=[],
95 |
96 | # If there are data files included in your packages that need to be
97 | # installed, specify them here. If using Python 2.6 or less, then these
98 | # have to be included in MANIFEST.in as well.
99 | include_package_data=True,
100 | package_data={},
101 |
102 | # Although 'package_data' is the preferred approach, in some case you may
103 | # need to place data files outside of your packages.
104 | # see http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files
105 | # In this case, 'data_file' will be installed into '/my_data'
106 | data_files=[],
107 |
108 | # To provide executable scripts, use entry points in preference to the
109 | # "scripts" keyword. Entry points provide cross-platform support and allow
110 | # pip to create the appropriate form of executable for the target platform.
111 | entry_points='''
112 | [ckan.plugins]
113 | extractor=ckanext.extractor.plugin:ExtractorPlugin
114 |
115 | [babel.extractors]
116 | ckan = ckan.lib.extract:extract_ckan
117 |
118 | [paste.paster_command]
119 | delete = ckanext.extractor.paster:DeleteCommand
120 | extract = ckanext.extractor.paster:ExtractCommand
121 | init = ckanext.extractor.paster:InitCommand
122 | list = ckanext.extractor.paster:ListCommand
123 | show = ckanext.extractor.paster:ShowCommand
124 | ''',
125 |
126 | # If you are changing from the default layout of your extension, you may
127 | # have to change the message extractors, you can read more about babel
128 | # message extraction at
129 | # http://babel.pocoo.org/docs/messages/#extraction-method-mapping-and-configuration
130 | message_extractors={
131 | 'ckanext': [
132 | ('**.py', 'python', None),
133 | ('**.js', 'javascript', None),
134 | ('**/templates/**.html', 'ckan', None),
135 | ],
136 | }
137 | )
138 |
139 |
--------------------------------------------------------------------------------
/test-local.ini.example:
--------------------------------------------------------------------------------
1 | # Example file for local test settings. Copy to `test-local.ini`
2 |
3 | # Test Configuration settings for your particular system (e.g. database
4 | # connection, Solr URL) should go into this file (`test-local.ini`). It
5 | # is automatically included in `test.ini` and not tracked by Git.
6 |
7 | [app:main]
8 | # Include default CKAN test configuration. You may have to update the
9 | # path if the CKAN sources are not in an adjacent directory.
10 | use = config:../ckan/test-core.ini
11 |
12 |
--------------------------------------------------------------------------------
/test.ini:
--------------------------------------------------------------------------------
1 | # ATTENTION: Do not edit this file directly for configurations related
2 | # to your particular system (e.g. database connection, Solr URL, etc.).
3 | # Put these into `test-local.ini` which is automatically included here
4 | # and not tracked by Git. See `test-local.ini.example` for details.
5 |
6 | [DEFAULT]
7 | debug = false
8 | smtp_server = localhost
9 | error_email_from = paste@localhost
10 |
11 | [server:main]
12 | use = egg:Paste#http
13 | host = 0.0.0.0
14 | port = 5000
15 |
16 | [app:main]
17 | use = config:test-local.ini
18 |
19 | ckan.plugins = extractor
20 |
21 | # Our tests assume that certain formats and fields are indexed while
22 | # others are ignored.
23 | ckanext.extractor.indexed_formats = pdf doc
24 | ckanext.extractor.indexed_fields = fulltext author
25 |
26 | # Logging configuration
27 | [loggers]
28 | keys = root, ckan, ckanext, sqlalchemy
29 |
30 | [handlers]
31 | keys = console
32 |
33 | [formatters]
34 | keys = generic
35 |
36 | [logger_root]
37 | level = WARN
38 | handlers = console
39 |
40 | [logger_ckan]
41 | qualname = ckan
42 | handlers = console
43 | level = INFO
44 | propagate = 0
45 |
46 | [logger_ckanext]
47 | qualname = ckanext
48 | handlers = console
49 | level = DEBUG
50 | propagate = 0
51 |
52 | [logger_sqlalchemy]
53 | handlers = console
54 | qualname = sqlalchemy.engine
55 | level = WARN
56 | propagate = 0
57 |
58 | [handler_console]
59 | class = StreamHandler
60 | args = (sys.stdout,)
61 | level = NOTSET
62 | formatter = generic
63 |
64 | [formatter_generic]
65 | format = %(asctime)s %(levelname)-5.5s [%(name)s] %(message)s
66 |
--------------------------------------------------------------------------------
/travis/build.bash:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | echo "This is travis-build.bash..."
5 |
6 | SOLR_VERSION=3.6.2
7 |
8 | echo "Installing the packages that CKAN requires..."
9 | sudo apt-get update -qq
10 | sudo apt-get install solr-tomcat=$SOLR_VERSION\*
11 |
12 | echo "Downloading Solr plugins"
13 | wget http://archive.apache.org/dist/lucene/solr/$SOLR_VERSION/apache-solr-$SOLR_VERSION.tgz
14 | tar xzf apache-solr-$SOLR_VERSION.tgz
15 | sudo mv -v apache-solr-$SOLR_VERSION /var/apache-solr
16 |
17 | echo "Configure Solr"
18 | sudo cp -v travis/solr/ckan-$CKANVERSION/* /etc/solr/conf/
19 |
20 | echo "Restarting Tomcat"
21 | sudo service tomcat6 restart
22 |
23 | echo "Checking that Tomcat is up"
24 | sudo service tomcat6 status
25 | curl http://127.0.0.1:8080
26 |
27 | echo "Checking that Solr is up"
28 | curl http://127.0.0.1:8080/solr/admin/ping
29 |
30 | echo "Installing CKAN and its Python dependencies..."
31 | git clone https://github.com/ckan/ckan
32 | pushd ckan
33 | if [ $CKANVERSION == 'master' ]
34 | then
35 | echo "CKAN version: master"
36 | else
37 | CKAN_TAG=$(git tag | grep ^ckan-$CKANVERSION | sort --version-sort | tail -n 1)
38 | git checkout $CKAN_TAG
39 | echo "CKAN version: ${CKAN_TAG#ckan-}"
40 |
41 | if [ $CKANVERSION == '2.6' ]
42 | then
43 | echo "Installing ckanext-rq"
44 | pushd ..
45 | git clone https://github.com/ckan/ckanext-rq.git
46 | cd ckanext-rq
47 | python setup.py develop
48 | pip install -r requirements.txt
49 | cd ..
50 | # Add `rq` to the list of active CKAN plugins
51 | sed -i '/^\s*ckan.plugins\s*=/ s/$/ rq/' test.ini
52 | popd
53 | fi
54 | fi
55 | # Unpin CKAN's psycopg2 dependency get an important bugfix
56 | # https://stackoverflow.com/questions/47044854/error-installing-psycopg2-2-6-2
57 | sed -i '/psycopg2/c\psycopg2' requirements.txt
58 | python setup.py develop
59 | pip install -r requirements.txt
60 | pip install -r dev-requirements.txt
61 | popd
62 |
63 | echo "Creating the PostgreSQL user and database..."
64 | sudo -u postgres psql -c "CREATE USER ckan_default WITH PASSWORD 'pass';"
65 | sudo -u postgres psql -c 'CREATE DATABASE ckan_test WITH OWNER ckan_default;'
66 |
67 | echo "Installing ckanext-extractor and its requirements..."
68 | python setup.py develop
69 | pip install -r requirements.txt
70 | pip install -r dev-requirements.txt
71 |
72 | echo "Moving test.ini into a subdir..."
73 | mkdir subdir
74 | mv test.ini subdir
75 |
76 | echo "Copying test-local.ini"
77 | cp -v travis/test-local.ini subdir/
78 |
79 | echo "Initialising the database..."
80 | pushd ckan
81 | paster db init -c test-core.ini
82 | popd
83 |
84 | echo "Initializing database for ckanext-extractor..."
85 | paster --plugin=ckanext-extractor init -c subdir/test.ini
86 |
87 | echo "travis-build.bash is done."
88 |
89 |
--------------------------------------------------------------------------------
/travis/run.bash:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | nosetests --ckan \
5 | --with-pylons=subdir/test.ini \
6 | --with-coverage \
7 | --cover-package=ckanext.extractor \
8 | --cover-erase \
9 | --cover-inclusive \
10 | ckanext
11 |
12 |
--------------------------------------------------------------------------------
/travis/solr/ckan-2.6/schema.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
23 |
24 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 | index_id
157 | text
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
--------------------------------------------------------------------------------
/travis/solr/ckan-2.6/solrconfig.xml:
--------------------------------------------------------------------------------
1 | ../solrconfig.xml
--------------------------------------------------------------------------------
/travis/solr/ckan-2.7/schema.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
23 |
24 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 | index_id
165 | text
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
--------------------------------------------------------------------------------
/travis/solr/ckan-2.7/solrconfig.xml:
--------------------------------------------------------------------------------
1 | ../solrconfig.xml
--------------------------------------------------------------------------------
/travis/solr/ckan-2.8/schema.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
23 |
24 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 | index_id
165 | text
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
--------------------------------------------------------------------------------
/travis/solr/ckan-2.8/solrconfig.xml:
--------------------------------------------------------------------------------
1 | ../solrconfig.xml
--------------------------------------------------------------------------------
/travis/solr/ckan-master/schema.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
23 |
24 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 | index_id
165 | text
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
--------------------------------------------------------------------------------
/travis/solr/ckan-master/solrconfig.xml:
--------------------------------------------------------------------------------
1 | ../solrconfig.xml
--------------------------------------------------------------------------------
/travis/test-local.ini:
--------------------------------------------------------------------------------
1 | [app:main]
2 | use = config:../ckan/test-core.ini
3 | solr_url = http://127.0.0.1:8080/solr
4 |
5 |
--------------------------------------------------------------------------------