├── .github └── FUNDING.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── docs ├── Makefile ├── conf.py ├── index.rst └── modules.rst ├── setup.py └── src ├── PyWSD ├── __init__.py ├── templates │ ├── ws-discovery__probe.xml │ ├── ws-discovery__resolve.xml │ ├── ws-eventing__get_status.xml │ ├── ws-eventing__renew.xml │ ├── ws-eventing__subscribe.xml │ ├── ws-eventing__unsubscribe.xml │ ├── ws-print__get_printer_elements.xml │ ├── ws-scan__cancel_job.xml │ ├── ws-scan__create_scan_job.xml │ ├── ws-scan__get_active_jobs.xml │ ├── ws-scan__get_job_elements.xml │ ├── ws-scan__get_job_history.xml │ ├── ws-scan__get_scanner_elements.xml │ ├── ws-scan__retrieve_image.xml │ ├── ws-scan__scan_available_event_subscribe.xml │ ├── ws-scan__validate_scan_ticket.xml │ └── ws-transfer__get.xml ├── wsd_common.py ├── wsd_discovery__operations.py ├── wsd_discovery__parsers.py ├── wsd_discovery__structures.py ├── wsd_eventing__operations.py ├── wsd_globals.py ├── wsd_print__operations.py ├── wsd_scan__events.py ├── wsd_scan__operations.py ├── wsd_scan__parsers.py ├── wsd_scan__structures.py ├── wsd_transfer__operations.py ├── wsd_transfer__structures.py └── xml_helpers.py └── bin └── wsdtool /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: roncapat 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | specs/* 2 | *.pyc 3 | *.jpeg 4 | *.bmp 5 | .idea/* 6 | venv/* 7 | docs/_build 8 | /log 9 | /build 10 | /dist 11 | /excluded 12 | *.egg-info -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project maintaniner at ronca.pat@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | I'm a student, and I don't have a job yet, so if you like my repo, please consider 2 | to gift me a cup of coffee :coffee: 3 | 4 | [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)]( 5 | https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=YRKMLJXGDD7XN) 6 | 7 | 8 | # PyWSD 9 | Web Services for Devices (WSD) tools and utilities for cross platform support. 10 | 11 | ## Documentation 12 | You can browse the documentation on [readthedocs.io](http://wsd-python.readthedocs.io/en/master/index.html). 13 | 14 | ## Abstract 15 | The Web Services for Devices is a set of specifications aimed to handle network 16 | communication between devices which offer some kind of functionality or need to signal events. 17 | There's a discovery protocol, a way to retrieve a list of services from endpoints, 18 | and a set of rules built on top of XML/SOAP messages over UDP for commands/events. 19 | 20 | Windows uses WSD as a way to discover and interact with a wide range of printers 21 | and scanners nowadays. Other WSD applications are less-known, but this project 22 | aims to cover the standard with a generic set of tools suitable even for those devices. 23 | 24 | Linux and Mac OS users everyday have to deal with a not-so-good (or absent) full support 25 | for printers/scanners. For example, Canon does not support Linux at all, and distributes 26 | bugged drivers that are not fully open source, nor integrates well with existing and 27 | coherent Linux printing and scanning frameworks. Device-initiated operations are not 28 | supported at all. This is going to change: WSD standards are not well-known, but fortunately 29 | they are documented, and easy to reverse-engineer if needed. 30 | 31 | So my idea is to get a good comprehension of the protocol, implement a draft library 32 | and a set of associated tools in python, then test it until the implementation is mature. 33 | The natural next step will be C implementation, that will finally enable the SANE and CUPS 34 | wsd backends implementations. 35 | 36 | A library for simulating/implementing new WSD devices could also be developed, and it would 37 | allow seamless integration of devices shared from a linux instance and a Windows-enabled 38 | client, for example. 39 | 40 | 41 | ## Developer notes 42 | Required python version: **3.6**\ 43 | Docstring style complies [IntelliJ PyCharm suggestions]( 44 | https://www.jetbrains.com/help/pycharm/type-hinting-in-pycharm.html#legacy) 45 | 46 | ## Project status 47 | As you can see, I'm the only developer. I need people to test my library, develop tools 48 | from it (some demo bits are among the modules, but they're just for on-the-fly debug 49 | while developing). 50 | 51 | Here's the list of targets for now: 52 | 53 | * Python library for scanners (70% done IMHO) 54 | * C library for scanners 55 | * SANE backend for scanners 56 | * Linux daemon for device-initiated scans 57 | 58 | 59 | ## Protocol public resources (PDF/DOC/HTML from MSDN/W3C/SOAP) 60 | [WS-Discovery](http://specs.xmlsoap.org/ws/2005/04/discovery/ws-discovery.pdf)\ 61 | [WS-Transfer](https://www.w3.org/Submission/WS-Transfer)\ 62 | [PNP-X](http://download.microsoft.com/download/a/f/7/af7777e5-7dcd-4800-8a0a-b18336565f5b/PnPX-spec.doc) 63 | 64 | [WSD-Profiles](http://specs.xmlsoap.org/ws/2006/02/devprof/devicesprofile.pdf) 65 | 66 | [WS-Print](http://download.microsoft.com/download/E/9/7/E974CFCB-4B3B-40CC-AF92-4F7F84477F0B/Printer.zip)\ 67 | [WS-Scan](http://download.microsoft.com/download/9/C/5/9C5B2167-8017-4BAE-9FDE-D599BAC8184A/ScanService.zip) 68 | 69 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python3 -msphinx 7 | SPHINXPROJ = PyWSD 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/stable/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | 11 | # If extensions (or modules to document with autodoc) are in another directory, 12 | # add these directories to sys.path here. If the directory is relative to the 13 | # documentation root, use os.path.abspath to make it absolute, like shown here. 14 | # 15 | import os 16 | import sys 17 | sys.path.append(os.path.abspath('../')) 18 | sys.path.append(os.path.abspath('./')) 19 | sys.path.append(os.path.abspath('../src')) 20 | 21 | # -- Project information ----------------------------------------------------- 22 | 23 | project = u'PyWSD' 24 | copyright = u'2018, Patrick Roncagliolo' 25 | author = u'Patrick Roncagliolo' 26 | 27 | # The short X.Y version 28 | version = u'' 29 | # The full version, including alpha/beta/rc tags 30 | release = u'' 31 | 32 | 33 | # -- General configuration --------------------------------------------------- 34 | 35 | # If your documentation needs a minimal Sphinx version, state it here. 36 | # 37 | # needs_sphinx = '1.0' 38 | 39 | # Add any Sphinx extension module names here, as strings. They can be 40 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 41 | # ones. 42 | extensions = [ 43 | 'sphinx.ext.autodoc', 44 | ] 45 | 46 | # Add any paths that contain templates here, relative to this directory. 47 | templates_path = ['_templates'] 48 | 49 | # The suffix(es) of source filenames. 50 | # You can specify multiple suffix as a list of string: 51 | # 52 | # source_suffix = ['.rst', '.md'] 53 | source_suffix = '.rst' 54 | 55 | # The master toctree document. 56 | master_doc = 'index' 57 | 58 | # The language for content autogenerated by Sphinx. Refer to documentation 59 | # for a list of supported languages. 60 | # 61 | # This is also used if you do content translation via gettext catalogs. 62 | # Usually you set "language" from the command line for these cases. 63 | language = None 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | # This pattern also affects html_static_path and html_extra_path . 68 | exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store'] 69 | 70 | # The name of the Pygments (syntax highlighting) style to use. 71 | pygments_style = 'sphinx' 72 | 73 | 74 | # -- Options for HTML output ------------------------------------------------- 75 | 76 | # The theme to use for HTML and HTML Help pages. See the documentation for 77 | # a list of builtin themes. 78 | # 79 | html_theme = "sphinx_rtd_theme" 80 | 81 | # Theme options are theme-specific and customize the look and feel of a theme 82 | # further. For a list of options available for each theme, see the 83 | # documentation. 84 | # 85 | # html_theme_options = {} 86 | 87 | # Add any paths that contain custom static files (such as style sheets) here, 88 | # relative to this directory. They are copied after the builtin static files, 89 | # so a file named "default.css" will overwrite the builtin "default.css". 90 | html_static_path = ['_static'] 91 | 92 | # Custom sidebar templates, must be a dictionary that maps document names 93 | # to template names. 94 | # 95 | # The default sidebars (for documents that don't match any pattern) are 96 | # defined by theme itself. Builtin themes are using these templates by 97 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 98 | # 'searchbox.html']``. 99 | # 100 | # html_sidebars = {} 101 | 102 | 103 | # -- Options for HTMLHelp output --------------------------------------------- 104 | 105 | # Output file base name for HTML help builder. 106 | htmlhelp_basename = 'PyWSDdoc' 107 | 108 | 109 | # -- Options for LaTeX output ------------------------------------------------ 110 | 111 | latex_elements = { 112 | # The paper size ('letterpaper' or 'a4paper'). 113 | # 114 | # 'papersize': 'letterpaper', 115 | 116 | # The font size ('10pt', '11pt' or '12pt'). 117 | # 118 | # 'pointsize': '10pt', 119 | 120 | # Additional stuff for the LaTeX preamble. 121 | # 122 | # 'preamble': '', 123 | 124 | # Latex figure (float) alignment 125 | # 126 | # 'figure_align': 'htbp', 127 | } 128 | 129 | # Grouping the document tree into LaTeX files. List of tuples 130 | # (source start file, target name, title, 131 | # author, documentclass [howto, manual, or own class]). 132 | latex_documents = [ 133 | (master_doc, 'PyWSD.tex', u'PyWSD Documentation', 134 | u'Patrick Roncagliolo', 'manual'), 135 | ] 136 | 137 | 138 | # -- Options for manual page output ------------------------------------------ 139 | 140 | # One entry per manual page. List of tuples 141 | # (source start file, name, description, authors, manual section). 142 | man_pages = [ 143 | (master_doc, 'pywsd', u'PyWSD Documentation', 144 | [author], 1) 145 | ] 146 | 147 | 148 | # -- Options for Texinfo output ---------------------------------------------- 149 | 150 | # Grouping the document tree into Texinfo files. List of tuples 151 | # (source start file, target name, title, author, 152 | # dir menu entry, description, category) 153 | texinfo_documents = [ 154 | (master_doc, 'PyWSD', u'PyWSD Documentation', 155 | author, 'PyWSD', 'One line description of project.', 156 | 'Miscellaneous'), 157 | ] 158 | 159 | 160 | # -- Extension configuration ------------------------------------------------- -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. PyWSD documentation master file, created by 2 | sphinx-quickstart on Sun Feb 25 18:50:07 2018. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to PyWSD's documentation! 7 | ================================= 8 | 9 | PyWSD is a library for interacting with WSD-enabled devices in your network. 10 | WSD stands for Web Services for Devices, a set of technologies based on the exchange 11 | of XML messages between devices such as a PC and a network printer, but in fact the 12 | scope of application is theoretically broader than just printers and scanners: you could 13 | query a WSD-enabled thermometer, for example. 14 | 15 | .. toctree:: 16 | :maxdepth: 2 17 | 18 | modules 19 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | Structures 2 | =========== 3 | 4 | Discovery 5 | ................................. 6 | 7 | .. automodule:: PyWSD.wsd_discovery__structures 8 | :members: 9 | 10 | Transfer 11 | ................................ 12 | 13 | .. automodule:: PyWSD.wsd_transfer__structures 14 | :members: 15 | 16 | Scan 17 | ............................ 18 | 19 | .. automodule:: PyWSD.wsd_scan__structures 20 | :members: 21 | 22 | 23 | Operations 24 | ========== 25 | 26 | Discovery 27 | ................................. 28 | 29 | .. automodule:: PyWSD.wsd_discovery__operations 30 | :members: 31 | :show-inheritance: 32 | 33 | Transfer 34 | ................................ 35 | 36 | .. automodule:: PyWSD.wsd_transfer__operations 37 | :members: 38 | :show-inheritance: 39 | 40 | Eventing 41 | ................................ 42 | 43 | .. automodule:: PyWSD.wsd_eventing__operations 44 | :members: 45 | :show-inheritance: 46 | 47 | Scan 48 | ............................ 49 | 50 | .. automodule:: PyWSD.wsd_scan__operations 51 | :members: 52 | :show-inheritance: 53 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | import os 3 | 4 | setup( 5 | name='PyWSD', 6 | version='0.21', 7 | package_dir={'': "src"}, 8 | packages=['PyWSD'], 9 | python_requires='>=3.6', 10 | install_requires=["argparse", "uuid", "lxml", "requests", "Pillow", "python-dateutil", "sphinx_rtd_theme", "urllib3"], 11 | url='https://github.com/roncapat/WSD-python', 12 | license='GPL v3.0', 13 | author='Patrick Roncagliolo', 14 | author_email='ronca.pat@gmail.com', 15 | description='A library for Web Services for Devices support', 16 | package_data={'PyWSD': ["templates/*.xml"]}, 17 | scripts=['src/bin/wsdtool'] 18 | ) 19 | -------------------------------------------------------------------------------- /src/PyWSD/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roncapat/WSD-python/ba348399db5fe476ba4dd5ed824bef4351dcf23c/src/PyWSD/__init__.py -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-discovery__probe.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe 7 | {{MSG_ID}} 8 | 9 | {{FROM}} 10 | 11 | urn:schemas-xmlsoap-org:ws:2005:04:discovery 12 | {{FROM}} 13 | 14 | 15 | 16 | {{OPT_TYPES}} 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-discovery__resolve.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | http://schemas.xmlsoap.org/ws/2005/04/discovery/Resolve 7 | 8 | {{FROM}} 9 | 10 | urn:schemas-xmlsoap-org:ws:2005:04:discovery 11 | {{MSG_ID}} 12 | {{FROM}} 13 | 14 | 15 | 16 | 17 | {{EP_ADDR}} 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-eventing__get_status.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | {{FROM}} 9 | 10 | {{TO}} 11 | http://schemas.xmlsoap.org/ws/2004/08/eventing/GetStatus 12 | {{MSG_ID}} 13 | 14 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 15 | 16 | {{SUBSCRIPTION_ID}} 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-eventing__renew.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | {{FROM}} 9 | 10 | {{TO}} 11 | http://schemas.xmlsoap.org/ws/2004/08/eventing/Renew 12 | {{MSG_ID}} 13 | 14 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 15 | 16 | {{SUBSCRIPTION_ID}} 17 | 18 | 19 | 20 | {{EXPIRES}} 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-eventing__subscribe.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | {{FROM}} 9 | 10 | {{TO}} 11 | http://schemas.xmlsoap.org/ws/2004/08/eventing/Subscribe 12 | {{MSG_ID}} 13 | 14 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 15 | 16 | 17 | 18 | 19 | 20 | 21 | {{NOTIFY_ADDR}} 22 | 23 | 24 | {{EVENT}} 25 | {{OPT_EXPIRATION}} 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-eventing__unsubscribe.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | {{FROM}} 9 | 10 | {{TO}} 11 | http://schemas.xmlsoap.org/ws/2004/08/eventing/Unsubscribe 12 | {{MSG_ID}} 13 | 14 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 15 | 16 | {{SUBSCRIPTION_ID}} 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-print__get_printer_elements.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | {{TO}} 7 | http://schemas.microsoft.com/windows/2006/08/wdp/print/GetPrinterElements 8 | {{MSG_ID}} 9 | 10 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 11 | 12 | 13 | {{FROM}} 14 | 15 | 16 | 17 | 18 | 19 | pri:PrinterStatus 20 | pri:PrinterDescription 21 | pri:PrinterConfiguration 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__cancel_job.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | {{TO}} 7 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/CancelJob 8 | 9 | {{FROM}} 10 | 11 | {{MSG_ID}} 12 | 13 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 14 | 15 | 16 | 17 | 18 | {{JOB_ID}} 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__create_scan_job.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | {{TO}} 8 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/CreateScanJob 9 | {{MSG_ID}} 10 | 11 | {{FROM}} 12 | 13 | 14 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 15 | 16 | 17 | 18 | 19 | {{SCAN_ID}} 20 | {{DEST_TOKEN}} 21 | 22 | 23 | {{JOB_NAME}} 24 | {{USER_NAME}} 25 | {{JOB_INFO}} 26 | 27 | 28 | {{FORMAT}} 29 | {{QUALITY_FACTOR}} 30 | {{IMG_NUM}} 31 | {{INPUT_SRC}} 32 | {{CONTENT_TYPE}} 33 | 34 | {{SIZE_AUTODETECT}} 35 | 36 | {{INPUT_W}} 37 | {{INPUT_H}} 38 | 39 | 40 | 41 | {{AUTO_EXPOSURE}} 42 | 43 | {{CONTRAST}} 44 | {{BRIGHTNESS}} 45 | {{SHARPNESS}} 46 | 47 | 48 | 49 | {{SCALING_W}} 50 | {{SCALING_H}} 51 | 52 | {{ROTATION}} 53 | 54 | 55 | 56 | {{FRONT_X_OFFSET}} 57 | {{FRONT_Y_OFFSET}} 58 | {{FRONT_SIZE_W}} 59 | {{FRONT_SIZE_H}} 60 | 61 | {{FRONT_COLOR}} 62 | 63 | {{FRONT_RES_W}} 64 | {{FRONT_RES_H}} 65 | 66 | 67 | 68 | 69 | {{BACK_X_OFFSET}} 70 | {{BACK_Y_OFFSET}} 71 | {{BACK_SIZE_W}} 72 | {{BACK_SIZE_H}} 73 | 74 | {{BACK_COLOR}} 75 | 76 | {{BACK_RES_W}} 77 | {{BACK_RES_H}} 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__get_active_jobs.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | {{TO}} 7 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/GetActiveJobs 8 | 9 | {{FROM}} 10 | 11 | {{MSG_ID}} 12 | 13 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__get_job_elements.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | {{TO}} 7 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/GetJobElements 8 | {{MSG_ID}} 9 | 10 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 11 | 12 | 13 | {{FROM}} 14 | 15 | 16 | 17 | 18 | {{JOB_ID}} 19 | 20 | sca:JobStatus 21 | sca:ScanTicket 22 | sca:Documents 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__get_job_history.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | {{TO}} 7 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/GetJobHistory 8 | 9 | {{FROM}} 10 | 11 | {{MSG_ID}} 12 | 13 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__get_scanner_elements.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | {{TO}} 7 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/GetScannerElements 8 | {{MSG_ID}} 9 | 10 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 11 | 12 | 13 | {{FROM}} 14 | 15 | 16 | 17 | 18 | 19 | sca:ScannerStatus 20 | sca:ScannerDescription 21 | sca:ScannerConfiguration 22 | sca:DefaultScanTicket 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__retrieve_image.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | {{TO}} 7 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/RetrieveImage 8 | {{MSG_ID}} 9 | 10 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 11 | 12 | 13 | {{FROM}} 14 | 15 | 16 | 17 | 18 | {{JOB_ID}} 19 | {{JOB_TOKEN}} 20 | 21 | {{DOC_DESCR}} 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__scan_available_event_subscribe.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | {{FROM}} 9 | 10 | {{TO}} 11 | http://schemas.xmlsoap.org/ws/2004/08/eventing/Subscribe 12 | {{MSG_ID}} 13 | 14 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 15 | 16 | 17 | 18 | 19 | 20 | 21 | {{NOTIFY_ADDR}} 22 | 23 | 24 | {{OPT_EXPIRATION}} 25 | 26 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScanAvailableEvent 27 | 28 | 29 | 30 | {{DISPLAY_STR}} 31 | {{CONTEXT}} 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-scan__validate_scan_ticket.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | {{TO}} 7 | http://schemas.microsoft.com/windows/2006/08/wdp/scan/ValidateScanTicket 8 | 9 | {{FROM}} 10 | 11 | {{MSG_ID}} 12 | 13 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 14 | 15 | 16 | 17 | 18 | 19 | 20 | {{JOB_NAME}} 21 | {{USER_NAME}} 22 | {{JOB_INFO}} 23 | 24 | 25 | {{FORMAT}} 26 | {{QUALITY_FACTOR}} 27 | {{IMG_NUM}} 28 | {{INPUT_SRC}} 29 | {{CONTENT_TYPE}} 30 | 31 | {{SIZE_AUTODETECT}} 32 | 33 | {{INPUT_W}} 34 | {{INPUT_H}} 35 | 36 | 37 | 38 | {{AUTO_EXPOSURE}} 39 | 40 | {{CONTRAST}} 41 | {{BRIGHTNESS}} 42 | {{SHARPNESS}} 43 | 44 | 45 | 46 | {{SCALING_W}} 47 | {{SCALING_H}} 48 | 49 | {{ROTATION}} 50 | 51 | 52 | 53 | {{FRONT_X_OFFSET}} 54 | {{FRONT_Y_OFFSET}} 55 | {{FRONT_SIZE_W}} 56 | {{FRONT_SIZE_H}} 57 | 58 | {{FRONT_COLOR}} 59 | 60 | {{FRONT_RES_W}} 61 | {{FRONT_RES_H}} 62 | 63 | 64 | 65 | 66 | {{BACK_X_OFFSET}} 67 | {{BACK_Y_OFFSET}} 68 | {{BACK_SIZE_W}} 69 | {{BACK_SIZE_H}} 70 | 71 | {{BACK_COLOR}} 72 | 73 | {{BACK_RES_W}} 74 | {{BACK_RES_H}} 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /src/PyWSD/templates/ws-transfer__get.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | {{TO}} 6 | http://schemas.xmlsoap.org/ws/2004/09/transfer/Get 7 | {{MSG_ID}} 8 | 9 | http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 10 | 11 | 12 | {{FROM}} 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_common.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | import datetime 5 | import os 6 | import random 7 | import time 8 | import typing 9 | import uuid 10 | 11 | import lxml.etree as etree 12 | import requests 13 | 14 | from PyWSD import wsd_globals 15 | 16 | NSMAP = {"soap": "http://www.w3.org/2003/05/soap-envelope", 17 | "mex": "http://schemas.xmlsoap.org/ws/2004/09/mex", 18 | "wsa": "http://schemas.xmlsoap.org/ws/2004/08/addressing", 19 | "wsd": "http://schemas.xmlsoap.org/ws/2005/04/discovery", 20 | "wse": "http://schemas.xmlsoap.org/ws/2004/08/eventing", 21 | "wsdp": "http://schemas.xmlsoap.org/ws/2006/02/devprof", 22 | "i": "http://printer.example.org/2003/imaging", 23 | "pri": "http://schemas.microsoft.com/windows/2006/08/wdp/print", 24 | "sca": "http://schemas.microsoft.com/windows/2006/08/wdp/scan", 25 | "pnpx": "http://schemas.microsoft.com/windows/pnpx/2005/10", 26 | "df": "http://schemas.microsoft.com/windows/2008/09/devicefoundation"} 27 | 28 | headers = {'user-agent': 'WSDAPI', 'content-type': 'application/soap+xml'} 29 | log_path = "../log" 30 | 31 | parser = etree.XMLParser(remove_blank_text=True) 32 | 33 | 34 | def gen_urn() \ 35 | -> str: 36 | """ 37 | Generate a URN. It can be used as device id and/or message id 38 | 39 | :return: a string of the form "urn:uuid:*************************" 40 | :rtype: str 41 | """ 42 | return "urn:uuid:" + str(uuid.uuid4()) 43 | 44 | 45 | # TODO: replace dumb text substitution with xml tree manipulation 46 | def message_from_file(fname: str, 47 | **kwargs) \ 48 | -> str: 49 | """ 50 | Loads an XML template file, minifies it, and fills it with values passed in the kwargs map. 51 | 52 | :param fname: the path of the file to load 53 | :type fname: str 54 | :param kwargs: the dictionary containing the values needed to fill the loaded XML template 55 | :return: a string representation of the processed xml file 56 | :rtype: str 57 | """ 58 | req = ''.join([l.strip() + ' ' for l in open(fname).readlines()]) \ 59 | .replace('\n', '') \ 60 | .replace('\r', '') 61 | for k in kwargs: 62 | req = req.replace('{{' + k + '}}', str(kwargs[k])) 63 | req = req.replace('{{MSG_ID}}', gen_urn()) 64 | return req 65 | 66 | 67 | def indent(text: str) \ 68 | -> str: 69 | """ 70 | Indent (multiline) text with tabs 71 | :param text: the text to indent 72 | :type text: str 73 | :return: the indented text 74 | :rtype: str 75 | """ 76 | s = "" 77 | for l in text.splitlines(): 78 | s += "\t%s\n" % l 79 | return s 80 | 81 | 82 | def abs_path(relpath: str) \ 83 | -> str: 84 | """ 85 | Obtain the absolute path of a file or folder, given its relative path from PyWSD directory. 86 | :param relpath: the relative path 87 | :return: the absolute path 88 | """ 89 | return os.path.abspath(os.path.join(os.path.dirname(__file__), relpath)) 90 | 91 | 92 | def soap_post_unicast(addr: str, 93 | data: str) \ 94 | -> typing.Union[str, None]: 95 | """ 96 | Send a SOAP message as an HTTP POST request. 97 | Implements the retry mechanism specified in the SOAP-over-UDP specification. 98 | :param addr: the address to send the message to 99 | :type addr: str 100 | :param data: the message content 101 | :type data: str 102 | :return: the reply message, if any 103 | :rtype: str | None 104 | """ 105 | min_delay = 50 106 | max_delay = 250 107 | upper_delay = 500 108 | try: 109 | repeat = 2 110 | t = random.uniform(min_delay, max_delay) 111 | while repeat: 112 | try: 113 | return requests.post(addr, headers=headers, data=data, timeout=2).content 114 | except requests.Timeout: 115 | time.sleep(t / 1000.0) 116 | t = t * 2 if t * 2 < upper_delay else upper_delay 117 | repeat -= 1 118 | return None 119 | except requests.ConnectionError: 120 | return None 121 | 122 | 123 | def submit_request(addrs: typing.Set[str], 124 | xml_template: str, 125 | fields_map: typing.Dict[str, str]) \ 126 | -> etree.ElementTree: 127 | """ 128 | Send a wsd xml/soap request to the specified device, and wait for response. 129 | Multiple addresses could be provided: the message will be sent to each one until 130 | the device replies. 131 | 132 | :param addrs: the addresses of the wsd service 133 | :type addrs: {str} 134 | :param xml_template: the *name* of the template file to use as payload.\ 135 | Should be of the form "prefix__some_words_for_description.xml" 136 | :type xml_template: str 137 | :param fields_map: the dictionary containing the values needed to fill the loaded XML template 138 | :type fields_map: {str: str} 139 | :return: the full XML response message 140 | :rtype: lxml.etree.ElementTree 141 | """ 142 | op_name = " ".join(xml_template.split("__")[1].split(".")[0].split("_")).upper() 143 | data = message_from_file(abs_path("templates/%s" % xml_template), **fields_map) 144 | 145 | if wsd_globals.debug: 146 | r = etree.fromstring(data.encode("ASCII"), parser=parser) 147 | print('##\n## %s REQUEST\n##\n' % op_name) 148 | log_xml(r) 149 | print(etree.tostring(r, pretty_print=True, xml_declaration=True).decode("ASCII")) 150 | 151 | for addr in addrs: 152 | # TODO: handle ipv6 link-local addresses, remember to specify interface in URI 153 | # requests.post('http://[fe80::4aba:4eff:fec9:3d84%wlp3s0]:3911/', ...) 154 | r = soap_post_unicast(addr, data) 155 | if r is None: 156 | continue 157 | 158 | x = etree.fromstring(r) 159 | 160 | if wsd_globals.debug: 161 | print('##\n## %s RESPONSE\n##\n' % op_name) 162 | log_xml(x) 163 | print(etree.tostring(x, pretty_print=True, xml_declaration=True).decode("ASCII")) 164 | 165 | return x 166 | 167 | raise StopIteration 168 | 169 | 170 | def check_fault(x: etree.ElementTree) \ 171 | -> bool: 172 | """ 173 | Check if this soap message represents a Fault or not 174 | 175 | :param x: an xml tree obtained by parsing a wsd service reply 176 | :type x: lxml.etree.ElementTree 177 | :return: True if a fault message is detected, False otherwise 178 | :rtype: bool 179 | """ 180 | if get_action_id(x) == 'http://schemas.xmlsoap.org/ws/2004/08/addressing/fault': 181 | code = get_xml_str(x, ".//soap:Code/soap:Value") 182 | subcode = get_xml_str(x, ".//soap:Subcode/soap:Value") 183 | reason = get_xml_str(x, ".//soap:Reason/soap:Text") 184 | detail = get_xml_str(x, ".//soap:Detail") 185 | if wsd_globals.debug: 186 | print('##\n## FAULT\n##\n') 187 | print("Code: %s\n" % code) 188 | print("Subcode: %s\n" % subcode) 189 | print("Reason: %s\n" % reason) 190 | print("Details: %s\n" % detail) 191 | return True 192 | else: 193 | return False 194 | 195 | 196 | def xml_find(xml_tree: etree.ElementTree, 197 | query: str) \ 198 | -> typing.Union[etree.ElementTree, None]: 199 | """ 200 | Wrapper for etree.find() method. When parsing wsd xml/soap messages, you should use this wrapper, 201 | because it encapsulates all the xml namespaces needed and avoids coding errors. 202 | 203 | :param xml_tree: the etree element to search in 204 | :type xml_tree: lxml.etree.ElementTree 205 | :param query: the XPath query 206 | :type query: str 207 | :return: the searched etree if found, or None otherwise 208 | :rtype: lxml.etree.ElementTree | None 209 | """ 210 | return xml_tree.find(query, NSMAP) 211 | 212 | 213 | def xml_findall(xml_tree: etree.ElementTree, 214 | query: str) \ 215 | -> typing.Union[etree.ElementTree, None]: 216 | """ 217 | Wrapper for etree.findall() method. When parsing wsd xml/soap messages, you should use this wrapper, 218 | because it encapsulates all the xml namespaces needed and avoids coding errors. 219 | 220 | :param xml_tree: the etree element to search in 221 | :type xml_tree: lxml.etree.ElementTree 222 | :param query: the XPath query 223 | :type query: str 224 | :return: a list of searched etrees if found, or None otherwise 225 | :rtype: lxml.etree.ElementTree | None 226 | """ 227 | return xml_tree.findall(query, NSMAP) 228 | 229 | 230 | def get_xml_str(xml_tree: etree.ElementTree, 231 | query: str) \ 232 | -> typing.Union[str, None]: 233 | """ 234 | Search for the specified node and extract the contained text. 235 | 236 | :param xml_tree: the etree element to search in 237 | :type xml_tree: lxml.etree.ElementTree 238 | :param query: the XPath query 239 | :type query: str 240 | :return: the text contained in the node, if any 241 | :rtype: str | None 242 | """ 243 | q = xml_find(xml_tree, query) 244 | return q.text if q is not None else None 245 | 246 | 247 | def get_xml_str_set(xml_tree: etree.ElementTree, 248 | query: str) \ 249 | -> typing.Union[typing.Set[str], None]: 250 | """ 251 | Search for the specified node and extract the contained strings. 252 | The text in the node is splitted considering standard separators. 253 | 254 | :param xml_tree: the etree element to search in 255 | :type xml_tree: lxml.etree.ElementTree 256 | :param query: the XPath query 257 | :type query: str 258 | :return: the strings contained in the node, if any 259 | :rtype: {str} | None 260 | """ 261 | q = xml_find(xml_tree, query) 262 | return set(q.text.split()) if q is not None else None 263 | 264 | 265 | def get_xml_int(xml_tree: etree.ElementTree, 266 | query: str) \ 267 | -> typing.Union[int, None]: 268 | q = xml_find(xml_tree, query) 269 | """ 270 | Search for the specified node and extract the contained integer value. 271 | 272 | :param xml_tree: the etree element to search in 273 | :type xml_tree: lxml.etree.ElementTree 274 | :param query: the XPath query 275 | :type query: str 276 | :return: the integer number contained in the node, if any 277 | :rtype: int | None 278 | """ 279 | return int(q.text) if q is not None else None 280 | 281 | 282 | def get_header_tree(xml_tree: etree.ElementTree) \ 283 | -> typing.Union[etree.ElementTree, None]: 284 | """ 285 | Extracts the xml node containing the SOAP header of the message, if any. 286 | 287 | :param xml_tree: the etree element to search in 288 | :type xml_tree: lxml.etree.ElementTree 289 | :return: the SOAP header node 290 | :rtype: etree.ElementTree | None 291 | """ 292 | return xml_find(xml_tree, ".//soap:Header") 293 | 294 | 295 | def get_body_tree(xml_tree: etree.ElementTree) \ 296 | -> typing.Union[etree.ElementTree, None]: 297 | """ 298 | Extracts the xml node containing the SOAP body of the message, if any. 299 | 300 | :param xml_tree: the etree element to search in 301 | :type xml_tree: lxml.etree.ElementTree 302 | :return: the SOAP body node 303 | :rtype: etree.ElementTree | None 304 | """ 305 | return xml_find(xml_tree, ".//soap:Body") 306 | 307 | 308 | def get_action_id(xml_tree: etree.ElementTree) \ 309 | -> typing.Union[str, None]: 310 | """ 311 | Extracts the action id from the WSA-compliant SOAP message. 312 | 313 | :param xml_tree: the etree element to search in 314 | :type xml_tree: lxml.etree.ElementTree 315 | :return: the WSA ation URI specified in the message, if any 316 | :rtype: str | None 317 | """ 318 | return get_xml_str(xml_tree, ".//wsa:Action") 319 | 320 | 321 | def get_message_id(xml_tree: etree.ElementTree) \ 322 | -> typing.Union[str, None]: 323 | """ 324 | Extracts the message id from the WSA-compliant SOAP message. 325 | 326 | :param xml_tree: the etree element to search in 327 | :type xml_tree: lxml.etree.ElementTree 328 | :return: the WSA unique message identifier specified in the message, if any 329 | :rtype: str | None 330 | """ 331 | return get_xml_str(xml_tree, ".//wsa:MessageID") 332 | 333 | 334 | def register_message_parser(action: str, 335 | msg_parser: typing.Callable) \ 336 | -> None: 337 | """ 338 | Associates a parser to a specific type of WSA message, globally. 339 | This will be the parser used by wsd_common.parse() 340 | 341 | :param action: the WSA action URI that the parser can handle. 342 | :type action: str 343 | :param msg_parser: a message parser. It will be called by passing the message 344 | xml tree and is expected to return an object of the relevant 345 | class abstracting the message 346 | :type msg_parser: callable 347 | """ 348 | wsd_globals.message_parsers[action] = msg_parser 349 | 350 | 351 | def unregister_message_parser(action: str) \ 352 | -> None: 353 | """ 354 | Removes the parser for a specific type of WSA message. 355 | 356 | :param action: the WSA action URI that the parser handle. 357 | :type action: str 358 | """ 359 | del wsd_globals.message_parsers[action] 360 | 361 | 362 | def parse(ws_msg: etree.ElementTree): 363 | """ 364 | Executes the parser associated with the WS message class/action. 365 | Parsers can be registered with wsd_common.register_message_parser() 366 | 367 | :param ws_msg: the etree element to search in 368 | :type ws_msg: lxml.etree.ElementTree 369 | :return: an object of the relevant class abstracting the message 370 | """ 371 | a = get_action_id(ws_msg) 372 | if a in wsd_globals.message_parsers: 373 | return wsd_globals.message_parsers[a](ws_msg) 374 | raise NotImplemented 375 | 376 | 377 | def record_message_id(msg_id: str) \ 378 | -> bool: 379 | """ 380 | Checks if the specified message is a duplicate, and records the id if not. 381 | 382 | :param msg_id: the WSA message id to check 383 | :type msg_id: str 384 | :return: True if the message is not a duplicate, False otherwise. 385 | :rtype: bool 386 | """ 387 | if msg_id in wsd_globals.last_msg_ids: 388 | return False 389 | wsd_globals.last_msg_ids[wsd_globals.last_msg_idx] = msg_id 390 | wsd_globals.last_msg_idx += 1 391 | wsd_globals.last_msg_idx %= len(wsd_globals.last_msg_ids) 392 | return True 393 | 394 | 395 | def log_xml(xml_tree: etree.ElementTree) \ 396 | -> None: 397 | """ 398 | Dumps the specified xml tree in a timestamped file in the log folder. 399 | 400 | :param xml_tree: the node to dump 401 | :type xml_tree: etree.ElementTree 402 | """ 403 | logfile = open(log_path + "/" + datetime.datetime.now().isoformat(), "w") 404 | logfile.write(etree.tostring(xml_tree, pretty_print=True, xml_declaration=True).decode("ASCII")) 405 | 406 | 407 | def enable_debug(status: bool = True) \ 408 | -> None: 409 | """ 410 | Enables echoing of exchanged messages on standard output. 411 | :param status: True to enable, False to disable 412 | """ 413 | wsd_globals.debug = status 414 | 415 | 416 | ####################### 417 | # INITIALIZATION CODE # 418 | ####################### 419 | 420 | wsd_globals.urn = gen_urn() 421 | try: 422 | os.mkdir(log_path) 423 | except FileExistsError: 424 | pass 425 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_discovery__operations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | import os 5 | import pickle 6 | import select 7 | import socket 8 | import sqlite3 9 | import struct 10 | import typing 11 | 12 | import lxml.etree as etree 13 | 14 | from PyWSD import wsd_common, \ 15 | wsd_discovery__structures, \ 16 | wsd_transfer__operations, \ 17 | wsd_globals 18 | 19 | discovery_verbosity = 0 20 | 21 | wsd_mcast_v4 = '239.255.255.250' 22 | wsd_mcast_v6 = 'FF02::C' 23 | wsd_udp_port = 3702 24 | 25 | db_path = os.environ.get("WSD_CACHE_PATH", "") 26 | 27 | 28 | def send_multicast_soap_msg(xml_template: str, 29 | fields_map: typing.Dict[str, str], 30 | timeout: int) \ 31 | -> socket.socket: 32 | """ 33 | Send a wsd xml/soap multicast request, and return the opened socket. 34 | 35 | :param xml_template: the name of the xml template to fill and send 36 | :type xml_template: str 37 | :param fields_map: the map of placeholders and strings to substitute inside the template 38 | :type fields_map: {str: str} 39 | :param timeout: the timeout of the socket 40 | :type timeout: int 41 | :return: the socket use for message delivery 42 | :rtype: socket.socket 43 | """ 44 | message = wsd_common.message_from_file(wsd_common.abs_path("templates/%s" % xml_template), 45 | **fields_map) 46 | 47 | op_name = " ".join(xml_template.split("__")[1].split(".")[0].split("_")).upper() 48 | 49 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 50 | sock.settimeout(timeout) 51 | ttl = struct.pack('b', 1) 52 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) 53 | sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) 54 | 55 | if wsd_globals.debug: 56 | r = etree.fromstring(message.encode("ASCII"), parser=wsd_common.parser) 57 | print('##\n## %s\n##\n' % op_name) 58 | wsd_common.log_xml(r) 59 | print(etree.tostring(r, pretty_print=True, xml_declaration=True).decode("ASCII")) 60 | sock.sendto(message.encode("UTF-8"), (wsd_mcast_v4, wsd_udp_port)) 61 | return sock 62 | 63 | 64 | # FIXME Check if this update mechanism is still needed 65 | def read_discovery_multicast_reply(sock: socket.socket, 66 | target_service: wsd_discovery__structures.TargetService) \ 67 | -> typing.Union[None, typing.Tuple[bool, typing.List[wsd_discovery__structures.TargetService]]]: 68 | """ 69 | Waits for a reply from an endpoint, containing info about the target itself. Used to 70 | catch wsd_probe and wsd_resolve responses. Updates the target_service with data collected. 71 | 72 | :param sock: The socket to read from 73 | :type sock: socket.socket 74 | :param target_service: an instance of TargetService to fill or update with data received 75 | :return: an updated target_service object, or False if the socket timeout is reached 76 | :rtype: wsd_discovery__structures.TargetService | False 77 | """ 78 | while True: 79 | try: 80 | data, server = sock.recvfrom(4096) 81 | except socket.timeout: 82 | if wsd_globals.debug: 83 | print('##\n## TIMEOUT\n##\n') 84 | return False, [] 85 | else: 86 | x = etree.fromstring(data) 87 | 88 | if not wsd_common.record_message_id(wsd_common.get_message_id(x)): 89 | continue 90 | 91 | action = wsd_common.get_action_id(x) 92 | 93 | if wsd_globals.debug: 94 | print('##\n## %s MATCH\n## %s\n##\n' % (action.split("/")[-1].upper(), server[0])) 95 | wsd_common.log_xml(x) 96 | print(etree.tostring(x, pretty_print=True, xml_declaration=True).decode("ASCII")) 97 | 98 | if action == "http://schemas.xmlsoap.org/ws/2005/04/discovery/ProbeMatches": 99 | tt = wsd_common.parse(x).get_target_services() 100 | return len(tt) > 1, tt 101 | if action == "http://schemas.xmlsoap.org/ws/2005/04/discovery/ResolveMatches": 102 | return False, wsd_common.parse(x).get_target_service() 103 | 104 | 105 | def open_multicast_udp_socket(addr: str, port: int) -> socket.socket: 106 | res = socket.getaddrinfo(addr, port, type=socket.SOCK_DGRAM) 107 | 108 | if not res: 109 | raise ConnectionError 110 | 111 | addrinfo = res[0] 112 | 113 | sock = socket.socket(addrinfo[0], socket.SOCK_DGRAM) 114 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 115 | sock.bind(('', port)) 116 | gbin = socket.inet_pton(addrinfo[0], addrinfo[4][0]) 117 | if addrinfo[0] == socket.AF_INET: 118 | mreq = gbin + struct.pack('=I', socket.INADDR_ANY) 119 | sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 120 | else: 121 | mreq = gbin + struct.pack('@I', 0) 122 | sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) 123 | 124 | return sock 125 | 126 | 127 | def init_multicast_listener() -> typing.List[socket.socket]: 128 | sock_1 = open_multicast_udp_socket(wsd_mcast_v4, wsd_udp_port) 129 | return [sock_1] 130 | # sock_2 = open_multicast_udp_socket(wsd_mcast_v6, wsd_udp_port) 131 | # return [sock_1, sock_2] #TODO: enable ipv6 support once stable 132 | 133 | 134 | def deinit_multicast_listener(sockets: typing.List[socket.socket]) -> None: 135 | for sock in sockets: 136 | sock.close() 137 | 138 | 139 | def listen_multicast_announcements(sockets: typing.List[socket.socket]) \ 140 | -> typing.Tuple[bool, wsd_discovery__structures.TargetService]: 141 | """ 142 | 143 | """ 144 | empty = [] 145 | readable = [] 146 | action = "" 147 | while action not in ["http://schemas.xmlsoap.org/ws/2005/04/discovery/Hello", 148 | "http://schemas.xmlsoap.org/ws/2005/04/discovery/Bye"]: 149 | while not readable: 150 | readable, writable, exceptional = select.select(sockets, empty, empty) 151 | 152 | data, server = readable[0].recvfrom(4096) 153 | x = etree.fromstring(data) 154 | action = wsd_common.get_action_id(x) 155 | readable = [] 156 | if not wsd_common.record_message_id(wsd_common.get_message_id(x)): 157 | continue 158 | 159 | if wsd_globals.debug: 160 | print('##\n## %s MATCH\n## %s\n##\n' % (action.split("/")[-1].upper(), server[0])) 161 | wsd_common.log_xml(x) 162 | print(etree.tostring(x, pretty_print=True, xml_declaration=True).decode("ASCII")) 163 | 164 | if action == "http://schemas.xmlsoap.org/ws/2005/04/discovery/Hello": 165 | return True, wsd_common.parse(x).get_target_service() 166 | if action == "http://schemas.xmlsoap.org/ws/2005/04/discovery/Bye": 167 | return False, wsd_common.parse(x).get_target_service() 168 | 169 | 170 | def wsd_probe(probe_timeout: int = 3, 171 | type_filter: typing.Set[str] = None) \ 172 | -> typing.Set[wsd_discovery__structures.TargetService]: 173 | """ 174 | Send a multicast discovery probe message, and wait for wsd-enabled devices to respond. 175 | 176 | :param probe_timeout: the number of seconds to wait for probe replies 177 | :type probe_timeout: int 178 | :param type_filter: a set of legal strings, each representing a device class 179 | :type type_filter: {str} 180 | :return: a set of wsd targets 181 | :rtype: {wsd_discovery__structures.TargetService} 182 | """ 183 | 184 | opt_types = "" if type_filter is None else "%s" % ' '.join(type_filter) 185 | 186 | fields = {"FROM": wsd_globals.urn, 187 | "OPT_TYPES": opt_types} 188 | sock = send_multicast_soap_msg("ws-discovery__probe.xml", 189 | fields, 190 | probe_timeout) 191 | 192 | target_services_list = set() 193 | 194 | while True: 195 | is_proxy, ts = read_discovery_multicast_reply(sock, wsd_discovery__structures.TargetService()) 196 | if not ts: 197 | break 198 | target_services_list.add(ts[0]) # TODO handle is_proxy 199 | discovery_log("FOUND " + ts[0].ep_ref_addr) 200 | 201 | sock.close() 202 | return target_services_list 203 | 204 | 205 | def wsd_resolve(target_service: wsd_discovery__structures.TargetService) \ 206 | -> typing.Tuple[bool, wsd_discovery__structures.TargetService]: 207 | """ 208 | Send a multicast resolve message, and wait for the targeted service to respond. 209 | 210 | :param target_service: A wsd target to resolve 211 | :type target_service: wsd_discovery__structures.TargetService 212 | :return: an updated TargetService with additional information gathered from resolving 213 | :rtype: wsd_discovery__structures.TargetService 214 | """ 215 | 216 | fields = {"FROM": wsd_globals.urn, 217 | "EP_ADDR": target_service.ep_ref_addr} 218 | sock = send_multicast_soap_msg("ws-discovery__resolve.xml", 219 | fields, 220 | 2) 221 | 222 | _, ts = read_discovery_multicast_reply(sock, target_service) 223 | sock.close() 224 | 225 | if not ts: 226 | discovery_log("UNRESOLVED " + target_service.ep_ref_addr) 227 | return False, target_service 228 | else: 229 | discovery_log("RESOLVED " + ts.ep_ref_addr) 230 | return True, ts 231 | 232 | 233 | def get_devices(cache: bool = True, 234 | discovery: bool = True, 235 | probe_timeout: int = 3, 236 | type_filter: typing.Set[str] = None) \ 237 | -> typing.Set[wsd_discovery__structures.TargetService]: 238 | """ 239 | Get a list of available wsd-enabled devices 240 | 241 | :param cache: True if you want to use the database pointed by *WSD_CACHE_PATH* env variable \ 242 | as a way to know about already discovered devices or not. 243 | :type cache: bool 244 | :param discovery: True if you want to rely on multicast probe for device discovery. 245 | :type discovery: bool 246 | :param probe_timeout: the amount of seconds to wait for a probe response 247 | :type probe_timeout: int 248 | :param type_filter: a set of device types (as strings) 249 | :type type_filter: {str} 250 | :return: a list of wsd targets as TargetService instances 251 | :rtype: {wsd_discovery__structures.TargetService} 252 | """ 253 | d_resolved = set() 254 | c_ok = set() 255 | 256 | if discovery is True: 257 | d = wsd_probe(probe_timeout, type_filter) 258 | 259 | for t in d: 260 | ok, t = wsd_resolve(t) 261 | if ok: 262 | d_resolved.add(t) 263 | 264 | if cache is True: 265 | db = sqlite3.connect(db_path) 266 | 267 | create_table_if_not_exists(db) 268 | 269 | c = read_targets_from_db(db) 270 | 271 | # Discard not-reachable targets 272 | for t in c: 273 | s = check_target_status(t) 274 | if s: 275 | c_ok.add(t) 276 | else: 277 | remove_target_from_db(db, t) 278 | 279 | # Add discovered entries to DB 280 | for i in d_resolved: 281 | add_target_to_db(db, i) 282 | 283 | db.close() 284 | 285 | result = set() 286 | for elem in set.union(c_ok, d_resolved): 287 | if not type_filter or not elem.types.isdisjoint(type_filter): 288 | result.add(elem) 289 | return result 290 | 291 | 292 | def create_table_if_not_exists(db: sqlite3.Connection) -> None: 293 | cursor = db.cursor() 294 | cursor.execute("CREATE TABLE IF NOT EXISTS WsdCache (" 295 | "EpRefAddr TEXT PRIMARY KEY, " 296 | "MetadataVersion INT NOT NULL, " 297 | "SerializedTarget TEXT);") 298 | db.commit() 299 | 300 | 301 | def check_target_status(t: wsd_discovery__structures.TargetService) -> bool: 302 | try: 303 | wsd_transfer__operations.wsd_get(t) 304 | discovery_log("VERIFIED " + t.ep_ref_addr) 305 | return True 306 | except (TimeoutError, StopIteration): 307 | return False 308 | 309 | 310 | def read_targets_from_db(db: sqlite3.Connection) -> typing.Set[wsd_discovery__structures.TargetService]: 311 | cursor = db.cursor() 312 | c = set() 313 | cursor.execute('SELECT DISTINCT EpRefAddr, SerializedTarget FROM WsdCache') 314 | for row in cursor: 315 | c.add(pickle.loads(row[1].encode())) 316 | return c 317 | 318 | 319 | def add_target_to_db(db: sqlite3.Connection, 320 | t: wsd_discovery__structures.TargetService) -> None: 321 | cursor = db.cursor() 322 | cursor.execute('UPDATE WsdCache ' 323 | 'SET EpRefAddr = :a, ' 324 | ' MetadataVersion = :b, ' 325 | ' SerializedTarget = :c ' 326 | 'WHERE EpRefAddr = :a ' 327 | 'AND MetadataVersion > :b', 328 | {"a": t.ep_ref_addr, 329 | "b": t.meta_ver, 330 | "c": pickle.dumps(t, 0).decode()}) 331 | if not cursor.rowcount: 332 | cursor.execute('INSERT OR IGNORE ' 333 | 'INTO WsdCache ' 334 | '(EpRefAddr, MetadataVersion, SerializedTarget) ' 335 | 'VALUES (:a,:b,:c)', 336 | {"a": t.ep_ref_addr, 337 | "b": t.meta_ver, 338 | "c": pickle.dumps(t, 0).decode()}) 339 | discovery_log("REGISTERED " + t.ep_ref_addr) 340 | db.commit() 341 | 342 | 343 | def remove_target_from_db(db: sqlite3.Connection, 344 | t: wsd_discovery__structures.TargetService) -> None: 345 | cursor = db.cursor() 346 | cursor.execute('DELETE FROM WsdCache WHERE EpRefAddr=?', (t.ep_ref_addr,)) 347 | discovery_log("UNREGISTERED " + t.ep_ref_addr) 348 | db.commit() 349 | 350 | 351 | def set_discovery_verbosity(lvl: int): 352 | global discovery_verbosity 353 | discovery_verbosity = lvl 354 | 355 | 356 | def discovery_log(text: str, lvl: int = 1): 357 | print(text) if discovery_verbosity >= lvl else None 358 | 359 | 360 | def open_db() -> sqlite3.Connection: 361 | return sqlite3.connect(db_path) 362 | 363 | 364 | ####################### 365 | # INITIALIZATION CODE # 366 | ####################### 367 | if not db_path: 368 | db_path = os.path.expanduser("~/.wsdcache.db") 369 | os.environ["WSD_CACHE_PATH"] = db_path 370 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_discovery__parsers.py: -------------------------------------------------------------------------------- 1 | import typing 2 | 3 | from lxml import etree 4 | 5 | from PyWSD import wsd_common, \ 6 | wsd_discovery__structures 7 | 8 | 9 | def get_sequence(xml_tree: etree.ElementTree) -> typing.List[int]: 10 | q = wsd_common.xml_find(xml_tree, ".//wsd:AppSequence") 11 | seq = [0, 0, 0] 12 | seq[0] = int(q.attrib['InstanceId']) 13 | if 'SequenceId' in q.attrib: 14 | seq[1] = int(q.attrib['SequenceId']) 15 | seq[2] = int(q.attrib['MessageNumber']) 16 | return seq 17 | 18 | 19 | def parser_target(xml_tree: etree.ElementTree) -> wsd_discovery__structures.TargetService: 20 | o = wsd_discovery__structures.TargetService() 21 | o.ep_ref_addr = wsd_common.get_xml_str(xml_tree, ".//wsa:EndpointReference/wsa:Address") 22 | o.types = wsd_common.get_xml_str_set(xml_tree, ".//wsd:Types") 23 | o.scopes = wsd_common.get_xml_str_set(xml_tree, ".//wsd:Scopes") 24 | o.xaddrs = wsd_common.get_xml_str_set(xml_tree, ".//wsd:XAddrs") 25 | o.metadata_version = wsd_common.get_xml_int(xml_tree, ".//wsd:MetadataVersion") 26 | return o 27 | 28 | 29 | def parser_hello(xml_tree: etree.ElementTree) -> wsd_discovery__structures.HelloMessage: 30 | o = wsd_discovery__structures.HelloMessage() 31 | header = wsd_common.get_header_tree(xml_tree) 32 | o.message_id = wsd_common.get_xml_str(header, ".//wsa:MessageID") 33 | o.relates_to = wsd_common.get_xml_str(header, ".//wsa:RelatesTo") 34 | o.app_sequence = get_sequence(header) 35 | body = wsd_common.get_body_tree(xml_tree) 36 | o.ts = parser_target(body) 37 | return o 38 | 39 | 40 | def parser_bye(xml_tree: etree.ElementTree) -> wsd_discovery__structures.ByeMessage: 41 | o = wsd_discovery__structures.ByeMessage() 42 | header = wsd_common.get_header_tree(xml_tree) 43 | o.message_id = wsd_common.get_xml_str(header, ".//wsa:MessageID") 44 | o.app_sequence = get_sequence(header) 45 | body = wsd_common.get_body_tree(xml_tree) 46 | o.ts = parser_target(body) 47 | return o 48 | 49 | 50 | def parser_probe_match(xml_tree: etree.ElementTree) -> wsd_discovery__structures.ProbeMatchesMessage: 51 | o = wsd_discovery__structures.ProbeMatchesMessage() 52 | header = wsd_common.get_header_tree(xml_tree) 53 | o.message_id = wsd_common.get_xml_str(header, ".//wsa:MessageID") 54 | o.relates_to = wsd_common.get_xml_str(header, ".//wsa:RelatesTo") 55 | o.to = wsd_common.get_xml_str(header, ".//wsa:To") 56 | o.app_sequence = get_sequence(header) 57 | body = wsd_common.get_body_tree(xml_tree) 58 | matches = wsd_common.xml_findall(body, "wsd:ProbeMatches/wsd:ProbeMatch") 59 | for match in matches: 60 | o.matches.append(parser_target(match)) 61 | return o 62 | 63 | 64 | def parser_resolve_match(xml_tree: etree.ElementTree) -> wsd_discovery__structures.ResolveMatchesMessage: 65 | o = wsd_discovery__structures.ResolveMatchesMessage() 66 | header = wsd_common.get_header_tree(xml_tree) 67 | o.message_id = wsd_common.get_xml_str(header, ".//wsa:MessageID") 68 | o.relates_to = wsd_common.get_xml_str(header, ".//wsa:RelatesTo") 69 | o.to = wsd_common.get_xml_str(header, ".//wsa:To") 70 | o.app_sequence = get_sequence(header) 71 | body = wsd_common.get_body_tree(xml_tree) 72 | match = wsd_common.xml_findall(body, "wsd:ResolveMatches/wsd:ResolveMatch") 73 | if match is not None: 74 | o.ts = parser_target(body) 75 | return o 76 | 77 | 78 | def init() -> None: 79 | wsd_common.register_message_parser("http://schemas.xmlsoap.org/ws/2005/04/discovery/Hello", parser_hello) 80 | wsd_common.register_message_parser("http://schemas.xmlsoap.org/ws/2005/04/discovery/Bye", parser_bye) 81 | wsd_common.register_message_parser("http://schemas.xmlsoap.org/ws/2005/04/discovery/ProbeMatches", 82 | parser_probe_match) 83 | wsd_common.register_message_parser("http://schemas.xmlsoap.org/ws/2005/04/discovery/ResolveMatches", 84 | parser_resolve_match) 85 | 86 | 87 | init() 88 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_discovery__structures.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | class TargetService: 6 | """ 7 | A WSD target service is an abstract entity that can be discovered on the network. 8 | Each WSD device must not impersonate more than one target service, even if it 9 | hosts multiple services like printing, scanning, etc. 10 | """ 11 | 12 | def __init__(self): 13 | self.ep_ref_addr = "" 14 | self.types = set() 15 | self.scopes = set() 16 | self.xaddrs = set() 17 | self.meta_ver = 0 18 | 19 | def __str__(self): 20 | s = "" 21 | s += "EndPoint reference: %s\n" % self.ep_ref_addr 22 | s += "Metadata version: %d\n" % self.meta_ver 23 | s += "Implemented Types: %s\n" % ', '.join(self.types) 24 | s += "Assigned Scopes: %s\n" % ', '.join(self.scopes) 25 | s += "Transport addresses: %s\n" % ', '.join(self.xaddrs) 26 | return s 27 | 28 | def __eq__(self, other): 29 | return self.ep_ref_addr == other.ep_ref_addr 30 | 31 | def __hash__(self): 32 | return self.ep_ref_addr.__hash__() 33 | 34 | 35 | class HelloMessage: 36 | def __init__(self): 37 | self.action = "http://schemas.xmlsoap.org/ws/2005/04/discovery/Hello" 38 | self.message_id = None 39 | self.relates_to = None # allowed only if a proxy replies to a multicast probe 40 | self.app_sequence = [0, 0, 0] # instance, sequence, message IDs 41 | self.ts = TargetService() 42 | 43 | def is_valid(self): 44 | valid = True 45 | valid = valid & (self.message_id is not None) 46 | valid = valid & (self.ts.ep_ref_addr is not None) 47 | return valid 48 | 49 | def get_target_service(self): 50 | if not self.is_valid(): 51 | print("Warning: invalid TargetService") 52 | return self.ts 53 | 54 | 55 | class ByeMessage: 56 | def __init__(self): 57 | self.action = "http://schemas.xmlsoap.org/ws/2005/04/discovery/Bye" 58 | self.message_id = None 59 | self.app_sequence = [0, 0, 0] # instance, sequence, message IDs 60 | self.ts = TargetService() 61 | 62 | def is_valid(self): 63 | valid = True 64 | valid = valid & (self.message_id is not None) 65 | valid = valid & (self.ts.ep_ref_addr is not None) 66 | return valid 67 | 68 | def get_target_service(self): 69 | if not self.is_valid(): 70 | print("Warning: invalid TargetService") 71 | return self.ts 72 | 73 | 74 | class ProbeMatchesMessage: 75 | def __init__(self): 76 | self.action = "http://schemas.xmlsoap.org/ws/2005/04/discovery/ProbeMatches" 77 | self.message_id = None 78 | self.relates_to = None 79 | self.to = None 80 | self.app_sequence = [0, 0, 0] # instance, sequence, message IDs 81 | self.matches = [] # at most one element if not from a discovery proxy 82 | 83 | def is_valid(self): 84 | valid = True 85 | valid = valid & (self.message_id is not None) 86 | valid = valid & (self.relates_to is not None) 87 | valid = valid & (self.to is not None) 88 | for ts in self.matches: 89 | valid = valid & (ts.ep_ref_addr is not None) 90 | return valid 91 | 92 | def get_target_services(self): 93 | if not self.is_valid(): 94 | print("Warning: invalid TargetService") 95 | return self.matches 96 | 97 | 98 | class ResolveMatchesMessage: 99 | def __init__(self): 100 | self.action = "http://schemas.xmlsoap.org/ws/2005/04/discovery/ResolveMatches" 101 | self.message_id = None 102 | self.relates_to = None 103 | self.to = None 104 | self.app_sequence = [0, 0, 0] # instance, sequence, message IDs 105 | self.ts = None # Allowed None only if it's a response from a discovery proxy 106 | 107 | def is_valid(self): 108 | valid = True 109 | valid = valid & (self.message_id is not None) 110 | valid = valid & (self.relates_to is not None) 111 | valid = valid & (self.to is not None) 112 | if self.ts is not None: 113 | valid = valid & (self.ts.ep_ref_addr is not None) 114 | valid = valid & (len(self.ts.xaddrs) > 0) 115 | return valid 116 | 117 | def get_target_service(self): 118 | if not self.is_valid(): 119 | print("Warning: invalid TargetService") 120 | return self.ts 121 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_eventing__operations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | import typing 5 | from datetime import datetime, timedelta 6 | 7 | import lxml.etree as etree 8 | 9 | from PyWSD import wsd_common, \ 10 | wsd_transfer__structures, \ 11 | xml_helpers, \ 12 | wsd_globals 13 | 14 | 15 | def wsd_subscribe(hosted_service: wsd_transfer__structures.HostedService, 16 | event_uri: str, 17 | notify_addr: str, 18 | expiration: typing.Union[datetime, timedelta] = None) \ 19 | -> typing.Union[etree.ElementTree, bool]: 20 | """ 21 | Subscribe to a certain type of events of a wsd service 22 | 23 | :param hosted_service: the wsd service to receive event notifications from 24 | :type hosted_service: wsd_transfer__structures.HostedService 25 | :param event_uri: the full URI of the targeted event class. \ 26 | Those URIs are taken from ws specifications 27 | :type event_uri: str 28 | :param notify_addr: The address to send notifications to. 29 | :type notify_addr: str 30 | :param expiration: Expiration time, as a datetime or timedelta object 31 | :type expiration: datetime | timedelta | None 32 | :return: the xml SubscribeResponse of the wsd service\ 33 | or False if a fault message is received instead 34 | :rtype: lxml.etree.ElementTree | False 35 | """ 36 | 37 | if expiration is None: 38 | pass 39 | elif isinstance(expiration, datetime): 40 | expiration = xml_helpers.fmt_as_xml_datetime(expiration) 41 | elif isinstance(expiration, timedelta): 42 | expiration = xml_helpers.fmt_as_xml_duration(expiration) 43 | else: 44 | raise TypeError("Type %s not allowed" % expiration.__class__) 45 | 46 | expiration_tag = "" 47 | if expiration is not None: 48 | expiration_tag = "%s" % expiration 49 | 50 | fields_map = {"FROM": wsd_globals.urn, 51 | "TO": hosted_service.ep_ref_addr, 52 | "NOTIFY_ADDR": notify_addr, 53 | "EXPIRES": expiration, 54 | "FILTER_DIALECT": "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action", 55 | "EVENT": event_uri, 56 | "OPT_EXPIRATION": expiration_tag} 57 | x = wsd_common.submit_request({hosted_service.ep_ref_addr}, 58 | "ws-eventing__subscribe.xml", 59 | fields_map) 60 | 61 | if wsd_common.check_fault(x): 62 | return False 63 | 64 | return wsd_common.xml_find(x, ".//wse:SubscribeResponse") 65 | 66 | 67 | def wsd_unsubscribe(hosted_service: wsd_transfer__structures.HostedService, 68 | subscription_id: str) \ 69 | -> bool: 70 | """ 71 | Unsubscribe from events notifications of a wsd service 72 | 73 | :param hosted_service: the wsd service from which you want to unsubscribe for events 74 | :type hosted_service: wsd_transfer__structures.HostedService 75 | :param subscription_id: the ID returned from a previous successful event subscription call 76 | :type subscription_id: str 77 | :return: False if a fault message is received instead, True otherwise 78 | :rtype: bool 79 | """ 80 | fields_map = {"FROM": wsd_globals.urn, 81 | "TO": hosted_service.ep_ref_addr, 82 | "SUBSCRIPTION_ID": subscription_id} 83 | x = wsd_common.submit_request({hosted_service.ep_ref_addr}, 84 | "ws-eventing__unsubscribe.xml", 85 | fields_map) 86 | 87 | return False if wsd_common.check_fault(x) else True 88 | 89 | 90 | def wsd_renew(hosted_service: wsd_transfer__structures.HostedService, 91 | subscription_id: str, 92 | expiration: typing.Union[datetime, timedelta] = None) \ 93 | -> bool: 94 | """ 95 | Renew an events subscription of a wsd service 96 | 97 | :param hosted_service: the wsd service that you want to renew the subscription 98 | :type hosted_service: wsd_transfer__structures.HostedService 99 | :param subscription_id: the ID returned from a previous successful event subscription call 100 | :type subscription_id: str 101 | :param expiration: Expiration time, as a datetime or timedelta object 102 | :type expiration: datetime | timedelta | None 103 | :return: False if a fault message is received instead, True otherwise 104 | :rtype: bool 105 | """ 106 | 107 | fields_map = {"FROM": wsd_globals.urn, 108 | "TO": hosted_service.ep_ref_addr, 109 | "SUBSCRIPTION_ID": subscription_id, 110 | "EXPIRES": expiration} 111 | x = wsd_common.submit_request({hosted_service.ep_ref_addr}, 112 | "ws-eventing__renew.xml", 113 | fields_map) 114 | 115 | return False if wsd_common.check_fault(x) else True 116 | 117 | 118 | def wsd_get_status(hosted_service: wsd_transfer__structures.HostedService, 119 | subscription_id: str) \ 120 | -> typing.Union[None, bool, datetime]: 121 | """ 122 | Get the status of an events subscription of a wsd service 123 | 124 | :param hosted_service: the wsd service from which you want to hear about the subscription status 125 | :type hosted_service: wsd_transfer__structures.HostedService 126 | :param subscription_id: the ID returned from a previous successful event subscription call 127 | :type subscription_id: str 128 | :return: False if a fault message is received instead, \ 129 | none if the subscription has no expiration set, \ 130 | the expiration date otherwise 131 | :rtype: None | False | datetime 132 | """ 133 | fields_map = {"FROM": wsd_globals.urn, 134 | "TO": hosted_service.ep_ref_addr, 135 | "SUBSCRIPTION_ID": subscription_id} 136 | x = wsd_common.submit_request({hosted_service.ep_ref_addr}, 137 | "ws-eventing__get_status.xml", 138 | fields_map) 139 | 140 | if wsd_common.check_fault(x): 141 | return False 142 | e = wsd_common.xml_find(x, ".//wse:Expires") 143 | return xml_helpers.parse_xml_datetime(e.text.replace(" ", ""), weak=True) if e is not None else None 144 | 145 | 146 | def __demo(): 147 | import wsd_scan__events 148 | import wsd_transfer__operations 149 | import wsd_discovery__operations 150 | 151 | wsd_common.init() 152 | tsl = wsd_discovery__operations.get_devices() 153 | for a in tsl: 154 | res = wsd_transfer__operations.wsd_get(a) 155 | if res is not False: 156 | (ti, hss) = res 157 | for b in hss: 158 | if "wscn:ScannerServiceType" in b.types: 159 | listen_addr = "http://192.168.1.109:6666/wsd" 160 | h = wsd_scan__events.wsd_scanner_all_events_subscribe(b, 161 | listen_addr, 162 | datetime.now() + timedelta(days=2)) 163 | # wsd_renew(b, h) 164 | print(wsd_get_status(b, h)) 165 | wsd_unsubscribe(b, h) 166 | 167 | 168 | if __name__ == "__main__": 169 | __demo() 170 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_globals.py: -------------------------------------------------------------------------------- 1 | message_parsers = dict() 2 | debug = False 3 | urn = "" 4 | last_msg_ids = ["" for i in range(0, 40)] 5 | last_msg_idx = 0 6 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_print__operations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | from PyWSD import wsd_common, \ 5 | wsd_discovery__operations, \ 6 | wsd_transfer__operations, \ 7 | wsd_globals 8 | 9 | 10 | def wsd_get_printer_elements(hosted_print_service): 11 | fields = {"FROM": wsd_globals.urn, 12 | "TO": hosted_print_service.ep_ref_addr} 13 | wsd_common.submit_request({hosted_print_service.ep_ref_addr}, 14 | "ws-print__get_printer_elements.xml", 15 | fields) 16 | 17 | 18 | if __name__ == "__main__": 19 | wsd_common.init() 20 | tsl = wsd_discovery__operations.get_devices() 21 | for a in tsl: 22 | print(a) 23 | (ti, hss) = wsd_transfer__operations.wsd_get(a) 24 | for b in hss: 25 | if "wprt:PrinterServiceType" in b.types: 26 | print(b) 27 | debug = True 28 | wsd_get_printer_elements(b) 29 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_scan__events.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | import copy 5 | import http.server 6 | import queue 7 | import threading 8 | import time 9 | import typing 10 | from datetime import datetime, timedelta 11 | 12 | import lxml.etree as etree 13 | 14 | from PyWSD import wsd_common, \ 15 | wsd_transfer__structures, \ 16 | wsd_eventing__operations, \ 17 | wsd_scan__operations, \ 18 | wsd_scan__parsers, \ 19 | xml_helpers, \ 20 | wsd_globals 21 | 22 | token_map = {} 23 | host_map = {} 24 | 25 | 26 | def wsd_scanner_all_events_subscribe(hosted_scan_service: wsd_transfer__structures.HostedService, 27 | notify_addr: str, 28 | expiration: typing.Union[datetime, timedelta] = None) \ 29 | -> typing.Union[False, str]: 30 | """ 31 | Subscribe to ScannerElementsChange events. 32 | 33 | :param hosted_scan_service: the wsd service to receive event notifications from 34 | :param expiration: Expiration time, as a datetime or timedelta object 35 | :param notify_addr: The address to send notifications to. 36 | :return: False if a fault message is received, a subscription ID otherwise 37 | """ 38 | event_uri = "http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScannerElementsChangeEvent" 39 | event_uri += " http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScannerStatusSummaryEvent" 40 | event_uri += " http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScannerStatusConditionEvent" 41 | event_uri += " http://schemas.microsoft.com/windows/2006/08/wdp/scan/JobStatusEvent" 42 | event_uri += " http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScannerStatusConditionClearedEvent" 43 | event_uri += " http://schemas.microsoft.com/windows/2006/08/wdp/scan/JobEndStateEvent" 44 | x = wsd_eventing__operations.wsd_subscribe(hosted_scan_service, 45 | event_uri, 46 | notify_addr, 47 | expiration) 48 | 49 | if x is False: 50 | return False 51 | return wsd_common.xml_find(x, ".//wse:Identifier").text 52 | 53 | 54 | def wsd_scanner_elements_change_subscribe(hosted_scan_service: wsd_transfer__structures.HostedService, 55 | notify_addr: str, 56 | expiration: typing.Union[datetime, timedelta] = None) \ 57 | -> typing.Union[False, str]: 58 | """ 59 | Subscribe to ScannerElementsChange events. 60 | 61 | :param hosted_scan_service: the wsd service to receive event notifications from 62 | :param expiration: Expiration time, as a datetime or timedelta object 63 | :param notify_addr: The address to send notifications to. 64 | :return: False if a fault message is received, a subscription ID otherwise 65 | """ 66 | event_uri = "http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScannerElementsChangeEvent" 67 | x = wsd_eventing__operations.wsd_subscribe(hosted_scan_service, 68 | event_uri, 69 | notify_addr, 70 | expiration) 71 | 72 | if x is False: 73 | return False 74 | return wsd_common.xml_find(x, ".//wse:Identifier").text 75 | 76 | 77 | def wsd_scanner_status_summary_subscribe(hosted_scan_service: wsd_transfer__structures.HostedService, 78 | notify_addr: str, 79 | expiration: typing.Union[datetime, timedelta] = None) \ 80 | -> typing.Union[False, str]: 81 | """ 82 | Subscribe to ScannerStatusSummary events. 83 | 84 | :param hosted_scan_service: the wsd service to receive event notifications from 85 | :param expiration: Expiration time, as a datetime or timedelta object 86 | :param notify_addr: The address to send notifications to. 87 | :return: False if a fault message is received, a subscription ID otherwise 88 | """ 89 | event_uri = "http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScannerStatusSummaryEvent" 90 | x = wsd_eventing__operations.wsd_subscribe(hosted_scan_service, 91 | event_uri, 92 | notify_addr, 93 | expiration) 94 | if x is False: 95 | return False 96 | return wsd_common.xml_find(x, ".//wse:Identifier").text 97 | 98 | 99 | def wsd_scanner_status_condition_subscribe(hosted_scan_service: wsd_transfer__structures.HostedService, 100 | notify_addr: str, 101 | expiration: typing.Union[datetime, timedelta] = None) \ 102 | -> typing.Union[False, str]: 103 | """ 104 | Subscribe to ScannerStatusCondition events. 105 | 106 | :param hosted_scan_service: the wsd service to receive event notifications from 107 | :param expiration: Expiration time, as a datetime or timedelta object 108 | :param notify_addr: The address to send notifications to. 109 | :return: False if a fault message is received, a subscription ID otherwise 110 | """ 111 | event_uri = "http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScannerStatusConditionEvent" 112 | x = wsd_eventing__operations.wsd_subscribe(hosted_scan_service, 113 | event_uri, 114 | notify_addr, 115 | expiration) 116 | if x is False: 117 | return False 118 | return wsd_common.xml_find(x, ".//wse:Identifier").text 119 | 120 | 121 | def wsd_scanner_status_condition_cleared_subscribe(hosted_scan_service: wsd_transfer__structures.HostedService, 122 | notify_addr: str, 123 | expiration: typing.Union[datetime, timedelta] = None) \ 124 | -> typing.Union[False, str]: 125 | """ 126 | Subscribe to ScannerStatusConditionCleared events. 127 | 128 | :param hosted_scan_service: the wsd service to receive event notifications from 129 | :param expiration: Expiration time, as a datetime or timedelta object 130 | :param notify_addr: The address to send notifications to. 131 | :return: False if a fault message is received, a subscription ID otherwise 132 | """ 133 | event_uri = "http://schemas.microsoft.com/windows/2006/08/wdp/scan/ScannerStatusConditionClearedEvent" 134 | x = wsd_eventing__operations.wsd_subscribe(hosted_scan_service, 135 | event_uri, 136 | notify_addr, 137 | expiration) 138 | if x is False: 139 | return False 140 | return wsd_common.xml_find(x, ".//wse:Identifier").text 141 | 142 | 143 | def wsd_job_status_subscribe(hosted_scan_service: wsd_transfer__structures.HostedService, 144 | notify_addr: str, 145 | expiration: typing.Union[datetime, timedelta] = None) \ 146 | -> typing.Union[False, str]: 147 | """ 148 | Subscribe to JobStatus events. 149 | 150 | :param hosted_scan_service: the wsd service to receive event notifications from 151 | :param expiration: Expiration time, as a datetime or timedelta object 152 | :param notify_addr: The address to send notifications to. 153 | :return: False if a fault message is received, a subscription ID otherwise 154 | """ 155 | event_uri = "http://schemas.microsoft.com/windows/2006/08/wdp/scan/JobStatusEvent" 156 | x = wsd_eventing__operations.wsd_subscribe(hosted_scan_service, 157 | event_uri, 158 | notify_addr, 159 | expiration) 160 | if x is False: 161 | return False 162 | return wsd_common.xml_find(x, ".//wse:Identifier").text 163 | 164 | 165 | def wsd_job_end_state_subscribe(hosted_scan_service: wsd_transfer__structures.HostedService, 166 | notify_addr: str, 167 | expiration: typing.Union[datetime, timedelta] = None) \ 168 | -> typing.Union[False, str]: 169 | """ 170 | Subscribe to JobEndState events. 171 | 172 | :param hosted_scan_service: the wsd service to receive event notifications from 173 | :param expiration: Expiration time, as a datetime or timedelta object 174 | :param notify_addr: The address to send notifications to. 175 | :return: False if a fault message is received, a subscription ID otherwise 176 | """ 177 | event_uri = "http://schemas.microsoft.com/windows/2006/08/wdp/scan/JobEndStateEvent" 178 | x = wsd_eventing__operations.wsd_subscribe(hosted_scan_service, 179 | event_uri, 180 | notify_addr, 181 | expiration) 182 | if x is False: 183 | return False 184 | return wsd_common.xml_find(x, ".//wse:Identifier").text 185 | 186 | 187 | # TODO: handle this subscription with wsd_eventing__operations.wsd_subscribe() 188 | def wsd_scan_available_event_subscribe(hosted_scan_service: wsd_transfer__structures.HostedService, 189 | display_str: str, 190 | context_str: str, 191 | notify_addr: str, 192 | expiration: typing.Union[datetime, timedelta] = None): 193 | """ 194 | Subscribe to ScanAvailable events. 195 | 196 | :param hosted_scan_service: the wsd service to receive event notifications from 197 | :param display_str: the string to display on the device control panel 198 | :param context_str: a string internally used to identify the selection of this wsd host as target of the scan 199 | :param notify_addr: The address to send notifications to. 200 | :param expiration: Expiration time, as a datetime or timedelta object 201 | :return: a subscription ID and the token needed in CreateScanJob to start a device-initiated scan, \ 202 | or False if a fault message is received instead 203 | """ 204 | 205 | if expiration is None: 206 | pass 207 | elif expiration.__class__ == "datetime.datetime": 208 | expiration = xml_helpers.fmt_as_xml_datetime(expiration) 209 | elif expiration.__class__ == "datetime.timedelta": 210 | expiration = xml_helpers.fmt_as_xml_duration(expiration) 211 | else: 212 | raise TypeError 213 | 214 | expiration_tag = "" 215 | if expiration is not None: 216 | expiration_tag = "%s" % expiration 217 | 218 | fields_map = {"FROM": wsd_globals.urn, 219 | "TO": hosted_scan_service.ep_ref_addr, 220 | "NOTIFY_ADDR": notify_addr, 221 | "OPT_EXPIRATION": expiration_tag, 222 | "DISPLAY_STR": display_str, 223 | "CONTEXT": context_str} 224 | try: 225 | x = wsd_common.submit_request({hosted_scan_service.ep_ref_addr}, 226 | "ws-scan__scan_available_event_subscribe.xml", 227 | fields_map) 228 | dest_token = wsd_common.xml_find(x, ".//sca:DestinationToken").text 229 | subscription_id = wsd_common.xml_find(x, ".//wse:Identifier").text 230 | return subscription_id, dest_token 231 | except TimeoutError: 232 | return False 233 | 234 | 235 | class QueuesSet: 236 | def __init__(self): 237 | self.sc_descr_q = queue.Queue() 238 | self.sc_conf_q = queue.Queue() 239 | self.sc_ticket_q = queue.Queue() 240 | self.sc_stat_sum_q = queue.Queue() 241 | self.sc_cond_q = queue.Queue() 242 | self.sc_cond_clr_q = queue.Queue() 243 | self.job_status_q = queue.Queue() 244 | self.job_ended_q = queue.Queue() 245 | 246 | 247 | class HTTPServerWithContext(http.server.HTTPServer): 248 | def __init__(self, server_address, request_handler_class, context, *args, **kw): 249 | super().__init__(server_address, request_handler_class, *args, **kw) 250 | self.context = context 251 | 252 | 253 | class RequestHandler(http.server.BaseHTTPRequestHandler): 254 | 255 | def do_POST(self): 256 | context = self.server.context 257 | # request_path = self.path 258 | request_headers = self.headers 259 | length = int(request_headers["content-length"]) 260 | 261 | message = self.rfile.read(length) 262 | 263 | self.protocol_version = "HTTP/1.1" 264 | self.send_response(202) 265 | self.send_header("Content-Type", "application/soap+xml") 266 | self.send_header("Content-Length", "0") 267 | self.send_header("Connection", "close") 268 | self.end_headers() 269 | 270 | x = etree.fromstring(message) 271 | action = wsd_common.xml_find(x, ".//wsa:Action").text 272 | (prefix, _, action) = action.rpartition('/') 273 | if prefix != 'http://schemas.microsoft.com/windows/2006/08/wdp/scan': 274 | return 275 | if action == 'ScanAvailableEvent' \ 276 | and context["allow_device_initiated_scans"] is True: 277 | self.handle_scan_available_event(x) 278 | 279 | elif action == 'ScannerElementsChangeEvent': 280 | self.handle_scanner_elements_change_event(context['queues'], x) 281 | 282 | elif action == 'ScannerStatusSummaryEvent': 283 | self.handle_scanner_status_summary_event(context['queues'], x) 284 | 285 | elif action == 'ScannerStatusConditionEvent': 286 | self.handle_scanner_status_condition_event(context['queues'], x) 287 | 288 | elif action == 'ScannerStatusConditionClearedEvent': 289 | self.handle_scanner_status_condition_cleared_event(context['queues'], x) 290 | 291 | elif action == 'JobStatusEvent': 292 | self.handle_job_status_event(context['queues'], x) 293 | 294 | elif action == 'JobEndStateEvent': 295 | self.handle_job_end_state_event(context['queues'], x) 296 | 297 | @staticmethod 298 | def handle_scan_available_event(xml_tree): 299 | if wsd_globals.debug is True: 300 | print('##\n## SCAN AVAILABLE EVENT\n##\n') 301 | print(etree.tostring(xml_tree, pretty_print=True, xml_declaration=True)) 302 | client_context = wsd_common.xml_find(xml_tree, ".//sca:ClientContext").text 303 | scan_identifier = wsd_common.xml_find(xml_tree, ".//sca:ScanIdentifier").text 304 | t = threading.Thread(target=device_initiated_scan_worker, 305 | args=(client_context, 306 | scan_identifier, 307 | "wsd-daemon-scan")) 308 | t.start() 309 | 310 | @staticmethod 311 | def handle_scanner_elements_change_event(queues, xml_tree): 312 | if wsd_globals.debug is True: 313 | print('##\n## SCANNER ELEMENTS CHANGE EVENT\n##\n') 314 | print(etree.tostring(xml_tree, pretty_print=True, xml_declaration=True)) 315 | 316 | sca_config = wsd_common.xml_find(xml_tree, ".//sca:ScannerConfiguration") 317 | sca_descr = wsd_common.xml_find(xml_tree, ".//sca:ScannerDescription") 318 | std_ticket = wsd_common.xml_find(xml_tree, ".//sca:DefaultScanTicket") 319 | 320 | description = wsd_scan__parsers.parse_scan_description(sca_descr) 321 | configuration = wsd_scan__parsers.parse_scan_configuration(sca_config) 322 | std_ticket = wsd_scan__parsers.parse_scan_ticket(std_ticket) 323 | 324 | queues.sc_descr_q.put(description) 325 | queues.sc_conf_q.put(configuration) 326 | queues.sc_ticket_q.put(std_ticket) 327 | 328 | @staticmethod 329 | def handle_scanner_status_summary_event(queues, xml_tree): 330 | if wsd_globals.debug is True: 331 | print('##\n## SCANNER STATUS SUMMARY EVENT\n##\n') 332 | print(etree.tostring(xml_tree, pretty_print=True, xml_declaration=True)) 333 | 334 | state = wsd_common.xml_find(xml_tree, ".//sca:ScannerState").text 335 | reasons = [] 336 | q = wsd_common.xml_find(xml_tree, ".//sca:ScannerStateReasons") 337 | if q is not None: 338 | dsr = wsd_common.xml_findall(q, ".//sca:ScannerStateReason") 339 | for sr in dsr: 340 | reasons.append(sr.text) 341 | queues.sc_stat_sum_q.put((state, reasons)) 342 | 343 | @staticmethod 344 | def handle_scanner_status_condition_event(queues, xml_tree): 345 | if wsd_globals.debug is True: 346 | print('##\n## SCANNER STATUS CONDITION EVENT\n##\n') 347 | print(etree.tostring(xml_tree, pretty_print=True, xml_declaration=True)) 348 | 349 | cond = wsd_common.xml_find(xml_tree, ".//sca:DeviceCondition") 350 | cond = wsd_scan__parsers.parse_scanner_condition(cond) 351 | queues.sc_cond_q.put(cond) 352 | 353 | @staticmethod 354 | def handle_scanner_status_condition_cleared_event(queues, xml_tree): 355 | if wsd_globals.debug is True: 356 | print('##\n## SCANNER STATUS CONDITION CLEARED EVENT\n##\n') 357 | print(etree.tostring(xml_tree, pretty_print=True, xml_declaration=True)) 358 | 359 | cond = wsd_common.xml_find(xml_tree, ".//sca:DeviceConditionCleared") 360 | cond_id = int(wsd_common.xml_find(cond, ".//sca:ConditionId").text) 361 | clear_time = wsd_common.xml_find(cond, ".//sca:ConditionClearTime").text 362 | queues.sc_cond_clr_q.put((cond_id, clear_time)) 363 | 364 | @staticmethod 365 | def handle_job_status_event(queues, xml_tree): 366 | if wsd_globals.debug is True: 367 | print('##\n## JOB STATUS EVENT\n##\n') 368 | print(etree.tostring(xml_tree, pretty_print=True, xml_declaration=True)) 369 | s = wsd_common.xml_find(xml_tree, ".//sca:JobStatus") 370 | queues.sc_job_status_q.put(wsd_scan__parsers.parse_job_status(s)) 371 | 372 | @staticmethod 373 | def handle_job_end_state_event(queues, xml_tree): 374 | if wsd_globals.debug is True: 375 | print('##\n## JOB END STATE EVENT\n##\n') 376 | print(etree.tostring(xml_tree, pretty_print=True, xml_declaration=True)) 377 | s = wsd_common.xml_find(xml_tree, ".//sca:JobEndState") 378 | queues.sc_job_ended_q.put(wsd_scan__parsers.parse_job_summary(s)) 379 | 380 | 381 | # TODO: implement multi-device simultaneous monitoring 382 | class WSDScannerMonitor: 383 | """ 384 | A class that abstracts event handling and data querying for a device. Programmer should instantiate this class 385 | and use its methods to retrieve tickets/configurations/status and more, instead of submitting a wsd request 386 | directly to the device. This class listens to events and so polling devices is no longer needed. 387 | """ 388 | 389 | def __init__(self, 390 | service: wsd_transfer__structures.HostedService, 391 | listen_addr, 392 | port): 393 | self.service = service 394 | (self.description, 395 | self.configuration, 396 | self.status, 397 | self.std_ticket) = wsd_scan__operations.wsd_get_scanner_elements(service) 398 | self.active_jobs = {} 399 | for aj in wsd_scan__operations.wsd_get_active_jobs(service): 400 | self.active_jobs[aj.status.id] = wsd_scan__operations.wsd_get_job_elements(service, aj.status.id) 401 | self.job_history = {} 402 | for ej in wsd_scan__operations.wsd_get_job_history(service): 403 | self.job_history[ej.status.id] = ej 404 | 405 | self.subscription_id = wsd_scanner_all_events_subscribe(service, listen_addr) 406 | 407 | self.queues = QueuesSet() 408 | 409 | context = {"allow_device_initiated_scans": False, 410 | "queues": self.queues} 411 | 412 | self.server = HTTPServerWithContext(('', port), RequestHandler, context) 413 | self.listener = threading.Thread(target=self.server.serve_forever, args=()) 414 | self.listener.start() 415 | 416 | def close(self): 417 | self.server.shutdown() 418 | self.listener.join() 419 | wsd_eventing__operations.wsd_unsubscribe(self.service, self.subscription_id) 420 | 421 | def get_scanner_description(self): 422 | """ 423 | Updates and returns the current description of the device. 424 | 425 | :return: a valid ScannerDescription instance 426 | """ 427 | while self.queues.sc_descr_q.empty() is not True: 428 | self.description = self.queues.sc_descr_q.get() 429 | self.queues.sc_descr_q.task_done() 430 | return self.description 431 | 432 | def get_scanner_configuration(self): 433 | """ 434 | Updates and returns the current configuration of the device. 435 | 436 | :return: a valid ScannerConfiguration instance 437 | """ 438 | while self.queues.sc_conf_q.empty() is not True: 439 | self.configuration = self.queues.sc_conf_q.get() 440 | self.queues.sc_conf_q.task_done() 441 | return self.configuration 442 | 443 | def get_default_ticket(self): 444 | """ 445 | Updates and returns the default scan ticket of the device. 446 | 447 | :return: a valid ScanTicket instance 448 | """ 449 | while self.queues.sc_ticket_q.empty() is not True: 450 | self.std_ticket = self.queues.sc_ticket_q.get() 451 | self.queues.sc_ticket_q.task_done() 452 | return self.std_ticket 453 | 454 | def get_scanner_status(self): 455 | """ 456 | Updates and returns the current status and conditions of the device. 457 | 458 | :return: a valid ScannerStatus instance 459 | """ 460 | while self.queues.sc_cond_q.empty() is not True: 461 | cond = self.queues.sc_cond_q.get() 462 | self.status.active_conditions[cond.id] = cond 463 | self.queues.sc_cond_q.task_done() 464 | while self.queues.sc_cond_clr_q.empty() is not True: 465 | (c_id, c_time) = self.queues.sc_cond_clr_q.get() 466 | self.status.conditions_history[c_time] = copy.deepcopy(self.status.active_conditions[c_id]) 467 | del self.status.active_conditions[c_id] 468 | self.queues.sc_cond_clr_q.task_done() 469 | while self.queues.sc_stat_sum_q.empty() is not True: 470 | (self.status.state, self.status.reasons) = self.queues.sc_stat_sum_q.get() 471 | self.queues.sc_stat_sum_q.task_done() 472 | return self.status 473 | 474 | def get_active_jobs(self): 475 | while self.queues.job_status_q.empty() is not True: 476 | status = self.queues.sc_cond_q.get() 477 | if status.id not in self.active_jobs.keys(): 478 | self.active_jobs[status.id] = wsd_scan__operations.wsd_get_job_elements(self.service, status.id) 479 | else: 480 | self.active_jobs[status.id][0] = status 481 | self.queues.job_status_q.task_done() 482 | while self.queues.job_ended_q.empty() is not True: 483 | summary = self.queues.sc_cond_q.get() 484 | del self.active_jobs[summary.status.id] 485 | self.job_history[summary.status.id] = summary 486 | self.queues.job_ended_q.task_done() 487 | return self.active_jobs 488 | 489 | def get_job_history(self): 490 | while self.queues.job_ended_q.empty() is not True: 491 | summary = self.queues.sc_cond_q.get() 492 | del self.active_jobs[summary.status.id] 493 | self.job_history[summary.status.id] = summary 494 | self.queues.job_ended_q.task_done() 495 | return self.job_history 496 | 497 | def scanner_description_has_changed(self): 498 | """ 499 | Check if the scanner status has been updated since last get_scanner_description() call 500 | 501 | :return: True if the scanner description has changed, False otherwise 502 | """ 503 | return not self.queues.sc_cond_q.empty() 504 | 505 | def scanner_configuration_has_changed(self): 506 | """ 507 | Check if the scanner status has been updated since last get_scanner_configuration() call 508 | 509 | :return: True if the scanner configuration has changed, False otherwise 510 | """ 511 | return not self.queues.sc_conf_q.empty() 512 | 513 | def default_scan_ticket_has_changed(self): 514 | """ 515 | Check if the scanner status has been updated since last get_default_ticket() call 516 | 517 | :return: True if the default scan ticket has changed, False otherwise 518 | """ 519 | return not self.queues.sc_ticket_q.empty() 520 | 521 | def scanner_status_has_changed(self): 522 | """ 523 | Check if the scanner status has been updated since last get_scanner_status() call 524 | 525 | :return: True if the scanner status has changed, False otherwise 526 | """ 527 | return not (self.queues.sc_cond_q.empty() 528 | and self.queues.sc_cond_clr_q.empty() 529 | and self.queues.sc_stat_sum_q.empty()) 530 | 531 | def job_status_has_changed(self): 532 | """ 533 | Check if the status of some jobs has been updated since last get_job_status() call 534 | 535 | :return: True if the status of some jobs has changed, False otherwise 536 | """ 537 | return not (self.queues.job_status_q.empty() 538 | and self.queues.job_ended_q.empty()) 539 | 540 | 541 | def device_initiated_scan_worker(client_context: str, 542 | scan_identifier: str, 543 | file_name: str): 544 | """ 545 | Reply to a ScanAvailable event by issuing the creation of a new scan job. 546 | Waits for job completion and writes the output to files. 547 | 548 | :param client_context: a string identifying a wsd host selection 549 | :type client_context: str 550 | :param scan_identifier: a string identifying the specific scan task to handle 551 | :type scan_identifier: str 552 | :param file_name: the prefix name of the files to write. 553 | :type file_name: str 554 | """ 555 | host = host_map[client_context] 556 | dest_token = token_map[client_context] 557 | ticket = wsd_scan__operations.wsd_get_scanner_elements(host).std_ticket 558 | job = wsd_scan__operations.wsd_create_scan_job(host, ticket, scan_identifier, dest_token) 559 | 560 | o = 0 561 | images = [] 562 | while o < ticket.doc_params.images_num: 563 | imgnum, imglist = wsd_scan__operations.wsd_retrieve_image(host, job, file_name) 564 | for i in imglist: 565 | i.save("%s_%d.jpeg" % (file_name, o), "BMP") 566 | o += 1 567 | images += imglist 568 | 569 | 570 | def __demo_simple_listener(): 571 | import wsd_discovery__operations 572 | import wsd_transfer__operations 573 | wsd_common.init() 574 | tsl = wsd_discovery__operations.get_devices() 575 | (ti, hss) = wsd_transfer__operations.wsd_get(list(tsl)[0]) 576 | for b in hss: 577 | if "wscn:ScannerServiceType" in b.types: 578 | listen_addr = "http://192.168.1.109:6666/wsd" 579 | wsd_scanner_all_events_subscribe(b, listen_addr) 580 | (xxx, dest_token) = wsd_scan_available_event_subscribe(b, 581 | "PROVA_PYTHON", 582 | "python_client", 583 | listen_addr) 584 | if dest_token is not None: 585 | token_map["python_client"] = dest_token 586 | host_map["python_client"] = b 587 | break 588 | 589 | server = HTTPServerWithContext(('', 6666), RequestHandler, "context") 590 | wsd_globals.debug = True 591 | server.serve_forever() 592 | 593 | 594 | def __demo_monitor(): 595 | import wsd_discovery__operations 596 | import wsd_transfer__operations 597 | tsl = wsd_discovery__operations.get_devices() 598 | (ti, hss) = wsd_transfer__operations.wsd_get(list(tsl)[0]) 599 | for b in hss: 600 | if "wscn:ScannerServiceType" in b.types: 601 | listen_addr = "http://192.168.1.109:6666/wsd" 602 | m = WSDScannerMonitor(b, listen_addr, 6666) 603 | while True: 604 | time.sleep(2) 605 | print(m.get_scanner_status()) 606 | 607 | 608 | if __name__ == "__main__": 609 | __demo_monitor() 610 | # __demo_simple_listener() 611 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_scan__operations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | import email 5 | import typing 6 | from io import BytesIO 7 | 8 | import lxml.etree as etree 9 | import requests 10 | from PIL import Image, ImageSequence 11 | 12 | from PyWSD import wsd_common, \ 13 | wsd_discovery__operations, \ 14 | wsd_scan__parsers, \ 15 | wsd_scan__structures, \ 16 | wsd_transfer__operations, \ 17 | wsd_transfer__structures, \ 18 | wsd_globals 19 | 20 | 21 | def wsd_get_scanner_elements(hosted_scan_service: wsd_transfer__structures.HostedService): 22 | """ 23 | Submit a GetScannerElements request, and parse the response. 24 | The device should reply with informations about itself, 25 | its configuration, its status and the defalt scan ticket 26 | 27 | :param hosted_scan_service: the wsd scan service to query 28 | :type hosted_scan_service: wsd_transfer__structures.HostedService 29 | :return: a tuple of the form (ScannerDescription, ScannerConfiguration, ScannerStatus, ScanTicket) 30 | """ 31 | fields = {"FROM": wsd_globals.urn, 32 | "TO": hosted_scan_service.ep_ref_addr} 33 | x = wsd_common.submit_request({hosted_scan_service.ep_ref_addr}, 34 | "ws-scan__get_scanner_elements.xml", 35 | fields) 36 | 37 | re = wsd_common.xml_find(x, ".//sca:ScannerElements") 38 | sca_status = wsd_common.xml_find(re, ".//sca:ScannerStatus") 39 | sca_config = wsd_common.xml_find(re, ".//sca:ScannerConfiguration") 40 | sca_descr = wsd_common.xml_find(re, ".//sca:ScannerDescription") 41 | std_ticket = wsd_common.xml_find(re, ".//sca:DefaultScanTicket") 42 | 43 | description = wsd_scan__parsers.parse_scan_description(sca_descr) 44 | status = wsd_scan__parsers.parse_scan_status(sca_status) 45 | config = wsd_scan__parsers.parse_scan_configuration(sca_config) 46 | std_ticket = wsd_scan__parsers.parse_scan_ticket(std_ticket) 47 | 48 | return description, config, status, std_ticket 49 | 50 | 51 | def wsd_validate_scan_ticket(hosted_scan_service: wsd_transfer__structures.HostedService, 52 | tkt: wsd_scan__structures.ScanTicket) \ 53 | -> typing.Tuple[bool, wsd_scan__structures.ScanTicket]: 54 | """ 55 | Submit a ValidateScanTicket request, and parse the response. 56 | Scanner devices can validate scan settings/parameters and fix errors if any. It is recommended to always 57 | validate a ticket before submitting the actual scan job. 58 | 59 | :param hosted_scan_service: the wsd scan service to query 60 | :type hosted_scan_service: wsd_transfer__structures.HostedService 61 | :param tkt: the ScanTicket to submit for validation purposes 62 | :type tkt: wsd_scan__structures.ScanTicket 63 | :return: a tuple of the form (boolean, ScanTicket), where the first field is True if no errors were found during\ 64 | validation, along with the same ticket submitted, or False if errors were found, along with a corrected ticket. 65 | """ 66 | 67 | fields = {"FROM": wsd_globals.urn, 68 | "TO": hosted_scan_service.ep_ref_addr} 69 | x = wsd_common.submit_request({hosted_scan_service.ep_ref_addr}, 70 | "ws-scan__validate_scan_ticket.xml", 71 | {**fields, **tkt.as_map()}) 72 | 73 | v = wsd_common.xml_find(x, ".//sca:ValidTicket") 74 | 75 | if v.text == 'true' or v.text == '1': 76 | return True, tkt 77 | else: 78 | return False, wsd_scan__parsers.parse_scan_ticket(wsd_common.xml_find(x, ".//sca::ValidScanTicket")) 79 | 80 | 81 | def wsd_create_scan_job(hosted_scan_service: wsd_transfer__structures.HostedService, 82 | tkt: wsd_scan__structures.ScanTicket, 83 | scan_identifier: str = "", 84 | dest_token: str = "") \ 85 | -> wsd_scan__structures.ScanJob: 86 | """ 87 | Submit a CreateScanJob request, and parse the response. 88 | This creates a scan job and starts the image(s) acquisition. 89 | 90 | :param hosted_scan_service: the wsd scan service to query 91 | :type hosted_scan_service: wsd_transfer__structures.HostedService 92 | :param tkt: the ScanTicket to submit for validation purposes 93 | :type tkt: wsd_scan__structures.ScanTicket 94 | :param scan_identifier: a string identifying the device-initiated scan to handle, if any 95 | :type scan_identifier: str 96 | :param dest_token: a token assigned by the scanner to this client, needed for device-initiated scans 97 | :type dest_token: str 98 | :return: a ScanJob instance 99 | :rtype: wsd_scan__structures.ScanJob 100 | """ 101 | 102 | fields = {"FROM": wsd_globals.urn, 103 | "TO": hosted_scan_service.ep_ref_addr, 104 | "SCAN_ID": scan_identifier, 105 | "DEST_TOKEN": dest_token} 106 | x = wsd_common.submit_request({hosted_scan_service.ep_ref_addr}, 107 | "ws-scan__create_scan_job.xml", 108 | {**fields, **tkt.as_map()}) 109 | 110 | x = wsd_common.xml_find(x, ".//sca:CreateScanJobResponse") 111 | 112 | return wsd_scan__parsers.parse_scan_job(x) 113 | 114 | 115 | def wsd_cancel_job(hosted_scan_service: wsd_transfer__structures.HostedService, 116 | job: wsd_scan__structures.ScanJob) \ 117 | -> bool: 118 | """ 119 | Submit a CancelJob request, and parse the response. 120 | Stops and aborts the specified scan job. 121 | 122 | :param hosted_scan_service: the wsd scan service to query 123 | :type hosted_scan_service: wsd_transfer__structures.HostedService 124 | :param job: the ScanJob instance representing the job to abort 125 | :type job: wsd_scan_structures.ScanJob 126 | :return: True if the job is found and then aborted, False if the specified job do not exists or already ended. 127 | :rtype: bool 128 | """ 129 | fields = {"FROM": wsd_globals.urn, 130 | "TO": hosted_scan_service.ep_ref_addr, 131 | "JOB_ID": job.id} 132 | x = wsd_common.submit_request({hosted_scan_service.ep_ref_addr}, 133 | "ws-scan__cancel_job.xml", 134 | fields) 135 | 136 | wsd_common.xml_find(x, ".//sca:ClientErrorJobIdNotFound") 137 | return x is None 138 | 139 | 140 | def wsd_get_job_elements(hosted_scan_service: wsd_transfer__structures.HostedService, 141 | job: wsd_scan__structures.ScanJob): 142 | """ 143 | Submit a GetJob request, and parse the response. 144 | The device should reply with info's about the specified job, such as its status, 145 | the ticket submitted for job initiation, the final parameters set effectively used to scan, and a document list. 146 | 147 | :param hosted_scan_service: the wsd scan service to query 148 | :type hosted_scan_service: wsd_transfer__structures.HostedService 149 | :param job: the ScanJob instance representing the job to abort 150 | :type job: wsd_scan_structures.ScanJob 151 | :return: a tuple of the form (JobStatus, ScanTicket, DocumentParams, doclist),\ 152 | where doclist is a list of document names 153 | """ 154 | fields = {"FROM": wsd_globals.urn, 155 | "TO": hosted_scan_service.ep_ref_addr, 156 | "JOB_ID": job.id} 157 | x = wsd_common.submit_request({hosted_scan_service.ep_ref_addr}, 158 | "ws-scan__get_job_elements.xml", 159 | fields) 160 | 161 | q = wsd_common.xml_find(x, ".//sca:JobStatus") 162 | jstatus = wsd_scan__parsers.parse_job_status(q) 163 | 164 | st = wsd_common.xml_find(x, ".//sca:ScanTicket") 165 | tkt = wsd_scan__parsers.parse_scan_ticket(st) 166 | 167 | dfp = wsd_common.xml_find(x, ".//sca:Documents/sca:DocumentFinalParameters") 168 | dps = wsd_scan__parsers.parse_document_params(dfp) 169 | dlist = [x.text for x in wsd_common.xml_findall(dfp, "sca:Document/sca:DocumentDescription/sca:DocumentName")] 170 | 171 | return jstatus, tkt, dps, dlist 172 | 173 | 174 | def wsd_get_active_jobs(hosted_scan_service: wsd_transfer__structures.HostedService) \ 175 | -> typing.List[wsd_scan__structures.JobSummary]: 176 | """ 177 | Submit a GetActiveJobs request, and parse the response. 178 | The device should reply with a list of all active scan jobs. 179 | 180 | :param hosted_scan_service: the wsd scan service to query 181 | :type hosted_scan_service: wsd_transfer__structures.HostedService 182 | :return: a list of JobSummary elements 183 | :rtype: list[wsd_scan__structures.JobSummary] 184 | """ 185 | fields = {"FROM": wsd_globals.urn, 186 | "TO": hosted_scan_service.ep_ref_addr} 187 | x = wsd_common.submit_request({hosted_scan_service.ep_ref_addr}, 188 | "ws-scan__get_active_jobs.xml", 189 | fields) 190 | 191 | jsl = [] 192 | for y in wsd_common.xml_findall(x, ".//sca:JobSummary"): 193 | jsl.append(wsd_scan__parsers.parse_job_summary(y)) 194 | 195 | return jsl 196 | 197 | 198 | def wsd_get_job_history(hosted_scan_service: wsd_transfer__structures.HostedService) \ 199 | -> typing.List[wsd_scan__structures.JobSummary]: 200 | """ 201 | Submit a GetJobHistory request, and parse the response. 202 | The device should reply with a list of recently ended jobs. 203 | Note that some device implementations do not keep or share job history through WSD. 204 | 205 | :param hosted_scan_service: the wsd scan service to query 206 | :type hosted_scan_service: wsd_transfer__structures.HostedService 207 | :return: a list of JobSummary elements. 208 | """ 209 | fields = {"FROM": wsd_globals.urn, 210 | "TO": hosted_scan_service.ep_ref_addr} 211 | x = wsd_common.submit_request({hosted_scan_service.ep_ref_addr}, 212 | "ws-scan__get_job_history.xml", 213 | fields) 214 | 215 | jsl = [] 216 | for y in wsd_common.xml_findall(x, ".//sca:JobSummary"): 217 | jsl.append(wsd_scan__parsers.parse_job_summary(y)) 218 | 219 | return jsl 220 | 221 | 222 | def wsd_retrieve_image(hosted_scan_service: wsd_transfer__structures.HostedService, 223 | job: wsd_scan__structures.ScanJob, 224 | docname: str) \ 225 | -> typing.Tuple[int, typing.List[Image.Image]]: 226 | """ 227 | Submit a RetrieveImage request, and parse the response. 228 | Retrieves a single image from the scanner, if the job has available images to send. If the file format 229 | selected in the scan ticket was multipage, retrieves a batch of images instead. 230 | Usually the client has approx. 60 seconds to start images acquisition after the creation of a job. 231 | 232 | :param hosted_scan_service: the wsd scan service to query 233 | :type hosted_scan_service: wsd_transfer__structures.HostedService 234 | :param job: the ScanJob instance representing the queried job. 235 | :type job: wsd_scan__structures.ScanJob 236 | :param docname: the name assigned to the image to retrieve. 237 | :type docname: str 238 | :return: the number of images retrieved, and an array of images 239 | :rtype: (int, list[PIL.Image]) 240 | """ 241 | 242 | data = wsd_common.message_from_file(wsd_common.abs_path("../templates/ws-scan__retrieve_image.xml"), 243 | FROM=wsd_globals.urn, 244 | TO=hosted_scan_service.ep_ref_addr, 245 | JOB_ID=job.id, 246 | JOB_TOKEN=job.token, 247 | DOC_DESCR=docname) 248 | 249 | if wsd_globals.debug: 250 | r = etree.fromstring(data.encode("ASCII"), parser=wsd_common.parser) 251 | print('##\n## RETRIEVE IMAGE REQUEST\n##\n') 252 | print(etree.tostring(r, pretty_print=True, xml_declaration=True).decode("ASCII")) 253 | 254 | r = requests.post(hosted_scan_service.ep_ref_addr, headers=wsd_common.headers, data=data) 255 | 256 | try: 257 | x = etree.fromstring(r.text) 258 | q = wsd_common.xml_find(x, ".//soap:Fault") 259 | if q is not None: 260 | e = wsd_common.xml_find(q, ".//soap:Code/soap:Subcode/soap:Value").text 261 | if e == "wscn:ClientErrorNoImagesAvailable": 262 | return 0, [] 263 | except etree.ParseError: 264 | content_with_header = b'Content-type: ' + r.headers['Content-Type'].encode('ascii') + r.content 265 | m = email.message_from_bytes(content_with_header) 266 | 267 | ls = list(m.walk()) 268 | 269 | if wsd_globals.debug: 270 | print('##\n## RETRIEVE IMAGE RESPONSE\n##\n%s\n' % ls[1]) 271 | 272 | img = Image.open(BytesIO(ls[2].get_payload(decode=True))) 273 | print("%s %s %s" % (img.format, img.size, img.mode)) 274 | 275 | count = 0 276 | imglist = [] 277 | 278 | for page in ImageSequence.Iterator(img): 279 | count += 1 280 | a = Image.new(page.mode, page.size) 281 | a.putdata(page.getdata()) 282 | imglist.append(a) 283 | 284 | return count, imglist 285 | 286 | 287 | def __demo(): 288 | wsd_common.init() 289 | wsd_globals.debug = False 290 | tsl = wsd_discovery__operations.get_devices() 291 | for a in tsl: 292 | (ti, hss) = wsd_transfer__operations.wsd_get(a) 293 | for b in hss: 294 | if "wscn:ScannerServiceType" in b.types: 295 | (d, c, s, std_ticket) = wsd_get_scanner_elements(b) 296 | print(a) 297 | print(ti) 298 | print(b) 299 | print(d) 300 | print(c) 301 | print(s) 302 | print(std_ticket) 303 | # t.doc_params.input_src = "ADF" 304 | # t.doc_params.images_num = 0 305 | (valid, ticket) = wsd_validate_scan_ticket(b, std_ticket) 306 | if valid: 307 | j = wsd_create_scan_job(b, ticket) 308 | print(j) 309 | (js, t, dp, dl) = wsd_get_job_elements(b, j) 310 | print(js) 311 | print(t) 312 | print(dp) 313 | print(dl) 314 | jobs = wsd_get_active_jobs(b) 315 | for i in jobs: 316 | print(i) 317 | jobs = wsd_get_job_history(b) 318 | for i in jobs: 319 | print(i) 320 | o = 0 321 | while o < ticket.doc_params.images_num: 322 | imgnum, imglist = wsd_retrieve_image(b, j, "prova.bmp") 323 | for i in imglist: 324 | i.save("prova_%d.bmp" % o, "BMP") 325 | o += 1 326 | 327 | 328 | if __name__ == "__main__": 329 | __demo() 330 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_scan__parsers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | import copy 5 | 6 | from PyWSD import wsd_common, \ 7 | wsd_scan__structures 8 | 9 | 10 | # try to use declxml https://github.com/gatkin/declxml 11 | # NB: declxml do not support namespaces AFAIK 12 | 13 | def parse_scan_ticket(std_ticket): 14 | st = wsd_scan__structures.ScanTicket() 15 | st.job_name = wsd_common.xml_find(std_ticket, ".//sca:JobDescription/sca:JobName").text 16 | st.job_user_name = wsd_common.xml_find(std_ticket, ".//sca:JobDescription/sca:JobOriginatingUserName").text 17 | q = wsd_common.xml_find(std_ticket, ".//sca:JobDescription/sca:JobInformation") 18 | if q is not None: 19 | st.job_info = q.text 20 | dps = wsd_common.xml_find(std_ticket, ".//sca:DocumentParameters") 21 | st.doc_params = parse_document_params(dps) 22 | return st 23 | 24 | 25 | def parse_media_side(ms): 26 | s = wsd_scan__structures.MediaSide() 27 | r = wsd_common.xml_find(ms, ".//sca:ScanRegion") 28 | if r is not None: 29 | q = wsd_common.xml_find(r, ".//sca:ScanRegionXOffset") 30 | if q is not None: 31 | s.offset = (int(q.text), s.offset[1]) 32 | q = wsd_common.xml_find(r, ".//sca:ScanRegionYOffset") 33 | if q is not None: 34 | s.offset = (s.offset[0], int(q.text)) 35 | v1 = wsd_common.xml_find(r, ".//sca:ScanRegionWidth") 36 | v2 = wsd_common.xml_find(r, ".//sca:ScanRegionHeight") 37 | s.size = (int(v1.text), int(v2.text)) 38 | q = wsd_common.xml_find(ms, ".//sca:ColorProcessing") 39 | if q is not None: 40 | s.color = q.text 41 | q = wsd_common.xml_find(ms, ".//sca:Resolution/sca:Width") 42 | s.res = (int(q.text), s.res[1]) 43 | q = wsd_common.xml_find(ms, ".//sca:Resolution/sca:Height") 44 | s.res = (s.res[0], int(q.text)) 45 | return s 46 | 47 | 48 | def parse_document_params(dps): 49 | dest = wsd_scan__structures.DocumentParams() 50 | q = wsd_common.xml_find(dps, ".//sca:Format") 51 | if q is not None: 52 | dest.format = q.text 53 | q = wsd_common.xml_find(dps, ".//sca:CompressionQualityFactor") 54 | if q is not None: 55 | dest.compression_factor = q.text 56 | q = wsd_common.xml_find(dps, ".//sca:ImagesToTransfer") 57 | if q is not None: 58 | dest.images_num = int(q.text) 59 | q = wsd_common.xml_find(dps, ".//sca:InputSource") 60 | if q is not None: 61 | dest.input_src = q.text 62 | q = wsd_common.xml_find(dps, ".//sca:ContentType") 63 | if q is not None: 64 | dest.content_type = q.text 65 | q = wsd_common.xml_find(dps, ".//sca:InputSize") 66 | if q is not None: 67 | autod = wsd_common.xml_find(q, ".//sca:DocumentAutoDetect") 68 | if autod is not None: 69 | dest.size_autodetect = True if autod.text == 'true' or autod.text == '1' else False 70 | v1 = wsd_common.xml_find(q, ".//sca:InputMediaSize/sca:Width") 71 | v2 = wsd_common.xml_find(q, ".//sca:InputMediaSize/sca:Height") 72 | dest.input_size = (int(v1.text), int(v2.text)) 73 | q = wsd_common.xml_find(dps, ".//sca:Exposure") 74 | if q is not None: 75 | autod = wsd_common.xml_find(q, ".//sca:AutoExposure") 76 | if autod is not None: 77 | dest.auto_exposure = True if autod.text == 'true' or autod.text == '1' else False 78 | dest.contrast = int(wsd_common.xml_find(q, ".//sca:ExposureSettings/sca:Contrast").text) 79 | dest.brightness = int(wsd_common.xml_find(q, ".//sca:ExposureSettings/sca:Brightness").text) 80 | dest.sharpness = int(wsd_common.xml_find(q, ".//sca:ExposureSettings/sca:Sharpness").text) 81 | q = wsd_common.xml_find(dps, ".//sca:Scaling") 82 | if q is not None: 83 | v1 = wsd_common.xml_find(q, ".//sca:ScalingWidth") 84 | v2 = wsd_common.xml_find(q, ".//sca:ScalingHeight") 85 | dest.scaling = (int(v1.text), int(v2.text)) 86 | q = wsd_common.xml_find(dps, ".//sca:Rotation") 87 | if q is not None: 88 | dest.rotation = int(q.text) 89 | q = wsd_common.xml_find(dps, ".//sca:MediaSides") 90 | if q is not None: 91 | f = wsd_common.xml_find(q, ".//sca:MediaFront") 92 | dest.front = parse_media_side(f) 93 | 94 | f = wsd_common.xml_find(q, ".//sca:MediaBack") 95 | if f is not None: 96 | dest.back = parse_media_side(f) 97 | else: 98 | dest.back = copy.deepcopy(dest.front) 99 | return dest 100 | 101 | 102 | def parse_scanner_condition(scond): 103 | c = wsd_scan__structures.ScannerCondition() 104 | c.id = int(scond.get("Id")) 105 | c.time = wsd_common.xml_find(scond, ".//sca:Time").text 106 | c.name = wsd_common.xml_find(scond, ".//sca:Name").text 107 | c.component = wsd_common.xml_find(scond, ".//sca:Component").text 108 | c.severity = wsd_common.xml_find(scond, ".//sca:Severity").text 109 | return c 110 | 111 | 112 | def parse_scanner_source_settings(se, name): 113 | sss = wsd_scan__structures.ScannerSourceSettings() 114 | v1 = wsd_common.xml_find(se, ".//sca:%sOpticalResolution/sca:Width" % name) 115 | v2 = wsd_common.xml_find(se, ".//sca:%sOpticalResolution/sca:Height" % name) 116 | sss.optical_res = (int(v1.text), int(v2.text)) 117 | q = wsd_common.xml_findall(se, ".//sca:%sResolutions/sca:Widths/sca:Width" % name) 118 | sss.width_res = [x.text for x in q] 119 | q = wsd_common.xml_findall(se, ".//sca:%sResolutions/sca:Heights/sca:Height" % name) 120 | sss.height_res = [x.text for x in q] 121 | q = wsd_common.xml_findall(se, ".//sca:%sColor/sca:ColorEntry" % name) 122 | sss.color_modes = [x.text for x in q] 123 | v1 = wsd_common.xml_find(se, ".//sca:%sMinimumSize/sca:Width" % name) 124 | v2 = wsd_common.xml_find(se, ".//sca:%sMinimumSize/sca:Height" % name) 125 | sss.min_size = (int(v1.text), int(v2.text)) 126 | v1 = wsd_common.xml_find(se, ".//sca:%sMaximumSize/sca:Width" % name) 127 | v2 = wsd_common.xml_find(se, ".//sca:%sMaximumSize/sca:Height" % name) 128 | sss.max_size = (int(v1.text), int(v2.text)) 129 | return sss 130 | 131 | 132 | def parse_job_summary(y): 133 | jsum = wsd_scan__structures.JobSummary() 134 | jsum.name = wsd_common.xml_find(y, "sca:JobName").text 135 | jsum.user_name = wsd_common.xml_find(y, "sca:JobOriginatingUserName").text 136 | jsum.status = parse_job_status(y) 137 | return jsum 138 | 139 | 140 | def parse_job_status(q): 141 | jstatus = wsd_scan__structures.JobStatus() 142 | jstatus.id = int(wsd_common.xml_find(q, "sca:JobId").text) 143 | q1 = wsd_common.xml_find(q, "sca:JobState") 144 | q2 = wsd_common.xml_find(q, "sca:JobCompletedState") 145 | jstatus.state = q1.text if q1 is not None else q2.text 146 | jstatus.reasons = [x.text for x in wsd_common.xml_findall(q, "sca:JobStateReasons")] 147 | jstatus.scans_completed = int(wsd_common.xml_find(q, "sca:ScansCompleted").text) 148 | a = wsd_common.xml_find(q, "sca:JobCreatedTime") 149 | jstatus.creation_time = q.text if a is not None else "" 150 | a = wsd_common.xml_find(q, "sca:JobCompletedTime") 151 | jstatus.completed_time = q.text if a is not None else "" 152 | return jstatus 153 | 154 | 155 | def parse_scan_configuration(sca_config): 156 | config = wsd_scan__structures.ScannerConfiguration() 157 | ds = wsd_common.xml_find(sca_config, ".//sca:DeviceSettings") 158 | pla = wsd_common.xml_find(sca_config, ".//sca:Platen") 159 | adf = wsd_common.xml_find(sca_config, ".//sca:ADF") 160 | # .//sca:Film omitted 161 | 162 | s = wsd_scan__structures.ScannerSettings() 163 | q = wsd_common.xml_findall(ds, ".//sca:FormatsSupported/sca:FormatValue") 164 | s.formats = [x.text for x in q] 165 | v1 = wsd_common.xml_find(ds, ".//sca:CompressionQualityFactorSupported/sca:MinValue") 166 | v2 = wsd_common.xml_find(ds, ".//sca:CompressionQualityFactorSupported/sca:MaxValue") 167 | s.compression_factor = (int(v1.text), int(v2.text)) 168 | q = wsd_common.xml_findall(ds, ".//sca:ContentTypesSupported/sca:ContentTypeValue") 169 | s.content_types = [x.text for x in q] 170 | q = wsd_common.xml_find(ds, ".//sca:DocumentSizeAutoDetectSupported") 171 | s.size_autodetect_sup = True if q.text == 'true' or q.text == '1' else False 172 | q = wsd_common.xml_find(ds, ".//sca:AutoExposureSupported") 173 | s.auto_exposure_sup = True if q.text == 'true' or q.text == '1' else False 174 | q = wsd_common.xml_find(ds, ".//sca:BrightnessSupported") 175 | s.brightness_sup = True if q.text == 'true' or q.text == '1' else False 176 | q = wsd_common.xml_find(ds, ".//sca:ContrastSupported") 177 | s.contrast_sup = True if q.text == 'true' or q.text == '1' else False 178 | v1 = wsd_common.xml_find(ds, ".//sca:ScalingRangeSupported/sca:ScalingWidth/sca:MinValue") 179 | v2 = wsd_common.xml_find(ds, ".//sca:ScalingRangeSupported/sca:ScalingWidth/sca:MaxValue") 180 | s.scaling_range_w = (int(v1.text), int(v2.text)) 181 | v1 = wsd_common.xml_find(ds, ".//sca:ScalingRangeSupported/sca:ScalingHeight/sca:MinValue") 182 | v2 = wsd_common.xml_find(ds, ".//sca:ScalingRangeSupported/sca:ScalingHeight/sca:MaxValue") 183 | s.scaling_range_h = (int(v1.text), int(v2.text)) 184 | q = wsd_common.xml_findall(ds, ".//sca:RotationsSupported/sca:RotationValue") 185 | s.rotations = [x.text for x in q] 186 | config.settings = s 187 | if pla is not None: 188 | config.platen = parse_scanner_source_settings(pla, "Platen") 189 | if adf is not None: 190 | q = wsd_common.xml_find(adf, ".//sca:ADFSupportsDuplex") 191 | config.adf_duplex = True if q.text == 'true' or q.text == '1' else False 192 | f = wsd_common.xml_find(adf, ".//sca:ADFFront") 193 | bk = wsd_common.xml_find(adf, ".//sca:ADFBack") 194 | if f is not None: 195 | config.front_adf = parse_scanner_source_settings(f, "ADF") 196 | if bk is not None: 197 | config.back_adf = parse_scanner_source_settings(bk, "ADF") 198 | return config 199 | 200 | 201 | def parse_scan_status(sca_status): 202 | status = wsd_scan__structures.ScannerStatus() 203 | 204 | status.time = wsd_common.xml_find(sca_status, ".//sca:ScannerCurrentTime").text 205 | status.state = wsd_common.xml_find(sca_status, ".//sca:ScannerState").text 206 | ac = wsd_common.xml_find(sca_status, ".//sca:ActiveConditions") 207 | if ac is not None: 208 | dcl = wsd_common.xml_findall(ac, ".//sca:DeviceCondition") 209 | for dc in dcl: 210 | c = parse_scanner_condition(dc) 211 | status.active_conditions[c.id] = c 212 | q = wsd_common.xml_find(sca_status, ".//sca:ScannerStateReasons") 213 | if q is not None: 214 | dsr = wsd_common.xml_findall(q, ".//sca:ScannerStateReason") 215 | for sr in dsr: 216 | status.reasons.append(sr.text) 217 | q = wsd_common.xml_find(sca_status, ".//sca:ConditionHistory") 218 | if q is not None: 219 | chl = wsd_common.xml_findall(q, ".//sca:ConditionHistoryEntry") 220 | for che in chl: 221 | c = parse_scanner_condition(che) 222 | status.conditions_history[wsd_common.xml_find(che, ".//sca:ClearTime").text] = c 223 | return status 224 | 225 | 226 | def parse_scan_description(sca_descr): 227 | description = wsd_scan__structures.ScannerDescription() 228 | 229 | description.name = wsd_common.xml_find(sca_descr, ".//sca:ScannerName").text 230 | q = wsd_common.xml_find(sca_descr, ".//sca:ScannerInfo") 231 | if q is not None: 232 | description.info = q.text 233 | q = wsd_common.xml_find(sca_descr, ".//sca:ScannerLocation") 234 | if q is not None: 235 | description.location = q.text 236 | return description 237 | 238 | 239 | def parse_scan_job(x): 240 | scnj = wsd_scan__structures.ScanJob() 241 | scnj.id = int(wsd_common.xml_find(x, ".//sca:JobId").text) 242 | scnj.token = wsd_common.xml_find(x, ".//sca:JobToken").text 243 | q = wsd_common.xml_find(x, ".//sca:ImageInformation/sca:MediaFrontImageInfo") 244 | scnj.f_pixel_line = int(wsd_common.xml_find(q, "sca:PixelsPerLine").text) 245 | scnj.f_num_lines = int(wsd_common.xml_find(q, "sca:NumberOfLines").text) 246 | scnj.f_byte_line = int(wsd_common.xml_find(q, "sca:BytesPerLine").text) 247 | q = wsd_common.xml_find(x, ".//sca:ImageInformation/sca:MediaBackImageInfo") 248 | if q is not None: 249 | scnj.b_pixel_line = int(wsd_common.xml_find(q, "sca:PixelsPerLine").text) 250 | scnj.b_num_lines = int(wsd_common.xml_find(q, "sca:NumberOfLines").text) 251 | scnj.b_byte_line = int(wsd_common.xml_find(q, "sca:BytesPerLine").text) 252 | dpf = wsd_common.xml_find(x, ".//sca:DocumentFinalParameters") 253 | scnj.doc_params = parse_document_params(dpf) 254 | return scnj 255 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_scan__structures.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | from PyWSD import wsd_common 5 | 6 | 7 | class ScannerCondition: 8 | def __init__(self): 9 | self.id = 0 10 | self.time = "" 11 | self.name = "" 12 | self.component = "" 13 | self.severity = "" 14 | 15 | def __str__(self): 16 | s = "" 17 | s += "Condition ID: %d\n" % self.id 18 | s += "Condition name: %s\n" % self.name 19 | s += "Condition time: %s\n" % self.time 20 | s += "Condition component: %s\n" % self.component 21 | s += "Condition severity: %s\n" % self.severity 22 | return s 23 | 24 | 25 | class ScannerStatus: 26 | def __init__(self): 27 | self.time = "" 28 | self.state = "" 29 | self.reasons = [] 30 | self.active_conditions = {} # dict {id, condition} 31 | self.conditions_history = {} # dict (time, condition) 32 | 33 | def __str__(self): 34 | s = "" 35 | s += "Scanner time: %s\n" % self.time 36 | s += "Scanner state: %s\n" % self.state 37 | s += "Reasons: %s\n" % ", ".join(self.reasons) 38 | s += "Active conditions:\n" 39 | for ac_id, ac in self.active_conditions.items(): 40 | s += wsd_common.indent(str(ac)) 41 | s += "Condition history:\n" 42 | for t, c in self.conditions_history.items(): 43 | s += wsd_common.indent(str(c)) 44 | s += wsd_common.indent("Clear time: %s\n" % t) 45 | return s 46 | 47 | 48 | class ScannerSettings: 49 | def __init__(self): 50 | self.formats = [] 51 | self.compression_factor = (0, 0) # (min, max) 52 | self.content_types = [] 53 | self.size_autodetect_sup = False 54 | self.auto_exposure_sup = False 55 | self.brightness_sup = False 56 | self.contrast_sup = False 57 | self.scaling_range_w = (0, 0) # (min, max) 58 | self.scaling_range_h = (0, 0) # (min, max) 59 | self.rotations = [] 60 | 61 | def __str__(self): 62 | s = '' 63 | s += "Supported formats: %s\n" % ', '.join(self.formats) 64 | s += "Compression range: %d - %d\n" % self.compression_factor 65 | s += "Content types: %s\n" % ', '.join(self.content_types) 66 | s += "Size autodetect: %r\n" % self.size_autodetect_sup 67 | s += "Auto exposure: %r\n" % self.auto_exposure_sup 68 | s += "Manual brightness: %r\n" % self.brightness_sup 69 | s += "Manual contrast: %r\n" % self.contrast_sup 70 | s += "Width scaling: %d - %d\n" % self.scaling_range_w 71 | s += "Height scaling: %d - %d\n" % self.scaling_range_h 72 | s += "Rotations: %s\n" % ', '.join(self.rotations) 73 | return s 74 | 75 | 76 | class ScannerSourceSettings: 77 | def __init__(self): 78 | self.optical_res = (0, 0) 79 | self.width_res = [] 80 | self.height_res = [] 81 | self.color_modes = [] 82 | self.min_size = (0, 0) 83 | self.max_size = (0, 0) 84 | 85 | def __str__(self): 86 | s = "" 87 | s += "Optical resolution: (%d, %d)\n" % self.optical_res 88 | s += "Width resolutions: %s\n" % ', '.join(self.width_res) 89 | s += "Height resolutions: %s\n" % ', '.join(self.height_res) 90 | s += "Color modes: %s\n" % ', '.join(self.color_modes) 91 | s += "Minimum size: (%d, %d)\n" % self.min_size 92 | s += "Maximum size: (%d, %d)\n" % self.max_size 93 | return s 94 | 95 | 96 | class DocumentParams: 97 | def __init__(self): 98 | self.format = "" 99 | self.compression_factor = "" 100 | self.images_num = 0 101 | self.input_src = "" 102 | self.content_type = "" 103 | self.size_autodetect = False 104 | self.input_size = (0, 0) 105 | self.auto_exposure = False 106 | self.contrast = 0 107 | self.brightness = 0 108 | self.sharpness = 0 109 | self.scaling = (100, 100) 110 | self.rotation = 0 111 | self.front = None 112 | self.back = None 113 | 114 | def __str__(self): 115 | s = "" 116 | s += "Format: %s\n" % self.format 117 | s += "Compression factor: %s\n" % self.compression_factor 118 | s += "Images count: %d\n" % self.images_num 119 | s += "Input source: %s\n" % self.input_src 120 | s += "Content type: %s\n" % self.content_type 121 | s += "Size autodetect: %r\n" % self.size_autodetect 122 | s += "Input size: (%d, %d)\n" % self.input_size 123 | s += "Auto exposure: %r\n" % self.auto_exposure 124 | s += "Contrast: %d\n" % self.contrast 125 | s += "Brightness: %d\n" % self.brightness 126 | s += "Sharpness: %d\n" % self.sharpness 127 | s += "Scaling: (%d, %d)\n" % self.scaling 128 | s += "Rotation: %d\n" % self.rotation 129 | if self.front is not None: 130 | s += "Front side:\n" 131 | s += wsd_common.indent(str(self.front)) 132 | if self.back is not None: 133 | s += "Back side:\n" 134 | s += wsd_common.indent(str(self.back)) 135 | return s 136 | 137 | 138 | class ScanTicket: 139 | def __init__(self): 140 | self.job_name = "" 141 | self.job_user_name = "" 142 | self.job_info = "" 143 | self.doc_params = None 144 | 145 | def __str__(self): 146 | s = "" 147 | s += "Job name: %s\n" % self.job_name 148 | s += "User name: %s\n" % self.job_user_name 149 | s += "Job info: %s\n" % self.job_info 150 | s += "Document parameters:\n" 151 | s += wsd_common.indent(str(self.doc_params)) 152 | return s 153 | 154 | def as_map(self): 155 | return {'JOB_NAME': self.job_name, 156 | 'USER_NAME': self.job_user_name, 157 | 'JOB_INFO': self.job_info, 158 | 'FORMAT': self.doc_params.format, 159 | 'QUALITY_FACTOR': self.doc_params.compression_factor, 160 | 'IMG_NUM': self.doc_params.images_num, 161 | 'INPUT_SRC': self.doc_params.input_src, 162 | 'CONTENT_TYPE': self.doc_params.content_type, 163 | 'SIZE_AUTODETECT': self.doc_params.size_autodetect, 164 | 'INPUT_W': self.doc_params.input_size[0], 165 | 'INPUT_H': self.doc_params.input_size[1], 166 | 'AUTO_EXPOSURE': self.doc_params.auto_exposure, 167 | 'CONTRAST': self.doc_params.contrast, 168 | 'BRIGHTNESS': self.doc_params.brightness, 169 | 'SHARPNESS': self.doc_params.sharpness, 170 | 'SCALING_W': self.doc_params.scaling[0], 171 | 'SCALING_H': self.doc_params.scaling[1], 172 | 'ROTATION': self.doc_params.rotation, 173 | 'FRONT_X_OFFSET': self.doc_params.front.offset[0], 174 | 'FRONT_Y_OFFSET': self.doc_params.front.offset[1], 175 | 'FRONT_SIZE_W': self.doc_params.front.size[0], 176 | 'FRONT_SIZE_H': self.doc_params.front.size[1], 177 | 'FRONT_COLOR': self.doc_params.front.color, 178 | 'FRONT_RES_W': self.doc_params.front.res[0], 179 | 'FRONT_RES_H': self.doc_params.front.res[1], 180 | 'BACK_X_OFFSET': self.doc_params.back.offset[0], 181 | 'BACK_Y_OFFSET': self.doc_params.back.offset[1], 182 | 'BACK_SIZE_W': self.doc_params.back.size[0], 183 | 'BACK_SIZE_H': self.doc_params.back.size[1], 184 | 'BACK_COLOR': self.doc_params.back.color, 185 | 'BACK_RES_W': self.doc_params.back.res[0], 186 | 'BACK_RES_H': self.doc_params.back.res[1]} 187 | 188 | 189 | class ScanJob: 190 | def __init__(self): 191 | self.id = 0 192 | self.token = "" 193 | self.f_pixel_line = 0 194 | self.f_num_lines = 0 195 | self.f_byte_line = 0 196 | self.b_pixel_line = None 197 | self.b_num_lines = None 198 | self.b_byte_line = None 199 | self.doc_params = None 200 | 201 | def __str__(self): 202 | s = "" 203 | s += "Job id: %d\n" % self.id 204 | s += "Job token: %s\n" % self.token 205 | s += "Front properties:\n" 206 | s += "\tPixels/line: %s\n" % self.f_pixel_line 207 | s += "\tLines count: %s\n" % self.f_num_lines 208 | s += "\tBytes/line: %s\n" % self.f_byte_line 209 | if self.b_pixel_line is not None: 210 | s += "Back properties:\n" 211 | s += "\tPixels/line: %s\n" % self.b_pixel_line 212 | s += "\tLines count: %s\n" % self.b_num_lines 213 | s += "\tBytes/line: %s\n" % self.b_byte_line 214 | s += "Document parameters:\n" 215 | s += wsd_common.indent(str(self.doc_params)) 216 | return s 217 | 218 | 219 | class JobStatus: 220 | def __init__(self): 221 | self.id = 0 222 | self.state = "" 223 | self.reasons = [] 224 | self.scans_completed = 0 225 | self.creation_time = "" 226 | self.completed_time = "" 227 | 228 | def __str__(self): 229 | s = "" 230 | s += "Job id: %d\n" % self.id 231 | s += "Job state: %s\n" % self.state 232 | s += "State reasons: %s\n" % ', '.join(self.reasons) 233 | s += "Scans completed: %d\n" % self.scans_completed 234 | s += "Job created at: %s\n" % self.creation_time 235 | s += "Job completed at: %s\n" % self.completed_time 236 | return s 237 | 238 | 239 | class JobSummary: 240 | def __init__(self): 241 | self.name = "" 242 | self.user_name = "" 243 | self.status = JobStatus() 244 | 245 | def __str__(self): 246 | s = "" 247 | s += "Job name: %s\n" % self.name 248 | s += "User name: %s\n" % self.user_name 249 | s += str(self.status) 250 | return s 251 | 252 | 253 | class MediaSide: 254 | def __init__(self): 255 | self.offset = (0, 0) 256 | self.size = (0, 0) 257 | self.color = "" 258 | self.res = (0, 0) 259 | 260 | def __str__(self): 261 | s = "" 262 | s += "Offset: (%d, %d)\n" % self.offset 263 | s += "Size: (%d, %d)\n" % self.size 264 | s += "Color mode: %s\n" % self.color 265 | s += "Resolution: (%d, %d)\n" % self.res 266 | return s 267 | 268 | 269 | class ScannerDescription: 270 | def __init__(self): 271 | self.name = "" 272 | self.info = "" 273 | self.location = "" 274 | 275 | def __str__(self): 276 | s = "" 277 | s += "Scanner name: %s\n" % self.name 278 | s += "Scanner info: %s\n" % self.info 279 | s += "Scanner location: %s\n" % self.location 280 | return s 281 | 282 | 283 | class ScannerConfiguration: 284 | def __init__(self): 285 | self.settings = ScannerSettings() 286 | self.platen = None 287 | self.adf_duplex = False 288 | self.front_adf = None 289 | self.back_adf = None 290 | 291 | def __str__(self): 292 | s = "" 293 | s += str(self.settings) 294 | if self.platen is not None: 295 | s += "Platen settings:\n" 296 | s += wsd_common.indent(str(self.platen)) 297 | if self.front_adf is not None: 298 | s += "ADF Duplex: %r\n" % self.adf_duplex 299 | s += "ADF front settings:\n" 300 | s += wsd_common.indent(str(self.front_adf)) 301 | if self.adf_duplex: 302 | s += "ADF back settings:\n" 303 | s += wsd_common.indent(str(self.back_adf)) 304 | return s 305 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_transfer__operations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | from PyWSD import wsd_common, \ 5 | wsd_discovery__operations, \ 6 | wsd_discovery__structures, \ 7 | wsd_transfer__structures, \ 8 | wsd_globals 9 | 10 | 11 | def wsd_get(target_service: wsd_discovery__structures.TargetService): 12 | """ 13 | Query wsd target for information about model/device and hosted services. 14 | 15 | :param target_service: A wsd target 16 | :type target_service: wsd_discovery__structures.TargetService 17 | :return: A tuple containing a TargetInfo and a list of HostedService instances. 18 | """ 19 | fields = {"FROM": wsd_globals.urn, 20 | "TO": target_service.ep_ref_addr} 21 | x = wsd_common.submit_request(target_service.xaddrs, 22 | "ws-transfer__get.xml", 23 | fields) 24 | 25 | if x is False: 26 | return False 27 | 28 | meta = wsd_common.xml_find(x, ".//mex:Metadata") 29 | meta_model = wsd_common.xml_find(meta, 30 | ".//mex:MetadataSection[@Dialect=\ 31 | 'http://schemas.xmlsoap.org/ws/2006/02/devprof/ThisModel']") 32 | meta_dev = wsd_common.xml_find(meta, 33 | ".//mex:MetadataSection[@Dialect=\ 34 | 'http://schemas.xmlsoap.org/ws/2006/02/devprof/ThisDevice']") 35 | meta_rel = wsd_common.xml_find(meta, 36 | ".//mex:MetadataSection[@Dialect=\ 37 | 'http://schemas.xmlsoap.org/ws/2006/02/devprof/Relationship']") 38 | 39 | tinfo = wsd_transfer__structures.TargetInfo() 40 | # WSD-Profiles section 5.1 (+ PNP-X) 41 | tinfo.manufacturer = wsd_common.xml_find(meta_model, ".//wsdp:Manufacturer").text 42 | q = wsd_common.xml_find(meta_model, ".//wsdp:ManufacturerUrl") 43 | if q is not None: 44 | tinfo.manufacturer_url = q.text 45 | tinfo.model_name = wsd_common.xml_find(meta_model, ".//wsdp:ModelName").text 46 | q = wsd_common.xml_find(meta_model, ".//wsdp:ModelNumber") 47 | if q is not None: 48 | tinfo.model_number = q.text 49 | q = wsd_common.xml_find(meta_model, ".//wsdp:ModelUrl") 50 | if q is not None: 51 | tinfo.model_url = q.text 52 | q = wsd_common.xml_find(meta_model, ".//wsdp:PresentationUrl") 53 | if q is not None: 54 | tinfo.presentation_url = q.text 55 | tinfo.device_cat = wsd_common.xml_find(meta_model, ".//pnpx:DeviceCategory").text.split() 56 | 57 | tinfo.friendly_name = wsd_common.xml_find(meta_dev, ".//wsdp:FriendlyName").text 58 | tinfo.fw_ver = wsd_common.xml_find(meta_dev, ".//wsdp:FirmwareVersion").text 59 | tinfo.serial_num = wsd_common.xml_find(meta_dev, ".//wsdp:SerialNumber").text 60 | 61 | hservices = [] 62 | # WSD-Profiles section 5.2 (+ PNP-X) 63 | wsd_common.xml_findall(meta_rel, ".//wsdp:Relationship[@Type='http://schemas.xmlsoap.org/ws/2006/02/devprof/host']") 64 | 65 | for r in meta_rel: 66 | # UNCLEAR how the host item should differ from the target endpoint, and how to manage multiple host items 67 | # TBD - need some real-case examples 68 | # host = xml_find(r, ".//wsdp:Host") 69 | # if host is not None: #"if omitted, implies the same endpoint reference of the targeted service" 70 | # xml_find(host, ".//wsdp:Types").text 71 | # xml_find(host, ".//wsdp:ServiceId").text 72 | # er = xml_find(host, ".//wsa:EndpointReference") 73 | # xml_find(er, ".//wsa:Address").text #Optional endpoint fields not implemented yet 74 | hosted = wsd_common.xml_findall(r, ".//wsdp:Hosted") 75 | for h in hosted: 76 | hs = wsd_transfer__structures.HostedService() 77 | hs.types = wsd_common.xml_find(h, ".//wsdp:Types").text.split() 78 | hs.service_id = wsd_common.xml_find(h, ".//wsdp:ServiceId").text 79 | q = wsd_common.xml_find(h, ".//pnpx:HardwareId") 80 | if q is not None: 81 | hs.hardware_id = q.text 82 | q = wsd_common.xml_find(h, ".//pnpx:CompatibleId") 83 | if q is not None: 84 | hs.compatible_id = q.text 85 | q = wsd_common.xml_find(h, ".//wsdp:ServiceAddress") 86 | if q is not None: 87 | hs.service_address = q.text 88 | er = wsd_common.xml_find(h, ".//wsa:EndpointReference") 89 | hs.ep_ref_addr = wsd_common.xml_find(er, ".//wsa:Address").text 90 | hservices.append(hs) 91 | 92 | # WSD-Profiles section 5.3 and 5.4 omitted 93 | return tinfo, hservices 94 | 95 | 96 | def __demo(): 97 | wsd_common.init() 98 | wsd_common.enable_debug() 99 | tsl = wsd_discovery__operations.get_devices() 100 | for a in tsl: 101 | print(a) 102 | try: 103 | (ti, hss) = wsd_get(a) 104 | print(ti) 105 | for b in hss: 106 | print(b) 107 | except TimeoutError: 108 | print("The target did not reply") 109 | 110 | 111 | if __name__ == "__main__": 112 | __demo() 113 | -------------------------------------------------------------------------------- /src/PyWSD/wsd_transfer__structures.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | class TargetInfo: 6 | """ 7 | Holds information about a certain target service, such as name, model, manufacturer, and so on. 8 | """ 9 | 10 | def __init__(self): 11 | self.manufacturer = "" 12 | self.manufacturer_url = "" 13 | self.model_name = "" 14 | self.model_number = "" 15 | self.model_url = "" 16 | self.presentation_url = "" 17 | self.device_cat = [] 18 | self.friendly_name = "" 19 | self.fw_ver = "" 20 | self.serial_num = "" 21 | 22 | def __str__(self): 23 | s = "" 24 | s += "Friendly name: %s\n" % self.friendly_name 25 | s += "Model name: %s\n" % self.model_name 26 | s += "Model number: %s\n" % self.model_number 27 | s += "Device categories: %s\n" % ', '.join(self.device_cat) 28 | s += "Manufacturer: %s\n" % self.manufacturer 29 | 30 | s += "Firmware version: %s\n" % self.fw_ver 31 | s += "Serial number: %s\n" % self.serial_num 32 | 33 | s += "Manufacturer URL: %s\n" % self.manufacturer_url 34 | s += "Model URL: %s\n" % self.model_url 35 | s += "Web UI URL: %s\n" % self.presentation_url 36 | return s 37 | 38 | 39 | class HostedService: 40 | """ 41 | An actual service offered by a certain wsd target. Each device is a target, but 42 | a target can publish multiple hosted services at once. 43 | """ 44 | 45 | def __init__(self): 46 | self.types = [] 47 | self.service_id = "" 48 | self.hardware_id = "" 49 | self.compatible_id = "" 50 | self.service_address = "" 51 | self.ep_ref_addr = "" 52 | 53 | def __str__(self): 54 | s = "" 55 | s += "Service path: %s\n" % self.ep_ref_addr 56 | s += "Service ID: %s\n" % self.service_id 57 | s += "Service types: %s\n" % ', '.join(self.types) 58 | s += "Compatible IDs: %s\n" % self.compatible_id 59 | s += "Hardware ID: %s\n" % self.hardware_id 60 | s += "Service address: %s\n" % self.service_address 61 | return s 62 | -------------------------------------------------------------------------------- /src/PyWSD/xml_helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- encoding: utf-8 -*- 3 | 4 | # http://www.datypic.com/sc/xsd/t-xsd_dateTime.html 5 | # http://www.datypic.com/sc/xsd/t-xsd_duration.html 6 | 7 | import re 8 | from datetime import datetime, timedelta, timezone 9 | 10 | from dateutil import tz 11 | 12 | 13 | def fmt_as_xml_datetime(dt: datetime): 14 | s = dt.strftime("%Y-%m-%dT%H:%M:%S.%f%z") 15 | fmtstring = s[:23] 16 | if dt.tzinfo is not None: 17 | fmtstring += s[26:29] + ":" + s[29:] 18 | else: 19 | fmtstring += "Z" 20 | return fmtstring 21 | 22 | 23 | def parse_xml_datetime(s: str, 24 | weak: bool = False): 25 | pattern = r""" 26 | ^ 27 | (?P\d{4}) 28 | - 29 | (?P\d{2}) 30 | - 31 | (?P\d{2}) 32 | T 33 | (?P\d{2}) 34 | : 35 | (?P\d{2}) 36 | : 37 | (?P\d{2}) 38 | (\. 39 | (?P\d{1,3}) 40 | )? 41 | ( 42 | (?PZ) 43 | | 44 | ( 45 | (?P[-+]) 46 | (?P\d{2}) 47 | : 48 | (?P\d{2}) 49 | ) 50 | )? 51 | $ 52 | """ 53 | 54 | weak_pattern = r""" 55 | ^ 56 | (?P\d{4}) 57 | - 58 | (?P\d{1,2}) 59 | - 60 | (?P\d{1,2}) 61 | T 62 | (?P\d{1,2}) 63 | : 64 | (?P\d{1,2}) 65 | : 66 | (?P\d{1,2}) 67 | (\. 68 | (?P\d{1,3}) 69 | )? 70 | ( 71 | (?PZ) 72 | | 73 | ( 74 | (?P[-+]) 75 | (?P\d{1,2}) 76 | : 77 | (?P\d{2}) 78 | ) 79 | )? 80 | $ 81 | """ 82 | 83 | p = re.compile(pattern if not weak else weak_pattern, re.VERBOSE) 84 | q = p.search(s) 85 | if q is None: 86 | raise SyntaxError("The passed string is incorrectly formatted") 87 | year = int(q.group("year")) 88 | month = int(q.group("month")) 89 | day = int(q.group("day")) 90 | hour = int(q.group("hours")) 91 | minute = int(q.group("minutes")) 92 | second = int(q.group("seconds")) 93 | micro = 0 if q.group("millis") is None else int(q.group("millis")) * 1000 94 | z = q.group("zulu") 95 | tz_sign = q.group("sign") 96 | tz_hour = None if q.group("tz_h") is None else int(q.group("tz_h")) 97 | tz_minute = None if q.group("tz_m") is None else int(q.group("tz_m")) 98 | 99 | zone = None 100 | if z is not None: 101 | zone = timezone.utc 102 | elif tz_sign == "+": 103 | zone = timezone(timedelta(hours=tz_hour, 104 | minutes=tz_minute)) 105 | elif tz_sign == "-": 106 | zone = timezone(-timedelta(hours=tz_hour, 107 | minutes=tz_minute)) 108 | 109 | return datetime(year, month, day, hour, minute, second, micro, zone) 110 | 111 | 112 | def fmt_as_xml_duration(dr: timedelta): 113 | (Y, D) = divmod(dr.days, 365) 114 | (M, D) = divmod(D, 31) 115 | (h, s) = divmod(dr.seconds, 3600) 116 | (m, s) = divmod(s, 60) 117 | return "P%dY%dM%dDT%sH%sM%sS" % (Y, M, D, h, m, s) 118 | 119 | 120 | def parse_xml_duration(s: str): 121 | pattern = r""" 122 | ^ 123 | P 124 | (?!$) 125 | ((?P\d+)Y)? 126 | ((?P\d+)M)? 127 | ((?P\d+)D)? 128 | ( 129 | T 130 | (?!$) 131 | ((?P\d+)H)? 132 | ((?P\d+)M)? 133 | ((?P\d+) 134 | (?P\.\d+)? 135 | S)? 136 | )? 137 | $ 138 | """ 139 | p = re.compile(pattern, re.VERBOSE) 140 | q = p.search(s) 141 | if q is None: 142 | raise SyntaxError("The passed string is incorrectly formatted") 143 | 144 | years = int(q.group("years")) if q.group("years") is not None else 0 145 | months = int(q.group("months")) if q.group("months") is not None else 0 146 | days = int(q.group("days")) if q.group("days") is not None else 0 147 | hours = int(q.group("hours")) if q.group("hours") is not None else 0 148 | minutes = int(q.group("minutes")) if q.group("minutes") is not None else 0 149 | seconds = int(q.group("seconds")) if q.group("seconds") is not None else 0 150 | millis = int(float(q.group("millis")) * 1000) if q.group("millis") is not None else 0 151 | 152 | return timedelta(days=365 * years + 31 * months + days, 153 | seconds=hours * 3600 + minutes * 60 + seconds, 154 | milliseconds=millis) 155 | 156 | 157 | if __name__ == "__main__": 158 | a = datetime.now(tz.gettz("CET")) 159 | print(fmt_as_xml_datetime(a)) 160 | print(a.__class__) 161 | 162 | td = timedelta(500, 4000) 163 | print(fmt_as_xml_duration(td)) 164 | 165 | print(parse_xml_datetime("2004-04-12T13:20:00Z")) 166 | parse_xml_duration("P2Y6M5DT12H35M30S") 167 | parse_xml_duration("P1DT2H") 168 | parse_xml_duration("P20M") 169 | parse_xml_duration("PT20M") 170 | parse_xml_duration("P0Y20M0D") 171 | parse_xml_duration("P0Y") 172 | parse_xml_duration("P60D") 173 | parse_xml_duration("PT1M30.5S") 174 | -------------------------------------------------------------------------------- /src/bin/wsdtool: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3.6 2 | import sys 3 | 4 | MIN_PYTHON = (3, 6) 5 | if sys.version_info < MIN_PYTHON: 6 | sys.exit("Python %s.%s or later is required.\n" % MIN_PYTHON) 7 | 8 | import argparse 9 | from urllib.parse import urlparse 10 | 11 | from PyWSD import wsd_common, \ 12 | wsd_discovery__operations, \ 13 | wsd_transfer__operations, \ 14 | wsd_discovery__parsers, \ 15 | wsd_globals 16 | 17 | 18 | def noop(args): 19 | pass 20 | 21 | 22 | def update_db(args): 23 | wsd_discovery__operations.set_discovery_verbosity(args.verbosity_lvl) 24 | wsd_discovery__operations.get_devices(probe_timeout=args.timeout) 25 | 26 | 27 | def monitor(args): 28 | wsd_discovery__operations.set_discovery_verbosity(args.verbosity_lvl) 29 | wsd_discovery__operations.get_devices(probe_timeout=args.timeout) 30 | 31 | db = wsd_discovery__operations.open_db() 32 | sockets = wsd_discovery__operations.init_multicast_listener() 33 | try: 34 | while True: 35 | (hello, target) = wsd_discovery__operations.listen_multicast_announcements(sockets) 36 | if hello: 37 | ok, target = wsd_discovery__operations.wsd_resolve(target) 38 | if ok: 39 | wsd_discovery__operations.add_target_to_db(db, target) 40 | else: 41 | wsd_discovery__operations.remove_target_from_db(db, target) 42 | except KeyboardInterrupt: 43 | pass 44 | wsd_discovery__operations.deinit_multicast_listener(sockets) 45 | db.close() 46 | 47 | 48 | def show_list(args): 49 | db = wsd_discovery__operations.open_db() 50 | targets = wsd_discovery__operations.read_targets_from_db(db) 51 | device_types = set() 52 | #TODO: resolve namespaces, do not compare raw labels 53 | if "p" in args.filter: 54 | device_types.add("wprt:PrintDeviceType") 55 | if "s" in args.filter: 56 | device_types.add("wscn:ScanDeviceType") 57 | 58 | print("\n WSD devices:") 59 | for target in targets: 60 | if not target.types.isdisjoint(device_types): 61 | try: 62 | (info, services) = wsd_transfer__operations.wsd_get(target) 63 | target_types = set() 64 | if "wprt:PrintDeviceType" in target.types: 65 | target_types.add("Printer") 66 | if "wscn:ScanDeviceType" in target.types: 67 | target_types.add("Scanner") 68 | dev_id = (info.manufacturer + "_" + info.model_name).replace(" ", "_").replace(".", "") 69 | dev_classes = "|".join(target_types) 70 | dev_addrs = ", ".join([urlparse(a).netloc for a in target.xaddrs]) 71 | print(wsd_common.indent(dev_id + " @ [" + dev_addrs + "] * [" + dev_classes + "]")) 72 | except TimeoutError: 73 | pass 74 | db.close() 75 | 76 | 77 | def parse_cmd_line(): 78 | help_filter = "Filter target types: p=printer, s=scanner" \ 79 | "" 80 | parser = argparse.ArgumentParser(description='WSD Utility') 81 | parser.add_argument('-d', '--debug', action="store_true", default=False, required=False, help='Enable debug') 82 | parser.add_argument('-t', '--timeout', action="store", required=False, type=int, default=2, help='Timeout') 83 | parser.set_defaults(func=noop) 84 | subparsers = parser.add_subparsers() 85 | 86 | list_parser = subparsers.add_parser("list") 87 | list_parser.add_argument('-f', '--filter', action="store", required=False, type=str, default="ps", help=help_filter) 88 | list_parser.set_defaults(func=show_list) 89 | 90 | monitor_parser = subparsers.add_parser("monitor") 91 | monitor_parser.add_argument('-v', '--verbosity_lvl', action="store", type=int, default=0, required=False, 92 | help='Enable verbosity') 93 | monitor_parser.set_defaults(func=monitor) 94 | 95 | update_db_parser = subparsers.add_parser("update_db") 96 | update_db_parser.add_argument('-v', '--verbosity_lvl', action="store", type=int, default=0, required=False, 97 | help='Enable verbosity') 98 | update_db_parser.set_defaults(func=update_db) 99 | 100 | args = parser.parse_args() 101 | wsd_common.enable_debug(args.debug) 102 | args.func(args) 103 | 104 | 105 | def __main(): 106 | parse_cmd_line() 107 | 108 | 109 | if __name__ == "__main__": 110 | __main() 111 | --------------------------------------------------------------------------------