PK PICq isogeo_search_engine/LICENSE GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
PK 0JC ! isogeo_search_engine/metadata.txt# This file contains metadata for your plugin. Since
# version 2.0 of QGIS this is the proper way to supply
# information about a plugin. The old method of
# embedding metadata in __init__.py will
# is no longer supported since version 2.0.
# This file should be included when you package your plugin.# Mandatory items:
[general]
name=Isogeo
qgisMinimumVersion=2.8
description=Isogeo search engine within QGIS
version=1.5.0
author=Isogeo,GeoJulien,Theo Sinatti
email=projects+qgis@isogeo.com
about=This plugin helps finding geodata, searching within Isogeo catalogs. To use it, you can ask a free access sending a mail to projects+qgis@isogeo.com.
tracker=https://github.com/isogeo/isogeo-plugin-qgis/issues
repository=https://github.com/isogeo/isogeo-plugin-qgis
# End of mandatory metadata
# Recommended items:
# Uncomment the following line and add your changelog:
# changelog=
# Tags are comma separated with spaces allowed
tags=REST API,catalog,search,explore,webservices,metadata,open data,INSPIRE
homepage=https://github.com/isogeo/isogeo-plugin-qgis
category=Web
icon=icon.png
# experimental flag
experimental=False
# deprecated flag (applies to the whole plugin, not just a single version)
deprecated=False
PK XqIr: isogeo_search_engine/README# Isogeo for QGIS
QGIS plugin for [Isogeo](http://www.isogeo.com/), a SaaS software to give an easier access to geodata.
Equivalent of [plugins for ArcGIS](http://www.isogeo.com/applications/).
You can see and vote for [this plugin on the official QGIS extensions website](http://plugins.qgis.org/plugins/isogeo_search_engine/).
## Purpose ##
Allow Isogeo users to search for datas in their own and external metadata catalogs and add it to a QGIS project. Its goal is to improve access to internal and external geodata.
## How does it works ##
### Technical
It's based on Isogeo API:
* REST-ful
* oAuth2 protocol used to authenticate shares
It's fully integrated with QGIS ecosystem:
* PyQGIS 2
* PyQt 4.8.x
### Features
- [X] Text search among Isogeo shares
- [X] Dynamic filter on keywords, INSPIRE themes, catalog owners, source coordinate system and available links
- [X] Geographic filter from a layer bounding box
- [X] Geographic filter from the map canvas bounding box
- [X] Order results by relevance, alphabetic, last updated date (data or metadata), creation date (data or metadata)
- [X] Add the related data directly to the map canvas throught raw data or web services
- [X] Display full metadata information in a separated window
- [X] Save search bookmarks
- [ ] Customize and manage data lists
## Screen captures ##
| Without any search | With some filters |
|:------------------:|:-----------------:|
| ![Search widget with no filters](img/ui_tabs_main_search_empty_en.png) | ![Search widget with some filters](img/ui_tabs_main_search_filtered_en.png) |
![Add data to the project](img/ui_tabs_main_add_dataset_file_annoted_en.png)
## Getting started ##
In a nutshell:
1. QGIS *Plugins* menu -> *Manage and Install Plugins...*;
2. Search for *isogeo*, select it and install it.
If you want a more advanced version, check the box allowing experimental extensions in settings.
See the documentation:
* en [français](doc/install_FR.md) ;
* in [English](doc/install_EN.md).
## Authors ##
Internship of [Théo SINATTI](https://github.com/TheoSinatti) supervised by [Julien Moura](https://github.com/Guts), at Isogeo: http://www.isogeo.com.
## Sponsors ##
This plugin is made thanks to some Isogeo active clients:
![Syndicat Mixte d'Aménagement de la Vallée de la Durance](img/sponsor_logo_SMAVD.jpg)
![Communauté d'Agglomération de Lorient](img/sponsor_logo_ca_lorient.png)
PK PIl isogeo_search_engine/__init__.py# -*- coding: utf-8 -*-
"""
/***************************************************************************
Isogeo
A QGIS plugin
Isogeo search engine within QGIS
-------------------
begin : 2016-07-22
copyright : (C) 2016 by Isogeo, Theo Sinatti, GeoJulien
email : projets+qgis@isogeo.fr
git sha : $Format:%H$
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
This script initializes the plugin, making it known to QGIS.
"""
# noinspection PyPep8Naming
def classFactory(iface): # pylint: disable=invalid-name
"""Load Isogeo class from file Isogeo.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
from .isogeo import Isogeo
return Isogeo(iface)
PK mJ"<^ <^ isogeo_search_engine/isogeo.py# -*- coding: utf-8 -*-
"""
/***************************************************************************
Isogeo
A QGIS plugin
Isogeo search engine within QGIS
-------------------
begin : 2016-07-22
git sha : $Format:%H$
copyright : (C) 2016 by Isogeo, Theo Sinatti, GeoJulien
email : projects+qgis@isogeo.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
# Standard library
import os.path
import json
import base64
import urllib
import logging
from logging.handlers import RotatingFileHandler
import platform # about operating systems
from collections import OrderedDict
from functools import partial
import operator
# PyQT
# from QByteArray
from PyQt4.QtCore import (QByteArray, QCoreApplication, QSettings,
Qt, QTranslator, QUrl, qVersion)
from PyQt4.QtGui import (QAction, QIcon, QMessageBox, QStandardItemModel,
QStandardItem, QProgressBar)
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest
# PyQGIS
import db_manager.db_plugins.postgis.connector as con
from qgis.utils import iface, plugin_times, QGis, reloadPlugin
from qgis.core import (QgsAuthManager, QgsAuthMethodConfig,
QgsCoordinateReferenceSystem, QgsCoordinateTransform,
QgsDataSourceURI,
QgsMapLayerRegistry, QgsMessageLog,
QgsNetworkAccessManager,
QgsPoint, QgsRectangle, QgsRasterLayer, QgsVectorLayer)
# Initialize Qt resources from file resources.py
import resources
# UI classes
from ui.isogeo_dockwidget import IsogeoDockWidget # main widget
from ui.auth.dlg_authentication import IsogeoAuthentication
from ui.credits.dlg_credits import IsogeoCredits
from ui.metadata.dlg_md_details import IsogeoMdDetails
from ui.quicksearch.dlg_quicksearch_new import QuicksearchNew
from ui.quicksearch.dlg_quicksearch_rename import QuicksearchRename
# Custom modules
from modules.api import IsogeoApiManager
from modules.metadata_display import MetadataDisplayer
from modules.results import ResultsManager
from modules.tools import Tools
from modules.url_builder import UrlBuilder
# ############################################################################
# ########## Globals ###############
# ##################################
# useful submodules and shortcuts
qgis_auth_mng = QgsAuthManager.instance()
custom_tools = Tools()
isogeo_api_mng = IsogeoApiManager()
msgBar = iface.messageBar()
network_mng = QNetworkAccessManager()
qsettings = QSettings()
srv_url_bld = UrlBuilder()
# LOG FILE ##
logger = logging.getLogger("IsogeoQgisPlugin")
logging.captureWarnings(True)
logger.setLevel(logging.INFO) # all errors will be get
# logger.setLevel(logging.DEBUG) # switch on it only for dev works
log_form = logging.Formatter("%(asctime)s || %(levelname)s "
"|| %(module)s || %(message)s")
logfile = RotatingFileHandler(os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"log_isogeo_plugin.log"),
"a", 5000000, 1)
logfile.setLevel(logging.INFO)
# logfile.setLevel(logging.DEBUG) # switch on it only for dev works
logfile.setFormatter(log_form)
logger.addHandler(logfile)
# ############################################################################
# ########## Classes ###############
# ##################################
class Isogeo:
"""QGIS Plugin Implementation."""
logger.info('\n\n\t========== Isogeo Search Engine for QGIS ==========')
logger.info('OS: {0}'.format(platform.platform()))
try:
logger.info('QGIS Version: {0}'.format(QGis.QGIS_VERSION))
except UnicodeEncodeError:
qgis_version = QGis.QGIS_VERSION.decode("latin1")
logger.info('QGIS Version: {0}'.format(qgis_version))
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = qsettings.value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'isogeo_search_engine_{}.qm'.format(locale))
logger.info('Language applied: {0}'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
if qVersion() > '4.3.3':
QCoreApplication.installTranslator(self.translator)
else:
pass
else:
pass
if locale == "fr":
self.lang = "fr"
else:
self.lang = "en"
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Isogeo')
self.toolbar = self.iface.addToolBar(u'Isogeo')
self.toolbar.setObjectName(u'Isogeo')
self.pluginIsActive = False
self.dockwidget = None
# network manager included within QGIS
self.manager = QgsNetworkAccessManager.instance()
# self.manager = QNetworkAccessManager()
self.md_display = MetadataDisplayer(IsogeoMdDetails())
# UI submodules
self.auth_prompt_form = IsogeoAuthentication()
self.quicksearch_new_dialog = QuicksearchNew()
self.quicksearch_rename_dialog = QuicksearchRename()
self.credits_dialog = IsogeoCredits()
self.md_display = MetadataDisplayer(IsogeoMdDetails())
self.results_mng = ResultsManager(self)
# start variables
self.savedSearch = "first"
self.requestStatusClear = True
self.loopCount = 0
self.hardReset = False
self.showResult = False
self.showDetails = False
self.store = False
self.settingsRequest = False
self.PostGISdict = srv_url_bld.build_postgis_dict(qsettings)
# self.currentUrl = "https://v1.api.isogeo.com/resources/search?
# _limit=10&_include=links&_lang={0}".format(self.lang)
self.old_text = ""
self.page_index = 1
basepath = os.path.dirname(os.path.realpath(__file__))
self.json_path = basepath + '/user_settings/saved_searches.json'
# noinspection PyMethodMayBeStatic
def tr(self, message, context="Isogeo"):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate(context, message)
def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToWebMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/Isogeo/icon.png'
self.add_action(
icon_path,
text=self.tr(u'Search within Isogeo catalogs'),
callback=self.run,
parent=self.iface.mainWindow())
# --------------------------------------------------------------------------
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed."""
# disconnects
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
# self.dockwidget = None
self.pluginIsActive = False
try:
reloadPlugin("isogeo_search_engine")
except TypeError:
pass
try:
reloadPlugin("isogeo_search_engine_dev")
except TypeError:
pass
def unload(self):
"""Remove the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginWebMenu(
self.tr(u'&Isogeo'),
action)
try:
self.iface.mainWindow().statusBar().removeWidget(self.bar)
except:
pass
self.iface.removeToolBarIcon(action)
logger.handlers = []
# remove the toolbar
del self.toolbar
# --------------------------------------------------------------------------
def user_authentication(self):
"""Test the validity of the user id and secret.
This is the first major function the plugin calls when executed. It
retrieves the id and secret from the config file. If they are set to
their default value, it asks for them.
If not, it tries to send a request.
"""
self.user_id = qsettings.value("isogeo-plugin/user-auth/id", 0)
self.user_secret = qsettings.value("isogeo-plugin/user-auth/secret", 0)
if self.user_id != 0 and self.user_secret != 0:
logging.info("User_authentication function is trying "
"to get a token from the id/secret")
self.ask_for_token(self.user_id, self.user_secret)
else:
logging.info("No id/secret. User authentication function "
"is showing the auth window.")
self.auth_prompt_form.show()
def write_ids_and_test(self):
"""Store the id & secret and launch the test function.
Called when the authentification window is closed,
it stores the values in the file, then call the
user_authentification function to test them.
"""
logging.info("Authentication window accepted. Writting"
" id/secret in QSettings.")
app_id = self.auth_prompt_form.ent_app_id.text()
app_secret = self.auth_prompt_form.\
ent_app_secret.text()
user_editor = self.auth_prompt_form.chb_isogeo_editor.isChecked()
# old name maintained for compatibility reasons
qsettings.setValue("isogeo-plugin/user-auth/id", app_id)
qsettings.setValue("isogeo-plugin/user-auth/secret", app_secret)
# new name to anticipate on future migration
qsettings.setValue("isogeo/api_auth/id", app_id)
qsettings.setValue("isogeo/api_auth/secret", app_secret)
qsettings.setValue("isogeo/user/editor", int(user_editor))
# anticipating on QGIS Auth Management
if qgis_auth_mng.authenticationDbPath():
logger.info("TRACKING - AUTH: new QGIS system already initialized")
auth_isogeo_id = qsettings.value("isogeo/app_auth/qgis_auth_id")
# already initialised => we are inside a QGIS app.
if (qgis_auth_mng.masterPasswordIsSet() and
auth_isogeo_id in qgis_auth_mng.availableAuthMethodConfigs()):
logger.info("TRACKING - AUTH: master password has been set"
" and Isogeo auth config already exists."
" Let's update it if needed.")
# get existing Isogeo auth id
auth_isogeo = qgis_auth_mng.availableAuthMethodConfigs()\
.get(auth_isogeo_id)
# update values from form
auth_isogeo.setConfig("username", app_id)
auth_isogeo.setConfig("password", app_secret)
# check if method parameters are correctly set and store it
if auth_isogeo.isValid():
qgis_auth_mng.updateAuthenticationConfig(auth_isogeo)
else:
logger.error("AUTH - Fail to create and store configuration")
elif (qgis_auth_mng.masterPasswordIsSet() and
auth_isogeo_id not in qgis_auth_mng.availableAuthMethodConfigs()):
logger.info("TRACKING - AUTH: master password has been set"
" and Isogeo auth config doesn't exist yet")
auth_isogeo_cfg = QgsAuthMethodConfig()
auth_isogeo_cfg.setName("Isogeo")
auth_isogeo_cfg.setMethod("Basic")
auth_isogeo_cfg.setUri("https://v1.api.isogeo.com/about")
auth_isogeo_cfg.setConfig("username", app_id)
auth_isogeo_cfg.setConfig("password", app_secret)
# check if method parameters are correctly set and store it
if auth_isogeo_cfg.isValid():
qgis_auth_mng.storeAuthenticationConfig(auth_isogeo_cfg)
qsettings.setValue("isogeo/app_auth/qgis_auth_id",
auth_isogeo_cfg.id())
else:
logger.error("AUTH - Fail to create and store configuration")
else:
logger.debug("TRACKING - AUTH: master password is not set")
pass
else:
pass
# launch authentication
self.user_authentication()
def ask_for_token(self, c_id, c_secret):
"""Ask a token from Isogeo API authentification page.
This send a POST request to Isogeo API with the user id and secret in
its header. The API should return an access token
"""
headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret)
data = urllib.urlencode({"grant_type": "client_credentials"})
databyte = QByteArray()
databyte.append(data)
url = QUrl('https://id.api.isogeo.com/oauth/token')
request = QNetworkRequest(url)
request.setRawHeader("Authorization", headervalue)
if self.requestStatusClear is True:
self.requestStatusClear = False
token_reply = self.manager.post(request, databyte)
token_reply.finished.connect(
partial(self.handle_token, answer=token_reply))
QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
def handle_token(self, answer):
"""Handle the API answer when asked for a token.
This handles the API answer. If it has sent an access token, it calls
the initialization function. If not, it raises an error, and ask
for new IDs
"""
logging.info("Asked a token and got a reply from the API.")
bytarray = answer.readAll()
content = str(bytarray)
try:
parsed_content = json.loads(content)
except ValueError as e:
if "No JSON object could be decoded" in e:
msgBar.pushMessage(self.tr("Request to Isogeo failed: please check your Internet connection."),
duration=10,
level=msgBar.WARNING)
logger.error("Internet connection failed")
self.pluginIsActive = False
# try:
# reloadPlugin("isogeo_search_engine")
# except TypeError:
# pass
# try:
# reloadPlugin("isogeo_search_engine_dev")
# except TypeError:
# pass
else:
pass
return
if 'access_token' in parsed_content:
logging.info("The API reply is an access token : "
"the request worked as expected.")
# TO DO : Appeler la fonction d'initialisation
self.token = "Bearer " + parsed_content.get('access_token')
if self.savedSearch == "first":
self.requestStatusClear = True
self.set_widget_status()
else:
self.requestStatusClear = True
self.send_request_to_isogeo_api(self.token)
# TO DO : Distinguer plusieurs cas d'erreur
elif 'error' in parsed_content:
logging.error("The API reply is an error. Id and secret must be "
"invalid. Asking for them again.")
QMessageBox.information(
iface.mainWindow(), self.tr("Error"), parsed_content['error'])
self.requestStatusClear = True
# displaying auth form
self.auth_prompt_form.ent_app_id.setText(self.user_id)
self.auth_prompt_form.ent_app_secret.setText(self.user_secret)
self.auth_prompt_form.show()
else:
self.requestStatusClear = True
logging.error("The API reply has an unexpected form : "
"{0}".format(parsed_content))
QMessageBox.information(
iface.mainWindow(), self.tr("Error"), self.tr("Unknown error"))
def send_request_to_isogeo_api(self, token, limit=10):
"""Send a content url to the Isogeo API.
This takes the currentUrl variable and send a request to this url,
using the token variable.
"""
myurl = QUrl(self.currentUrl)
request = QNetworkRequest(myurl)
request.setRawHeader("Authorization", token)
if self.requestStatusClear is True:
self.requestStatusClear = False
api_reply = self.manager.get(request)
api_reply.finished.connect(
partial(self.handle_api_reply, answer=api_reply))
else:
pass
def handle_api_reply(self, answer):
"""Handle the different possible Isogeo API answer.
This is called when the answer from the API is finished. If it's
content, it calls update_fields(). If it isn't, it means the token has
expired, and it calls ask_for_token()
"""
logging.info("Request sent to API and reply received.")
bytarray = answer.readAll()
content = str(bytarray)
if answer.error() == 0 and content != "":
logging.info("Reply is a result json.")
if self.showDetails is False and self.settingsRequest is False:
self.loopCount = 0
parsed_content = json.loads(content)
self.requestStatusClear = True
self.update_fields(parsed_content)
del parsed_content
elif self.showDetails is True:
self.showDetails = False
self.loopCount = 0
parsed_content = json.loads(content)
self.requestStatusClear = True
self.md_display.show_complete_md(parsed_content)
del parsed_content
elif self.settingsRequest is True:
self.settingsRequest = False
self.loopCount = 0
parsed_content = json.loads(content)
self.requestStatusClear = True
self.write_shares_info(parsed_content)
del parsed_content
elif answer.error() == 204:
logging.info("Token expired. Renewing it.")
self.loopCount = 0
self.requestStatusClear = True
self.ask_for_token(self.user_id, self.user_secret)
elif content == "":
logging.info("Empty reply. Weither no catalog is shared with the "
"plugin, or there is a problem (2 requests sent "
"together)")
if self.loopCount < 3:
self.loopCount += 1
answer.abort()
del answer
self.requestStatusClear = True
self.ask_for_token(self.user_id, self.user_secret)
else:
self.requestStatusClear = True
msgBar.pushMessage(
self.tr("The script is looping. Make sure you shared a "
"catalog with the plugin. If so, please report "
"this on the bug tracker."))
else:
self.requestStatusClear = True
QMessageBox.information(iface.mainWindow(),
self.tr("Error"),
self.tr("You are facing an unknown error. "
"Code: ") +
str(answer.error()) +
"\nPlease report tis on the bug tracker.")
# method end
return
def update_fields(self, result):
"""Update the fields content.
This takes an API answer and update the fields accordingly. It also
calls show_results in the end. This may change, so results would be
shown only when a specific button is pressed.
"""
# logs
logger.info("Update_fields function called on the API reply. reset = "
"{0}".format(self.hardReset))
QgsMessageLog.logMessage("Query sent & received: {}"
.format(result.get("query")),
"Isogeo")
# parsing
tags = isogeo_api_mng.get_tags(result)
self.old_text = self.dockwidget.txt_input.text()
# Getting the index of selected items in each combobox
params = self.save_params()
# Show how many results there are
self.results_count = result.get('total')
self.dockwidget.btn_show.setText(
str(self.results_count) + self.tr(" results"))
# Setting the number of rows in the result table
self.nb_page = str(custom_tools.results_pages_counter(self.results_count))
self.dockwidget.lbl_page.setText(
"page " + str(self.page_index) + self.tr(' on ') + self.nb_page)
# CREATING ALIASES FOR THE FREQUENTLY CALLED WIDGETS
# User text input
txt_input = self.dockwidget.txt_input
# Owners
cbb_owner = self.dockwidget.cbb_owner
# Inspire keywords
cbb_inspire = self.dockwidget.cbb_inspire
# Formats
cbb_format = self.dockwidget.cbb_format
# Coordinate systems
cbb_srs = self.dockwidget.cbb_srs
# Geographical filter
cbb_geofilter = self.dockwidget.cbb_geofilter
# Operator for the geographical filter
cbb_geo_op = self.dockwidget.cbb_geo_op
# Data type
cbb_type = self.dockwidget.cbb_type
# Sorting order
cbb_ob = self.dockwidget.cbb_ob
# Sorting direction
cbb_od = self.dockwidget.cbb_od
# Quick searches
cbb_quicksearch = self.dockwidget.cbb_quicksearch
# Action : view
cb_view = self.dockwidget.chb_view
# Action : download
cb_dl = self.dockwidget.chb_download
# Action : other
cb_other = self.dockwidget.chb_other
# Action : None
cb_none = self.dockwidget.chb_none
# Results table
tbl_result = self.dockwidget.tbl_result
# clearing the result table
tbl_result.clearContents()
tbl_result.setRowCount(0)
# Clearing the user input comboboxes
cbb_inspire.clear()
cbb_owner.clear()
cbb_format.clear()
cbb_srs.clear()
cbb_geofilter.clear()
cbb_type.clear()
# Filling the quick search combobox (also the one in settings tab)
with open(self.json_path) as data_file:
saved_searches = json.load(data_file)
search_list = saved_searches.keys()
search_list.pop(search_list.index('_default'))
if '_current' in search_list:
search_list.pop(search_list.index('_current'))
cbb_quicksearch.clear()
self.dockwidget.cbb_modify_sr.clear()
icon = QIcon(':/plugins/Isogeo/resources/bolt.svg')
cbb_quicksearch.addItem(icon, self.tr('Quick Search'))
for i in search_list:
cbb_quicksearch.addItem(i, i)
self.dockwidget.cbb_modify_sr.addItem(i, i)
# Initiating the "nothing selected" and "None" items in each combobox
cbb_inspire.addItem(" - ")
icon = QIcon(':/plugins/Isogeo/resources/none.svg')
cbb_inspire.addItem(icon,
self.tr("None"),
"has-no:keyword:inspire-theme")
cbb_owner.addItem(" - ")
cbb_format.addItem(" - ")
cbb_format.addItem(icon, self.tr("None"), "has-no:format")
cbb_srs.addItem(" - ")
cbb_srs.addItem(icon, self.tr("None"), "has-no:coordinate-system")
cbb_geofilter.addItem(" - ")
cbb_type.addItem(self.tr("All types"))
# Initializing the cbb that dont't need to be actualised.
if self.savedSearch == "_default" or self.hardReset is True:
tbl_result.horizontalHeader().setResizeMode(1)
tbl_result.horizontalHeader().setResizeMode(1, 0)
tbl_result.horizontalHeader().setResizeMode(2, 0)
tbl_result.horizontalHeader().resizeSection(1, 80)
tbl_result.horizontalHeader().resizeSection(2, 50)
tbl_result.verticalHeader().setResizeMode(3)
# Geographical operator cbb
dict_operation = OrderedDict([(self.tr(
'Intersects'), "intersects"),
(self.tr('within'), "within"),
(self.tr('contains'), "contains")])
for key in dict_operation.keys():
cbb_geo_op.addItem(key, dict_operation.get(key))
# Order by cbb
dict_ob = OrderedDict([(self.tr("Relevance"), "relevance"),
(self.tr("Alphabetical order"), "title"),
(self.tr("Data modified"), "modified"),
(self.tr("Data created"), "created"),
(self.tr("Metadata modified"), "_modified"),
(self.tr("Metadata created"), "_created")]
)
for key in dict_ob.keys():
cbb_ob.addItem(key, dict_ob.get(key))
# Order direction cbb
dict_od = OrderedDict([(self.tr("Descending"), "desc"),
(self.tr("Ascendant"), "asc")]
)
for key in dict_od.keys():
cbb_od.addItem(key, dict_od.get(key))
# Creating combobox items, with their displayed text, and their value
# Owners
ordered = sorted(tags.get("owner").items(), key=operator.itemgetter(1))
for i in ordered:
cbb_owner.addItem(i[1], i[0])
# INSPIRE keywords
ordered = sorted(tags.get('themeinspire').items(),
key=operator.itemgetter(1))
for i in ordered:
cbb_inspire.addItem(i[1], i[0])
width = cbb_inspire.view().sizeHintForColumn(0) + 10
cbb_inspire.view().setMinimumWidth(width)
# Formats
ordered = sorted(tags.get('formats').items(),
key=operator.itemgetter(1))
for i in ordered:
cbb_format.addItem(i[1], i[0])
# Coordinate system
ordered = sorted(tags.get('srs').items(), key=operator.itemgetter(1))
for i in ordered:
cbb_srs.addItem(i[1], i[0])
# Resource type
ordered = sorted(tags.get('type').items(), key=operator.itemgetter(1))
for i in ordered:
cbb_type.addItem(i[1], i[0])
# Geographical filter
cbb_geofilter.addItem(self.tr("Map canvas"), "mapcanvas")
layers = QgsMapLayerRegistry.instance().mapLayers().values()
polycon = QIcon(':/plugins/Isogeo/resources/polygon.png')
linicon = QIcon(':/plugins/Isogeo/resources/line.png')
pointicon = QIcon(':/plugins/Isogeo/resources/point.png')
for layer in layers:
if layer.type() == 0:
if layer.geometryType() == 2:
cbb_geofilter.addItem(polycon, layer.name(), layer)
elif layer.geometryType() == 1:
cbb_geofilter.addItem(linicon, layer.name(), layer)
elif layer.geometryType() == 0:
cbb_geofilter.addItem(pointicon, layer.name(), layer)
# Putting all the comboboxes selected index to their previous
# location. Necessary as all comboboxes items have been removed and
# put back in place. We do not want each combobox to go back to their
# default selected item
if self.hardReset is False:
if self.savedSearch is False:
# Owners
previous_index = cbb_owner.findData(params.get('owner'))
cbb_owner.setCurrentIndex(previous_index)
# Inspire keywords
previous_index = cbb_inspire.findData(params.get('inspire'))
cbb_inspire.setCurrentIndex(previous_index)
# Data type
previous_index = cbb_type.findData(params.get('datatype'))
cbb_type.setCurrentIndex(previous_index)
# Data format
previous_index = cbb_format.findData(params.get('format'))
cbb_format.setCurrentIndex(previous_index)
# Coordinate system
previous_index = cbb_srs.findData(params.get('srs'))
cbb_srs.setCurrentIndex(previous_index)
# Sorting order
cbb_ob.setCurrentIndex(cbb_ob.findData(params.get('ob')))
# Sorting direction
cbb_od.setCurrentIndex(cbb_od.findData(params.get('od')))
# Quick searches
previous_index = cbb_quicksearch.findData(params.get('favorite'))
cbb_quicksearch.setCurrentIndex(previous_index)
# Operator for geographical filter
previous_index = cbb_geo_op.findData(params.get('operation'))
cbb_geo_op.setCurrentIndex(previous_index)
# Geographical filter
if params.get('geofilter') == "mapcanvas":
previous_index = cbb_geofilter.findData("mapcanvas")
cbb_geofilter.setCurrentIndex(previous_index)
else:
prev_index = cbb_geofilter.findText(params['geofilter'])
cbb_geofilter.setCurrentIndex(prev_index)
# Filling the keywords special combobox (items checkable)
# In the case where it isn't a saved research. So we have to
# check the items that were previously checked
model = QStandardItemModel(5, 1) # 5 rows, 1 col
# Creating the "None" option, always on top.
none_item = QStandardItem(self.tr('None'))
none_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
none_item.setData("has-no:keyword", 32)
if none_item.data(32) in params.get('keys'):
none_item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(1, none_item)
else:
none_item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.insertRow(1, none_item)
# Filling the combobox with all the normal items
i = 2
ordered = sorted(tags.get('keywords').items(),
key=operator.itemgetter(1))
for a in ordered:
item = QStandardItem(a[1])
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(a[0], 32)
# As all items have been destroyed and generated again, we
# have to set the checkstate (checked/unchecked) according
# to what the user had chosen.
if item.data(32) in params.get('keys'):
item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(0, item)
else:
item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.setItem(i, 0, item)
i += 1
# Creating the first item, that is just a banner for
# the combobox.
first_item = QStandardItem(self.tr('---- Keywords ----'))
icon = QIcon(':/plugins/Isogeo/resources/tag.svg')
first_item.setIcon(icon)
first_item.setSelectable(False)
model.insertRow(0, first_item)
model.itemChanged.connect(self.search)
self.dockwidget.cbb_keywords.setModel(model)
# When it is a saved research, we have to look in the json, and
# check the items accordingly (quite close to the previous case)
else:
# Opening the json and getting the keywords
with open(self.json_path) as data_file:
saved_searches = json.load(data_file)
search_params = saved_searches.get(self.savedSearch)
keywords_list = []
for a in search_params.keys():
if a.startswith("keyword"):
keywords_list.append(search_params.get(a))
model = QStandardItemModel(5, 1) # 5 rows, 1 col
# None item, on top of the cbb
none_item = QStandardItem(self.tr('None'))
none_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
none_item.setData("has-no:keyword", 32)
if none_item.data(32) in keywords_list:
none_item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(1, none_item)
else:
none_item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.insertRow(1, none_item)
# Filling with the standard items
i = 2
ordered = sorted(tags.get('keywords').items(),
key=operator.itemgetter(1))
for a in ordered:
item = QStandardItem(a[1])
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(a[0], 32)
# As all items have been destroyed and generated again, we
# have to set the checkstate (checked/unchecked) according
# to what the user had chosen.
if a[0] in keywords_list:
item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(0, item)
else:
item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.setItem(i, 0, item)
i += 1
# Banner item
first_item = QStandardItem(self.tr('---- Keywords ----'))
icon = QIcon(':/plugins/Isogeo/resources/tag.svg')
first_item.setIcon(icon)
first_item.setSelectable(False)
model.insertRow(0, first_item)
model.itemChanged.connect(self.search)
self.dockwidget.cbb_keywords.setModel(model)
# Putting widgets to their previous states according
# to the json content
# Line edit content
txt_input.setText(search_params.get('text'))
# Owners
saved_index = cbb_owner.findData(search_params.get('owner'))
cbb_owner.setCurrentIndex(saved_index)
# Inspire keywords
value = search_params.get('inspire')
saved_index = cbb_inspire.findData(value)
cbb_inspire.setCurrentIndex(saved_index)
# Formats
saved_index = cbb_format.findData(search_params.get('format'))
cbb_format.setCurrentIndex(saved_index)
# Coordinate systems
saved_index = cbb_srs.findData(search_params.get('srs'))
cbb_srs.setCurrentIndex(saved_index)
# Geographical filter
value = search_params.get('geofilter')
saved_index = cbb_geofilter.findData(value)
cbb_geofilter.setCurrentIndex(saved_index)
# Operator for the geographical filter
value = search_params.get('operation')
saved_index = cbb_geo_op.findData(value)
cbb_geo_op.setCurrentIndex(saved_index)
# Data type
saved_index = cbb_type.findData(search_params.get('datatype'))
cbb_type.setCurrentIndex(saved_index)
# Sorting order
saved_index = cbb_ob.findData(search_params.get('ob'))
cbb_ob.setCurrentIndex(saved_index)
# Sorting direction
saved_index = cbb_od.findData(search_params.get('od'))
cbb_od.setCurrentIndex(saved_index)
# Quick searches
if self.savedSearch != "_default":
saved_index = cbb_quicksearch.findData(self.savedSearch)
cbb_quicksearch.setCurrentIndex(saved_index)
# Action : view
if search_params.get('view'):
cb_view.setCheckState(Qt.Checked)
# Action : download
if search_params.get('download'):
cb_dl.setCheckState(Qt.Checked)
# Action : other
if search_params.get('other'):
cb_other.setCheckState(Qt.Checked)
# Action : None
if search_params.get('noaction'):
cb_none.setCheckState(Qt.Checked)
self.savedSearch = False
# In case of a hard reset, we don't have to worry about widgets
# previous state as they are to be reset
else:
model = QStandardItemModel(5, 1) # 5 rows, 1 col
# None item
none_item = QStandardItem(self.tr('None'))
none_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
none_item.setData("has-no:keyword", 32)
if none_item.data(32) in params['keys']:
none_item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(1, none_item)
else:
none_item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.insertRow(1, none_item)
# Standard items
i = 2
ordered = sorted(tags.get('keywords').items(),
key=operator.itemgetter(1))
for a in ordered:
item = QStandardItem(a[1])
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(a[0], 32)
# As all items have been destroyed and generated again, we have
# to set the checkstate (checked/unchecked) according to what
# the user had chosen
item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.setItem(i, 0, item)
i += 1
# Banner item
first_item = QStandardItem(self.tr('---- Keywords ----'))
icon = QIcon(':/plugins/Isogeo/resources/tag.svg')
first_item.setIcon(icon)
first_item.setSelectable(False)
model.insertRow(0, first_item)
model.itemChanged.connect(self.search)
self.dockwidget.cbb_keywords.setModel(model)
# Make th checkboxes unckeckable if needed
# View
if 'action:view' in tags.get('actions'):
cb_view.setEnabled(True)
else:
cb_view.setEnabled(False)
# Download
if 'action:download' in tags.get('actions'):
cb_dl.setEnabled(True)
else:
cb_dl.setEnabled(False)
# Other action
if 'action:other' in tags.get('actions'):
cb_other.setEnabled(True)
else:
cb_other.setEnabled(False)
# Coloring the Show result button
self.dockwidget.btn_show.setStyleSheet(
"QPushButton "
"{background-color: rgb(255, 144, 0); color: white}")
# Show result, if we want them to be shown (button 'show result', 'next
# page' or 'previous page' pressed)
if self.showResult is True:
self.dockwidget.btn_next.setEnabled(True)
self.dockwidget.btn_previous.setEnabled(True)
cbb_ob.setEnabled(True)
cbb_od.setEnabled(True)
self.dockwidget.btn_show.setStyleSheet("")
# self.show_results(result)
self.results_mng.show_results(result,
self.dockwidget.tbl_result,
progress_bar=self.bar)
self.write_search_params('_current', search_kind="Current")
self.store = True
# Re enable all user input fields now the search function is
# finished.
self.switch_widgets_on_and_off()
if self.results_count == 0:
self.dockwidget.btn_show.setEnabled(False)
# hard reset
self.hardReset = False
self.showResult = False
def add_loading_bar(self):
"""Display a "loading" bar."""
self.bar = QProgressBar()
self.bar.setRange(0, 0)
self.bar.setFixedWidth(120)
iface.mainWindow().statusBar().insertPermanentWidget(0, self.bar)
def add_layer(self, layer_info):
"""Add a layer to QGIS map canvas.
This take as an argument the index of the layer. From this index,
search the information needed to add it in the temporary dictionnary
constructed in the show_results function. It then adds it.
"""
logger.info("add_layer method called.")
if layer_info[0] == "index":
combobox = self.dockwidget.tbl_result.cellWidget(layer_info[1], 3)
layer_info = combobox.itemData(combobox.currentIndex())
elif layer_info[0] == "info":
layer_info = layer_info[1]
else:
pass
if type(layer_info) == list:
# If the layer to be added is a vector file
if layer_info[0] == "vector":
path = layer_info[1]
name = os.path.basename(path).split(".")[0]
layer = QgsVectorLayer(path, layer_info[2], 'ogr')
if layer.isValid():
lyr = QgsMapLayerRegistry.instance().addMapLayer(layer)
# fill QGIS metadata from Isogeo
lyr.setTitle(layer_info[2])
lyr.setAbstract(layer_info[3])
lyr.setKeywordList(",".join(layer_info[4]))
try:
QgsMessageLog.logMessage("Data layer added: {}"
.format(name),
"Isogeo")
logger.info("Vector layer added: {}".format(path))
except UnicodeEncodeError:
QgsMessageLog.logMessage(
"Vector layer added:: {}".format(
name.decode("latin1")), "Isogeo")
logger.info("Vector layer added: {}"
.format(name.decode("latin1")))
else:
logger.info("Layer not valid. path = {0}".format(path))
QMessageBox.information(
iface.mainWindow(),
self.tr('Error'),
self.tr('The layer is not valid.'))
# If raster file
elif layer_info[0] == "raster":
path = layer_info[1]
name = os.path.basename(path).split(".")[0]
layer = QgsRasterLayer(path, name)
if layer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(layer)
# fill QGIS metadata from Isogeo
lyr.setTitle(layer_info[2])
lyr.setAbstract(layer_info[3])
lyr.setKeywordList(",".join(layer_info[4]))
logger.info("Raster datasource added: {0}".format(path))
else:
logger.warning("Invalid datasource: {0}".format(path))
QMessageBox.information(
iface.mainWindow(),
self.tr('Error'),
self.tr('The layer is not valid.'))
# If WFS link
elif layer_info[0] == 'WFS':
url = layer_info[2]
name = layer_info[1]
layer = QgsVectorLayer(url, name, 'WFS')
if layer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(layer)
logger.info("WFS service layer added: {0}".format(url))
else:
error_msg = layer.error().message()
name_url = srv_url_bld.new_build_wfs_url(layer_info[3],
layer_info[4],
mode="complete")
if name_url[0] != 0:
layer = QgsVectorLayer(name_url[2], name_url[1], 'WFS')
if layer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(layer)
logger.info("WFS service layer added: {0}".format(url))
else:
error_msg = layer.error().message()
logger.warning("Invalid service: {0}"
.format(url, error_msg.encode("latin1")))
else:
QMessageBox.information(
iface.mainWindow(),
self.tr('Error'),
self.tr("The linked WFS is not valid. QGIS says: {}")
.format(error_msg))
# If WMS link
elif layer_info[0] == 'WMS':
url = layer_info[2]
name = layer_info[1]
layer = QgsRasterLayer(url, name, 'wms', 1)
if layer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(layer)
logger.info("WMS service layer added: {0}".format(url))
else:
error_msg = layer.error().message()
name_url = srv_url_bld.new_build_wms_url(layer_info[3],
layer_info[4],
mode="complete")
if name_url[0] != 0:
layer = QgsRasterLayer(name_url[2], name_url[1], 'wms')
if layer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(layer)
logger.info("WMS service layer added: {0}".format(url))
else:
error_msg = layer.error().message()
logger.warning("Invalid service: {0}"
.format(url, error_msg.encode("latin1")))
else:
QMessageBox.information(
iface.mainWindow(),
self.tr('Error'),
self.tr("The linked WMS is not valid. QGIS says: {}")
.format(error_msg))
# If WMTS link
elif layer_info[0] == 'WMTS':
url = layer_info[2]
name = layer_info[1]
layer = QgsRasterLayer(url, name, 'wms')
if layer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(layer)
logger.info("WMTS service layer added: {0}".format(url))
else:
error_msg = layer.error().message()
logger.warning("Invalid service: {0}"
.format(url, error_msg.encode("latin1")))
QMessageBox.information(
iface.mainWindow(),
self.tr('Error'),
self.tr("The linked WMTS is not valid. QGIS says: {} {}")
.format(error_msg))
else:
pass
# If the data is a PostGIS table
elif type(layer_info) == dict:
logger.info("Data type: PostGIS")
# Give aliases to the data passed as arguement
base_name = layer_info.get("base_name", "")
schema = layer_info.get("schema", "")
table = layer_info.get("table", "")
# Retrieve the database information stored in the PostGISdict
uri = QgsDataSourceURI()
host = self.PostGISdict[base_name]['host']
port = self.PostGISdict[base_name]['port']
user = self.PostGISdict[base_name]['username']
password = self.PostGISdict[base_name]['password']
# set host name, port, database name, username and password
uri.setConnection(host, port, base_name, user, password)
# Get the geometry column name from the database connexion & table
# name.
c = con.PostGisDBConnector(uri)
dico = c.getTables()
for i in dico:
if i[0 == 1] and i[1] == table:
geometry_column = i[8]
# set database schema, table name, geometry column
uri.setDataSource(schema, table, geometry_column)
# Adding the layer to the map canvas
layer = QgsVectorLayer(uri.uri(), table, "postgres")
# layer.setTitle(layer_info.get("title", "notitle"))
# layer.setAbstract(layer_info.get("abstract", ""))
# layer.setKeywordList(",".join(layer_info.get("keywords", ())))
if layer.isValid():
lyr = QgsMapLayerRegistry.instance().addMapLayer(layer)
# fill QGIS metadata from Isogeo
lyr.setTitle(layer_info.get("title", "notitle"))
lyr.setAbstract(layer_info.get("abstract", ""))
lyr.setKeywordList(",".join(layer_info.get("keywords", ())))
logger.info("Data added: {}".format(table))
elif not layer.isValid() and\
custom_tools.last_error[0] == "postgis" and\
"prim" in custom_tools.last_error[1]:
logger.info("PostGIS layer may be a view, "
"so key column is missing. "
"Trying to automatically set one...")
# get layer fields to set as key column
fields = layer.dataProvider().fields()
fields_names = [i.name() for i in fields]
# sort them by name containing id to better perf
fields_names.sort(key=lambda x: ("id" not in x, x))
for field in fields_names:
uri.setKeyColumn(field)
layer = QgsVectorLayer(uri.uri(True), table, "postgres")
if layer.isValid():
lyr = QgsMapLayerRegistry.instance().addMapLayer(layer)
# fill QGIS metadata from Isogeo
lyr.setTitle(layer_info.get("title", "notitle"))
lyr.setAbstract(layer_info.get("abstract", ""))
lyr.setKeywordList(",".join(layer_info.get("keywords", ())))
logger.info("PostGIS view layer added with [{}] as key column"
.format(field))
return 1
else:
continue
else:
logger.info("Layer not valid. table = {0}".format(table))
QMessageBox.information(
iface.mainWindow(),
self.tr("Error"),
self.tr("The PostGIS layer is not valid."
" Reason: {}".format(custom_tools.last_error)))
return 0
return 1
def save_params(self):
"""Save the widgets state/index.
This save the current state/index of each user input so we can put them
back to their previous state/index after they have been updated
(cleared and filled again).
"""
# get the data of the item which index is (get the combobox current
# index)
owner_param = self.dockwidget.cbb_owner.itemData(
self.dockwidget.cbb_owner.currentIndex())
inspire_param = self.dockwidget.cbb_inspire.itemData(
self.dockwidget.cbb_inspire.currentIndex())
format_param = self.dockwidget.cbb_format.itemData(
self.dockwidget.cbb_format.currentIndex())
srs_param = self.dockwidget.cbb_srs.itemData(
self.dockwidget.cbb_srs.currentIndex())
if self.dockwidget.cbb_geofilter.currentIndex() < 2:
geofilter_param = self.dockwidget.cbb_geofilter.itemData(
self.dockwidget.cbb_geofilter.currentIndex())
else:
geofilter_param = self.dockwidget.cbb_geofilter.currentText()
favorite_param = self.dockwidget.cbb_quicksearch.itemData(
self.dockwidget.cbb_quicksearch.currentIndex())
type_param = self.dockwidget.cbb_type.itemData(
self.dockwidget.cbb_type.currentIndex())
operation_param = self.dockwidget.cbb_geo_op.itemData(
self.dockwidget.cbb_geo_op.currentIndex())
order_param = self.dockwidget.cbb_ob.itemData(
self.dockwidget.cbb_ob.currentIndex())
dir_param = self.dockwidget.cbb_od.itemData(
self.dockwidget.cbb_od.currentIndex())
# Getting the text in the search line
text = self.dockwidget.txt_input.text()
# Saving the keywords that are selected : if a keyword state is
# selected, he is added to the list
key_params = []
for i in xrange(self.dockwidget.cbb_keywords.count()):
if self.dockwidget.cbb_keywords.itemData(i, 10) == 2:
key_params.append(self.dockwidget.cbb_keywords.itemData(i, 32))
# Saving the checked checkboxes (useful for the search saving)
if self.dockwidget.chb_view.isChecked():
view_param = True
else:
view_param = False
if self.dockwidget.chb_download.isChecked():
download_param = True
else:
download_param = False
if self.dockwidget.chb_other.isChecked():
other_param = True
else:
other_param = False
if self.dockwidget.chb_none.isChecked():
noaction_param = True
else:
noaction_param = False
params = {}
params['owner'] = owner_param
params['inspire'] = inspire_param
params['format'] = format_param
params['srs'] = srs_param
params['favorite'] = favorite_param
params['keys'] = key_params
params['geofilter'] = geofilter_param
params['view'] = view_param
params['download'] = download_param
params['other'] = other_param
params['noaction'] = noaction_param
params['text'] = text
params['datatype'] = type_param
params['operation'] = operation_param
params['ob'] = order_param
params['od'] = dir_param
# check geographic filter
if params.get('geofilter') == "mapcanvas":
e = iface.mapCanvas().extent()
extent = [e.xMinimum(),
e.yMinimum(),
e.xMaximum(),
e.yMaximum()]
params['extent'] = extent
epsg = int(iface.mapCanvas().mapRenderer(
).destinationCrs().authid().split(':')[1])
params['epsg'] = epsg
params['coord'] = self.get_coords('canvas')
elif params.get('geofilter') in QgsMapLayerRegistry.instance().mapLayers().values():
params['coord'] = self.get_coords(params.get('geofilter'))
else:
pass
# saving params in QSettings
qsettings.setValue("isogeo/settings/georelation", operation_param)
logger.info(params)
return params
def search(self):
"""Build the request url to be sent to Isogeo API.
This builds the url, retrieving the parameters from the widgets. When
the final url is built, it calls send_request_to_isogeo_api
"""
logger.info("Search function called. Building the "
"url that is to be sent to the API")
# Disabling all user inputs during the search function is running
self.switch_widgets_on_and_off(0)
# STORING THE PREVIOUS SEARCH
if self.store is True:
# Open json file
with open(self.json_path) as data_file:
saved_searches = json.load(data_file)
# Store the search
name = self.tr("Last search")
saved_searches[name] = saved_searches.get(
'_current',
"https://v1.api.isogeo.com/resources/search?&_limit=0")
# Refresh the quick searches comboboxes content
search_list = saved_searches.keys()
search_list.pop(search_list.index('_default'))
search_list.pop(search_list.index('_current'))
self.dockwidget.cbb_quicksearch.clear()
icon = QIcon(':/plugins/Isogeo/resources/bolt.png')
self.dockwidget.cbb_quicksearch.addItem(icon, self.tr('Quick Search'))
self.dockwidget.cbb_modify_sr.clear()
for i in search_list:
self.dockwidget.cbb_quicksearch.addItem(i, i)
self.dockwidget.cbb_modify_sr.addItem(i, i)
# Write modifications in the json
with open(self.json_path, 'w') as outfile:
json.dump(saved_searches, outfile,
sort_keys=True, indent=4)
self.store = False
else:
pass
# STORING ALL THE INFORMATIONS NEEDED TO BUILD THE URL
# Widget position
params = self.save_params()
# Info for _offset parameter
self.page_index = 1
params['page'] = self.page_index
# Info for _limit parameter
if self.showResult is True:
params['show'] = True
else:
params['show'] = False
# Info for _lang parameter
params['lang'] = self.lang
# URL BUILDING FUNCTION CALLED.
self.currentUrl = isogeo_api_mng.build_request_url(params)
logger.info(self.currentUrl)
# Sending the request to Isogeo API
if self.requestStatusClear is True:
self.send_request_to_isogeo_api(self.token)
else:
pass
# method end
return
def next_page(self):
"""Add the _offset parameter to the current url to display next page.
Close to the search() function (lot of code in common) but
triggered on the click on the change page button.
"""
logger.info("next_page function called.")
# Testing if the user is asking for a unexisting page (ex : page 6 out
# of 5)
if self.page_index >= custom_tools.results_pages_counter(self.results_count):
return False
else:
# Adding the loading bar
self.add_loading_bar()
# Info about the widget status
params = self.save_params()
# Info for _limit parameter
self.showResult = True
params['show'] = True
self.switch_widgets_on_and_off(0)
# Building up the request
self.page_index += 1
params['page'] = self.page_index
# Info for _lang parameter
params['lang'] = self.lang
# URL BUILDING FUNCTION CALLED.
self.currentUrl = isogeo_api_mng.build_request_url(params)
# Sending the request
if self.requestStatusClear is True:
self.send_request_to_isogeo_api(self.token)
def previous_page(self):
"""Add the _offset parameter to the url to display previous page.
Close to the search() function (lot of code in common) but
triggered on the click on the change page button.
"""
logger.info("previous_page function called.")
# testing if the user is asking for something impossible : page 0
if self.page_index < 2:
return False
else:
# Adding the loading bar
self.add_loading_bar()
# Info about the widget status
params = self.save_params()
# Info for _limit parameter
self.showResult = True
params['show'] = True
self.switch_widgets_on_and_off(0)
# Building up the request
self.page_index -= 1
params['page'] = self.page_index
# Info for _lang parameter
params['lang'] = self.lang
# URL BUILDING FUNCTION CALLED.
self.currentUrl = isogeo_api_mng.build_request_url(params)
# Sending the request
if self.requestStatusClear is True:
self.send_request_to_isogeo_api(self.token)
def write_search_params(self, search_name, search_kind="Default"):
"""Write a new element in the json file when a search is saved."""
# Open the saved_search file as a dict. Each key is a search name,
# each value is a dict containing the parameters for this search name
with open(self.json_path) as data_file:
saved_searches = json.load(data_file)
# If the name already exists, ask for a new one. ================ TO DO
# Write the current parameters in a dict, and store it in the saved
# search dict
params = self.save_params()
params['url'] = self.currentUrl
for i in xrange(len(params.get('keys'))):
params['keyword_{0}'.format(i)] = params.get('keys')[i]
params.pop('keys', None)
saved_searches[search_name] = params
# writing file
with open(self.json_path, 'w') as outfile:
json.dump(saved_searches, outfile,
sort_keys=True, indent=4)
# Log and messages
logger.info("{} search stored: {}. Parameters: {}"
.format(search_kind, search_name, params))
if search_kind != "Current":
msgBar.pushMessage(self.tr("{} successfully saved: {}")
.format(search_kind, search_name),
duration=3)
else:
pass
return
def set_widget_status(self):
"""Set a few variable and send the request to Isogeo API."""
selected_search = self.dockwidget.cbb_quicksearch.currentText()
if selected_search != self.tr('Quick Search'):
logger.info("Set_widget_status function called. "
"User is executing a saved search.")
self.switch_widgets_on_and_off(0)
selected_search = self.dockwidget.cbb_quicksearch.currentText()
with open(self.json_path) as data_file:
saved_searches = json.load(data_file)
if selected_search == "":
self.savedSearch = '_default'
search_params = saved_searches.get('_default')
else:
self.savedSearch = selected_search
search_params = saved_searches[selected_search]
self.currentUrl = search_params.get('url')
if 'epsg' in search_params:
epsg = int(iface.mapCanvas().mapRenderer(
).destinationCrs().authid().split(':')[1])
if epsg == search_params.get('epsg'):
canvas = iface.mapCanvas()
e = search_params.get('extent')
rect = QgsRectangle(e[0], e[1], e[2], e[3])
canvas.setExtent(rect)
canvas.refresh()
else:
canvas = iface.mapCanvas()
canvas.mapRenderer().setProjectionsEnabled(True)
canvas.mapRenderer().setDestinationCrs(
QgsCoordinateReferenceSystem(
search_params.get('epsg'),
QgsCoordinateReferenceSystem.EpsgCrsId))
e = search_params.get('extent')
rect = QgsRectangle(e[0], e[1], e[2], e[3])
canvas.setExtent(rect)
canvas.refresh()
if self.requestStatusClear is True:
self.send_request_to_isogeo_api(self.token)
# ------------ Quicksearches ------------------------------------------
def quicksearch_save(self):
"""Call the write_search() function and refresh the combobox."""
# retrieve quicksearch given name and store it
search_name = self.quicksearch_new_dialog.txt_quicksearch_name.text()
self.write_search_params(search_name, search_kind="Quicksearch")
# load all saved quicksearches and populate drop-down (combobox)
with open(self.json_path, "r") as saved_searches_file:
saved_searches = json.load(saved_searches_file)
search_list = saved_searches.keys()
search_list.pop(search_list.index('_default'))
search_list.pop(search_list.index('_current'))
self.dockwidget.cbb_quicksearch.clear()
icon = QIcon(':/plugins/Isogeo/resources/bolt.svg')
self.dockwidget.cbb_quicksearch.addItem(icon, self.tr('Quick Search'))
self.dockwidget.cbb_modify_sr.clear()
for i in search_list:
self.dockwidget.cbb_quicksearch.addItem(i, i)
self.dockwidget.cbb_modify_sr.addItem(i, i)
# inform user
# msgBar.pushMessage("Isogeo",
# self.tr("New quicksearch saved: {}")\
# .format(search_name),
# level=msgBar.INFO,
# duration=3)
# method ending
return
def quicksearch_rename(self):
"""Modify the json file in order to rename a search."""
old_name = self.dockwidget.cbb_modify_sr.currentText()
with open(self.json_path, "r") as saved_searches_file:
saved_searches = json.load(saved_searches_file)
new_name = self.quicksearch_rename_dialog.txt_quicksearch_rename.text()
saved_searches[new_name] = saved_searches[old_name]
saved_searches.pop(old_name)
search_list = saved_searches.keys()
search_list.pop(search_list.index('_default'))
search_list.pop(search_list.index('_current'))
self.dockwidget.cbb_quicksearch.clear()
icon = QIcon(':/plugins/Isogeo/resources/bolt.svg')
self.dockwidget.cbb_quicksearch.addItem(icon, self.tr('Quick Search'))
self.dockwidget.cbb_modify_sr.clear()
for i in search_list:
self.dockwidget.cbb_quicksearch.addItem(i, i)
self.dockwidget.cbb_modify_sr.addItem(i, i)
# Update JSON file
with open(self.json_path, 'w') as outfile:
json.dump(saved_searches, outfile,
sort_keys=True, indent=4)
# inform user
msgBar.pushMessage("Isogeo",
self.tr("Quicksearch renamed: from {} to {}")
.format(old_name, new_name),
level=msgBar.INFO,
duration=3)
# method ending
return
def quicksearch_remove(self):
"""Modify the json file in order to delete a search."""
to_be_deleted = self.dockwidget.cbb_modify_sr.currentText()
with open(self.json_path, "r") as saved_searches_file:
saved_searches = json.load(saved_searches_file)
saved_searches.pop(to_be_deleted)
search_list = saved_searches.keys()
search_list.pop(search_list.index('_default'))
search_list.pop(search_list.index('_current'))
self.dockwidget.cbb_quicksearch.clear()
icon = QIcon(':/plugins/Isogeo/resources/bolt.svg')
self.dockwidget.cbb_quicksearch.addItem(icon, self.tr('Quick Search'))
self.dockwidget.cbb_modify_sr.clear()
for i in search_list:
self.dockwidget.cbb_quicksearch.addItem(i, i)
self.dockwidget.cbb_modify_sr.addItem(i, i)
# Update JSON file
with open(self.json_path, 'w') as outfile:
json.dump(saved_searches, outfile,
sort_keys=True, indent=4)
# inform user
msgBar.pushMessage("Isogeo",
self.tr("Quicksearch removed: {}")
.format(to_be_deleted),
level=msgBar.INFO,
duration=3)
# method ending
return
# ----------------------------------------------------------------
def get_coords(self, filter):
"""Get the canvas coordinates in the right format and SRS (WGS84)."""
if filter == 'canvas':
e = iface.mapCanvas().extent()
current_epsg = custom_tools.get_map_crs()
else:
index = self.dockwidget.cbb_geofilter.findText(filter)
layer = self.dockwidget.cbb_geofilter.itemData(index)
e = layer.extent()
current_epsg = layer.crs().authid()
# epsg code as integer
current_epsg = int(current_epsg.split(':')[1])
if current_epsg == 4326:
coord = "{0},{1},{2},{3}".format(
e.xMinimum(), e.yMinimum(), e.xMaximum(), e.yMaximum())
return coord
elif type(current_epsg) is int:
current_srs = QgsCoordinateReferenceSystem(
current_epsg, QgsCoordinateReferenceSystem.EpsgCrsId)
wgs = QgsCoordinateReferenceSystem(
4326, QgsCoordinateReferenceSystem.EpsgCrsId)
xform = QgsCoordinateTransform(current_srs, wgs)
minimum = xform.transform(QgsPoint(e.xMinimum(), e.yMinimum()))
maximum = xform.transform(QgsPoint(e.xMaximum(), e.yMaximum()))
coord = "{0},{1},{2},{3}".format(
minimum[0], minimum[1], maximum[0], maximum[1])
return coord
else:
logger.info('Wrong EPSG')
return False
def reinitialize_search(self):
"""Clear all widget, putting them all back to their default value.
Clear all widget and send a request to the API (which ends up updating
the fields : send_request() calls handle_reply(), which calls
update_fields())
"""
logger.info("Reinitialize_search function called.")
self.hardReset = True
self.dockwidget.chb_view.setCheckState(Qt.Unchecked)
self.dockwidget.chb_download.setCheckState(Qt.Unchecked)
self.dockwidget.chb_other.setCheckState(Qt.Unchecked)
self.dockwidget.chb_none.setCheckState(Qt.Unchecked)
self.dockwidget.txt_input.clear()
self.dockwidget.cbb_keywords.clear()
self.dockwidget.cbb_type.clear()
self.dockwidget.cbb_geofilter.clear()
self.dockwidget.cbb_owner.clear()
self.dockwidget.cbb_inspire.clear()
self.dockwidget.cbb_format.clear()
self.dockwidget.cbb_srs.clear()
self.dockwidget.cbb_geo_op.clear()
self.dockwidget.cbb_ob.clear()
self.dockwidget.cbb_od.clear()
self.search()
def search_with_content(self):
"""Launch a search request that will end up in showing the results."""
self.add_loading_bar()
self.showResult = True
self.search()
def switch_widgets_on_and_off(self, mode=1):
"""Disable all the UI widgets when a request is being sent.
Deactivate the widgets while a funcion is running so the user doesn't
clic everywhere ending up in multiple requests being sent at the same
time, making the plugin crash.
"""
if mode:
self.dockwidget.txt_input.setReadOnly(False)
self.dockwidget.cbb_quicksearch.setEnabled(True)
self.dockwidget.grp_filters.setEnabled(True)
self.dockwidget.widget.setEnabled(True)
self.dockwidget.btn_reinit.setEnabled(True)
self.dockwidget.btn_save.setEnabled(True)
self.dockwidget.btn_show.setEnabled(True)
self.dockwidget.tbl_result.setEnabled(True)
else:
self.dockwidget.txt_input.setReadOnly(True)
self.dockwidget.cbb_quicksearch.setEnabled(False)
self.dockwidget.grp_filters.setEnabled(False)
self.dockwidget.widget.setEnabled(False)
self.dockwidget.btn_next.setEnabled(False)
self.dockwidget.btn_previous.setEnabled(False)
self.dockwidget.cbb_ob.setEnabled(False)
self.dockwidget.cbb_od.setEnabled(False)
self.dockwidget.btn_reinit.setEnabled(False)
self.dockwidget.btn_save.setEnabled(False)
self.dockwidget.btn_show.setEnabled(False)
self.dockwidget.tbl_result.setEnabled(False)
def show_popup(self, popup):
"""Open the pop up window that asks a name to save the search."""
if popup == 'ask_name':
self.quicksearch_new_dialog.show()
elif popup == 'new_name':
self.quicksearch_rename_dialog.show()
elif popup == 'credits':
self.credits_dialog.show()
else:
pass
def send_details_request(self, md_id):
"""Send a request for aditionnal info about one data."""
logger.info("Full metatada sheet asked. Building the url.")
self.currentUrl = "https://v1.api.isogeo.com/resources/{}{}"\
.format(md_id,
"?_include=conditions,contacts,"
"coordinate-system,events,"
"feature-attributes,limitations,"
"keywords,specifications")
self.showDetails = True
if self.requestStatusClear is True:
self.send_request_to_isogeo_api(self.token)
else:
pass
def edited_search(self):
"""On the Qline edited signal, decide weither a search has to be launched."""
try:
logger.info("Editing finished signal sent.")
except AttributeError:
pass
if self.dockwidget.txt_input.text() == self.old_text:
try:
logger.info("The lineEdit text hasn't changed."
" So pass without sending a request.")
except AttributeError as e:
logger.error(e)
pass
pass
else:
try:
logger.info("The line Edit text changed."
" Calls the search function.")
except AttributeError as e:
logger.error(e)
pass
if self.dockwidget.txt_input.text() == "Ici c'est Isogeo !":
custom_tools.special_search("isogeo")
return
else:
pass
self.search()
# ------------ SETTINGS - Shares -----------------------------------------
def ask_shares_info(self, index):
"""TODO : Only if not already done before."""
if index == 0:
pass
elif index == 1 and self.requestStatusClear is True:
if self.dockwidget.txt_shares.toPlainText() == "":
self.settingsRequest = True
self.oldUrl = self.currentUrl
self.currentUrl = 'https://v1.api.isogeo.com/shares'
self.send_request_to_isogeo_api(self.token)
else:
pass
else:
pass
QgsMessageLog.logMessage("Shares information retrieved in settings tab.",
"Isogeo")
# method end
return
def write_shares_info(self, content):
"""Write informations about the shares in the Settings pannel."""
self.currentUrl = self.oldUrl
text = u"" # opening html content
# Isogeo application authenticated in the plugin
app = content[0].get("applications")[0]
text += self.tr(u"
This plugin is authenticated as "
u"{} and ")\
.format(app.get("url", "https://github.com/isogeo/isogeo-plugin-qgis/wiki"),
app.get("name", "Isogeo plugin for QGIS"))
# shares feeding the application
if len(content) == 1:
text += self.tr(u" powered by 1 share:
")
else:
text += self.tr(u" powered by {0} shares:
")\
.format(len(content))
# shares details
for share in sorted(content):
# share variables
creator_name = share.get("_creator").get("contact").get("name")
creator_email = share.get("_creator").get("contact").get("email")
creator_id = share.get("_creator").get("_tag")[6:]
share_url = "https://app.isogeo.com/groups/{}/admin/shares/{}"\
.format(creator_id, share.get("_id"))
# formatting text
text += u"
"\
.format(share_url,
share.get("name"))
text += self.tr(u"
Updated: {}
")\
.format(custom_tools.handle_date(share.get("_modified")))
text += self.tr(u"
Contact: {} - {}
")\
.format(creator_name,
creator_email)
text += u""
text += u""
self.dockwidget.txt_shares.setText(text)
# method ending
return
# --------------------------------------------------------------------------
# This function is launched when the plugin is activated.
def run(self):
"""Run method that loads and starts the plugin."""
if not self.pluginIsActive:
self.pluginIsActive = True
# dockwidget may not exist if:
# first run of plugin
# removed on close (see self.onClosePlugin method)
if self.dockwidget is None:
# Create the dockwidget (after translation) and keep reference
self.dockwidget = IsogeoDockWidget()
logger.info("Plugin load time: {}"
.format(plugin_times.get("isogeo_search_engine",
"NR")))
# connect to provide cleanup on closing of dockwidget
self.dockwidget.closingPlugin.connect(self.onClosePlugin)
# show the dockwidget
# TODO: fix to allow choice of dock location
self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
self.dockwidget.show()
# Fixing a qgis.core bug that shows a warning banner "connexion time
# out" whenever a request is sent (even successfully) See :
# http://gis.stackexchange.com/questions/136369/download-file-from-network-using-pyqgis-2-x#comment299999_136427
# msgBar.widgetAdded.connect(msgBar.clearWidgets)
""" --- CONNECTING FUNCTIONS --- """
# Write in the config file when the user accept the authentification
# window
self.auth_prompt_form.accepted.connect(self.write_ids_and_test)
# Connecting the comboboxes to the search function
self.dockwidget.cbb_owner.activated.connect(self.search)
self.dockwidget.cbb_inspire.activated.connect(self.search)
self.dockwidget.cbb_format.activated.connect(self.search)
self.dockwidget.cbb_srs.activated.connect(self.search)
self.dockwidget.cbb_geofilter.activated.connect(self.search)
self.dockwidget.cbb_type.activated.connect(self.search)
# Connecting the text input to the search function
self.dockwidget.txt_input.editingFinished.connect(self.edited_search)
# Connecting the checkboxes to the search function
self.dockwidget.chb_view.clicked.connect(self.search)
self.dockwidget.chb_download.clicked.connect(self.search)
self.dockwidget.chb_other.clicked.connect(self.search)
self.dockwidget.chb_none.clicked.connect(self.search)
# Connecting the radio buttons
# Connecting the previous and next page buttons to their functions
self.dockwidget.btn_next.pressed.connect(self.next_page)
self.dockwidget.btn_previous.pressed.connect(self.previous_page)
# Connecting the bug tracker button to its function
self.dockwidget.btn_report.pressed.connect(
partial(custom_tools.open_webpage,
link=self.tr(u'https://github.com/isogeo/isogeo-plugin-qgis/issues')
))
self.dockwidget.btn_help.pressed.connect(
partial(custom_tools.open_webpage,
link="https://github.com/isogeo/isogeo-plugin-qgis/wiki"
))
# view credits
self.dockwidget.btn_credits.pressed.connect(
partial(self.show_popup, popup='credits'))
# Connecting the "reinitialize search button" to a search without
# filters
self.dockwidget.btn_reinit.pressed.connect(self.reinitialize_search)
# Change user
self.dockwidget.btn_change_user.pressed.connect(
partial(custom_tools.display_auth_form,
ui_auth_form=self.auth_prompt_form))
# show results
self.dockwidget.btn_show.pressed.connect(self.search_with_content)
self.dockwidget.cbb_ob.activated.connect(self.search_with_content)
self.dockwidget.cbb_od.activated.connect(self.search_with_content)
# Button 'save favorite' connected to the opening of the pop up that
# asks for a name
self.dockwidget.btn_save.pressed.connect(
partial(self.show_popup, popup='ask_name'))
# Connect the accepted signal of the popup to the function that write
# the search name and parameter to the file, and update the combobox
self.quicksearch_new_dialog.accepted.connect(self.quicksearch_save)
# Button 'rename search' connected to the opening of the pop up that
# asks for a new name
self.dockwidget.btn_rename_sr.pressed.connect(
partial(self.show_popup, popup='new_name'))
# Connect the accepted signal of the popup to the function that rename
# a search.
self.quicksearch_rename_dialog.accepted.connect(self.quicksearch_rename)
# Connect the delete button to the delete function
self.dockwidget.btn_delete_sr.pressed.connect(self.quicksearch_remove)
# Connect the activation of the "saved search" combobox with the
# set_widget_status function
self.dockwidget.cbb_quicksearch.activated.connect(
self.set_widget_status)
# G default
self.dockwidget.btn_default.pressed.connect(
partial(self.write_search_params, '_default', "Default"))
self.auth_prompt_form.btn_account_new.pressed.connect(partial(
custom_tools.mail_to_isogeo, lang=self.lang))
self.dockwidget.tabWidget.currentChanged.connect(self.ask_shares_info)
self.dockwidget.txt_shares.setOpenLinks(False)
self.dockwidget.txt_shares.anchorClicked.connect(custom_tools.open_webpage)
# catch QGIS log messages
QgsMessageLog.instance().messageReceived.connect(custom_tools.error_catcher)
""" --- Actions when the plugin is launched --- """
custom_tools.test_proxy_configuration()
self.user_authentication()
self.dockwidget.txt_input.setFocus()
PK PI
}] ( isogeo_search_engine/modules/__init__.py# -*- coding: utf-8 -*-
PK JZ'6 6 # isogeo_search_engine/modules/api.py# -*- coding: utf-8 -*-
# Standard library
import base64
from functools import partial
import json
import logging
from urllib import urlencode
# PyQT
from PyQt4.QtCore import QByteArray, QFile, QIODevice, QSettings, QUrl
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest
# PyQGIS
from qgis.core import QgsMessageLog
# ############################################################################
# ########## Globals ###############
# ##################################
qsettings = QSettings()
logger = logging.getLogger("IsogeoQgisPlugin")
# ############################################################################
# ########## Classes ###############
# ##################################
class IsogeoApiManager(object):
"""Basic class that holds utilitary methods for the plugin."""
def __init__(self):
"""Construct."""
self.api_id = qsettings.value("isogeo-plugin/user-auth/id", 0)
self.api_secret = qsettings.value("isogeo-plugin/user-auth/secret", 0)
self.currentUrl = ""
self.request_status_clear = 1
# API COMMUNICATION ------------------------------------------------------
def ask_for_token(self, c_id, c_secret):
"""Ask a token from Isogeo API authentification page.
This send a POST request to Isogeo API with the user id and secret in
its header. The API should return an access token
"""
# check if API access are already set
if self.api_id != 0 and self.api_secret != 0:
logger.info("User_authentication function is trying "
"to get a token from the id/secret")
self.request_status_clear = 1
pass
else:
logger.error("No id/secret.")
return 0
# API token request
headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret)
data = urlencode({"grant_type": "client_credentials"})
databyte = QByteArray()
databyte.append(data)
url = QUrl('https://id.api.isogeo.com/oauth/token')
request = QNetworkRequest(url)
request.setRawHeader("Authorization", headervalue)
if self.request_status_clear:
self.request_status_clear = 0
token_reply = self.manager.post(request, databyte)
token_reply.finished.connect(
partial(self.handle_token, answer=token_reply))
QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
else:
pass
def handle_token(self, answer):
"""Handle the API answer when asked for a token.
This handles the API answer. If it has sent an access token, it calls
the initialization function. If not, it raises an error, and ask
for new IDs
"""
logger.info("Asked a token and got a reply from the API.")
bytarray = answer.readAll()
content = str(bytarray)
parsed_content = json.loads(content)
if 'access_token' in parsed_content:
logger.info("The API reply is an access token : "
"the request worked as expected.")
# TO DO : Appeler la fonction d'initialisation
self.token = "Bearer " + parsed_content['access_token']
if self.savedSearch == "first":
self.requestStatusClear = True
self.set_widget_status()
else:
self.requestStatusClear = True
self.send_request_to_isogeo_api(self.token)
# TO DO : Distinguer plusieurs cas d'erreur
elif 'error' in parsed_content:
logger.error("The API reply is an error. Id and secret must be "
"invalid. Asking for them again.")
QMessageBox.information(
iface.mainWindow(), self.tr("Error"), parsed_content['error'])
self.requestStatusClear = True
self.auth_prompt_form.show()
else:
self.requestStatusClear = True
logger.error("The API reply has an unexpected form : "
"{0}".format(parsed_content))
QMessageBox.information(
iface.mainWindow(), self.tr("Error"), self.tr("Unknown error"))
# def handle_api_reply(self, answer):
# """Handle the different possible Isogeo API answer.
# This is called when the answer from the API is finished. If it's
# content, it calls update_fields(). If it isn't, it means the token has
# expired, and it calls ask_for_token()
# """
# logger.info("Request sent to API and reply received.")
# bytarray = answer.readAll()
# content = str(bytarray)
# if answer.error() == 0 and content != "":
# logger.info("Reply is a result json.")
# if self.showDetails is False and self.settingsRequest is False:
# self.loopCount = 0
# parsed_content = json.loads(content)
# self.requestStatusClear = True
# self.update_fields(parsed_content)
# elif self.showDetails is True:
# self.showDetails = False
# self.loopCount = 0
# parsed_content = json.loads(content)
# self.requestStatusClear = True
# self.show_complete_md(parsed_content)
# elif self.settingsRequest is True:
# self.settingsRequest = False
# self.loopCount = 0
# parsed_content = json.loads(content)
# self.requestStatusClear = True
# self.write_shares_info(parsed_content)
# elif answer.error() == 204:
# logger.info("Token expired. Renewing it.")
# self.loopCount = 0
# self.requestStatusClear = True
# self.ask_for_token(self.user_id, self.user_secret,
# self.requestStatusClear)
# elif content == "":
# logger.info("Empty reply. Weither no catalog is shared with the "
# "plugin, or there is a problem (2 requests sent "
# "together)")
# if self.loopCount < 3:
# self.loopCount += 1
# answer.abort()
# del answer
# self.requestStatusClear = True
# self.ask_for_token(self.user_id, self.user_secret,
# self.requestStatusClear)
# else:
# self.requestStatusClear = True
# msgBar.pushMessage(
# self.tr("The script is looping. Make sure you shared a "
# "catalog with the plugin. If so, please report "
# "this on the bug tracker."))
# else:
# self.requestStatusClear = True
# QMessageBox.information(iface.mainWindow(),
# self.tr("Error"),
# self.tr("You are facing an unknown error. "
# "Code: ") +
# str(answer.error()) +
# "\nPlease report tis on the bug tracker.")
# # method end
# return
def send_request_to_isogeo_api(self, token, limit=10):
"""Send a content url to the Isogeo API.
This takes the currentUrl variable and send a request to this url,
using the token variable.
"""
myurl = QUrl(self.currentUrl)
request = QNetworkRequest(myurl)
request.setRawHeader("Authorization", token)
if self.requestStatusClear is True:
self.requestStatusClear = False
api_reply = self.manager.get(request)
api_reply.finished.connect(
partial(self.handle_api_reply, answer=api_reply))
else:
pass
# REQUEST and RESULTS ----------------------------------------------------
def build_request_url(self, params):
"""Build the request url according to the widgets."""
# Base url for a request to Isogeo API
url = 'https://v1.api.isogeo.com/resources/search?'
# Build the url according to the params
if params.get("text") != "":
filters = params.get("text") + " "
else:
filters = ""
# Owner
if params.get('owner') is not None:
filters += params.get('owner') + " "
# SRS
if params.get('srs') is not None:
filters += params.get('srs') + " "
# INSPIRE keywords
if params.get('inspire') is not None:
filters += params.get('inspire') + " "
# Format
if params.get('format') is not None:
filters += params.get('format') + " "
# Data type
if params.get('datatype') is not None:
filters += params.get('datatype') + " "
# Action : view
if params.get("view"):
filters += "action:view "
# Action : download
if params.get("download"):
filters += "action:download "
# Action : Other
if params.get("other"):
filters += "action:other "
# No actions
if params.get("noaction"):
filters += "has-no:action "
# Keywords
for keyword in params.get("keys"):
filters += keyword + " "
# Formating the filters
if filters != "":
filters = "q=" + filters[:-1]
# Geographical filter
if params.get("geofilter") is not None:
if params.get("coord") is not False:
filters += "&box={0}&rel={1}".format(params.get("coord"),
params.get("operation"))
else:
pass
else:
pass
# Sorting order and direction
if params.get("show"):
filters += "&ob={0}&od={1}".format(params.get("ob"),
params.get("od"))
filters += "&_include=links,serviceLayers,layers"
limit = 10
else:
limit = 0
# Limit and offset
offset = (params.get("page") - 1) * 10
filters += "&_limit={0}&_offset={1}".format(limit, offset)
# Language
filters += "&_lang={0}".format(params.get("lang"))
# BUILDING FINAL URL
url += filters
# method ending
return url
def get_tags(self, answer):
"""Return a tag dictionnary from the API answer.
This parse the tags contained in API_answer[tags] and class them so
they are more easy to handle in other function such as
update_fields()
"""
# Initiating the dicts
tags = answer.get('tags')
resources_types = {}
owners = {}
keywords = {}
themeinspire = {}
formats = {}
srs = {}
actions = {}
conformity = 0
# loops that sort each tag in the corresponding dict, keeping the
# same "key : value" structure.
for tag in tags.keys():
# owners
if tag.startswith('owner'):
owners[tag] = tags.get(tag)
# custom keywords
elif tag.startswith('keyword:isogeo'):
keywords[tag] = tags.get(tag)
# INSPIRE themes
elif tag.startswith('keyword:inspire-theme'):
themeinspire[tag] = tags.get(tag)
# formats
elif tag.startswith('format'):
formats[tag] = tags.get(tag)
# coordinate systems
elif tag.startswith('coordinate-system'):
srs[tag] = tags.get(tag)
# available actions (the last 2 are a bit specific as the value
# field is empty and have to be filled manually)
elif tag.startswith('action'):
if tag.startswith('action:view'):
actions[tag] = u'View'
elif tag.startswith('action:download'):
actions[tag] = u'Download'
elif tag.startswith('action:other'):
actions[tag] = u'Other action'
# Test : to be removed eventually
else:
actions[tag] = u'fonction get_tag à revoir'
self.dockwidget.txt_input.setText(tag)
# resources type
elif tag.startswith('type'):
if tag.startswith('type:vector'):
resources_types[tag] = u'Vecteur'
elif tag.startswith('type:raster'):
resources_types[tag] = u'Raster'
elif tag.startswith('type:resource'):
resources_types[tag] = u'Ressource'
elif tag.startswith('type:service'):
resources_types[tag] = u'Service géographique'
elif tag.startswith('conformity'):
conformity = 1
# Creating the final object the function will return : a dictionary
# of dictionaries
new_tags = {}
new_tags['type'] = resources_types
new_tags['owner'] = owners
new_tags['keywords'] = keywords
new_tags['themeinspire'] = themeinspire
new_tags['formats'] = formats
new_tags['srs'] = srs
new_tags['actions'] = actions
new_tags['inspire_conformity'] = conformity
# log
logger.info("Tags retrieved")
# method ending
return new_tags
PK J7]kc kc 0 isogeo_search_engine/modules/metadata_display.py# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function, unicode_literals)
# Standard library
import logging
from datetime import datetime
# PyQGIS
from qgis.core import (QgsMapLayerRegistry, QgsMessageLog,
QgsVectorLayer, QgsPoint, QgsRectangle, QgsFeature,
QgsGeometry, QgsRasterLayer)
from qgis.gui import QgsMapCanvasLayer
# PyQT
from PyQt4.QtCore import QSettings, Qt
from PyQt4.QtGui import QTableWidgetItem
# Custom modules
from .api import IsogeoApiManager
from .tools import Tools
from .translator import IsogeoTranslator
from .url_builder import UrlBuilder
# ############################################################################
# ########## Globals ###############
# ##################################
custom_tools = Tools()
isogeo_api_mng = IsogeoApiManager()
logger = logging.getLogger("IsogeoQgisPlugin")
qsettings = QSettings()
srv_url_bld = UrlBuilder()
# ############################################################################
# ########## Classes ###############
# ##################################
class MetadataDisplayer(object):
"""Basic class that holds utilitary methods for the plugin."""
url_edition = "https://app.isogeo.com"
def __init__(self, ui_md_details):
"""Class constructor."""
self.complete_md = ui_md_details
self.complete_md.stackedWidget.setCurrentIndex(0)
# some basic settings
self.complete_md.wid_bbox.setCanvasColor(Qt.white)
self.complete_md.wid_bbox.enableAntiAliasing(True)
world_wmts_url = "contextualWMSLegend=0&crs=EPSG:4326&dpiMode=7&"\
"featureCount=10&format=image/jpeg&layers=opengeo:countries&"\
"styles=&tileMatrixSet=EPSG:4326&"\
"url=http://suite.opengeo.org/geoserver/gwc/service/wmts?request%3DGetCapabilities"
self.world_lyr = QgsRasterLayer(world_wmts_url, "Countries", 'wms')
self.complete_md.btn_md_edit.pressed.connect(lambda: custom_tools.open_webpage(link=self.url_edition))
def show_complete_md(self, md, lang="EN"):
"""Open the pop up window that shows the metadata sheet details."""
logger.info("Displaying the whole metadata sheet.")
tags = isogeo_api_mng.get_tags(md)
isogeo_tr = IsogeoTranslator(qsettings.value('locale/userLocale')[0:2])
# clean map canvas
vec_lyr = [i for i in self.complete_md.wid_bbox.layers() if i.type() == 0]
QgsMapLayerRegistry.instance().removeMapLayers(vec_lyr)
self.complete_md.wid_bbox.refresh()
# -- GENERAL ---------------------------------------------------------
title = md.get("title", "NR")
self.complete_md.lbl_title.setText(md.get("title", "NR"))
self.complete_md.val_owner.setText(md.get("_creator")
.get("contact")
.get("name", "NR"))
# Keywords
kwords = tags.get("keywords", {"none": "NR"})
self.complete_md.val_keywords.setText(" ; ".join(kwords.values()))
# INSPIRE themes and conformity
themes = tags.get("themeinspire", {"none": "NR"})
self.complete_md.val_inspire_themes.setText(" ; ".join(themes.values()))
if tags.get("inspire_conformity"):
self.complete_md.ico_inspire_conformity.setEnabled(1)
self.complete_md.ico_inspire_conformity.setToolTip(
isogeo_tr.tr("quality",
"isConform")\
+ " INSPIRE")
else:
self.complete_md.ico_inspire_conformity.setDisabled(1)
self.complete_md.ico_inspire_conformity.setToolTip(
isogeo_tr.tr("quality",
"isNotConform")\
+ " INSPIRE")
# Abstract
self.complete_md.val_abstract.setText(md.get("abstract", "NR"))
# -- FEATURE ATTRIBUTES ----------------------------------------------
if md.get("type") == "vectorDataset":
# display
menu_list = self.complete_md.li_menu
item = menu_list.item(1)
item.setHidden(0)
# fillfull
tbl_attr = self.complete_md.tbl_attributes
fields = md.get("feature-attributes", dict())
tbl_attr.setRowCount(len(fields))
idx = 0
for i in fields:
tbl_attr.setItem(idx, 0, QTableWidgetItem(i.get("name", "NR")))
tbl_attr.setItem(idx, 1, QTableWidgetItem(i.get("alias", "")))
tbl_attr.setItem(idx, 2, QTableWidgetItem(i.get("dataType", "")))
tbl_attr.setItem(idx, 3, QTableWidgetItem(i.get("description", "")))
idx += 1
# adapt size
tbl_attr.horizontalHeader().setStretchLastSection(True)
tbl_attr.verticalHeader().setResizeMode(3)
else:
menu_list = self.complete_md.li_menu
item = menu_list.item(1)
item.setHidden(1)
pass
# -- CONTACTS --------------------------------------------------------
contacts = md.get("contacts", dict())
contacts_pt_cct = ["{1} ({2})"
" {3}"
" {4}"
" {5} {6}"
" {7} {8}"
" {8}"
" {9}"
.format(isogeo_tr.tr("roles", ctact.get("role")),
ctact.get("contact").get("name", "NR"),
ctact.get("contact").get("organization", "NR"),
ctact.get("contact").get("email", "NR"),
ctact.get("contact").get("phone", "NR"),
ctact.get("contact").get("addressLine1", ""),
ctact.get("contact").get("addressLine2", ""),
ctact.get("contact").get("zipCode", ""),
ctact.get("contact").get("city", ""),
ctact.get("contact").get("country", ""))\
for ctact in sorted(contacts) if ctact.get("role", "NR") == "pointOfContact"]
contacts_other_cct = ["{0} - {1} ({2})"
" {3}"
" {4}"
" {5} {6}"
" {7} {8}"
" {9}"
.format(isogeo_tr.tr("roles", ctact.get("role")),
ctact.get("contact").get("name", "NR"),
ctact.get("contact").get("organization", "NR"),
ctact.get("contact").get("email", "NR"),
ctact.get("contact").get("phone", ""),
ctact.get("contact").get("addressLine1", ""),
ctact.get("contact").get("addressLine2", ""),
ctact.get("contact").get("zipCode", ""),
ctact.get("contact").get("city", ""),
ctact.get("contact").get("country", ""),)
for ctact in sorted(contacts) if ctact.get("role") != "pointOfContact"]
# write
self.complete_md.val_ct_pointof.setText(" ".join(contacts_pt_cct))
self.complete_md.val_ct_other.setText(" ".join(contacts_other_cct))
# -- HISTORY ---------------------------------------------------------
# Data creation and last update dates
self.complete_md.val_data_crea.setText(custom_tools.handle_date(
md.get("_created", "NR")))
self.complete_md.val_data_update.setText(custom_tools.handle_date(
md.get("_modified", "NR")))
# Update frequency information
if md.get("updateFrequency", None):
freq = md.get("updateFrequency")
frequency_info = "{}{} {}"\
.format(isogeo_tr.tr(None, "frequencyUpdateHelp"),
''.join(i for i in freq if i.isdigit()),
isogeo_tr.tr("frequencyShortTypes",
freq[-1]))
self.complete_md.val_frequency.setText(frequency_info)
else:
self.complete_md.val_frequency.setText("NR")
# Validity
self.complete_md.val_valid_start.setText(custom_tools.handle_date(
md.get("validFrom", "NR")))
self.complete_md.val_valid_end.setText(custom_tools.handle_date(
md.get("validTo", "NR")))
self.complete_md.val_valid_comment.setText(md.get("validityComment", "NR"))
# Collect information
self.complete_md.val_method.setText(md.get("collectionMethod", "NR"))
self.complete_md.val_context.setText(md.get("collectionContext", "NR"))
# last modifications
events = md.get("events", dict())
tbl_events = self.complete_md.tbl_events
tbl_events.setRowCount(len(events))
idx = 0
for e in events:
if e.get("kind") == "update":
tbl_events.setItem(idx, 0, QTableWidgetItem(custom_tools.handle_date(e.get("date", "NR"))))
tbl_events.setItem(idx, 1, QTableWidgetItem(e.get("description", "")))
idx += 1
else:
pass
# adapt size
tbl_events.horizontalHeader().setStretchLastSection(True)
tbl_events.verticalHeader().setResizeMode(3)
# -- TECHNICAL -------------------------------------------------------
# SRS
coord_sys = md.get("coordinate-system", {"None": "NR"})
self.complete_md.val_srs.setText("{} (EPSG:{})"
.format(coord_sys.get("name", "NR"),
coord_sys.get("code", "NR")))
# Set the data format
if tags.get('formats') != {}:
self.complete_md.val_format.setText(
tags.get('formats').values()[0])
else:
self.complete_md.val_format.setText('NR')
# feature info
self.complete_md.val_feat_count.setText(str(md.get("features", "/")))
self.complete_md.val_geometry.setText(md.get("geometry", ""))
self.complete_md.val_resolution.setText(str(md.get("distance", "")) + " m")
self.complete_md.val_scale.setText("1:" + str(md.get("scale", "")))
# Quality
self.complete_md.val_topology.setText(md.get("topologicalConsistency", ""))
# Specifications
specs_in = md.get("specifications", dict())
specs_out = []
for s_in in specs_in:
# translate specification conformity
if s_in.get("conformant"):
s_conformity = isogeo_tr.tr("quality", "isConform")
else:
s_conformity = isogeo_tr.tr("quality", "isNotConform")
# make data human readable
s_date = datetime.strptime(s_in.get("specification").get("published"),
"%Y-%m-%dT%H:%M:%S")
s_date = s_date.strftime("%Y-%m-%d")
# prepare text
spec_text = "{0} ({2}): {3}"\
.format(s_in.get("specification").get("name", "NR"),
s_in.get("specification").get("link", ""),
s_date,
s_conformity)
# store into the final list
specs_out.append(spec_text)
# write
self.complete_md.val_specifications.setText(" ".join(specs_out))
# Geography
if "envelope" in md:
# display
self.complete_md.wid_bbox.setDisabled(0)
# get convex hull coordinates and create the polygon
md_lyr = self.envelope2layer(md.get("envelope"))
# add layers
QgsMapLayerRegistry.instance().addMapLayers([md_lyr,
self.world_lyr],
0)
map_canvas_layer_list = [QgsMapCanvasLayer(md_lyr),
QgsMapCanvasLayer(self.world_lyr)]
self.complete_md.wid_bbox.setLayerSet(map_canvas_layer_list)
self.complete_md.wid_bbox.setExtent(md_lyr.extent())
else:
self.complete_md.wid_bbox.setExtent(self.world_lyr.extent())
self.complete_md.grp_bbox.setDisabled(1)
# -- CGUs ------------------------------------------------------------
# Licences
cgus_in = md.get("conditions", dict())
cgus_out = []
for c_in in cgus_in:
if "license" in c_in:
cgu_text = "{0}"\
" {2}"\
" {3}".format(c_in.get("license").get("name", "NR"),
c_in.get("license").get("link", ""),
c_in.get("description", ""),
c_in.get("license").get("content", ""))
else:
cgu_text = "{0}"\
" {1}".format(isogeo_tr.tr("conditions", "noLicense"),
c_in.get("description", ""))
# store into the final list
cgus_out.append(cgu_text)
# write
self.complete_md.val_licenses.setText(" ".join(cgus_out))
# Limitations
lims_in = md.get("limitations", dict())
lims_out = []
for l_in in lims_in:
lim_text = "{0}"\
" {1}".format(isogeo_tr.tr("limitations", l_in.get("type")),
l_in.get("description", ""))
# legal type
if l_in.get("type") == "legal":
lim_text += " " + isogeo_tr.tr("restrictions", l_in.get("restriction"))
else:
pass
# INSPIRE precision
if "directive" in l_in:
lim_text += " INSPIRE "\
"
{}
{}
"\
.format(l_in.get("directive").get("name"),
l_in.get("directive").get("description"))
else:
pass
# store into the final list
lims_out.append(lim_text)
# write
self.complete_md.val_limitations.setText(" ".join(lims_out))
# -- ADVANCED TAB ---------------------------------------------------
# Workgroup owner
wg_id = md.get("_creator").get("_id")
wg_contact = md.get("_creator").get("contact")
self.complete_md.val_owner_name.setText(wg_contact.get("name", ""))
self.complete_md.val_owner_email.setText(wg_contact.get("email", ""))
self.complete_md.val_owner_phone.setText(wg_contact.get("phone", ""))
self.complete_md.val_owner_address.setText("{} {}"
.format(wg_contact.get("addressLine1", "NR"),
wg_contact.get("addressLine2", "")))
self.complete_md.val_owner_city.setText(wg_contact.get("zipCode", ""))
self.complete_md.val_owner_country.setText(wg_contact.get("countryCode", ""))
# Metadata
self.complete_md.val_md_lang.setText(md.get("language", "NR"))
self.complete_md.val_md_date_crea.setText(custom_tools.handle_date(
md.get("_modified")[:19]))
self.complete_md.val_md_date_update.setText(custom_tools.handle_date(
md.get("_created")[:19]))
# -- EDIT LINK -------------------------------------------------------
self.url_edition = "https://app.isogeo.com/groups/{}/resources/{}"\
.format(wg_id, md.get("_id"))
# only if user declared himself as Isogeo editor in authentication form
self.complete_md.btn_md_edit.setEnabled(qsettings
.value("isogeo/user/editor", 1))
# -- ADD OPTIONS ------------------------------------------------------
self.complete_md.btn_addtomap.setHidden(1)
self.complete_md.btn_xml_dl.setHidden(1)
# -- DISPLAY ---------------------------------------------------------
self.fields_displayer(md.get("type"), md.get("series"))
# Finally open the damned window
self.complete_md.show()
try:
QgsMessageLog.logMessage("Detailed metadata displayed: {}"
.format(title),
"Isogeo")
except UnicodeEncodeError:
QgsMessageLog.logMessage("Detailed metadata displayed: {}"
.format(title.encode("latin1")),
"Isogeo")
def envelope2layer(self, envelope):
"""Transform metadata envelope into a QGIS layer."""
# layer
md_lyr = QgsVectorLayer("Polygon?crs=epsg:4326",
"Metadata envelope",
"memory")
md_lyr.setLayerTransparency(75)
if envelope.get("type") == "Polygon":
# parse coordinates
coords = envelope.get("coordinates")[0]
poly_pts = [QgsPoint(round(i[0], 3),
round(i[1], 3))
for i in coords]
# add geometry to layer
poly = QgsFeature()
poly.setGeometry(QgsGeometry.fromPolygon([poly_pts]))
md_lyr.dataProvider().addFeatures([poly])
md_lyr.updateExtents()
elif envelope.get("type") == "MultiPolygon":
coords = envelope.get("bbox")
bbox = QgsRectangle(round(coords[0], 3),
round(coords[1], 3),
round(coords[2], 3),
round(coords[3], 3),)
poly = QgsFeature()
poly.setGeometry(QgsGeometry.fromWkt(bbox.asWktPolygon()))
md_lyr.dataProvider().addFeatures([poly])
md_lyr.updateExtents()
elif envelope.get("type") == "Point":
return md_lyr
else:
pass
# method ending
return md_lyr
def fields_displayer(self, md_type="vectorDataset", series=0):
"""Adapt display according to metadata type."""
menu_list = self.complete_md.li_menu
if md_type == "vectorDataset":
# general
self.complete_md.val_inspire_themes.setHidden(0)
self.complete_md.ico_inspire_themes.setHidden(0)
self.complete_md.ico_inspire_conformity.setHidden(0)
self.complete_md.val_feat_count.setHidden(0)
self.complete_md.val_geometry.setHidden(0)
# history
self.complete_md.lbl_frequency.setHidden(0)
self.complete_md.ico_frequency.setHidden(0)
self.complete_md.val_frequency.setHidden(0)
self.complete_md.lbl_valid_start.setHidden(0)
self.complete_md.ico_valid_start.setHidden(0)
self.complete_md.val_valid_start.setHidden(0)
self.complete_md.lbl_valid_end.setHidden(0)
self.complete_md.ico_valid_end.setHidden(0)
self.complete_md.val_valid_end.setHidden(0)
self.complete_md.lbl_valid_comment.setHidden(0)
self.complete_md.ico_valid_comment.setHidden(0)
self.complete_md.val_valid_comment.setHidden(0)
self.complete_md.grp_collect_context.setHidden(0)
self.complete_md.grp_collect_method.setHidden(0)
# geography
self.complete_md.grp_technic.setHidden(0)
self.complete_md.ico_feat_count.setHidden(0)
self.complete_md.lbl_feat_count.setHidden(0)
self.complete_md.val_feat_count.setHidden(0)
self.complete_md.ico_geometry.setHidden(0)
self.complete_md.lbl_geometry.setHidden(0)
self.complete_md.val_geometry.setHidden(0)
# menus
menu_list.item(1).setHidden(0) # attributes
menu_list.item(4).setHidden(0) # geography and technical
return
elif md_type == "rasterDataset" and not series:
# geography
self.complete_md.val_feat_count.setHidden(1)
self.complete_md.val_geometry.setHidden(1)
# geography
self.complete_md.grp_technic.setHidden(0)
# menus
menu_list.item(1).setHidden(1) # attributes
menu_list.item(4).setHidden(0) # geography and technical
return
elif md_type == "rasterDataset" and series:
# geography
self.complete_md.ico_feat_count.setHidden(1)
self.complete_md.lbl_feat_count.setHidden(1)
self.complete_md.val_feat_count.setHidden(1)
self.complete_md.ico_geometry.setHidden(1)
self.complete_md.lbl_geometry.setHidden(1)
self.complete_md.val_geometry.setHidden(1)
# geography
self.complete_md.grp_technic.setHidden(0)
# menus
menu_list.item(1).setHidden(1) # attributes
menu_list.item(4).setHidden(0) # geography and technical
return
elif md_type == "service":
# general
self.complete_md.val_inspire_themes.setHidden(1)
self.complete_md.ico_inspire_themes.setHidden(1)
self.complete_md.ico_inspire_conformity.setHidden(1)
# history
self.complete_md.lbl_frequency.setHidden(1)
self.complete_md.ico_frequency.setHidden(1)
self.complete_md.val_frequency.setHidden(1)
self.complete_md.lbl_valid_start.setHidden(1)
self.complete_md.ico_valid_start.setHidden(1)
self.complete_md.val_valid_start.setHidden(1)
self.complete_md.lbl_valid_end.setHidden(1)
self.complete_md.ico_valid_end.setHidden(1)
self.complete_md.val_valid_end.setHidden(1)
self.complete_md.lbl_valid_comment.setHidden(1)
self.complete_md.ico_valid_comment.setHidden(1)
self.complete_md.val_valid_comment.setHidden(1)
self.complete_md.grp_collect_context.setHidden(1)
self.complete_md.grp_collect_method.setHidden(1)
# geography
self.complete_md.grp_technic.setHidden(0)
# menus
menu_list.item(1).setHidden(1) # attributes
menu_list.item(4).setHidden(0) # geography and technical
return
elif md_type == "resource":
# history
self.complete_md.lbl_frequency.setHidden(1)
self.complete_md.ico_frequency.setHidden(1)
self.complete_md.val_frequency.setHidden(1)
self.complete_md.lbl_valid_start.setHidden(1)
self.complete_md.ico_valid_start.setHidden(1)
self.complete_md.val_valid_start.setHidden(1)
self.complete_md.lbl_valid_end.setHidden(1)
self.complete_md.ico_valid_end.setHidden(1)
self.complete_md.val_valid_end.setHidden(1)
self.complete_md.lbl_valid_comment.setHidden(1)
self.complete_md.ico_valid_comment.setHidden(1)
self.complete_md.val_valid_comment.setHidden(1)
self.complete_md.grp_collect_context.setHidden(1)
self.complete_md.grp_collect_method.setHidden(1)
# menus
menu_list.item(1).setHidden(1) # attributes
menu_list.item(4).setHidden(1) # geography and technical
return
else:
# should not exist
logger.error("Metadata type not recognized:", md_type)
return
PK Jrk7[ [ ' isogeo_search_engine/modules/results.py# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
# Standard library
import logging
from functools import partial
# PyQT
# from QByteArray
from PyQt4.QtCore import QSettings
from PyQt4.QtGui import QIcon, QTableWidgetItem, QComboBox, QPushButton, QLabel, QPixmap, QProgressBar
# PyQGIS
from qgis.utils import iface
# Custom modules
from .tools import Tools
from .url_builder import UrlBuilder
# ############################################################################
# ########## Globals ###############
# ##################################
custom_tools = Tools()
srv_url_bld = UrlBuilder()
qsettings = QSettings()
logger = logging.getLogger("IsogeoQgisPlugin")
# Isogeo geometry types
polygon_list = ("CurvePolygon", "MultiPolygon",
"MultiSurface", "Polygon", "PolyhedralSurface")
point_list = ("Point", "MultiPoint")
line_list = ("CircularString", "CompoundCurve", "Curve",
"LineString", "MultiCurve", "MultiLineString")
multi_list = ("Geometry", "GeometryCollection")
# Isogeo formats
vectorformat_list = ('shp', 'dxf', 'dgn', 'filegdb', 'tab')
rasterformat_list = ('esriasciigrid', 'geotiff',
'intergraphgdb', 'jpeg', 'png', 'xyz', 'ecw')
# ############################################################################
# ########## Classes ###############
# ##################################
class ResultsManager(object):
"""Basic class that holds utilitary methods for the plugin."""
def __init__(self, isogeo_plugin):
"""Class constructor."""
self.isogeo_widget = isogeo_plugin.dockwidget
self.add_layer = isogeo_plugin.add_layer
self.send_details_request = isogeo_plugin.send_details_request
self.tr = isogeo_plugin.tr
self.pg_connections = srv_url_bld.build_postgis_dict(qsettings)
def show_results(self, api_results, tbl_result=None, pg_connections=dict(), progress_bar=QProgressBar):
"""Display the results in a table ."""
logger.info("Results manager called. Displaying the results")
# check parameters
if not tbl_result:
tbl_result = self.isogeo_widget.tbl_result
else:
pass
# Get the name (and other informations) of all databases whose
# connection is set up in QGIS
if pg_connections == {}:
pg_connections = self.pg_connections
else:
pass
# Set rable rows
if api_results.get('total') >= 10:
tbl_result.setRowCount(10)
else:
tbl_result.setRowCount(api_results.get('total'))
# Looping inside the table lines. For each of them, showing the title,
# abstract, geometry type, and a button that allow to add the data
# to the canvas.
count = 0
for i in api_results.get('results'):
# get useful metadata
md_id = i.get('_id')
md_keywords = [i.get("tags").get(k)
for k in i.get("tags", ["NR", ])
if k.startswith("keyword:isogeo")]
md_title = i.get("title", "NR")
ds_geometry = i.get('geometry')
# Displaying the metadata title inside a button
btn_md_title = QPushButton(custom_tools.format_button_title(md_title))
# Connecting the button to the full metadata popup
btn_md_title.pressed.connect(partial(
self.send_details_request, md_id=md_id))
# Putting the abstract as a tooltip on this button
btn_md_title.setToolTip(i.get('abstract', "")[:300])
# Insert it in column 1
tbl_result.setCellWidget(
count, 0, btn_md_title)
# Insert the modification date in column 2
tbl_result.setItem(
count, 1, QTableWidgetItem(
custom_tools.handle_date(i.get('_modified'))))
# Getting the geometry
label = QLabel()
if ds_geometry:
# If the geometry type is point, insert point icon in column 3
if ds_geometry in point_list:
pix = QPixmap(':/plugins/Isogeo/resources/point.png')
label.setPixmap(pix)
tbl_result.setCellWidget(count, 2, label)
# If the type is polygon, insert polygon icon in column 3
elif ds_geometry in polygon_list:
pix = QPixmap(':/plugins/Isogeo/resources/polygon.png')
label.setPixmap(pix)
tbl_result.setCellWidget(count, 2, label)
# If the type is line, insert line icon in column 3
elif ds_geometry in line_list:
pix = QPixmap(':/plugins/Isogeo/resources/line.png')
label.setPixmap(pix)
tbl_result.setCellWidget(count, 2, label)
# If the type is multi, insert multi icon in column 3
elif ds_geometry in multi_list:
pix = QPixmap(':/plugins/Isogeo/resources/multi.png')
label.setPixmap(pix)
tbl_result.setCellWidget(count, 2, label)
# If the type is TIN, insert TIN text in column 3
elif ds_geometry == "TIN":
tbl_result.setItem(
count, 2, QTableWidgetItem(u'TIN'))
# If the type isn't any of the above, unknown(shouldn't happen)
else:
tbl_result.setItem(
count, 2, QTableWidgetItem(
self.tr('Unknown geometry', "ResultsManager")))
# If the data doesn't have a geometry type
else:
# It may be a raster, then raster icon in column 3
if "rasterDataset" in i.get('type'):
pix = QPixmap(':/plugins/Isogeo/resources/raster.png')
label.setPixmap(pix)
tbl_result.setCellWidget(count, 2, label)
# Or it isn't spatial, then "no geometry" icon in column 3
else:
pix = QPixmap(':/plugins/Isogeo/resources/ban.png')
label.setPixmap(pix)
tbl_result.setCellWidget(count, 2, label)
# We are still looping inside the table lines. For a given line, we
# have displayed title, date, and geometry type. Now we have to
# deal with the "add data" column. We need to see if the data can
# be added directly, and/or using a geographical service.
link_dict = {}
if 'format' in i.keys():
# If the data is a vector and the path is available, store
# useful information in the dict
if i.get('format', "NR") in vectorformat_list and 'path' in i:
path = custom_tools.format_path(i.get('path'))
try:
open(path)
params = ["vector", path,
i.get("title", "NR"),
i.get("abstract", "NR"),
md_keywords]
link_dict[self.tr('Data file', "ResultsManager")] = params
except IOError:
pass
# Same if the data is a raster
elif i.get('format') in rasterformat_list and 'path' in i:
path = custom_tools.format_path(i.get('path'))
try:
open(path)
params = ["raster", path,
i.get("title", "NR"),
i.get("abstract", "NR"),
md_keywords]
link_dict[self.tr('Data file', "ResultsManager")] = params
except IOError:
pass
# If the data is a postGIS table and the connexion has
# been saved in QGIS.
elif i.get('format') == 'postgis':
# Récupère le nom de la base de données
base_name = i.get('path')
if base_name in pg_connections.keys():
params = {}
params['base_name'] = base_name
schema_table = i.get('name')
if schema_table is not None and "." in schema_table:
params['schema'] = schema_table.split(".")[0]
params['table'] = schema_table.split(".")[1]
params['abstract'] = i.get("abstract", None)
params['title'] = i.get("title", None)
params['keywords'] = md_keywords
link_dict[self.tr('PostGIS table', "ResultsManager")] = params
else:
pass
else:
pass
else:
pass
# We are now testing the WMS and WFS links that may be associated
# to the metadata sheet
# First, we look in "links". This is the old deprecated syntax.
# At some point, all services should be associated using the new
# one and this part of the code should be removed.
for link in i.get('links'):
# If the link is a WMS
if link.get('kind') == 'wms':
# Test if all the needed information is in the url.
url = [link.get('title'), link.get('url')]
name_url = srv_url_bld.build_wms_url(url, rsc_type="link")
# In which case, store it in the dict.
if name_url != 0:
link_dict[u"WMS : " + name_url[1]] = name_url
else:
pass
# If the link is a WFS
elif link.get('kind') == 'wfs':
url = [link.get('title'), link.get('url')]
name_url = srv_url_bld.build_wfs_url(url, rsc_type="link")
if name_url != 0:
link_dict[u"WFS : " + name_url[1]] = name_url
else:
pass
# If the link is a second level association
elif link.get('type') == 'link':
_link = link.get('link')
if 'kind' in _link:
# WMS
if _link.get('kind') == 'wms':
url = [link.get('title'), link.get('url')]
name_url = srv_url_bld.build_wms_url(url, rsc_type="link")
if name_url != 0:
link_dict[u"WMS : " + name_url[1]] = name_url
else:
pass
# WFS
elif _link.get('kind') == 'wfs':
url = [link.get('title'), link.get('url')]
name_url = srv_url_bld.build_wfs_url(url, rsc_type="link")
if name_url != 0:
link_dict[u"WFS : " + name_url[1]] = name_url
else:
pass
else:
pass
else:
pass
else:
pass
# This is the new association mode. The layer and service
# information are stored in the "serviceLayers" include, when
# associated with a vector or raster data.
d_type = i.get('type')
if d_type == "vectorDataset" or d_type == "rasterDataset":
for layer in i.get('serviceLayers'):
service = layer.get("service")
if service is not None:
srv_details = {"path": service.get("path", "NR"),
"formatVersion": service.get("formatVersion")}
# WFS
if service.get("format") == "wfs":
try:
path = "{0}?typeName={1}".format(service.get("path"),
layer.get("id"))
except UnicodeEncodeError:
logger.error("Encoding error in service layer name (UID). Metadata: {0} | service layer: {1}"
.format(i.get("_id"),
layer.get("_id")))
continue
name_url = srv_url_bld.new_build_wfs_url(layer, srv_details,
rsc_type="ds_dyn_lyr_srv",
mode="quicky")
if name_url[0] != 0:
link_dict[name_url[5]] = name_url
else:
pass
# WMS
elif service.get("format") == "wms":
try:
path = "{0}?layers={1}".format(service.get("path"),
layer.get("id"))
except UnicodeEncodeError:
logger.error("Encoding error in service layer name (UID). Metadata: {0} | service layer: {1}"
.format(i.get("_id"),
layer.get("_id")))
continue
name_url = srv_url_bld.new_build_wms_url(layer, srv_details,
rsc_type="ds_dyn_lyr_srv",
mode="quicky")
if name_url[0] != 0:
link_dict[name_url[5]] = name_url
else:
pass
# WMTS
elif service.get("format") == "wmts":
# try:
# path = "{0}?layers={1}".format(service.get("path"),
# layer.get("id"))
# except UnicodeEncodeError:
# logger.error("Encoding error in service layer name (UID). Metadata: {0} | service layer: {1}"
# .format(i.get("_id"),
# layer.get("_id")))
# continue
name_url = srv_url_bld.build_wmts_url(layer, srv_details,
rsc_type="ds_dyn_lyr_srv")
if name_url[0] != 0:
link_dict[u"WMTS : " + name_url[1]] = name_url
else:
pass
else:
pass
else:
pass
# New association mode. For services metadata sheet, the layers
# are stored in the purposely named include: "layers".
elif i.get('type') == "service":
if i.get("layers") is not None:
srv_details = {"path": i.get("path", "NR"),
"formatVersion": i.get("formatVersion")}
# WFS
if i.get("format") == "wfs":
for layer in i.get('layers'):
try:
path = "{0}?typeName={1}".format(srv_details.get("path"),
layer.get("id"))
except UnicodeEncodeError:
logger.error("Encoding error in service layer name (UID). Metadata: {0} | service layer: {1}"
.format(i.get("_id"),
layer.get("_id")))
continue
name_url = srv_url_bld.new_build_wfs_url(layer, srv_details,
rsc_type="service",
mode="quicky")
if name_url[0] != 0:
link_dict[name_url[5]] = name_url
else:
continue
pass
# WMS
elif i.get("format") == "wms":
for layer in i.get('layers'):
try:
path = "{0}?layers={1}".format(srv_details.get("path"),
layer.get("id"))
except UnicodeEncodeError:
logger.error("Encoding error in service layer name (UID). Metadata: {0} | service layer: {1}"
.format(i.get("_id"),
layer.get("_id")))
continue
name_url = srv_url_bld.new_build_wms_url(layer, srv_details,
rsc_type="service",
mode="quicky")
if name_url[0] != 0:
link_dict[name_url[5]] = name_url
# link_dict["WMS : " + name_url[1]] = name_url
else:
continue
pass
# WMTS
elif i.get("format") == "wmts":
for layer in i.get('layers'):
# try:
# path = "{0}?layers={1}".format(srv_details.get("path"),
# layer.get("id"))
# except UnicodeEncodeError:
# logger.error("Encoding error in service layer name (UID). Metadata: {0} | service layer: {1}"
# .format(i.get("_id"),
# layer.get("_id")))
# continue
name_url = srv_url_bld.build_wmts_url(layer, srv_details,
rsc_type="service")
if name_url[0] != 0:
btn_label = "WMTS : {}".format(name_url[1])
link_dict[btn_label] = name_url
else:
continue
pass
else:
pass
else:
pass
# Now the plugin has tested every possibility for the layer to be
# added. The "Add" column has to be filled accordingly.
# If the data can't be added, just insert "can't" text.
if link_dict == {}:
text = self.tr("Can't be added", "ResultsManager")
fake_button = QPushButton(text)
fake_button.setStyleSheet("text-align: left")
fake_button.setEnabled(False)
tbl_result.setCellWidget(count, 3, fake_button)
# If there is only one way for the data to be added, insert a
# button.
elif len(link_dict) == 1:
text = link_dict.keys()[0]
params = link_dict.get(text)
if text.startswith("WMS"):
icon = QIcon(':/plugins/Isogeo/resources/wms.png')
elif text.startswith("WFS"):
icon = QIcon(':/plugins/Isogeo/resources/wfs.png')
elif text.startswith("WMTS"):
icon = QIcon(':/plugins/Isogeo/resources/wms.png')
elif text.startswith(self.tr('PostGIS table', "ResultsManager")):
icon = QIcon(':/plugins/Isogeo/resources/database.svg')
elif text.startswith(self.tr('Data file', "ResultsManager")):
icon = QIcon(':/plugins/Isogeo/resources/file.svg')
add_button = QPushButton(icon, text)
add_button.setStyleSheet("text-align: left")
add_button.pressed.connect(partial(self.add_layer,
layer_info=["info", params])
)
tbl_result.setCellWidget(count, 3, add_button)
# Else, add a combobox, storing all possibilities.
else:
combo = QComboBox()
for key in link_dict.keys():
if key.startswith("WMS"):
icon = QIcon(':/plugins/Isogeo/resources/wms.png')
elif key.startswith("WFS"):
icon = QIcon(':/plugins/Isogeo/resources/wfs.png')
elif key.startswith("WMTS"):
icon = QIcon(':/plugins/Isogeo/resources/wms.png')
elif key.startswith(self.tr('PostGIS table', "ResultsManager")):
icon = QIcon(':/plugins/Isogeo/resources/database.svg')
elif key.startswith(self.tr('Data file', "ResultsManager")):
icon = QIcon(':/plugins/Isogeo/resources/file.svg')
combo.addItem(icon, key, link_dict[key])
combo.activated.connect(partial(self.add_layer,
layer_info=["index", count]))
tbl_result.setCellWidget(count, 3, combo)
count += 1
# Remove the "loading" bar
iface.mainWindow().statusBar().removeWidget(progress_bar)
# method ending
return None
PK 5^JIJ/ J/ % isogeo_search_engine/modules/tools.py# -*- coding: utf-8 -*-
# Standard library
import datetime
import logging
from functools import partial
from os import path
from urllib import getproxies, unquote, urlencode
import webbrowser
# PyQGIS
from qgis.core import QgsMapLayerRegistry, QgsRectangle, QgsVectorLayer
from qgis.utils import iface
# PyQT
from PyQt4.QtCore import QSettings, QUrl
from PyQt4.QtGui import QMessageBox
# ############################################################################
# ########## Globals ###############
# ##################################
qsettings = QSettings()
logger = logging.getLogger("IsogeoQgisPlugin")
# ############################################################################
# ########## Classes ###############
# ##################################
class Tools(object):
"""Basic class that holds utilitary methods for the Isogeo plugin."""
last_error = None
def error_catcher(self, msg, tag, level):
"""Catch QGIS error messages for introspection."""
# print(type(logger), dir(logger))
# print(msg, tag, level)
if tag == 'WMS' and level != 0:
# logger.error("WMS error: {}".format(msg))
self.last_error = "wms", msg
elif tag == 'PostGIS' and level != 0:
self.last_error = "postgis", msg
else:
pass
def format_button_title(self, title):
"""Format the title for it to fit the button."""
words = title.split(' ')
line_length = 0
lines = []
string = ""
for word in words:
line_length += len(word)
if line_length < 22:
string += word + " "
else:
line_length = len(word)
lines.append(string[:-1])
string = word + " "
if string[:-1] not in lines:
lines.append(string[:-1])
final_text = ""
for line in lines:
final_text += line + "\n"
final_text = final_text[:-1]
# method ending
return final_text
def format_path(self, string):
"""Reformat windows path for them to be understood by QGIS."""
new_string = ""
for character in string:
if character == '\\':
new_string += "/"
else:
new_string += character
# method ending
return new_string
def get_map_crs(self):
"""Get QGIS map canvas current EPSG code."""
current_crs = str(iface.mapCanvas()
.mapRenderer()
.destinationCrs()
.authid())
return current_crs
def handle_date(self, input_date):
"""Create a date object with the string given as a date by the API."""
if input_date != "NR":
date = input_date.split("T")[0]
year = int(date.split('-')[0])
month = int(date.split('-')[1])
day = int(date.split('-')[2])
new_date = datetime.date(year, month, day)
# method ending
return new_date.strftime("%Y-%m-%d")
else:
return input_date
pass
def mail_to_isogeo(self, lang):
"""Open the credentials request online form in web browser."""
if lang == "fr":
webbrowser.open('http://www.isogeo.com/fr/Plugin-QGIS/22',
new=0,
autoraise=True
)
else:
webbrowser.open('http://www.isogeo.com/en/QGIS-Plugin/22',
new=0,
autoraise=True
)
# method ending
logger.info("Bugtracker launched in the default web browser")
return
def open_webpage(self, link):
"""Open the bugtracker on the user's default browser."""
if type(link) is QUrl:
link = link.toString()
webbrowser.open(
link,
new=0,
autoraise=True)
# method ending
logger.info("Bugtracker launched in the default web browser")
return
def results_pages_counter(self, nb_fiches):
"""Calculate the number of pages for a given number of results."""
if nb_fiches <= 10:
nb_page = 1
else:
if (nb_fiches % 10) == 0:
nb_page = (nb_fiches / 10)
else:
nb_page = (nb_fiches / 10) + 1
# method ending
return nb_page
def display_auth_form(self, ui_auth_form):
"""Show authentication form with prefilled fields."""
# fillfull auth form fields from stored settings
ui_auth_form.ent_app_id.setText(qsettings
.value("isogeo-plugin/user-auth/id", 0))
ui_auth_form.ent_app_secret.setText(qsettings
.value("isogeo-plugin/user-auth/secret", 0))
ui_auth_form.chb_isogeo_editor.setChecked(qsettings
.value("isogeo/user/editor", 0))
# check auth validity
# connect check button
# ui_auth_form.btn_check_auth.connect(partial(print("check API authentication")))
# display
ui_auth_form.show()
def special_search(self, easter_code="isogeo"):
"""Make some special actions in certains cases."""
canvas = iface.mapCanvas()
if easter_code == "isogeo":
# WMS
# wms_params = {"service": "WMS",
# "version": "1.3.0",
# "request": "GetMap",
# "layers": "Isogeo:isogeo_logo",
# "crs": "EPSG:3857",
# "format": "image/png",
# "styles": "isogeo_logo",
# "url": "http://noisy.hq.isogeo.fr:6090/geoserver/Isogeo/ows?"
# }
# wms_uri = unquote(urlencode(wms_params))
# wms_lyr = QgsRasterLayer(wms_uri, u"Ici c'est Isogeo !", "wms")
# if wms_lyr.isValid:
# QgsMapLayerRegistry.instance().addMapLayer(wms_lyr)
# logger.info("Isogeo easter egg used and WMS displayed!")
# else:
# logger.error("WMS layer failed: {}"
# .format(wms_lyr.error().message()))
# WFS
wfs_params = {"service": "WFS",
"version": "1.0.0",
"request": "GetFeature",
"typename": "Isogeo:isogeo_logo",
"srsname": "EPSG:3857",
}
wfs_uri = "http://noisy.hq.isogeo.fr:6090/geoserver/Isogeo/ows?"\
+ unquote(urlencode(wfs_params))
wfs_lyr = QgsVectorLayer(wfs_uri, u"Ici c'est Isogeo !", "WFS")
if wfs_lyr.isValid:
wfs_style = path.join(path.dirname(path.realpath(__file__)),
"isogeo.qml")
wfs_lyr.loadNamedStyle(wfs_style)
QgsMapLayerRegistry.instance().addMapLayer(wfs_lyr)
logger.info("Isogeo easter egg used and WFS displayed!")
else:
logger.error("WFS layer failed: {}"
.format(wfs_lyr.error().message()))
canvas.setExtent(QgsRectangle(2.224199,48.815573,2.469921, 48.902145))
else:
pass
# ending method
return
def test_proxy_configuration(self):
"""Check adequation between system and QGIS proxy configuration.
If a proxy configuration is set up for the computer, and for QGIS.
If none or both is set up, pass. But if there is a proxy config for the
computer but not in QGIS, pops an alert message.
"""
system_proxy_config = getproxies()
if system_proxy_config == {}:
logger.info("No proxy found on the OS: OK.")
return 0
else:
qgis_proxy = qsettings.value("proxy/proxyEnabled", "")
if str(qgis_proxy) == "true":
http = system_proxy_config.get('http')
if http is None:
pass
else:
elements = http.split(':')
if len(elements) == 2:
host = elements[0]
port = elements[1]
qgis_host = qsettings.value("proxy/proxyHost", "")
qgis_port = qsettings.value("proxy/proxyPort", "")
if qgis_host == host:
if qgis_port == port:
logger.info("A proxy is set up both in QGIS "
"and the OS and they match => "
"Proxy config : OK")
pass
else:
QMessageBox.information(iface.mainWindow(
), self.tr('Alert'),
self.tr("Proxy issue : \nQGIS and your OS "
"have different proxy set up."))
else:
QMessageBox.information(iface.mainWindow(
), self.tr('Alert'),
self.tr("Proxy issue : \nQGIS and your OS have"
" different proxy set ups."))
elif len(elements) == 3 and elements[0] == 'http':
host_short = elements[1][2:]
host_long = elements[0] + ':' + elements[1]
port = elements[2]
qgis_host = qsettings.value("proxy/proxyHost", "")
qgis_port = qsettings.value("proxy/proxyPort", "")
if qgis_host == host_short or qgis_host == host_long:
if qgis_port == port:
logger.info("A proxy is set up both in QGIS"
" and the OS and they match "
"=> Proxy config : OK")
pass
else:
logger.error("OS and QGIS proxy ports do not "
"match. => Proxy config: not OK")
QMessageBox.information(iface.mainWindow(
), self.tr('Alert'),
self.tr("Proxy issue : \nQGIS and your OS"
" have different proxy set ups."))
else:
logger.error("OS and QGIS proxy hosts do not "
"match. => Proxy config: not OK")
QMessageBox.information(iface.mainWindow(
), self.tr('Alert'),
self.tr("Proxy issue : \nQGIS and your OS have"
" different proxy set ups."))
else:
logger.error("OS uses a proxy but it isn't set up in QGIS."
" => Proxy config: not OK")
QMessageBox.information(iface.mainWindow(
), self.tr('Alert'),
self.tr("Proxy issue : \nYou have a proxy set up on your"
" OS but none in QGIS.\nPlease set it up in "
"'Preferences/Options/Network'."))
PK .uJJME * isogeo_search_engine/modules/translator.py# -*- coding: UTF-8 -*-
#!/usr/bin/env python
from __future__ import (absolute_import, unicode_literals)
# ----------------------------------------------------------------------------
"""
Additionnal strings to be translated in the exports.
"""
# Created: 18/10/2016
# Updated: 22/11/2016
# ---------------------------------------------------------------------------
# ##############################################################################
# ########## Globals ###############
# ##################################
dict_md_fields_fr = {
"restrictions": {
"none": " ",
"copyright": "Copyright",
"patent": "Brevet",
"patentPending": "Brevet en attente",
"trademark": "Marque déposée",
"license": "Licence",
"intellectualPropertyRights": "Droits de propriété intellectuelle",
"restricted": "Limité",
"other": "Autre"
},
"limitations": {
"title": "Limitations",
"add": "Ajouter une nouvelle limitation",
"edit": "Editer la limitation",
"restriction": "Restriction :",
"description": "Description :",
"type": "Type :",
"directive": "Directive :",
"legal": "Légale",
"security": "Sécurité"
},
"conditions": {
"license": "Licence :",
"noLicense": "Pas de licence associée"
},
"constraintType": {
"none": " ",
"access": "Accès",
"usage": "Usage"
},
"formatTypes": {
"vectorDataset": "Vecteur",
"vector-dataset": "Vecteur",
"rasterDataset": "Raster",
"raster-dataset": "Raster",
"resource": "Ressources",
"service": "Service géographique"
},
"roles": {
"author": "Auteur",
"pointOfContact": "Point de contact",
"custodian": "Administrateur",
"distributor": "Distributeur",
"originator": "Créateur",
"owner": "Propriétaire",
"principalInvestigator": "Analyste principal",
"processor": "Responsable du traitement",
"publisher": "Éditeur (publication)",
"resourceProvider": "Fournisseur",
"user": "Utilisateur"
},
"frequencyUpdateHelp": "Tous les ",
"frequencyTypes": {
"years": "an(s)",
"months": "mois",
"weeks": "semaine(s)",
"days": "jour(s)",
"hours": "heure(s)",
"minutes": "minute(s)",
"seconds": "seconde(s)"
},
"frequencyShortTypes": {
"Y": "an(s)",
"M": "mois",
"W": "semaine(s)",
"D": "jour(s)",
"H": "heure(s)",
"M": "minute(s)",
"S": "seconde(s)"
},
"events": {
"update": "Mise à jour",
"creation": "Création",
"published": "Publication"
},
"quality": {
"specification": "Spécification",
"conformant": "Conformité",
"isConform": "Conforme",
"isNotConform": "Non conforme",
"topologicalConsistency": "Cohérence topologique"
},
}
dict_md_fields_en = {
"restrictions": {
"none": " ",
"copyright": "Copyright",
"patent": "Patent",
"patentPending": "Patent pending",
"trademark": "Trademark",
"license": "License",
"intellectualPropertyRights": "Intellectual property rights",
"restricted": "Restricted",
"other": "Other"
},
"limitations": {
"title": "Limitations",
"add": "Add new limitation",
"edit": "Edit limitation",
"restriction": "Restriction:",
"description": "Description:",
"type": "Type:",
"directive": "Directive:",
"legal": "Legal",
"security": "Security"
},
"conditions": {
"license": "License:",
"noLicense": "No attached license"
},
"constraintType": {
"none": " ",
"access": "Access",
"usage": "Usage"
},
"formatTypes": {
"vectorDataset": "Vector",
"vector-dataset": "Vector",
"rasterDataset": "Raster",
"raster-dataset": "Raster",
"resource": "Resources",
"series": "Series",
"service": "Service"
},
"roles": {
"author": "Author",
"pointOfContact": "Point of contact",
"custodian": "Custodian",
"distributor": "Distributor",
"originator": "Originator",
"owner": "Owner",
"principalInvestigator": "Principal investigator",
"processor": "Processor",
"publisher": "Publisher",
"resourceProvider": "Resource provider",
"user": "User"
},
"frequencyUpdateHelp": "Every ",
"frequencyTypes": {
"years": "year(s)",
"months": "month(s)",
"weeks": "week(s)",
"days": "day(s)",
"hours": "hour(s)",
"minutes": "minute(s)",
"seconds": "second(s)"
},
"frequencyShortTypes": {
"Y": "year(s)",
"M": "month(s)",
"W": "week(s)",
"D": "day(s)",
"H": "hour(s)",
"M": "minute(s)",
"S": "second(s)"
},
"events": {
"update": "Update",
"creation": "Creation",
"published": "Publication"
},
"quality": {
"specification": "Specification",
"conformant": "Conformity",
"isConform": "Conformant",
"isNotConform": "Not conformant",
"topologicalConsistency": "Topological consistency"
},
}
# ##############################################################################
# ########## Classes ###############
# ##################################
class IsogeoTranslator(object):
"""Makes easier the translation of Isogeo API specific strings."""
def __init__(self, lang="FR"):
"""Set text dictionary depending on language passed."""
if lang.upper() == "FR":
self.translations = dict_md_fields_fr
else:
self.translations = dict_md_fields_en
super(IsogeoTranslator, self).__init__()
def tr(self, subdomain=None, string_to_translate=""):
"""Returns translation of string passed."""
if subdomain:
str_translated = self.translations.get(subdomain, {"error": "Subdomain not found: {}".format(subdomain)})\
.get(string_to_translate, "String not found")
else:
str_translated = self.translations.get(string_to_translate, "String not found")
# end of method
return str_translated
# ##############################################################################
# ##### Stand alone program ########
# ##################################
if __name__ == '__main__':
"""Standalone execution."""
# French
translator_fr = IsogeoTranslator("FR")
print(translator_fr.tr("roles", "pointOfContact"))
print(translator_fr.tr(None, "frequencyUpdateHelp"))
# English
translator_en = IsogeoTranslator("EN")
print(translator_en.tr("roles", "pointOfContact"))
# print(dict_md_fields_fr.get("roles"))
# print(dict_md_fields_fr.get("frequencyTypes"))
PK =JPx| x| + isogeo_search_engine/modules/url_builder.py# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function, unicode_literals)
# Standard library
from datetime import datetime
import logging
import re
from urllib import unquote, urlencode
from urlparse import urlparse
# PyQT
from PyQt4.QtCore import QSettings, QUrl
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest
# QGIS
from qgis.core import QgsNetworkAccessManager,\
QgsVectorLayer, QgsMapLayerRegistry, QgsRasterLayer
# Custom modules
from .tools import Tools
# ############################################################################
# ########## Globals ###############
# ##################################
custom_tools = Tools()
qsettings = QSettings()
logger = logging.getLogger("IsogeoQgisPlugin")
qgis_wms_formats = ('image/png', 'image/png8',
'image/jpeg',
'image/svg',
'image/gif',
'image/geotiff', 'image/tiff')
# ############################################################################
# ##### Conditional imports ########
# ##################################
try:
from owslib.wms import WebMapService
from owslib.wmts import WebMapTileService
from owslib.util import ServiceException
import owslib
logger.info("Depencencies - owslib version: {}"
.format(owslib.__version__))
except ImportError as e:
logger.error("Depencencies - owslib is not present")
# raise e
try:
from owslib.wfs import WebFeatureService
except ImportError as e:
logger.error("Depencencies - owslib WFS issue: {}"
.format(e))
try:
from owslib.util import HTTPError
logger.info("Depencencies - HTTPError within owslib")
except ImportError as e:
from urllib2 import HTTPError
logger.error("Depencencies - HTTPError not within owslib."
"Directly imported from urllib2.")
try:
import requests
logger.info("Depencencies - Requests version: {}"
.format(requests.__version__))
except ImportError as e:
logger.warning("Depencencies - Requests not available")
# ############################################################################
# ########## Classes ###############
# ##################################
class UrlBuilder(object):
"""Basic class that holds utilitary methods for the plugin."""
def __init__(self):
"""Class constructor."""
self.cached_wfs = dict()
self.cached_wms = dict()
self.cached_wmts = dict()
def build_wfs_url(self, raw_url, rsc_type="service"):
"""Reformat the input WFS url so it fits QGIS criterias.
Tests weither all the needed information is provided in the url, and
then build the url in the syntax understood by QGIS.
rsc_type: possible values = "service" or "link"
"""
logger.debug("WFS URL TYPE: " + rsc_type)
title = raw_url[0]
input_url = raw_url[1].split("?")[0] + "?"
try:
list_parameters = raw_url[1].split("?")[1].split('&')
except IndexError, e:
logger.error("Build WFS URL failed: {}".format(e))
return 0
valid = False
srs_defined = False
for i in list_parameters:
ilow = i.lower()
if "typename=" in ilow:
valid = True
name = i.split('=')[1]
typename = i
elif "layers=" in ilow or "layer=" in ilow:
valid = True
name = i.split('=')[1]
typename = "typename=" + name
elif "getcapabilities" in ilow:
valid = True
name = title
typename = "typename=" + name
elif "srsname=" in ilow:
srs_defined = True
srs = i
if valid is True:
output_url = input_url + typename
if srs_defined is True:
output_url += '&' + srs
output_url += '&service=WFS&version=1.0.0&request=GetFeature'
output = ["WFS", name, output_url]
return output
else:
return 0
def build_wms_url(self, raw_url, rsc_type="service"):
"""Reformat the input WMS url so it fits QGIS criterias.
Tests weither all the needed information is provided in the url, and
then build the url in the syntax understood by QGIS.
"""
# METHOD
title = raw_url[0]
input_url = raw_url[1].split("?")[0] + "?"
try:
list_parameters = raw_url[1].split("?")[1].split('&')
except IndexError, e:
logger.error("Build WMS URL failed: {}".format(e))
return 0
valid = False
style_defined = False
srs_defined = False
format_defined = False
for i in list_parameters:
ilow = i.lower()
if "layers=" in ilow:
valid = True
name = i.split('=')[1]
layers = i
elif "layer=" in ilow:
valid = True
name = i.split('=')[1]
layers = "layers=" + name
elif "getcapabilities" in ilow:
valid = True
name = title
layers = "layers=" + title
elif "styles=" in ilow:
style_defined = True
style = i
elif "crs=" in ilow:
srs_defined = True
srs = i
elif "format=" in ilow:
format_defined = True
imgformat = i
if valid is True:
if input_url.lower().startswith('url='):
output_url = input_url + "&" + layers
else:
output_url = "url=" + input_url + "&" + layers
if style_defined is True:
output_url += '&' + style
else:
output_url += '&styles='
if format_defined is True:
output_url += '&' + imgformat
else:
output_url += '&format=image/png'
if srs_defined is True:
output_url += '&' + srs
output = ["WMS", name, output_url]
return output
else:
return 0
def build_postgis_dict(self, input_dict):
"""Build the dict that stores informations about PostGIS connexions."""
final_dict = {}
for k in sorted(input_dict.allKeys()):
if k.startswith("PostgreSQL/connections/")\
and k.endswith("/database"):
if len(k.split("/")) == 4:
connection_name = k.split("/")[2]
password_saved = input_dict.value(
'PostgreSQL/connections/' +
connection_name +
'/savePassword')
user_saved = input_dict.value(
'PostgreSQL/connections/' +
connection_name +
'/saveUsername')
if password_saved == 'true' and user_saved == 'true':
dictionary = {'name':
input_dict.value(
'PostgreSQL/connections/' +
connection_name +
'/database'),
'host':
input_dict.value(
'PostgreSQL/connections/' +
connection_name +
'/host'),
'port':
input_dict.value(
'PostgreSQL/connections/' +
connection_name +
'/port'),
'username':
input_dict.value(
'PostgreSQL/connections/' +
connection_name +
'/username'),
'password':
input_dict.value(
'PostgreSQL/connections/' +
connection_name +
'/password')}
final_dict[
input_dict.value('PostgreSQL/connections/' +
connection_name +
'/database')
] = dictionary
else:
continue
else:
pass
else:
pass
return final_dict
# FIXING #90 -------------------------------------------------------------
def new_build_wfs_url(self, api_layer, srv_details, rsc_type="ds_dyn_lyr_srv", mode="complete"):
"""Reformat the input WMS url so it fits QGIS criterias.
Tests weither all the needed information is provided in the url, and
then build the url in the syntax understood by QGIS.
"""
# local variables
layer_title = api_layer.get("titles")[0].get("value", "WFS Layer")
wfs_url_getcap = srv_details.get("path")\
+ "?request=GetCapabilities&service=WFS"
geoserver = "geoserver" in wfs_url_getcap
layer_id = api_layer.get("id")
layer_name = re.sub('\{.*?}', "", layer_id)
# handling WFS namespaces
if "{" in layer_id:
namespace = layer_id[layer_id.find("{") + 1:layer_id.find("}")]
logging.debug("WFS - Namespace: " + namespace)
else:
namespace = ""
if mode == "quicky":
# let's try a quick & dirty url build
srs_map = custom_tools.get_map_crs()
wfs_url_base = srv_details.get("path")
if "?" not in wfs_url_base:
wfs_url_base = wfs_url_base + "?"
else:
pass
wfs_url_params = {"SERVICE": "WFS",
"VERSION": "1.0.0",
"typename": layer_name,
"srsname": srs_map,
"REQUEST": "GetFeature",
"namespace": namespace,
}
wfs_url_quicky = wfs_url_base +\
unquote(urlencode(wfs_url_params, "utf8"))
# prevent encoding errors (#102)
try:
btn_lbl = "WFS : {}".format(layer_title)
return ["WFS", layer_title, wfs_url_quicky,
api_layer, srv_details, btn_lbl]
except UnicodeEncodeError as e:
btn_lbl = "WFS : {}".format(layer_name)
logger.debug(e)
return ["WFS", layer_title, wfs_url_quicky,
api_layer, srv_details, btn_lbl]
elif mode == "complete":
# Clean, complete but slower way - OWSLib -------------------------
if srv_details.get("path") == self.cached_wfs.get("srv_path"):
logger.debug("WFS: already in cache")
else:
self.cached_wfs["srv_path"] = srv_details.get("path")
logger.debug("WFS: new service")
pass
# basic checks on service url
try:
wfs = WebFeatureService(wfs_url_getcap)
except ServiceException as e:
logger.error(str(e))
return 0, "WFS - Bad operation: " + wfs_url_getcap, str(e)
except HTTPError as e:
logger.error(str(e))
return 0, "WFS - Service not reached: " + wfs_url_getcap, str(e)
except Exception as e:
return 0, e
# check if GetFeature and DescribeFeatureType operation are available
if not hasattr(wfs, "getfeature") or "GetFeature" not in [op.name for op in wfs.operations]:
self.cached_wfs["GetFeature"] = 0
return 0, "Required GetFeature operation not available in: " + wfs_url_getcap
else:
self.cached_wfs["GetFeature"] = 1
logger.info("GetFeature available")
pass
if "DescribeFeatureType" not in [op.name for op in wfs.operations]:
self.cached_wfs["DescribeFeatureType"] = 0
return 0, "Required DescribeFeatureType operation not available in: " + wfs_url_getcap
else:
self.cached_wfs["DescribeFeatureType"] = 1
logger.info("DescribeFeatureType available")
pass
# check if required layer is present
try:
wfs_lyr = wfs[layer_name]
except KeyError as e:
logger.error("Layer {} not found in WFS service: {}"
.format(layer_name,
wfs_url_getcap))
if geoserver and layer_name in [l.split(":")[1] for l in list(wfs.contents)]:
layer_name = list(wfs.contents)[[l.split(":")[1]
for l in list(wfs.contents)].index(layer_name)]
try:
wfs_lyr = wfs[layer_name]
except KeyError as e:
return (0,
"Layer {} not found in WFS service: {}"
.format(layer_name,
wfs_url_getcap),
e)
# SRS definition
srs_map = custom_tools.get_map_crs()
srs_lyr_new = qsettings.value("/Projections/defaultBehaviour")
srs_lyr_crs = qsettings.value("/Projections/layerDefaultCrs")
srs_qgs_new = qsettings.value("/Projections/projectDefaultCrs")
srs_qgs_otf_on = qsettings.value("/Projections/otfTransformEnabled")
srs_qgs_otf_auto = qsettings.value("/Projections/otfTransformAutoEnable")
# DEV
# print("CRS: ", wms_lyr.crsOptions,
# "For new layers: " + srs_lyr_new + srs_lyr_crs,
# "For new projects: " + srs_qgs_new,
# "OTF enabled: " + srs_qgs_otf_on,
# "OTF smart enabled: " + srs_qgs_otf_auto,
# "Map canvas SRS:" + custom_tools.get_map_crs())
wfs_lyr_crs_epsg = ["{}:{}".format(srs.authority, srs.code)
for srs in wfs_lyr.crsOptions]
self.cached_wfs["CRS"] = wfs_lyr_crs_epsg
if srs_map in wfs_lyr_crs_epsg:
logger.debug("It's a SRS match! With map canvas: " + srs_map)
srs = srs_map
elif srs_qgs_new in wfs_lyr_crs_epsg\
and srs_qgs_otf_on == "false"\
and srs_qgs_otf_auto == "false":
logger.debug("It's a SRS match! With default new project: " + srs_qgs_new)
srs = srs_qgs_new
elif srs_lyr_crs in wfs_lyr_crs_epsg and srs_lyr_new == "useGlobal":
logger.debug("It's a SRS match! With default new layer: " + srs_lyr_crs)
srs = srs_lyr_crs
elif "EPSG:4326" in wfs_lyr_crs_epsg:
logger.debug("It's a SRS match! With standard WGS 84 (EPSG:4326)")
srs = "EPSG:4326"
else:
logger.debug("Map Canvas SRS not available within service CRS.")
srs = wfs_lyr_crs_epsg[0]
# Style definition
# print("Styles: ", wms_lyr.styles, type(wms_lyr.styles))
# lyr_style = wfs_lyr.styles.keys()[0]
# print(lyr_style)
# GetFeature URL
wfs_lyr_url = wfs.getOperationByName('GetFeature').methods
wfs_lyr_url = wfs_lyr_url[0].get("url")
if wfs_lyr_url[-1] != "&":
wfs_lyr_url = wfs_lyr_url + "&"
else:
pass
self.cached_wfs["url"] = wfs_lyr_url
# url construction
try:
wfs_url_params = {"SERVICE": "WFS",
"VERSION": "1.0.0",
"TYPENAME": layer_name,
"SRSNAME": srs,
}
wfs_url_final = wfs_lyr_url + unquote(urlencode(wfs_url_params, "utf8"))
except UnicodeEncodeError:
wfs_url_params = {"SERVICE": "WFS",
"VERSION": "1.0.0",
"TYPENAME": layer_name.decode("latin1"),
"SRSNAME": srs,
}
wfs_url_final = wfs_lyr_url + unquote(urlencode(wfs_url_params))
# method ending
logger.debug(wfs_url_final)
return ["WFS", layer_title, wfs_url_final]
else:
return None
def new_build_wms_url(self, api_layer, srv_details, rsc_type="ds_dyn_lyr_srv", mode="complete"):
"""Reformat the input WMS url so it fits QGIS criterias.
Tests weither all the needed information is provided in the url, and
then build the url in the syntax understood by QGIS.
"""
# local variables
layer_name = api_layer.get("id")
layer_title = api_layer.get("titles")[0].get("value", "WMS Layer")
wms_url_getcap = srv_details.get("path")\
+ "?request=GetCapabilities&service=WMS"
geoserver = "geoserver" in wms_url_getcap
if mode == "quicky":
# let's try a quick & dirty url build
srs_map = custom_tools.get_map_crs()
wms_url_base = srv_details.get("path")
if "?" not in wms_url_base:
wms_url_base = wms_url_base + "?"
else:
pass
# url construction
wms_url_params = {"SERVICE": "WMS",
"VERSION": srv_details.get("formatVersion", "1.3.0"),
"REQUEST": "GetMap",
"layers": layer_name,
"crs": srs_map,
"format": "image/png",
"styles": "",
"url": wms_url_base,
}
wms_url_quicky = unquote(urlencode(wms_url_params, "utf8"))
# prevent encoding errors (#102)
try:
btn_lbl = "WMS : {}".format(layer_title)
return ["WMS", layer_title, wms_url_quicky,
api_layer, srv_details, btn_lbl]
except UnicodeEncodeError as e:
btn_lbl = "WMS : {}".format(layer_name)
logger.debug(e)
return ["WMS", layer_title, wms_url_quicky,
api_layer, srv_details, btn_lbl]
elif mode == "complete":
# Clean, complete but slower way - OWSLib -------------------------
if srv_details.get("path") == self.cached_wms.get("srv_path"):
logger.debug("WMS: already in cache")
else:
self.cached_wms["srv_path"] = srv_details.get("path")
logger.debug("WMS: new service")
pass
# basic checks on service url
try:
wms = WebMapService(wms_url_getcap)
self.cached_wms["Reachable"] = 1
except ServiceException as e:
logger.error(str(e))
self.cached_wms["Reachable"] = 0
return 0, "WMS - Bad operation: " + wms_url_getcap, str(e)
except HTTPError as e:
self.cached_wms["Reachable"] = 0
logger.error(str(e))
return 0, "WMS - Service not reached: " + wms_url_getcap, str(e)
except Exception as e:
self.cached_wms["Reachable"] = 0
logger.error(str(e))
return 0, e
# check if GetMap operation is available
if not hasattr(wms, "getmap") or "GetMap" not in [op.name for op in wms.operations]:
self.cached_wms["GetMap"] = 1
return 0, "Required GetMap operation not available in: "\
+ wms_url_getcap
else:
self.cached_wms["GetMap"] = 0
pass
# check if layer is present and queryable
try:
wms_lyr = wms[layer_name]
except KeyError as e:
logger.error("Layer {} not found in WMS service: {}"
.format(layer_name,
wms_url_getcap))
return (0,
"Layer {} not found in WMS service: {}"
.format(layer_name,
wms_url_getcap), e)
# SRS definition
srs_map = custom_tools.get_map_crs()
srs_lyr_new = qsettings.value("/Projections/defaultBehaviour")
srs_lyr_crs = qsettings.value("/Projections/layerDefaultCrs")
srs_qgs_new = qsettings.value("/Projections/projectDefaultCrs")
srs_qgs_otf_on = qsettings.value("/Projections/otfTransformEnabled")
srs_qgs_otf_auto = qsettings.value("/Projections/otfTransformAutoEnable")
# DEV
# print("CRS: ", wms_lyr.crsOptions,
# "For new layers: " + srs_lyr_new + srs_lyr_crs,
# "For new projects: " + srs_qgs_new,
# "OTF enabled: " + srs_qgs_otf_on,
# "OTF smart enabled: " + srs_qgs_otf_auto,
# "Map canvas SRS:" + custom_tools.get_map_crs())
self.cached_wms["CRS"] = wms_lyr.crsOptions
if srs_map in wms_lyr.crsOptions:
logger.debug("It's a SRS match! With map canvas: " + srs_map)
srs = srs_map
elif srs_qgs_new in wms_lyr.crsOptions\
and srs_qgs_otf_on == "false"\
and srs_qgs_otf_auto == "false":
logger.debug("It's a SRS match! With default new project: " + srs_qgs_new)
srs = srs_qgs_new
elif srs_lyr_crs in wms_lyr.crsOptions and srs_lyr_new == "useGlobal":
logger.debug("It's a SRS match! With default new layer: " + srs_lyr_crs)
srs = srs_lyr_crs
elif "EPSG:4326" in wms_lyr.crsOptions:
logger.debug("It's a SRS match! With standard WGS 84 (EPSG:4326)")
srs = "EPSG:4326"
else:
logger.debug("Map Canvas SRS not available within service CRS.")
srs = wms_lyr.crsOptions[0]
# Format definition
wms_lyr_formats = wms.getOperationByName('GetMap').formatOptions
formats_image = [f.split(" ", 1)[0] for f in wms_lyr_formats
if f in qgis_wms_formats]
self.cached_wms["formats"] = formats_image
if "image/png" in formats_image:
layer_format = "image/png"
elif "image/jpeg" in formats_image:
layer_format = "image/jpeg"
else:
layer_format = formats_image[0]
# Style definition
lyr_style = wms_lyr.styles.keys()[0]
# GetMap URL
wms_lyr_url = wms.getOperationByName('GetMap').methods
wms_lyr_url = wms_lyr_url[0].get("url")
if wms_lyr_url[-1] == "&":
wms_lyr_url = wms_lyr_url[:-1]
else:
pass
self.cached_wms["url"] = wms_lyr_url
# url construction
try:
wms_url_params = {"SERVICE": "WMS",
"VERSION": srv_details.get("formatVersion", "1.3.0"),
"REQUEST": "GetMap",
"layers": layer_name,
"crs": srs,
"format": layer_format,
"styles": "",
# "styles": lyr_style,
# "url": srv_details.get("path"),
"url": wms_lyr_url,
}
wms_url_final = unquote(urlencode(wms_url_params, "utf8"))
except UnicodeEncodeError:
wms_url_params = {"SERVICE": "WMS",
"VERSION": srv_details.get("formatVersion", "1.3.0"),
"REQUEST": "GetMap",
"layers": layer_name.decode("latin1"),
"crs": srs,
"format": layer_format,
"styles": "",
# "styles": lyr_style,
# "url": srv_details.get("path"),
"url": wms_lyr_url,
}
wms_url_final = unquote(urlencode(wms_url_params, "utf8"))
# method ending
return ["WMS", layer_title, wms_url_final]
else:
return None
def build_wmts_url(self, api_layer, srv_details, rsc_type="ds_dyn_lyr_srv", mode="complete"):
"""Format the input WMTS URL to fit QGIS criterias.
Retrieve GetCapabilities from information transmitted by Isogeo API
to complete URL syntax.
"""
# local variables
layer_name = api_layer.get("id")
layer_title = api_layer.get("titles")[0].get("value", "WMTS Layer")
wmts_url_getcap = srv_details.get("path")\
+ "?request=GetCapabilities&service=WMTS"
geoserver = "geoserver" in wmts_url_getcap
# basic checks on service url
try:
wmts = WebMapTileService(wmts_url_getcap)
except TypeError as e:
logger.error("WMTS - OWSLib mixing str and unicode args", e)
wmts = WebMapTileService(unicode(wmts_url_getcap))
except ServiceException as e:
logger.error(e)
return 0, "WMTS - Bad operation: " + wmts_url_getcap, str(e)
except HTTPError as e:
logger.error(e)
return 0, "WMTS - Service not reached: " + wmts_url_getcap, e
except Exception as e:
logger.error("WMTS - {}: {}".format(wmts_url_getcap, e))
return 0, "WMTS - Service not reached: " + wmts_url_getcap, e
# check if GetTile operation is available
if not hasattr(wmts, "gettile") or "GetTile" not in [op.name for op in wmts.operations]:
return 0, "Required GetTile operation not available in: " + wmts_url_getcap
else:
logger.debug("GetTile available")
pass
# check if layer is present and queryable
try:
wmts_lyr = wmts[layer_name]
layer_title = wmts_lyr.title
layer_id = wmts_lyr.id
except KeyError as e:
logger.error("Layer {} not found in WMTS service: {}"
.format(layer_name,
wmts_url_getcap))
return (0,
"Layer {} not found in WMS service: {}"
.format(layer_name,
wmts_url_getcap), e)
# Tile Matrix Set & SRS
srs_map = custom_tools.get_map_crs()
def_tile_matrix_set = wmts_lyr.tilematrixsets[0]
if srs_map in wmts_lyr.tilematrixsets:
logger.debug("WMTS - It's a SRS match! With map canvas: " + srs_map)
tile_matrix_set = wmts.tilematrixsets.get(srs_map).identifier
srs = srs_map
elif "EPSG:4326" in wmts_lyr.tilematrixsets:
logger.debug("WMTS - It's a SRS match! With standard WGS 84 (4326)")
tile_matrix_set = wmts.tilematrixsets.get("EPSG:4326").identifier
srs = "EPSG:4326"
elif "EPSG:900913" in wmts_lyr.tilematrixsets:
logger.debug("WMTS - It's a SRS match! With Google (900913)")
tile_matrix_set = wmts.tilematrixsets.get("EPSG:900913").identifier
srs = "EPSG:900913"
else:
logger.debug("WMTS - Searched SRS not available within service CRS.")
tile_matrix_set = wmts.tilematrixsets.get(def_tile_matrix_set).identifier
srs = tile_matrix_set
# Format definition
wmts_lyr_formats = wmts.getOperationByName('GetTile').formatOptions
formats_image = [f.split(" ", 1)[0] for f in wmts_lyr_formats
if f in qgis_wms_formats]
if len(formats_image):
if "image/png" in formats_image:
layer_format = "image/png"
elif "image/jpeg" in formats_image:
layer_format = "image/jpeg"
else:
layer_format = formats_image[0]
else:
logger.debug("WMTS - No format available among preferred by QGIS.")
layer_format = "image/png"
# Style definition
lyr_style = wmts_lyr.styles.keys()[0]
# GetTile URL
wmts_lyr_url = wmts.getOperationByName('GetTile').methods
wmts_lyr_url = wmts_lyr_url[0].get("url")
if wmts_lyr_url[-1] == "&":
wmts_lyr_url = wmts_lyr_url[:-1]
else:
pass
# construct URL
wmts_url_params = {"SERVICE": "WMTS",
"VERSION": "1.0.0",
"REQUEST": "GetCapabilities",
"layers": layer_id,
"crs": srs,
"format": layer_format,
"styles": "",
"tileMatrixSet": tile_matrix_set,
"url": wmts_lyr_url,
}
wmts_url_final = unquote(urlencode(wmts_url_params))
logger.debug(wmts_url_final)
# prevent encoding errors (#102)
# try:
# layer_title = str(layer_title)
# except UnicodeEncodeError as e:
# layer_title = layer_title.encode("latin1")
# logger.debug(e)
# except UnicodeDecodeError as e:
# layer_title = layer_title.decode("latin1")
# logger.debug(e)
# method ending
return ["WMTS", layer_title, wmts_url_final]
# return QgsRasterLayer(wms_url_final, layer_title, 'wms')
PK @Ir/_= = ' isogeo_search_engine/modules/isogeo.qml
000ID00generatedlayout2
PK YrJ:{Y Y + isogeo_search_engine/resources/arrows-h.svgPK PI?:l l + isogeo_search_engine/resources/asterisk.svg
PK PIx &