├── .gitignore ├── AUTHORS ├── COPYING ├── COPYING.LESSER ├── MANIFEST.in ├── README.rst ├── build-release.py ├── doc ├── Makefile ├── _build │ └── ._ ├── _static │ └── ._ ├── _templates │ └── ._ ├── agi │ ├── core.rst │ └── index.rst ├── ami │ ├── actions │ │ ├── app_confbridge.rst │ │ ├── app_meetme.rst │ │ ├── core.rst │ │ ├── dahdi.rst │ │ └── index.rst │ ├── events │ │ ├── app_confbridge.rst │ │ ├── app_meetme.rst │ │ ├── core.rst │ │ ├── dahdi.rst │ │ └── index.rst │ └── index.rst ├── conf.py ├── examples │ ├── agi.rst │ ├── ami.rst │ ├── fastagi.rst │ └── index.rst └── index.rst ├── pystrix ├── __init__.py ├── agi │ ├── __init__.py │ ├── agi.py │ ├── agi_core.py │ ├── core.py │ └── fastagi.py └── ami │ ├── __init__.py │ ├── ami.py │ ├── app_confbridge.py │ ├── app_confbridge_events.py │ ├── app_meetme.py │ ├── app_meetme_events.py │ ├── core.py │ ├── core_events.py │ ├── dahdi.py │ ├── dahdi_events.py │ └── generic_transforms.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | # IDE stuff 60 | .idea/ -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | [Ivrnet, inc.](http://www.ivrnet.com/) 2 | * Initial development of pystrix was funded by Ivrnet 3 | * Ivrnet is a software-as-a-service company that develops and operates intelligent software applications, delivered through traditional phone networks and over the Internet. These applications facilitate automated interaction, personalized communication between people, mass communication for disseminating information to thousands of people concurrently, and personalized communication between people and automated systems. Ivrnet's applications are accessible through nearly any form of communication technology, at any time, from anywhere in North America, via voice, phone, fax, email, texting, and the Internet. 4 | 5 | [Neil Tallim](http://uguu.ca/) 6 | * Development lead 7 | * Programming 8 | 9 | 10 | Other contributions 11 | ------------------- 12 | 13 | [Marta Solano](marta.solano@ivrtechnology.com ) 14 | * Bug solving - Programming 15 | * Pip package maintenance 16 | 17 | [Eric Lee](eric@ivrtechnology.com) 18 | * Python 2 to 3 migration - compatibility 19 | * Programming 20 | 21 | [Karthic Raghupathi](karthicr@gmail.com) 22 | * Bug Fixes / Programming 23 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER 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 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include COPYING -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | **pystrix** is an attempt at creating a versatile `Asterisk `_-interface package for AMI and (Fast)AGI needs. It is published as an open-source library under the LGPLv3 by `Ivrnet, inc. `_, welcoming contributions from all users. 2 | 3 | **** 4 | 5 | ======== 6 | Overview 7 | ======== 8 | 9 | pystrix runs on python 2.7/python 3.4+ on any platform. It's targeted at Asterisk 1.10+ and provides a rich, easy-to-extend set of bindings for AGI, FastAGI, and AMI. 10 | 11 | ================ 12 | Release Schedule 13 | ================ 14 | 15 | The current code in the repository correspond to version **1.1.8** of the package. When a bug is found and fixed a new version of the package will be generated in order to keep it updated and as bug-free as possible. 16 | 17 | New releases will follow the format: .. according to the change made to the code. 18 | 19 | ======= 20 | History 21 | ======= 22 | 23 | After some research, we found that what was available was either incompatible with the architecture model we needed to work with `Twisted `_, (while excellent for a great many things, isn't always the right choice), was targeting an outdated version of Asterisk, or had a very rigid, monolithic design. Identifying the `pyst `_ and `py-asterisk `_ packages as being similar, but structurally incompatible, to what we wanted, pyst was chosen as the basis for this project, with a full rewrite of its AGI and AMI systems to provide a uniform-looking, highly modular design that incorporates logic and ideas from py-asterisk. The end result is a package that should satisfy anyone who was looking at either of its ancestors and that should be easier to extend as Asterisk continues to evolve. 24 | 25 | ============ 26 | Installation 27 | ============ 28 | 29 | * From pip 30 | 31 | .. code:: bash 32 | 33 | $ pip install pystrix 34 | 35 | * From github 36 | 37 | .. code:: bash 38 | 39 | $ pip install -e git://github.com/marsoguti/pystrix.git#egg=pystrix 40 | 41 | ===== 42 | Usage 43 | ===== 44 | 45 | Detailed usage information is provided in the documentation, along with simple examples that should help to get anyone started. 46 | 47 | ============= 48 | Documentation 49 | ============= 50 | 51 | Online documentation is available at http://pystrix.readthedocs.io/. 52 | 53 | Inline documentation is complete and made readable by `reStructuredText `_, so you'll never be completely lost. 54 | 55 | **** 56 | 57 | ======= 58 | Credits 59 | ======= 60 | 61 | `Ivrnet, inc. `_ 62 | * Initial development of pystrix was funded by Ivrnet 63 | * Ivrnet is a software-as-a-service company that develops and operates intelligent software applications, delivered through traditional phone networks and over the Internet. These applications facilitate automated interaction, personalized communication between people, mass communication for disseminating information to thousands of people concurrently, and personalized communication between people and automated systems. Ivrnet's applications are accessible through nearly any form of communication technology, at any time, from anywhere in North America, via voice, phone, fax, email, texting, and the Internet. 64 | 65 | `Neil Tallim `_ 66 | * Development lead 67 | * Programming 68 | 69 | 70 | Other contributions and current package maintenance 71 | --------------------------------------------------- 72 | 73 | `Marta Solano `_ 74 | * Bug solving - Programming 75 | * Pip package maintenance 76 | 77 | `Eric Lee `_ 78 | * Python 2 to 3 migration - compatibility 79 | * Programming 80 | 81 | `Karthic Raghupathi `_ 82 | * Bug solving - Programming 83 | * Pip package maintenance 84 | -------------------------------------------------------------------------------- /build-release.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Release-building script for pystrix. 4 | """ 5 | import tarfile 6 | import fileinput 7 | 8 | from pystrix import VERSION 9 | 10 | def _filter(tarinfo, acceptable_extensions): 11 | if tarinfo.name.startswith('.'): #Ignore hidden files 12 | return None 13 | 14 | if tarinfo.isdir(): #Directories are good 15 | return tarinfo 16 | 17 | if tarinfo.name.endswith(acceptable_extensions): #It's a file we want 18 | print("\tAdded " + tarinfo.name) 19 | return tarinfo 20 | 21 | return None #DO NOT WANT 22 | 23 | def python_filter(tarinfo): 24 | return _filter(tarinfo, ('.py',)) 25 | 26 | def doc_filter(tarinfo): 27 | return _filter(tarinfo, ('.py','.rst','Makefile')) 28 | 29 | if __name__ == '__main__': 30 | base_name = "pystrix-" + VERSION 31 | archive_name = base_name + ".tar.bz2" 32 | print("Assembling " + archive_name) 33 | f = tarfile.open(name=archive_name, mode="w:bz2") 34 | for line in fileinput.input("pystrix.spec", inplace=True, backup=False): 35 | if line.startswith('%define initversion'): 36 | line = "%%define initversion %s" % VERSION 37 | print("%s" % (line.rstrip())) 38 | f.add('pystrix.spec', arcname="%s/pystrix.spec" % base_name) 39 | f.add('COPYING', arcname="%s/COPYING" % base_name) 40 | f.add('COPYING.LESSER', arcname="%s/COPYING.LESSER" % base_name) 41 | print("\tAdded license files") 42 | f.add('doc',arcname="%s/doc" % base_name, filter=doc_filter) 43 | f.add('build-release.py', arcname="%s/build-release.py" % base_name, filter=python_filter) 44 | f.add('setup.py', arcname="%s/setup.py" % base_name, filter=python_filter) 45 | f.add('pystrix', arcname="%s/pystrix" % base_name, filter=python_filter) 46 | f.close() 47 | 48 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | 9 | # Internal variables. 10 | PAPEROPT_a4 = -D latex_paper_size=a4 11 | PAPEROPT_letter = -D latex_paper_size=letter 12 | ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 13 | 14 | .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest 15 | 16 | help: 17 | @echo "Please use \`make ' where is one of" 18 | @echo " html to make standalone HTML files" 19 | @echo " dirhtml to make HTML files named index.html in directories" 20 | @echo " pickle to make pickle files" 21 | @echo " json to make JSON files" 22 | @echo " htmlhelp to make HTML files and a HTML help project" 23 | @echo " qthelp to make HTML files and a qthelp project" 24 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 25 | @echo " changes to make an overview of all changed/added/deprecated items" 26 | @echo " linkcheck to check all external links for integrity" 27 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 28 | 29 | clean: 30 | -rm -rf _build/* 31 | 32 | html: 33 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html 34 | @echo 35 | @echo "Build finished. The HTML pages are in _build/html." 36 | 37 | dirhtml: 38 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) _build/dirhtml 39 | @echo 40 | @echo "Build finished. The HTML pages are in _build/dirhtml." 41 | 42 | pickle: 43 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle 44 | @echo 45 | @echo "Build finished; now you can process the pickle files." 46 | 47 | json: 48 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json 49 | @echo 50 | @echo "Build finished; now you can process the JSON files." 51 | 52 | htmlhelp: 53 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp 54 | @echo 55 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 56 | ".hhp project file in _build/htmlhelp." 57 | 58 | qthelp: 59 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) _build/qthelp 60 | @echo 61 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 62 | ".qhcp project file in _build/qthelp, like this:" 63 | @echo "# qcollectiongenerator _build/qthelp/pystrix.qhcp" 64 | @echo "To view the help file:" 65 | @echo "# assistant -collectionFile _build/qthelp/pystrix.qhc" 66 | 67 | latex: 68 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex 69 | @echo 70 | @echo "Build finished; the LaTeX files are in _build/latex." 71 | @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ 72 | "run these through (pdf)latex." 73 | 74 | changes: 75 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes 76 | @echo 77 | @echo "The overview file is in _build/changes." 78 | 79 | linkcheck: 80 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck 81 | @echo 82 | @echo "Link check complete; look for any errors in the above output " \ 83 | "or in _build/linkcheck/output.txt." 84 | 85 | doctest: 86 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) _build/doctest 87 | @echo "Testing of doctests in the sources finished, look at the " \ 88 | "results in _build/doctest/output.txt." 89 | -------------------------------------------------------------------------------- /doc/_build/._: -------------------------------------------------------------------------------- 1 | mercurial placeholder file 2 | -------------------------------------------------------------------------------- /doc/_static/._: -------------------------------------------------------------------------------- 1 | mercurial placeholder file 2 | -------------------------------------------------------------------------------- /doc/_templates/._: -------------------------------------------------------------------------------- 1 | mercurial placeholder file 2 | -------------------------------------------------------------------------------- /doc/agi/core.rst: -------------------------------------------------------------------------------- 1 | Core 2 | ==== 3 | 4 | By default, Asterisk exposes a number of ways to interact with a channel, all of which are described 5 | below. 6 | 7 | Members 8 | ------- 9 | 10 | All of the following objects should be accessed as part of the `agi.core` namespace, regardless of 11 | the modules in which they are defined. 12 | 13 | Constants 14 | +++++++++ 15 | 16 | .. data:: CHANNEL_DOWN_AVAILABLE 17 | 18 | Channel is down and available 19 | 20 | .. data:: CHANNEL_DOWN_RESERVED 21 | 22 | Channel is down and reserved 23 | 24 | .. data:: CHANNEL_OFFHOOK 25 | 26 | Channel is off-hook 27 | 28 | .. data:: CHANNEL_DIALED 29 | 30 | A destination address has been specified 31 | 32 | .. data:: CHANNEL_ALERTING 33 | 34 | The channel is locally ringing 35 | 36 | .. data:: CHANNEL_REMOTE_ALERTING 37 | 38 | The channel is remotely ringing 39 | 40 | .. data:: CHANNEL_UP 41 | 42 | The channel is connected 43 | 44 | .. data:: CHANNEL_BUSY 45 | 46 | The channel is in a busy, non-conductive state 47 | 48 | .. data:: FORMAT_SLN 49 | :noindex: 50 | 51 | Selects the `sln` audio format 52 | 53 | .. data:: FORMAT_G723 54 | :noindex: 55 | 56 | Selects the `g723` audio format 57 | 58 | .. data:: FORMAT_G729 59 | :noindex: 60 | 61 | Selects the `g729` audio format 62 | 63 | .. data:: FORMAT_GSM 64 | :noindex: 65 | 66 | Selects the `gsm` audio format 67 | 68 | .. data:: FORMAT_ALAW 69 | :noindex: 70 | 71 | Selects the `alaw` audio format 72 | 73 | .. data:: FORMAT_ULAW 74 | :noindex: 75 | 76 | Selects the `ulaw` audio format 77 | 78 | .. data:: FORMAT_VOX 79 | :noindex: 80 | 81 | Selects the `vox` audio format 82 | 83 | .. data:: FORMAT_WAV 84 | :noindex: 85 | 86 | Selects the `wav` audio format 87 | 88 | .. data:: LOG_DEBUG 89 | 90 | The Asterisk logging level equivalent to 'debug' 91 | 92 | .. data:: LOG_INFO 93 | 94 | The Asterisk logging level equivalent to 'info' 95 | 96 | .. data:: LOG_WARN 97 | 98 | The Asterisk logging level equivalent to 'warn' 99 | 100 | .. data:: LOG_ERROR 101 | 102 | The Asterisk logging level equivalent to 'error' 103 | 104 | .. data:: LOG_CRITICAL 105 | 106 | The Asterisk logging level equivalent to 'critical' 107 | 108 | .. data:: TDD_ON 109 | 110 | Sets TDD to on 111 | 112 | .. data:: TDD_OFF 113 | 114 | Sets TDD to off 115 | 116 | .. data:: TDD_MATE 117 | 118 | Sets TDD to mate 119 | 120 | Actions 121 | +++++++ 122 | 123 | .. autoclass:: agi.core.Answer 124 | 125 | .. autoclass:: agi.core.ChannelStatus 126 | 127 | .. autoclass:: agi.core.ControlStreamFile 128 | 129 | .. autoclass:: agi.core.DatabaseDel 130 | 131 | .. autoclass:: agi.core.DatabaseDeltree 132 | 133 | .. autoclass:: agi.core.DatabaseGet 134 | 135 | .. autoclass:: agi.core.DatabasePut 136 | 137 | .. autoclass:: agi.core.Exec 138 | 139 | .. autoclass:: agi.core.GetData 140 | 141 | .. autoclass:: agi.core.GetFullVariable 142 | 143 | .. autoclass:: agi.core.GetOption 144 | 145 | .. autoclass:: agi.core.GetVariable 146 | 147 | .. autoclass:: agi.core.Hangup 148 | 149 | .. autoclass:: agi.core.Noop 150 | 151 | .. autoclass:: agi.core.ReceiveChar 152 | 153 | .. autoclass:: agi.core.ReceiveText 154 | 155 | .. autoclass:: agi.core.RecordFile 156 | 157 | .. autoclass:: agi.core.SayAlpha 158 | 159 | .. autoclass:: agi.core.SayDate 160 | 161 | .. autoclass:: agi.core.SayDatetime 162 | 163 | .. autoclass:: agi.core.SayDigits 164 | 165 | .. autoclass:: agi.core.SayNumber 166 | 167 | .. autoclass:: agi.core.SayPhonetic 168 | 169 | .. autoclass:: agi.core.SayTime 170 | 171 | .. autoclass:: agi.core.SendImage 172 | 173 | .. autoclass:: agi.core.SendText 174 | 175 | .. autoclass:: agi.core.SetAutohangup 176 | 177 | .. autoclass:: agi.core.SetCallerid 178 | 179 | .. autoclass:: agi.core.SetContext 180 | 181 | .. autoclass:: agi.core.SetExtension 182 | 183 | .. autoclass:: agi.core.SetMusic 184 | 185 | .. autoclass:: agi.core.SetPriority 186 | 187 | .. autoclass:: agi.core.SetVariable 188 | 189 | .. autoclass:: agi.core.StreamFile 190 | 191 | .. autoclass:: agi.core.TDDMode 192 | 193 | .. autoclass:: agi.core.Verbose 194 | 195 | .. autoclass:: agi.core.WaitForDigit 196 | 197 | Exceptions 198 | ++++++++++ 199 | 200 | .. autoexception:: agi.core.AGIDBError 201 | :show-inheritance: 202 | 203 | -------------------------------------------------------------------------------- /doc/agi/index.rst: -------------------------------------------------------------------------------- 1 | Asterisk Gateway Interface (AGI) 2 | ================================ 3 | 4 | The AGI interface consists of a number of action classes that are sent to Asterisk to effect actions 5 | on active channels. Two different means of getting access to a channel are defined: AGI and FastAGI, 6 | with the difference between them being that every AGI instance runs as a child process of Asterisk 7 | (full Python interpreter and everything), while FastAGI runs over a TCP/IP socket, allowing for 8 | faster startup times and lower overhead, with the cost of a little more development investment. 9 | 10 | pystrix exposes the same feature-set and interaction model for both AGI and FastAGI, allowing any 11 | of the actions defined in the following sections to be instantiated and passed (any number of times) 12 | to :meth:`agi.AGI.execute`. 13 | 14 | .. toctree:: 15 | :maxdepth: 3 16 | 17 | core.rst 18 | 19 | Members 20 | ------- 21 | 22 | All of the following objects should be accessed as part of the `agi` namespace, regardless of the 23 | modules in which they are defined. 24 | 25 | Classes 26 | +++++++ 27 | 28 | .. autoclass:: agi.AGI 29 | :members: 30 | :inherited-members: 31 | 32 | .. autoclass:: agi.FastAGIServer 33 | :members: 34 | 35 | .. attribute:: timeout 36 | 37 | The number of seconds to wait for a request when using :meth:`handle_request`. Has no effect 38 | on :meth:`serve_forever`. 39 | 40 | .. method:: handle_request() 41 | 42 | Handles at most one request in a separate thread or times out and returns control silently. 43 | 44 | .. method:: serve_forever() 45 | 46 | Continues to serve requests as they are received, handling each in a new thread, until 47 | :meth:`shutdown` is called. 48 | 49 | .. method:: shutdown() 50 | 51 | Interrupts :meth:`serve_forever` gracefully. 52 | 53 | Exceptions 54 | ++++++++++ 55 | 56 | .. autoexception:: agi.AGIException 57 | :show-inheritance: 58 | 59 | .. attribute:: items 60 | 61 | A dictionary containing any key-value items received from Asterisk to explain the exception. 62 | 63 | .. autoexception:: agi.AGIError 64 | :show-inheritance: 65 | 66 | .. autoexception:: agi.AGIUnknownError 67 | :show-inheritance: 68 | 69 | .. autoexception:: agi.AGIAppError 70 | :show-inheritance: 71 | 72 | .. autoexception:: agi.AGIHangup 73 | :show-inheritance: 74 | 75 | .. autoexception:: agi.AGISIGPIPEHangup 76 | :show-inheritance: 77 | 78 | .. autoexception:: agi.AGISIGHUPHangup 79 | :show-inheritance: 80 | 81 | .. autoexception:: agi.AGIResultHangup 82 | :show-inheritance: 83 | 84 | .. autoexception:: agi.AGIDeadChannelError 85 | :show-inheritance: 86 | 87 | .. autoexception:: agi.AGIUsageError 88 | :show-inheritance: 89 | 90 | .. autoexception:: agi.AGIInvalidCommandError 91 | :show-inheritance: 92 | 93 | -------------------------------------------------------------------------------- /doc/ami/actions/app_confbridge.rst: -------------------------------------------------------------------------------- 1 | (Application) Confbridge 2 | ======================== 3 | 4 | Confbridge is Asterisk's new conferencing subsystem, providing far greater functionality than 5 | Meetme, with better performance and structural design. While technically a part of Asterisk's core, 6 | it's specialised enough that pystrix treats it as a module. 7 | 8 | Members 9 | ------- 10 | 11 | All of the following objects should be accessed as part of the `ami.app_confbirdge` namespace, 12 | regardless of the modules in which they are defined. 13 | 14 | Actions 15 | +++++++ 16 | 17 | .. autoclass:: ami.app_confbridge.ConfbridgeKick 18 | :show-inheritance: 19 | :members: __init__ 20 | 21 | .. autoclass:: ami.app_confbridge.ConfbridgeList 22 | :show-inheritance: 23 | :members: __init__ 24 | 25 | .. autoclass:: ami.app_confbridge.ConfbridgeListRooms 26 | :show-inheritance: 27 | :members: __init__ 28 | 29 | .. autoclass:: ami.app_confbridge.ConfbridgeLock 30 | :show-inheritance: 31 | :members: __init__ 32 | 33 | .. autoclass:: ami.app_confbridge.ConfbridgeUnlock 34 | :show-inheritance: 35 | :members: __init__ 36 | 37 | .. autoclass:: ami.app_confbridge.ConfbridgeMoHOn 38 | :show-inheritance: 39 | :members: __init__ 40 | 41 | .. autoclass:: ami.app_confbridge.ConfbridgeMoHOff 42 | :show-inheritance: 43 | :members: __init__ 44 | 45 | .. autoclass:: ami.app_confbridge.ConfbridgeMute 46 | :show-inheritance: 47 | :members: __init__ 48 | 49 | .. autoclass:: ami.app_confbridge.ConfbridgeUnmute 50 | :show-inheritance: 51 | :members: __init__ 52 | 53 | .. autoclass:: ami.app_confbridge.ConfbridgePlayFile 54 | :show-inheritance: 55 | :members: __init__ 56 | 57 | .. autoclass:: ami.app_confbridge.ConfbridgeStartRecord 58 | :show-inheritance: 59 | :members: __init__ 60 | 61 | .. autoclass:: ami.app_confbridge.ConfbridgeStopRecord 62 | :show-inheritance: 63 | :members: __init__ 64 | 65 | .. autoclass:: ami.app_confbridge.ConfbridgeSetSingleVideoSrc 66 | :show-inheritance: 67 | :members: __init__ 68 | 69 | -------------------------------------------------------------------------------- /doc/ami/actions/app_meetme.rst: -------------------------------------------------------------------------------- 1 | (Application) Meetme 2 | ==================== 3 | 4 | Meetme is Asterisk's long-standing, now-being-phased-out conferencing subsystem. While technically a 5 | part of Asterisk's core, it's specialised enough that pystrix treats it as a module. 6 | 7 | Members 8 | ------- 9 | 10 | All of the following objects should be accessed as part of the `ami.app_meetme` namespace, 11 | regardless of the modules in which they are defined. 12 | 13 | Actions 14 | +++++++ 15 | 16 | .. autoclass:: ami.app_meetme.MeetmeList 17 | :show-inheritance: 18 | :members: __init__ 19 | 20 | .. autoclass:: ami.app_meetme.MeetmeListRooms 21 | :show-inheritance: 22 | :members: __init__ 23 | 24 | .. autoclass:: ami.app_meetme.MeetmeMute 25 | :show-inheritance: 26 | :members: __init__ 27 | 28 | .. autoclass:: ami.app_meetme.MeetmeUnmute 29 | :show-inheritance: 30 | :members: __init__ 31 | 32 | -------------------------------------------------------------------------------- /doc/ami/actions/core.rst: -------------------------------------------------------------------------------- 1 | Core 2 | ==== 3 | 4 | Asterisk provides a rich collection of features by default, the standard set of which are described 5 | here. 6 | 7 | Members 8 | ------- 9 | 10 | All of the following objects should be accessed as part of the `ami.core` namespace, regardless of 11 | the modules in which they are defined. 12 | 13 | Constants 14 | +++++++++ 15 | 16 | .. data:: AUTHTYPE_MD5 17 | 18 | Uses MD5 authentication when logging into AMI 19 | 20 | .. data:: EVENTMASK_ALL 21 | 22 | Turns on all events with the :class:`ami.core.Events` action 23 | 24 | .. data:: EVENTMASK_NONE 25 | 26 | Turns off all events with the :class:`ami.core.Events` action 27 | 28 | .. data:: EVENTMASK_CALL 29 | 30 | Turns on call events with the :class:`ami.core.Events` action 31 | 32 | .. data:: EVENTMASK_LOG 33 | 34 | Turns on log events with the :class:`ami.core.Events` action 35 | 36 | .. data:: EVENTMASK_SYSTEM 37 | 38 | Turns on system events with the :class:`ami.core.Events` action 39 | 40 | .. data:: FORMAT_SLN 41 | 42 | Selects the `sln` audio format 43 | 44 | .. data:: FORMAT_G723 45 | 46 | Selects the `g723` audio format 47 | 48 | .. data:: FORMAT_G729 49 | 50 | Selects the `g729` audio format 51 | 52 | .. data:: FORMAT_GSM 53 | 54 | Selects the `gsm` audio format 55 | 56 | .. data:: FORMAT_ALAW 57 | 58 | Selects the `alaw` audio format 59 | 60 | .. data:: FORMAT_ULAW 61 | 62 | Selects the `ulaw` audio format 63 | 64 | .. data:: FORMAT_VOX 65 | 66 | Selects the `vox` audio format 67 | 68 | .. data:: FORMAT_WAV 69 | 70 | Selects the `wav` audio format 71 | 72 | .. data:: ORIGINATE_RESULT_REJECT 73 | 74 | Remote extension rejected (hung up) without answering 75 | 76 | .. data:: ORIGINATE_RESULT_RING_LOCAL 77 | 78 | Local extension rang, but didn't answer 79 | 80 | .. data:: ORIGINATE_RESULT_RING_REMOTE 81 | 82 | Remote extension rang, but didn't answer 83 | 84 | .. data:: ORIGINATE_RESULT_ANSWERED 85 | 86 | Remote extension answered 87 | 88 | .. data:: ORIGINATE_RESULT_BUSY 89 | 90 | Remote extension was busy 91 | 92 | .. data:: ORIGINATE_RESULT_CONGESTION 93 | 94 | Remote extension was unreachable 95 | 96 | .. data:: ORIGINATE_RESULT_INCOMPLETE 97 | 98 | Remote extension could not be identified 99 | 100 | Actions 101 | +++++++ 102 | 103 | .. autoclass:: ami.core.AbsoluteTimeout 104 | :show-inheritance: 105 | :members: __init__ 106 | 107 | .. autoclass:: ami.core.AGI 108 | :show-inheritance: 109 | :members: __init__ 110 | 111 | .. autoclass:: ami.core.Bridge 112 | :show-inheritance: 113 | :members: __init__ 114 | 115 | .. autoclass:: ami.core.Challenge 116 | :show-inheritance: 117 | :members: __init__ 118 | 119 | .. autoclass:: ami.core.ChangeMonitor 120 | :show-inheritance: 121 | :members: __init__ 122 | 123 | .. autoclass:: ami.core.Command 124 | :show-inheritance: 125 | :members: __init__ 126 | 127 | .. autoclass:: ami.core.CoreShowChannels 128 | :show-inheritance: 129 | :members: __init__ 130 | 131 | .. autoclass:: ami.core.CreateConfig 132 | :show-inheritance: 133 | :members: __init__ 134 | 135 | .. autoclass:: ami.core.DBDel 136 | :show-inheritance: 137 | :members: __init__ 138 | 139 | .. autoclass:: ami.core.DBDelTree 140 | :show-inheritance: 141 | :members: __init__ 142 | 143 | .. autoclass:: ami.core.DBGet 144 | :show-inheritance: 145 | :members: __init__ 146 | 147 | .. autoclass:: ami.core.DBPut 148 | :show-inheritance: 149 | :members: __init__ 150 | 151 | .. autoclass:: ami.core.Events 152 | :show-inheritance: 153 | :members: __init__ 154 | 155 | .. autoclass:: ami.core.ExtensionState 156 | :show-inheritance: 157 | :members: __init__ 158 | 159 | .. autoclass:: ami.core.GetConfig 160 | :show-inheritance: 161 | :members: __init__ 162 | 163 | .. method:: get_lines() 164 | 165 | Provides a generator that yields every line in order. 166 | 167 | .. autoclass:: ami.core.Getvar 168 | :show-inheritance: 169 | :members: __init__ 170 | 171 | .. autoclass:: ami.core.Hangup 172 | :show-inheritance: 173 | :members: __init__ 174 | 175 | .. autoclass:: ami.core.ListCommands 176 | :show-inheritance: 177 | :members: __init__ 178 | 179 | .. autoclass:: ami.core.ListCategories 180 | :show-inheritance: 181 | :members: __init__ 182 | 183 | .. autoclass:: ami.core.LocalOptimizeAway 184 | :show-inheritance: 185 | :members: __init__ 186 | 187 | .. autoclass:: ami.core.Login 188 | :show-inheritance: 189 | :members: __init__ 190 | 191 | .. autoclass:: ami.core.Logoff 192 | :show-inheritance: 193 | :members: __init__ 194 | 195 | .. autoclass:: ami.core.ModuleLoad 196 | :show-inheritance: 197 | :members: __init__ 198 | 199 | .. autoclass:: ami.core.Monitor 200 | :show-inheritance: 201 | :members: __init__ 202 | 203 | .. autoclass:: ami.core.MuteAudio 204 | :show-inheritance: 205 | :members: __init__ 206 | 207 | .. autoclass:: ami.core.Originate_Application 208 | :show-inheritance: 209 | :members: __init__ 210 | 211 | .. autoclass:: ami.core.Originate_Context 212 | :show-inheritance: 213 | :members: __init__ 214 | 215 | .. autoclass:: ami.core.Park 216 | :show-inheritance: 217 | :members: __init__ 218 | 219 | .. autoclass:: ami.core.ParkedCalls 220 | :show-inheritance: 221 | :members: __init__ 222 | 223 | .. autoclass:: ami.core.PauseMonitor 224 | :show-inheritance: 225 | :members: __init__ 226 | 227 | .. autoclass:: ami.core.Ping 228 | :show-inheritance: 229 | :members: __init__ 230 | 231 | .. autoclass:: ami.core.PlayDTMF 232 | :show-inheritance: 233 | :members: __init__ 234 | 235 | .. autoclass:: ami.core.QueueAdd 236 | :show-inheritance: 237 | :members: __init__ 238 | 239 | .. autoclass:: ami.core.QueueLog 240 | :show-inheritance: 241 | :members: __init__ 242 | 243 | .. autoclass:: ami.core.QueuePause 244 | :show-inheritance: 245 | :members: __init__ 246 | 247 | .. autoclass:: ami.core.QueuePenalty 248 | :show-inheritance: 249 | :members: __init__ 250 | 251 | .. autoclass:: ami.core.QueueReload 252 | :show-inheritance: 253 | :members: __init__ 254 | 255 | .. autoclass:: ami.core.QueueRemove 256 | :show-inheritance: 257 | :members: __init__ 258 | 259 | .. autoclass:: ami.core.QueueStatus 260 | :show-inheritance: 261 | :members: __init__ 262 | 263 | .. autoclass:: ami.core.QueueSummary 264 | :show-inheritance: 265 | :members: __init__ 266 | 267 | .. autoclass:: ami.core.Redirect 268 | :show-inheritance: 269 | :members: __init__ 270 | 271 | .. autoclass:: ami.core.Reload 272 | :show-inheritance: 273 | :members: __init__ 274 | 275 | .. autoclass:: ami.core.SendText 276 | :show-inheritance: 277 | :members: __init__ 278 | 279 | .. autoclass:: ami.core.SetCDRUserField 280 | :show-inheritance: 281 | :members: __init__ 282 | 283 | .. autoclass:: ami.core.Setvar 284 | :show-inheritance: 285 | :members: __init__ 286 | 287 | .. autoclass:: ami.core.SIPnotify 288 | :show-inheritance: 289 | :members: __init__ 290 | 291 | .. autoclass:: ami.core.SIPpeers 292 | :show-inheritance: 293 | :members: __init__ 294 | 295 | .. autoclass:: ami.core.SIPqualify 296 | :show-inheritance: 297 | :members: __init__ 298 | 299 | .. autoclass:: ami.core.SIPshowpeer 300 | :show-inheritance: 301 | :members: __init__ 302 | 303 | .. autoclass:: ami.core.SIPshowregistry 304 | :show-inheritance: 305 | :members: __init__ 306 | 307 | .. autoclass:: ami.core.Status 308 | :show-inheritance: 309 | :members: __init__ 310 | 311 | .. autoclass:: ami.core.StopMonitor 312 | :show-inheritance: 313 | :members: __init__ 314 | 315 | .. autoclass:: ami.core.UnpauseMonitor 316 | :show-inheritance: 317 | :members: __init__ 318 | 319 | .. autoclass:: ami.core.UpdateConfig 320 | :show-inheritance: 321 | :members: __init__ 322 | 323 | .. autoclass:: ami.core.UserEvent 324 | :show-inheritance: 325 | :members: __init__ 326 | 327 | .. autoclass:: ami.core.VoicemailUsersList 328 | :show-inheritance: 329 | :members: __init__ 330 | 331 | Exceptions 332 | ++++++++++ 333 | 334 | .. autoexception:: ami.core.ManagerAuthError 335 | :show-inheritance: 336 | 337 | -------------------------------------------------------------------------------- /doc/ami/actions/dahdi.rst: -------------------------------------------------------------------------------- 1 | DAHDI 2 | ===== 3 | 4 | DAHDI is an interface layer for integrating traditional telephony technologies with digital formats. 5 | 6 | Members 7 | ------- 8 | 9 | All of the following objects should be accessed as part of the `ami.dahdi` namespace, regardless of 10 | the modules in which they are defined. 11 | 12 | Actions 13 | +++++++ 14 | 15 | .. autoclass:: ami.dahdi.DAHDIDNDoff 16 | :show-inheritance: 17 | :members: __init__ 18 | 19 | .. autoclass:: ami.dahdi.DAHDIDNDon 20 | :show-inheritance: 21 | :members: __init__ 22 | 23 | .. autoclass:: ami.dahdi.DAHDIDialOffhook 24 | :show-inheritance: 25 | :members: __init__ 26 | 27 | .. autoclass:: ami.dahdi.DAHDIHangup 28 | :show-inheritance: 29 | :members: __init__ 30 | 31 | .. autoclass:: ami.dahdi.DAHDIRestart 32 | :show-inheritance: 33 | :members: __init__ 34 | 35 | .. autoclass:: ami.dahdi.DAHDIShowChannels 36 | :show-inheritance: 37 | :members: __init__ 38 | 39 | -------------------------------------------------------------------------------- /doc/ami/actions/index.rst: -------------------------------------------------------------------------------- 1 | Actions 2 | ======= 3 | 4 | The AMI reacts primarily to requests submitted to it in the form of actions, which are described 5 | in this section. Their usage is consistently a matter of instantiating a class, then passing it 6 | (as many times as you'd like) to :meth:`ami.Manager.send_action` 7 | 8 | .. toctree:: 9 | 10 | core.rst 11 | dahdi.rst 12 | app_confbridge.rst 13 | app_meetme.rst 14 | 15 | 16 | -------------------------------------------------------------------------------- /doc/ami/events/app_confbridge.rst: -------------------------------------------------------------------------------- 1 | (Application) Confbridge 2 | ======================== 3 | 4 | Confbridge is Asterisk's new conferencing subsystem, providing far greater functionality than 5 | Meetme, with better performance and structural design. While technically a part of Asterisk's core, 6 | it's specialised enough that pystrix treats it as a module. 7 | 8 | Members 9 | ------- 10 | 11 | All of the following objects should be accessed as part of the `ami.app_confbridge_events` 12 | namespace, regardless of the modules in which they are defined. 13 | 14 | Events 15 | ++++++ 16 | 17 | .. autoclass:: ami.app_confbridge_events.ConfbridgeEnd 18 | :show-inheritance: 19 | :members: 20 | 21 | .. autoclass:: ami.app_confbridge_events.ConfbridgeJoin 22 | :show-inheritance: 23 | :members: 24 | 25 | .. autoclass:: ami.app_confbridge_events.ConfbridgeLeave 26 | :show-inheritance: 27 | :members: 28 | 29 | .. autoclass:: ami.app_confbridge_events.ConfbridgeList 30 | :show-inheritance: 31 | :members: 32 | 33 | .. autoclass:: ami.app_confbridge_events.ConfbridgeListComplete 34 | :show-inheritance: 35 | :members: 36 | 37 | .. autoclass:: ami.app_confbridge_events.ConfbridgeListRooms 38 | :show-inheritance: 39 | :members: 40 | 41 | .. autoclass:: ami.app_confbridge_events.ConfbridgeListRoomsComplete 42 | :show-inheritance: 43 | :members: 44 | 45 | .. autoclass:: ami.app_confbridge_events.ConfbridgeStart 46 | :show-inheritance: 47 | :members: 48 | 49 | .. autoclass:: ami.app_confbridge_events.ConfbridgeTalking 50 | :show-inheritance: 51 | :members: 52 | 53 | Aggregate Events 54 | ++++++++++++++++ 55 | 56 | .. autoclass:: ami.app_confbridge_events.ConfbridgeList_Aggregate 57 | :show-inheritance: 58 | :members: 59 | 60 | .. autoclass:: ami.app_confbridge_events.ConfbridgeListRooms_Aggregate 61 | :show-inheritance: 62 | :members: 63 | 64 | -------------------------------------------------------------------------------- /doc/ami/events/app_meetme.rst: -------------------------------------------------------------------------------- 1 | (Application) Meetme 2 | ==================== 3 | 4 | Meetme is Asterisk's long-standing, now-being-phased-out conferencing subsystem. While technically a 5 | part of Asterisk's core, it's specialised enough that pystrix treats it as a module. 6 | 7 | Members 8 | ------- 9 | 10 | All of the following objects should be accessed as part of the `ami.app_meetme_events` namespace, 11 | regardless of the modules in which they are defined. 12 | 13 | Events 14 | ++++++ 15 | 16 | .. autoclass:: ami.app_meetme_events.MeetmeJoin 17 | :show-inheritance: 18 | :members: 19 | 20 | .. autoclass:: ami.app_meetme_events.MeetmeList 21 | :show-inheritance: 22 | :members: 23 | 24 | .. autoclass:: ami.app_meetme_events.MeetmeListRooms 25 | :show-inheritance: 26 | :members: 27 | 28 | .. autoclass:: ami.app_meetme_events.MeetmeMute 29 | :show-inheritance: 30 | :members: 31 | 32 | Aggregate Events 33 | ++++++++++++++++ 34 | 35 | .. autoclass:: ami.app_meetme_events.MeetmeList_Aggregate 36 | :show-inheritance: 37 | :members: 38 | 39 | .. autoclass:: ami.app_meetme_events.MeetmeListRooms_Aggregate 40 | :show-inheritance: 41 | :members: 42 | 43 | -------------------------------------------------------------------------------- /doc/ami/events/core.rst: -------------------------------------------------------------------------------- 1 | Core 2 | ==== 3 | 4 | Asterisk provides a rich assortment of information-carrying events by default, the standard set of 5 | which are described here. 6 | 7 | Members 8 | ------- 9 | 10 | All of the following objects should be accessed as part of the `ami.core_events` namespace, 11 | regardless of the modules in which they are defined. 12 | 13 | Events 14 | ++++++ 15 | 16 | .. autoclass:: ami.core_events.AGIExec 17 | :show-inheritance: 18 | :members: 19 | 20 | .. autoclass:: ami.core_events.AsyncAGI 21 | :show-inheritance: 22 | :members: 23 | 24 | .. autoclass:: ami.core_events.ChannelUpdate 25 | :show-inheritance: 26 | :members: 27 | 28 | .. autoclass:: ami.core_events.CoreShowChannel 29 | :show-inheritance: 30 | :members: 31 | 32 | .. autoclass:: ami.core_events.CoreShowChannelsComplete 33 | :show-inheritance: 34 | :members: 35 | 36 | .. autoclass:: ami.core_events.DBGetResponse 37 | :show-inheritance: 38 | :members: 39 | 40 | .. autoclass:: ami.core_events.DTMF 41 | :show-inheritance: 42 | :members: 43 | 44 | .. autoclass:: ami.core_events.FullyBooted 45 | :show-inheritance: 46 | :members: 47 | 48 | .. autoclass:: ami.core_events.Hangup 49 | :show-inheritance: 50 | :members: 51 | 52 | .. autoclass:: ami.core_events.HangupRequest 53 | :show-inheritance: 54 | :members: 55 | 56 | .. autoclass:: ami.core_events.MonitorStart 57 | :show-inheritance: 58 | :members: 59 | 60 | .. autoclass:: ami.core_events.MonitorStop 61 | :show-inheritance: 62 | :members: 63 | 64 | .. autoclass:: ami.core_events.NewAccountCode 65 | :show-inheritance: 66 | :members: 67 | 68 | .. autoclass:: ami.core_events.Newchannel 69 | :show-inheritance: 70 | :members: 71 | 72 | .. autoclass:: ami.core_events.Newexten 73 | :show-inheritance: 74 | :members: 75 | 76 | .. autoclass:: ami.core_events.Newstate 77 | :show-inheritance: 78 | :members: 79 | 80 | .. autoclass:: ami.core_events.OriginateResponse 81 | :show-inheritance: 82 | :members: 83 | 84 | .. autoclass:: ami.core_events.ParkedCall 85 | :show-inheritance: 86 | :members: 87 | 88 | .. autoclass:: ami.core_events.ParkedCallsComplete 89 | :show-inheritance: 90 | :members: 91 | 92 | .. autoclass:: ami.core_events.PeerEntry 93 | :show-inheritance: 94 | :members: 95 | 96 | .. autoclass:: ami.core_events.PeerlistComplete 97 | :show-inheritance: 98 | :members: 99 | 100 | .. autoclass:: ami.core_events.QueueEntry 101 | :show-inheritance: 102 | :members: 103 | 104 | .. autoclass:: ami.core_events.QueueMember 105 | :show-inheritance: 106 | :members: 107 | 108 | .. autoclass:: ami.core_events.QueueMemberAdded 109 | :show-inheritance: 110 | :members: 111 | 112 | .. autoclass:: ami.core_events.QueueMemberPaused 113 | :show-inheritance: 114 | :members: 115 | 116 | .. autoclass:: ami.core_events.QueueMemberRemoved 117 | :show-inheritance: 118 | :members: 119 | 120 | .. autoclass:: ami.core_events.QueueParams 121 | :show-inheritance: 122 | :members: 123 | 124 | .. autoclass:: ami.core_events.QueueStatusComplete 125 | :show-inheritance: 126 | :members: 127 | 128 | .. autoclass:: ami.core_events.QueueSummary 129 | :show-inheritance: 130 | :members: 131 | 132 | .. autoclass:: ami.core_events.QueueSummaryComplete 133 | :show-inheritance: 134 | :members: 135 | 136 | .. autoclass:: ami.core_events.RegistryEntry 137 | :show-inheritance: 138 | :members: 139 | 140 | .. autoclass:: ami.core_events.RegistrationsComplete 141 | :show-inheritance: 142 | :members: 143 | 144 | .. autoclass:: ami.core_events.Reload 145 | :show-inheritance: 146 | :members: 147 | 148 | .. autoclass:: ami.core_events.RTCPReceived 149 | :show-inheritance: 150 | :members: 151 | 152 | .. autoclass:: ami.core_events.RTCPSent 153 | :show-inheritance: 154 | :members: 155 | 156 | .. autoclass:: ami.core_events.Shutdown 157 | :show-inheritance: 158 | :members: 159 | 160 | .. autoclass:: ami.core_events.SoftHangupRequest 161 | :show-inheritance: 162 | :members: 163 | 164 | .. autoclass:: ami.core_events.Status 165 | :show-inheritance: 166 | :members: 167 | 168 | .. autoclass:: ami.core_events.StatusComplete 169 | :show-inheritance: 170 | :members: 171 | 172 | .. autoclass:: ami.core_events.UserEvent 173 | :show-inheritance: 174 | :members: 175 | 176 | .. autoclass:: ami.core_events.VarSet 177 | :show-inheritance: 178 | :members: 179 | 180 | .. autoclass:: ami.core_events.VoicemailUserEntry 181 | :show-inheritance: 182 | :members: 183 | 184 | .. autoclass:: ami.core_events.VoicemailUserEntryComplete 185 | :show-inheritance: 186 | :members: 187 | 188 | Aggregate Events 189 | ++++++++++++++++ 190 | 191 | .. autoclass:: ami.core_events.CoreShowChannels_Aggregate 192 | :show-inheritance: 193 | :members: 194 | 195 | .. autoclass:: ami.core_events.ParkedCalls_Aggregate 196 | :show-inheritance: 197 | :members: 198 | 199 | .. autoclass:: ami.core_events.QueueStatus_Aggregate 200 | :show-inheritance: 201 | :members: 202 | 203 | .. autoclass:: ami.core_events.QueueSummary_Aggregate 204 | :show-inheritance: 205 | :members: 206 | 207 | .. autoclass:: ami.core_events.SIPpeers_Aggregate 208 | :show-inheritance: 209 | :members: 210 | 211 | .. autoclass:: ami.core_events.SIPshowregistry_Aggregate 212 | :show-inheritance: 213 | :members: 214 | 215 | .. autoclass:: ami.core_events.Status_Aggregate 216 | :show-inheritance: 217 | :members: 218 | 219 | .. autoclass:: ami.core_events.VoicemailUsersList_Aggregate 220 | :show-inheritance: 221 | :members: 222 | 223 | -------------------------------------------------------------------------------- /doc/ami/events/dahdi.rst: -------------------------------------------------------------------------------- 1 | DAHDI 2 | ===== 3 | 4 | DAHDI is an interface layer for integrating traditional telephony technologies with digital formats. 5 | 6 | Members 7 | ------- 8 | 9 | All of the following objects should be accessed as part of the `ami.dahdi_events` namespace, 10 | regardless of the modules in which they are defined. 11 | 12 | Events 13 | ++++++ 14 | 15 | .. autoclass:: ami.dahdi_events.DAHDIShowChannels 16 | :show-inheritance: 17 | :members: 18 | 19 | .. autoclass:: ami.dahdi_events.DAHDIShowChannelsComplete 20 | :show-inheritance: 21 | :members: 22 | 23 | Aggregate Events 24 | ++++++++++++++++ 25 | 26 | .. autoclass:: ami.dahdi_events.DAHDIShowChannels_Aggregate 27 | :show-inheritance: 28 | :members: 29 | 30 | -------------------------------------------------------------------------------- /doc/ami/events/index.rst: -------------------------------------------------------------------------------- 1 | Events 2 | ====== 3 | 4 | The AMI generates events in response to changes in its environment (unsolicited) or as a response to 5 | certain request actions. All known events are described in this section. Their usage is consistently 6 | a matter of registering a callback handler for an event with 7 | :meth:`ami.Manager.register_callback` and then waiting for the event to occur. 8 | 9 | .. toctree:: 10 | 11 | core.rst 12 | dahdi.rst 13 | app_confbridge.rst 14 | app_meetme.rst 15 | 16 | 17 | -------------------------------------------------------------------------------- /doc/ami/index.rst: -------------------------------------------------------------------------------- 1 | Asterisk Management Interface (AMI) 2 | =================================== 3 | 4 | The AMI interface consists primarily of a number of action classes that are sent to Asterisk to 5 | ellicit responses. Additionally, a number of event classes are defined to provide convenience 6 | processing on the various messages Asterisk generates. 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | actions/index.rst 12 | events/index.rst 13 | 14 | All of these concepts are bound together by the :class:`ami.Manager` class, which provides 15 | facilities for sending actions and serving callback handlers when events are received. 16 | 17 | Members 18 | ------- 19 | 20 | All of the following objects should be accessed as part of the `ami` namespace, regardless of the 21 | modules in which they are defined. 22 | 23 | Constants 24 | +++++++++ 25 | 26 | Aside, perhaps, from the "GENERIC" values, to be matched against :attr:`ami.ami._Message.name` responses, 27 | these constants are largely unnecessary outside of internal module usage, but they're exposed for 28 | convenience's sake. 29 | 30 | .. data:: RESPONSE_GENERIC 31 | 32 | A header-value provided as a surrogate for unidentifiable responses 33 | 34 | .. data:: EVENT_GENERIC 35 | 36 | A header-value provided as a surrogate for unidentifiable unsolicited events 37 | 38 | .. data:: KEY_ACTION 39 | 40 | The header key used to identify an action being requested of Asterisk 41 | 42 | .. data:: KEY_ACTIONID 43 | 44 | The header key used to hold the ActionID of a request, for matching with responses 45 | 46 | .. data:: KEY_EVENT 47 | 48 | The header key used to hold the event-name of a response 49 | 50 | .. data:: KEY_RESPONSE 51 | 52 | The header key used to hold the event-name of a request 53 | 54 | Classes 55 | +++++++ 56 | 57 | .. autoclass:: ami.Manager 58 | :members: 59 | 60 | Internal classes 61 | ~~~~~~~~~~~~~~~~ 62 | 63 | The following classes are not meant to be worked with directly, but are important for other parts of 64 | the system, with members that are worth knowing about. 65 | 66 | .. autoclass:: ami.ami._MessageTemplate 67 | 68 | .. attribute:: action_id 69 | 70 | The Asterisk Action-ID associated with this message, or `None` if undefined, as is the case 71 | with unsolicited events. 72 | 73 | .. autoclass:: ami.ami._Aggregate 74 | :show-inheritance: 75 | 76 | .. attribute:: valid 77 | 78 | Indicates whether the aggregate is consistent with Asterisk's protocol. 79 | 80 | .. attribute:: error_message 81 | 82 | If `valid` is `False`, this will offer a string explaining why validation failed. 83 | 84 | .. autoclass:: ami.ami._Event 85 | :show-inheritance: 86 | 87 | .. automethod:: ami.ami._Event.process 88 | 89 | .. autoclass:: ami.ami._Message 90 | :show-inheritance: 91 | 92 | .. attribute:: data 93 | 94 | A series of lines containing the message's payload from Asterisk. 95 | 96 | .. attribute:: headers 97 | 98 | A reference to a dictionary containing all headers associated with this message. Simply 99 | treating the message itself as a dictionary for headers is preferred, however; the two 100 | methods are equivalent. 101 | 102 | .. attribute:: raw 103 | 104 | The raw response from Asterisk as a series of lines, provided for applications that need 105 | access to the original data. 106 | 107 | .. autoclass:: ami.ami._Request 108 | 109 | .. attribute:: aggregate 110 | 111 | If `True` (`False` by default), an aggregate-event will be generated after the list of 112 | independent events generated by this request. 113 | 114 | This only has an effect with requests that generate lists of events to begin with and will 115 | be ignored in other cases. 116 | 117 | .. attribute:: synchronous 118 | 119 | If `True` (`False` by default), any events generated by this request will be collected and 120 | returned in the response. 121 | 122 | Synchronous requests will suppress generation of associated asynchronous events and 123 | aggregates. 124 | 125 | .. attribute:: timeout 126 | 127 | The number of seconds to wait before considering this request timed out, defaulting to `5`; 128 | may be a float. 129 | 130 | Indefinite waiting is not supported, but arbitrarily large values may be provided. 131 | 132 | A request that has timed out may still be serviced by Asterisk, with the notification being 133 | treated as an orphaned event. 134 | 135 | Changing the timeout value of the request object has no effect on any previously-sent 136 | instances of the request object, since the value is copied at dispatch-time. 137 | 138 | .. class:: ami.ami._Response 139 | 140 | .. attribute:: action_id 141 | 142 | The action-ID associated with the request that led to the creation of this response. 143 | 144 | .. attribute:: events 145 | 146 | If the corresponding request was `synchronous`, this is a dictionary containing any events 147 | emitted in response. If not, this is `None`. 148 | 149 | The dictionary will contain references to either the events themselves or lists of events, 150 | depending on what is appropriate, keyed by the event's class-object and its friendly name 151 | as a string, like `pystrix.ami.core_events.CoreShowChannels` and "CoreShowChannels". 152 | 153 | .. attribute:: events_timeout 154 | 155 | A boolean value indicating whether any events were still unreceived when the response was 156 | returned. This is meaningful only if the reqyest had `synchronous` set. 157 | 158 | .. attribute:: response 159 | 160 | The response from Asterisk, without any post-processing applied. You will generally want to 161 | use `result` instead, unless you need to see exactly what Asterisk returned. 162 | 163 | .. attribute:: request 164 | 165 | The request object that led to this response. This will be `None` if the response is an 166 | orhpan, which may happen when a request times out, but a response is generated anyway, 167 | if multiple AMI clients are working with the same Asterisk instance (they won't know each 168 | other's action-IDs), or when working with buggy or experimental versions of Asterisk. 169 | 170 | .. attribute:: result 171 | 172 | The response from Asterisk, with post-processing applied to make it easier to work with in 173 | Python. This is the attribute about which you will likely care most. 174 | 175 | .. attribute:: success 176 | 177 | A boolean value that indicates whether the response appears to indicate that the request 178 | succeeded. 179 | 180 | .. attribute:: time 181 | 182 | The amount of time, as a UNIX timestamp, that elapsed while waiting for a response. 183 | 184 | Exceptions 185 | ++++++++++ 186 | 187 | .. autoexception:: ami.Error 188 | :show-inheritance: 189 | 190 | .. autoexception:: ami.ManagerError 191 | :show-inheritance: 192 | 193 | .. autoexception:: ami.ManagerSocketError 194 | :show-inheritance: 195 | 196 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import sys, os, re 3 | 4 | sys.path.append(os.path.abspath('..')) 5 | import pystrix as module 6 | sys.path.remove(os.path.abspath('..')) 7 | sys.path.append(os.path.abspath('../pystrix')) 8 | 9 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage'] 10 | templates_path = ['_templates'] 11 | source_suffix = '.rst' 12 | master_doc = 'index' 13 | 14 | project = u'pystrix' 15 | copyright = module.COPYRIGHT 16 | version = re.match('^(\d+\.\d+)', module.VERSION).group(1) 17 | release = module.VERSION 18 | 19 | exclude_trees = ['_build'] 20 | 21 | pygments_style = 'sphinx' 22 | 23 | html_theme = 'default' 24 | html_static_path = ['_static'] 25 | html_show_sourcelink = False 26 | 27 | htmlhelp_basename = 'pystrixdoc' 28 | 29 | latex_documents = [ 30 | ('index', 'pystrix.tex', u'pystrix Documentation', 31 | re.search(', (.*?) <', module.COPYRIGHT).group(1), 'manual'), 32 | ] 33 | -------------------------------------------------------------------------------- /doc/examples/agi.rst: -------------------------------------------------------------------------------- 1 | Asterisk Gateway Interface (AGI) 2 | ================================ 3 | 4 | A simple AGI implementation is provided below, demonstrating how to handle requests from Asterisk, 5 | like, as illustrated, answering a call, playing a message, and hanging up:: 6 | 7 | #!/usr/bin/env python 8 | import pystrix 9 | 10 | if __name__ == '__main__': 11 | agi = pystrix.agi.AGI() 12 | 13 | agi.execute(pystrix.agi.core.Answer()) #Answer the call 14 | 15 | response = agi.execute(pystrix.agi.core.StreamFile('demo-thanks', escape_digits=('1', '2'))) #Play a file; allow DTMF '1' or '2' to interrupt 16 | if response: #Playback was interrupted; if you don't care, you don't need to catch this 17 | (dtmf_character, offset) = response #The key pressed by the user and the playback time 18 | 19 | agi.execute(pystrix.agi.core.Hangup()) #Hang up the call 20 | 21 | -------------------------------------------------------------------------------- /doc/examples/ami.rst: -------------------------------------------------------------------------------- 1 | Asterisk Management Interface (AMI) 2 | =================================== 3 | 4 | A simple, if verbose, AMI implementation is provided below, demonstrating how to connect to Asterisk 5 | with MD5-based authentication, how to connect callback handlers for events, and how to send requests 6 | for information:: 7 | 8 | import time 9 | 10 | import pystrix 11 | 12 | #Just a few constants for logging in. Putting them directly into code is usually a bad idea. 13 | _HOST = 'localhost' 14 | _USERNAME = 'admin' 15 | _PASSWORD = 'wordpass' 16 | 17 | class AMICore(object): 18 | """ 19 | The class that will be used to hold the logic for this AMI session. You could also just work 20 | with the `Manager` object directly, but this is probably a better approach for most 21 | general-purpose applications. 22 | """ 23 | _manager = None #The AMI conduit for communicating with the local Asterisk server 24 | _kill_flag = False #True when the core has shut down of its own accord 25 | 26 | def __init__(self): 27 | #The manager supports Python's native logging module and has optional features; see its 28 | #constructor's documentation for details. 29 | self._manager = pystrix.ami.Manager() 30 | 31 | #Before connecting to Asterisk, callback handlers should be registered to avoid missing 32 | #any events. 33 | self._register_callbacks() 34 | 35 | try: 36 | #Attempt to connect to Asterisk 37 | self._manager.connect(_HOST) 38 | 39 | #The first thing to be done is to ask the Asterisk server for a challenge token to 40 | #avoid sending the password in plain-text. This step is optional, however, and can 41 | #be bypassed by simply omitting the 'challenge' parameter in the Login action. 42 | challenge_response = self._manager.send_action(pystrix.ami.core.Challenge()) 43 | #This command demonstrates the common case of constructing a request action and 44 | #sending it to Asterisk to await a response. 45 | 46 | if challenge_response and challenge_response.success: 47 | #The response is either a named tuple or None, with the latter occuring in case 48 | #the request timed out. Requests are blocking (expected to be near-instant), but 49 | #thread-safe, so you can build complex threading logic if necessary. 50 | action = pystrix.ami.core.Login( 51 | _USERNAME, _PASSWORD, challenge=challenge_response.result['Challenge'] 52 | ) 53 | self._manager.send_action(action) 54 | #As with the Challenge action before, a Login action is assembled and sent to 55 | #Asterisk, only in two steps this time, for readability. 56 | #The Login class has special response-processing logic attached to it that 57 | #causes authentication failures to raise a ManagerAuthException error, caught 58 | #below. It will still return the same named tuple if you need to extract 59 | #additional information upon success, however. 60 | else: 61 | self._kill_flag = True 62 | raise ConnectionError( 63 | "Asterisk did not provide an MD5 challenge token" + 64 | (challenge_response is None and ': timed out' or '') 65 | ) 66 | except pystrix.ami.ManagerSocketError as e: 67 | self._kill_flag = True 68 | raise ConnectionError("Unable to connect to Asterisk server: %(error)s" % { 69 | 'error': str(e), 70 | }) 71 | except pystrix.ami.core.ManagerAuthError as reason: 72 | self._kill_flag = True 73 | raise ConnectionError("Unable to authenticate to Asterisk server: %(reason)s" % { 74 | 'reason': reason, 75 | }) 76 | except pystrix.ami.ManagerError as reason: 77 | self._kill_flag = True 78 | raise ConnectionError("An unexpected Asterisk error occurred: %(reason)s" % { 79 | 'reason': reason, 80 | }) 81 | 82 | #Start a thread to make is_connected() fail if Asterisk dies. 83 | #This is not done automatically because it disallows the possibility of immediate 84 | #correction in applications that could gracefully replace their connection upon receipt 85 | #of a `ManagerSocketError`. 86 | self._manager.monitor_connection() 87 | 88 | def _register_callbacks(self): 89 | #This sets up some event callbacks, so that interesting things, like calls being 90 | #established or torn down, will be processed by your application's logic. Of course, 91 | #since this is just an example, the same event will be registered using two different 92 | #methods. 93 | 94 | #The event that will be registered is 'FullyBooted', sent by Asterisk immediately after 95 | #connecting, to indicate that everything is online. What the following code does is 96 | #register two different callback-handlers for this event using two different 97 | #match-methods: string comparison and class-match. String-matching and class-resolution 98 | #are equal in performance, so choose whichever you think looks better. 99 | self._manager.register_callback('FullyBooted', self._handle_string_event) 100 | self._manager.register_callback(pystrix.ami.core_events.FullyBooted, self._handle_class_event) 101 | #Now, when 'FullyBooted' is received, both handlers will be invoked in the order in 102 | #which they were registered. 103 | 104 | #A catch-all-handler can be set using the empty string as a qualifier, causing it to 105 | #receive every event emitted by Asterisk, which may be useful for debugging purposes. 106 | self._manager.register_callback('', self._handle_event) 107 | 108 | #Additionally, an orphan-handler may be provided using the special qualifier None, 109 | #causing any responses not associated with a request to be received. This should only 110 | #apply to glitches in pre-production versions of Asterisk or requests that timed out 111 | #while waiting for a response, which is also indicative of glitchy behaviour. This 112 | #handler could be used to process the orphaned response in special cases, but is likely 113 | #best relegated to a logging role. 114 | self._manager.register_callback(None, self._handle_event) 115 | 116 | #And here's another example of a registered event, this time catching Asterisk's 117 | #Shutdown signal, emitted when the system is shutting down. 118 | self._manager.register_callback('Shutdown', self._handle_shutdown) 119 | 120 | def _handle_shutdown(self, event, manager): 121 | self._kill_flag = True 122 | 123 | def _handle_event(self, event, manager): 124 | print("Received event: %s" % event.name) 125 | 126 | def _handle_string_event(self, event, manager): 127 | print("Received string event: %s" % event.name) 128 | 129 | def _handle_class_event(self, event, manager): 130 | print("Received class event: %s" % event.name) 131 | 132 | def is_alive(self): 133 | return not self._kill_flag 134 | 135 | def kill(self): 136 | self._manager.close() 137 | 138 | 139 | class Error(Exception): 140 | """ 141 | The base class from which all exceptions native to this module inherit. 142 | """ 143 | 144 | class ConnectionError(Error): 145 | """ 146 | Indicates that a problem occurred while connecting to the Asterisk server 147 | or that the connection was severed unexpectedly. 148 | """ 149 | 150 | if __name__ == '__main__': 151 | ami_core = AMICore() 152 | 153 | while ami_core.is_alive(): 154 | #In a larger application, you'd probably do something useful in another non-daemon 155 | #thread or maybe run a parallel FastAGI server. The pystrix implementation has the AMI 156 | #threads run daemonically, however, so a block like this in the main thread is necessary 157 | time.sleep(1) 158 | ami_core.kill() 159 | 160 | -------------------------------------------------------------------------------- /doc/examples/fastagi.rst: -------------------------------------------------------------------------------- 1 | Fast Asterisk Gateway Interface (FastAGI) 2 | ========================================= 3 | 4 | A simple FastAGI implementation is provided below, demonstrating how to listen for and handle 5 | requests from Asterisk, like, as illustrated, answering a call, playing a message, and hanging 6 | up:: 7 | 8 | import re 9 | import threading 10 | import time 11 | 12 | import pystrix 13 | 14 | class FastAGIServer(threading.Thread): 15 | """ 16 | A simple thread that runs a FastAGI server forever. 17 | """ 18 | _fagi_server = None #The FastAGI server controlled by this thread 19 | 20 | def __init__(self): 21 | threading.Thread.__init__(self) 22 | self.daemon = True 23 | 24 | self._fagi_server = pystrix.agi.FastAGIServer() 25 | 26 | self._fagi_server.register_script_handler(re.compile('demo'), self._demo_handler) 27 | self._fagi_server.register_script_handler(None, self._noop_handler) 28 | 29 | def _demo_handler(self, agi, args, kwargs, match, path): 30 | """ 31 | `agi` is the AGI instance used to process events related to the channel, `args` is a 32 | collection of positional arguments provided with the script as a tuple, `kwargs` is a 33 | dictionary of keyword arguments supplied with the script (values are enumerated in a list), 34 | `match` is the regex match object (None if the fallback handler), and `path` is the string 35 | path supplied by Asterisk, in case special processing is needed. 36 | 37 | The directives issued in this function can all raise Hangup exceptions, which should be 38 | caught if doing anything complex, but an uncaught exception will simply cause a warning to 39 | be raised, making AGI scripts very easy to write. 40 | """ 41 | agi.execute(pystrix.agi.core.Answer()) #Answer the call 42 | 43 | response = agi.execute(pystrix.agi.core.StreamFile('demo-thanks', escape_digits=('1', '2'))) #Play a file; allow DTMF '1' or '2' to interrupt 44 | if response: #Playback was interrupted; if you don't care, you don't need to catch this 45 | (dtmf_character, offset) = response #The key pressed by the user and the playback time 46 | 47 | agi.execute(pystrix.agi.core.Hangup()) #Hang up the call 48 | 49 | def _noop_handler(self, agi, args, kwargs, match, path): 50 | """ 51 | Does nothing, causing control to return to Asterisk's dialplan immediately; provided just 52 | to demonstrate the fallback handler. 53 | """ 54 | 55 | def kill(self): 56 | self._fagi_server.shutdown() 57 | 58 | def run(self): 59 | self._fagi_server.serve_forever() 60 | 61 | 62 | 63 | if __name__ == '__main__': 64 | fastagi_core = FastAGIServer() 65 | fastagi_core.start() 66 | 67 | while fastagi_core.is_alive(): 68 | #In a larger application, you'd probably do something useful in another non-daemon 69 | #thread or maybe run a parallel AMI server 70 | time.sleep(1) 71 | fastagi_core.kill() 72 | 73 | -------------------------------------------------------------------------------- /doc/examples/index.rst: -------------------------------------------------------------------------------- 1 | Example usage 2 | ============= 3 | 4 | The following sections contain a single, well-documented-but-minimal example of how to use pystrix 5 | for the associated Asterisk function. 6 | 7 | .. toctree:: 8 | 9 | ami.rst 10 | agi.rst 11 | fastagi.rst 12 | 13 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | pystrix user documentation 2 | ========================== 3 | 4 | pystrix's main design goal is to provide a consistent, easy-to-extend API for interacting with 5 | Asterisk. This documentation exists to prevent you from needing to go trawling through source code 6 | when all you really need to do is see a class's constructor and read about what it does. 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | examples/index.rst 12 | agi/index.rst 13 | ami/index.rst 14 | 15 | -------------------------------------------------------------------------------- /pystrix/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix 3 | ======= 4 | 5 | pystrix is a collection of classes that provide a simple interface for 6 | interacting with an Asterisk server with Python. 7 | 8 | It differs from its contemporaries by being provided as a toolkit, rather than 9 | a framework, allowing it to be used as part of larger projects that may be 10 | incompatible, by design or evolution, with the Twisted framework. 11 | 12 | Usage 13 | ----- 14 | 15 | Importing this package, or the 'agi' or 'ami' sub-packages is recommended over 16 | importing individual modules. 17 | 18 | Legal 19 | ----- 20 | 21 | This file is part of pystrix. 22 | pystrix is free software; you can redistribute it and/or modify 23 | it under the terms of the GNU Lesser General Public License as published 24 | by the Free Software Foundation; either version 3 of the License, or 25 | (at your option) any later version. 26 | 27 | This program is distributed in the hope that it will be useful, 28 | but WITHOUT ANY WARRANTY; without even the implied warranty of 29 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 30 | GNU Lesser General Public License for more details. 31 | 32 | You should have received a copy of the GNU General Public License and 33 | GNU Lesser General Public License along with this program. If not, see 34 | . 35 | 36 | (C) Ivrnet, inc., 2011 37 | 38 | Authors: 39 | 40 | - Neil Tallim 41 | """ 42 | import pystrix.agi 43 | import pystrix.ami 44 | 45 | VERSION = '1.2.0' 46 | COPYRIGHT = '2013, Neil Tallim ' 47 | -------------------------------------------------------------------------------- /pystrix/agi/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.agi 3 | =========== 4 | 5 | Provides a library suitable for interacting with an Asterisk server using the 6 | Asterisk Gateway Interface (AGI) protocol. 7 | 8 | Usage 9 | ----- 10 | 11 | Importing this package is recommended over importing individual modules. 12 | 13 | Legal 14 | ----- 15 | 16 | This file is part of pystrix. 17 | pystrix is free software; you can redistribute it and/or modify 18 | it under the terms of the GNU Lesser General Public License as published 19 | by the Free Software Foundation; either version 3 of the License, or 20 | (at your option) any later version. 21 | 22 | This program is distributed in the hope that it will be useful, 23 | but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | GNU Lesser General Public License for more details. 26 | 27 | You should have received a copy of the GNU General Public License and 28 | GNU Lesser General Public License along with this program. If not, see 29 | . 30 | 31 | (C) Ivrnet, inc., 2011 32 | 33 | Authors: 34 | 35 | - Neil Tallim 36 | """ 37 | from pystrix.agi.agi_core import ( 38 | AGIException, AGIError, AGINoResultError, AGIUnknownError, AGIAppError, 39 | AGIHangup, AGISIGPIPEHangup, AGIResultHangup, 40 | AGIDeadChannelError, AGIUsageError, AGIInvalidCommandError, 41 | ) 42 | 43 | from pystrix.agi.agi import ( 44 | AGI, 45 | AGISIGHUPHangup, 46 | ) 47 | 48 | from pystrix.agi.fastagi import ( 49 | FastAGIServer, FastAGI, 50 | ) 51 | 52 | from pystrix.agi import core 53 | 54 | -------------------------------------------------------------------------------- /pystrix/agi/agi.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.agi.agi 3 | =============== 4 | 5 | Provides a class that exposes methods for communicating with Asterisk from an 6 | AGI (script) context. 7 | 8 | Legal 9 | ----- 10 | 11 | This file is part of pystrix. 12 | pystrix is free software; you can redistribute it and/or modify 13 | it under the terms of the GNU Lesser General Public License as published 14 | by the Free Software Foundation; either version 3 of the License, or 15 | (at your option) any later version. 16 | 17 | This program is distributed in the hope that it will be useful, 18 | but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | GNU Lesser General Public License for more details. 21 | 22 | You should have received a copy of the GNU General Public License and 23 | GNU Lesser General Public License along with this program. If not, see 24 | . 25 | 26 | (C) Ivrnet, inc., 2011 27 | 28 | Authors: 29 | 30 | - Neil Tallim 31 | """ 32 | import signal 33 | import sys 34 | 35 | from pystrix.agi.agi_core import * 36 | from pystrix.agi.agi_core import _AGI 37 | 38 | class AGI(_AGI): 39 | """ 40 | An interface to Asterisk, exposing request-response functions for 41 | synchronous management of the call associated with this channel. 42 | """ 43 | _got_sighup = False #True when a hangup signal has been received. 44 | 45 | def __init__(self, debug=False): 46 | """ 47 | Binds the SIGHUP signal and associates I/O with stdin/stdout. 48 | 49 | `debug` should only be turned on for library development. 50 | """ 51 | signal.signal(signal.SIGHUP, self._handle_sighup) 52 | self._rfile = sys.stdin 53 | self._wfile = sys.stdout 54 | 55 | _AGI.__init__(self, debug) 56 | 57 | def _handle_sighup(self, signum, frame): 58 | """ 59 | Sets the has-hungup flag to trigger an exception when the next command 60 | is received. 61 | """ 62 | self._got_sighup = True 63 | 64 | def _test_hangup(self): 65 | """ 66 | If SIGHUP has been received, or another hangup flag has been set, an 67 | exception is raised; if not, this function is a no-op. 68 | 69 | Raises `AGISIGHUPHangup` if SIGHUP has been recieved, or any other exceptions 70 | normally raised by `_AGI`'s `_test_hangup()`. 71 | """ 72 | if self._got_sighup: 73 | raise AGISIGHUPHangup("Received SIGHUP from Asterisk") 74 | 75 | _AGI._test_hangup(self) 76 | 77 | class AGISIGHUPHangup(AGIHangup): 78 | """ 79 | Indicates that the script's process received the SIGHUP signal, implying 80 | Asterisk has hung up the call. Specific to script-based instances. 81 | """ 82 | 83 | -------------------------------------------------------------------------------- /pystrix/agi/agi_core.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.agi.agi_core 3 | ==================== 4 | 5 | The core framework needed for an AGI session, regardless of interface. 6 | 7 | Usage 8 | ----- 9 | 10 | This module should not be used directly; instead, import one of `agi` 11 | or `fastagi`. 12 | 13 | Legal 14 | ----- 15 | 16 | This file is part of pystrix. 17 | pystrix is free software; you can redistribute it and/or modify 18 | it under the terms of the GNU Lesser General Public License as published 19 | by the Free Software Foundation; either version 3 of the License, or 20 | (at your option) any later version. 21 | 22 | This program is distributed in the hope that it will be useful, 23 | but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | GNU Lesser General Public License for more details. 26 | 27 | You should have received a copy of the GNU General Public License and 28 | GNU Lesser General Public License along with this program. If not, see 29 | . 30 | 31 | (C) Ivrnet, inc., 2011 32 | 33 | Authors: 34 | 35 | - Neil Tallim 36 | """ 37 | import collections 38 | import re 39 | import time 40 | 41 | import sys 42 | 43 | _Response = collections.namedtuple('Response', ('items', 'code', 'raw')) 44 | _ValueData = collections.namedtuple('ValueData', ('value', 'data')) 45 | 46 | _RE_CODE = re.compile(r'(^\d+)\s*(.+)') #Matches Asterisk's response-code lines 47 | _RE_KV = re.compile(r'(?P\w+)=(?P[^\s]+)?(?:\s+\((?P.*)\))?') #Matches Asterisk's key-value response-pairs 48 | 49 | _RESULT_KEY = 'result' 50 | 51 | 52 | #Functions 53 | ############################################################################### 54 | def quote(value): 55 | """ 56 | Encapsulates `value` in double-quotes and coerces it into a string, if 57 | necessary. 58 | """ 59 | return '"%(value)s"' % { 60 | 'value': str(value), 61 | } 62 | 63 | 64 | #Classes 65 | ############################################################################### 66 | class _AGI(object): 67 | """ 68 | This class encapsulates communication between Asterisk an a python script. 69 | It handles encoding commands to Asterisk and parsing responses from 70 | Asterisk. 71 | """ 72 | _environment = None #The environment variables received from Asterisk for this channel 73 | _debug = False #If True, development information is printed to console 74 | _rfile = None #The input file-like-object 75 | _wfile = None #The output file-like-object 76 | 77 | def __init__(self, debug=False): 78 | """ 79 | Sets up variables required to process an AGI session. 80 | 81 | `debug` should only be turned on for library development. 82 | """ 83 | self._debug = debug 84 | 85 | self._environment = {} 86 | self._parse_agi_environment() 87 | 88 | def execute(self, action): 89 | """ 90 | Sends a request to Asterisk and waits for a response before returning control to the caller. 91 | 92 | The given `_Action` object, `action`, carries the command, arguments, and result-processing 93 | logic used to communicate with Asterisk. 94 | 95 | The state of the channel is verified with each call to this function, to ensure that it is 96 | still connected. An instance of `AGIHangup` is raised if it is not. 97 | """ 98 | self._test_hangup() 99 | 100 | self._send_command(action.command) 101 | return action.process_response(self._get_result(action.check_hangup)) 102 | 103 | def get_environment(self): 104 | """ 105 | Returns Asterisk's initial environment variables as a dictionary. 106 | 107 | Note that this function returns a copy of the values, so repeated calls 108 | are less favourable than storing the returned value locally and 109 | dissecting it there. 110 | """ 111 | return self._environment.copy() 112 | 113 | def _get_result(self, check_hangup=True): 114 | """ 115 | Waits for a response from Asterisk, parses it, validates its contents, and returns it as a 116 | named tuple with 'items', 'code', and 'raw' attributes, where 'items' is a dictionary of 117 | Asterisk response-keys and value/data pairs, themselves in named tupled with 'value' and 118 | 'data' attributes, 'code' is the numeric code received from Asterisk, and 'raw' is the line 119 | received, excluding the code. 120 | 121 | `check_hangup`, if `True`, the default, will cause `AGIResultHangup` to be raised if the 122 | 'data' attribute of the 'result' key is 'hangup'. 123 | 124 | If the result indicates failure, `AGIAppError` is raised. 125 | 126 | If no 'result' key is provided, `AGIError` is raised. 127 | 128 | `AGIInvalidCommandError` is raised if the given command is unrecognised, either because the 129 | requested function isn't implemented in the current version of Asterisk or because the 130 | `execute()` function was invoked incorrectly. 131 | 132 | `AGIUsageError` is emitted if the arguments provided for a command are invalid. 133 | 134 | `AGIDeadChannelError` occurs if a command is attempted on a dead channel. 135 | 136 | `AGIUnknownError` covers any unrecognised Asterisk response code. 137 | """ 138 | code = 0 139 | response = {} 140 | 141 | line = self._read_line() 142 | m = _RE_CODE.search(line) 143 | if m: 144 | code = int(m.group(1)) 145 | 146 | if code == 200: 147 | raw = m.group(2) #The entire line, excluding the code 148 | for (key, value, data) in _RE_KV.findall(m.group(2)): 149 | response[key] = _ValueData(value or '', data) 150 | 151 | if not _RESULT_KEY in response: #Must always be present. 152 | raise AGINoResultError("Asterisk did not provide a '%(result-key)s' key-value pair" % { 153 | 'result-key': _RESULT_KEY, 154 | }, response) 155 | 156 | result = response.get(_RESULT_KEY) 157 | if check_hangup and result.data == 'hangup': #A 'hangup' response usually indicates that the channel was hungup, but it is a legal variable value 158 | raise AGIResultHangup("User hung up during execution", response) 159 | 160 | return _Response(response, code, raw) 161 | elif code == 0: 162 | # No code was returned by Asterisk. 163 | # The only other possible codes returned by Asterisk are 200, 510, 511 and 520 which is being handled. 164 | # We probably got a signal like SIGHUP, so move on and do nothing 165 | pass 166 | elif code == 510: 167 | raise AGIInvalidCommandError(response) 168 | elif code == 511: 169 | raise AGIDeadChannelError(response) 170 | elif code == 520: 171 | usage = [line] 172 | while True: 173 | line = self._read_line() 174 | usage.append(line) 175 | if '520 End of proper usage.' in line: 176 | break 177 | raise AGIUsageError('\n'.join(usage + [''])) 178 | else: 179 | raise AGIUnknownError("Unhandled code or undefined response: %(code)i : %(line)s" % { 180 | 'code': code, 181 | 'line': repr(line), 182 | }) 183 | 184 | def _parse_agi_environment(self): 185 | """ 186 | Reads all of Asterisk's environment variables and stores them in memory. 187 | """ 188 | while True: 189 | line = self._read_line() 190 | if line == '': #Blank line signals end 191 | break 192 | 193 | if ':' in line: 194 | (key, data) = line.split(':', 1) 195 | key = key.strip() 196 | data = data.strip() 197 | if key: 198 | self._environment[key] = data 199 | 200 | def _read_line(self, should_strip=True): 201 | """ 202 | Reads and returns a line from the Asterisk pipe, blocking until a complete line is 203 | assembled. 204 | 205 | If the pipe is closed before this happens, `AGISIGPIPEHangup` is raised. 206 | """ 207 | try: 208 | line = self._rfile.readline() 209 | try: 210 | line = line.decode() # decode line if it comes in bytes, example if it comes from a socket 211 | except: 212 | pass # line it's a string, so nothing to change - it's string if it's using stdin as _rfile for example 213 | # Check to see if we received a HANGUP because AGISIGHUP was not set explicitly or is no 214 | # and then handle the HANGUP which is being returned because the AGI script can still interact with 215 | # Asterisk after the call was hungup in DeadAGI mode (which Asterisk converts the channel to automatically) 216 | # All commands won't work in DeadAGI but that is not our concern here because if such a command is issued 217 | # which indeed requires channel interaction, Asterisk will respond with a 511 code. 218 | if 'no' == self._environment.get('AGISIGHUP', 'no') and 'HANGUP\n' == line: 219 | line = self._read_line(should_strip=False) # read from pipe again to get response for the given command 220 | if not line: #EOF encountered 221 | raise AGISIGPIPEHangup("Process input pipe closed") 222 | elif not line.endswith('\n'): #Fragment encountered 223 | #Recursively append to the current fragment until the line is 224 | #complete or the socket dies. 225 | line += self._read_line() 226 | return line.strip() if should_strip else line 227 | except IOError as e: 228 | raise AGISIGPIPEHangup("Process input pipe broken: %(error)s" % { 229 | 'error': str(e), 230 | }) 231 | 232 | def _send_command(self, command, *args): 233 | """ 234 | Formats a `command` and sends it to Asterisk. 235 | 236 | The formatted command is constructed by joining the action verb component with every 237 | following argument, discarding those that are `None`. 238 | 239 | If the connection to Asterisk is broken, `AGISIGPIPEHangup` is raised. 240 | """ 241 | try: 242 | if self._wfile is not sys.stdout: # stdout handles str instead of bytes, so we don't encode 243 | command = command.encode() 244 | self._wfile.write(command) 245 | self._wfile.flush() 246 | except Exception as e: 247 | raise AGISIGPIPEHangup("Socket link broken: %(error)s" % { 248 | 'error': str(e), 249 | }) 250 | 251 | def _test_hangup(self): 252 | """ 253 | Tests to see if the channel has been hung up. 254 | 255 | At present, this is a no-op because no generic hang-up conditions are 256 | known, but subclasses may have specific scenarios to test for. 257 | """ 258 | return 259 | 260 | class _Action(object): 261 | """ 262 | Provides the basis for assembling and issuing an action via AGI. 263 | """ 264 | _command = None #The command that drives this action 265 | _arguments = None #A tuple of arguments to qualify the command 266 | check_hangup = True #True if the output of this action is sure to be hangup-detection-safe 267 | 268 | def __init__(self, command, *arguments): 269 | self._command = command 270 | self._arguments = arguments 271 | 272 | @property 273 | def command(self): 274 | command = ' '.join([self._command.strip()] + [str(arg) for arg in self._arguments if not arg is None]).strip() 275 | if not command.endswith('\n'): 276 | command += '\n' 277 | return command 278 | 279 | def process_response(self, response): 280 | """ 281 | Just returns the `response` from Asterisk verbatim. May be overridden to allow for 282 | sophisticated processing. 283 | """ 284 | return response 285 | 286 | 287 | #Exceptions 288 | ############################################################################### 289 | class AGIException(Exception): 290 | """ 291 | The base exception from which all exceptions native to this module inherit. 292 | """ 293 | items = None #Any items received from Asterisk, as a dictionary. 294 | 295 | def __init__(self, message, items=None): 296 | Exception.__init__(self, message) 297 | self.items = items if items else {} 298 | 299 | class AGIError(AGIException): 300 | """ 301 | The base error from which all errors native to this module inherit. 302 | """ 303 | 304 | class AGINoResultError(AGIException): 305 | """ 306 | Indicates that Asterisk did not return a 'result' parameter in a 200 response. 307 | """ 308 | 309 | class AGIUnknownError(AGIError): 310 | """ 311 | An error raised when an unknown response is received from Asterisk. 312 | """ 313 | 314 | class AGIAppError(AGIError): 315 | """ 316 | An error raised when an attempt to make use of an Asterisk application 317 | fails. 318 | """ 319 | 320 | class AGIDeadChannelError(AGIError): 321 | """ 322 | Indicates that a command was issued on a channel that can no longer process 323 | it. 324 | """ 325 | 326 | class AGIInvalidCommandError(AGIError): 327 | """ 328 | Indicates that a request made to Asterisk was not understood. 329 | """ 330 | 331 | class AGIUsageError(AGIError): 332 | """ 333 | Indicates that a request made to Asterisk was sent with invalid syntax. 334 | """ 335 | 336 | class AGIHangup(AGIException): 337 | """ 338 | The base exception used to indicate that the call has been completed or 339 | abandoned. 340 | """ 341 | 342 | class AGISIGPIPEHangup(AGIHangup): 343 | """ 344 | Indicates that the communications pipe to Asterisk has been severed. 345 | """ 346 | 347 | class AGIResultHangup(AGIHangup): 348 | """ 349 | Indicates that Asterisk received a clean hangup event. 350 | """ 351 | 352 | -------------------------------------------------------------------------------- /pystrix/agi/core.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.agi.core 3 | ================ 4 | 5 | All standard AGI actions as instantiable classes, suitable for passing to the 6 | `execute()` function of an AGI interface. 7 | 8 | Also includes constants to make programmatic interaction cleaner. 9 | 10 | Legal 11 | ----- 12 | 13 | This file is part of pystrix. 14 | pystrix is free software; you can redistribute it and/or modify 15 | it under the terms of the GNU Lesser General Public License as published 16 | by the Free Software Foundation; either version 3 of the License, or 17 | (at your option) any later version. 18 | 19 | This program is distributed in the hope that it will be useful, 20 | but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | GNU Lesser General Public License for more details. 23 | 24 | You should have received a copy of the GNU General Public License and 25 | GNU Lesser General Public License along with this program. If not, see 26 | . 27 | 28 | (C) Ivrnet, inc., 2011 29 | 30 | Authors: 31 | 32 | - Neil Tallim 33 | """ 34 | import time 35 | 36 | from pystrix.agi.agi_core import ( 37 | _Action, 38 | quote, 39 | _RESULT_KEY, 40 | AGIAppError, 41 | ) 42 | 43 | CHANNEL_DOWN_AVAILABLE = 0 # Channel is down and available 44 | CHANNEL_DOWN_RESERVED = 1 # Channel is down and reserved 45 | CHANNEL_OFFHOOK = 2 # Channel is off-hook 46 | CHANNEL_DIALED = 3 # A destination address has been specified 47 | CHANNEL_ALERTING = 4 # The channel is locally ringing 48 | CHANNEL_REMOTE_ALERTING = 5 # The channel is remotely ringing 49 | CHANNEL_UP = 6 # The channel is connected 50 | CHANNEL_BUSY = 7 # The channel is in a busy, non-conductive state 51 | 52 | FORMAT_SLN = 'sln' 53 | FORMAT_G723 = 'g723' 54 | FORMAT_G729 = 'g729' 55 | FORMAT_GSM = 'gsm' 56 | FORMAT_ALAW = 'alaw' 57 | FORMAT_ULAW = 'ulaw' 58 | FORMAT_VOX = 'vox' 59 | FORMAT_WAV = 'wav' 60 | 61 | LOG_DEBUG = 0 62 | LOG_INFO = 1 63 | LOG_WARN = 2 64 | LOG_ERROR = 3 65 | LOG_CRITICAL = 4 66 | 67 | TDD_ON = 'on' 68 | TDD_OFF = 'off' 69 | TDD_MATE = 'mate' 70 | 71 | 72 | # Functions 73 | ############################################################################### 74 | def _convert_to_char(value, items): 75 | """ 76 | Converts the given value into an ASCII character or raises `AGIAppError` with `items` as the 77 | payload. 78 | """ 79 | try: 80 | return chr(int(value)) 81 | except ValueError: 82 | raise AGIAppError("Unable to convert Asterisk result to DTMF character: %(value)r" % { 83 | 'value': value, 84 | }, items) 85 | 86 | 87 | def _convert_to_int(items): 88 | """ 89 | Extracts the offset-value from Asterisk's response, `items`, or returns -1 if the value 90 | can't be parsed. 91 | """ 92 | offset = items.get('endpos') 93 | if offset and offset.data.isdigit(): 94 | return int(offset.data) 95 | else: 96 | return -1 97 | 98 | 99 | def _process_digit_list(digits): 100 | """ 101 | Ensures that digit-lists are processed uniformly. 102 | """ 103 | if type(digits) in (list, tuple, set, frozenset): 104 | digits = ''.join([str(d) for d in digits]) 105 | return quote(digits) 106 | 107 | 108 | # Classes 109 | ############################################################################### 110 | class Answer(_Action): 111 | """ 112 | Answers the call on the channel. 113 | 114 | If the channel has already been answered, this is a no-op. 115 | 116 | `AGIAppError` is raised on failure, most commonly because the connection 117 | could not be established. 118 | """ 119 | 120 | def __init__(self): 121 | _Action.__init__(self, 'ANSWER') 122 | 123 | 124 | class ChannelStatus(_Action): 125 | """ 126 | Provides the current state of this channel or, if `channel` is set, that of the named 127 | channel. 128 | 129 | Returns one of the channel-state constants listed below: 130 | 131 | - CHANNEL_DOWN_AVAILABLE: Channel is down and available 132 | - CHANNEL_DOWN_RESERVED: Channel is down and reserved 133 | - CHANNEL_OFFHOOK: Channel is off-hook 134 | - CHANNEL_DIALED: A destination address has been specified 135 | - CHANNEL_ALERTING: The channel is locally ringing 136 | - CHANNEL_REMOTE_ALERTING: The channel is remotely ringing 137 | - CHANNEL_UP: The channel is connected 138 | - CHANNEL_BUSY: The channel is in a busy, non-conductive state 139 | 140 | The value returned is an integer in the range 0-7; values outside of 141 | that range were undefined at the time of writing, but will be returned 142 | verbatim. Applications unprepared to handle unknown states should 143 | raise an exception upon their receipt or otherwise handle the code 144 | gracefully. 145 | 146 | `AGIAppError` is raised on failure, most commonly because the channel is 147 | in a hung-up state. 148 | """ 149 | 150 | def __init__(self, channel=None): 151 | _Action.__init__(self, 'CHANNEL STATUS', (channel and quote(channel)) or None) 152 | 153 | def process_response(self, response): 154 | result = response.items.get(_RESULT_KEY) 155 | try: 156 | return int(result.value) 157 | except ValueError: 158 | raise AGIAppError( 159 | "'%(result-key)s' key-value pair received from Asterisk contained a non-numeric value: %(value)r" % { 160 | 'result-key': _RESULT_KEY, 161 | 'value': result.value, 162 | }, response.items) 163 | 164 | 165 | class ControlStreamFile(_Action): 166 | """ 167 | See also `GetData`, `GetOption`, `StreamFile`. 168 | 169 | Plays back the specified file, which is the `filename` of the file to be played, either in 170 | an Asterisk-searched directory or as an absolute path, without extension. ('myfile.wav' 171 | would be specified as 'myfile', to allow Asterisk to choose the most efficient encoding, 172 | based on extension, for the channel) 173 | 174 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 175 | of possibly mixed ints and strings. Playback ends immediately when one is received. 176 | 177 | `sample_offset` may be used to jump an arbitrary number of milliseconds into the audio data. 178 | 179 | If specified, `forward`, `rewind`, and `pause` are DTMF characters that will seek forwards 180 | and backwards in the audio stream or pause it temporarily; by default, these features are 181 | disabled. 182 | 183 | If a DTMF key is received, it is returned as a string. If nothing is received or the file 184 | could not be played back (see Asterisk logs), None is returned. 185 | 186 | `AGIAppError` is raised on failure, most commonly because the channel was 187 | hung-up. 188 | """ 189 | 190 | def __init__(self, filename, escape_digits='', sample_offset=0, forward='', rewind='', pause=''): 191 | escape_digits = _process_digit_list(escape_digits) 192 | _Action.__init__(self, 'CONTROL STREAM FILE', quote(filename), 193 | quote(escape_digits), quote(sample_offset), 194 | quote(forward), quote(rewind), quote(pause) 195 | ) 196 | 197 | def process_response(self, response): 198 | result = response.items.get(_RESULT_KEY) 199 | if not result.value == '0': 200 | return _convert_to_char(result.value, response.items) 201 | return None 202 | 203 | 204 | class DatabaseDel(_Action): 205 | """ 206 | Deletes the specified family/key entry from Asterisk's database. 207 | 208 | `AGIAppError` is raised on failure. 209 | 210 | `AGIDBError` is raised if the key could not be removed, which usually indicates that it 211 | didn't exist in the first place. 212 | """ 213 | 214 | def __init__(self, family, key): 215 | _Action.__init__(self, 'DATABASE DEL', quote(family), quote(key)) 216 | self.family = family 217 | self.key = key 218 | 219 | def process_response(self, response): 220 | result = response.items.get(_RESULT_KEY) 221 | if result.value == '0': 222 | raise AGIDBError("Unable to delete from database: family=%(family)r, key=%(key)r" % { 223 | 'family': self.family, 224 | 'key': self.key, 225 | }, response.items) 226 | 227 | 228 | class DatabaseDeltree(_Action): 229 | """ 230 | Deletes the specificed family (and optionally keytree) from Asterisk's database. 231 | 232 | `AGIAppError` is raised on failure. 233 | 234 | `AGIDBError` is raised if the family (or keytree) could not be removed, which usually 235 | indicates that it didn't exist in the first place. 236 | """ 237 | 238 | def __init__(self, family, keytree=None): 239 | _Action.__init__(self, 240 | 'DATABASE DELTREE', quote(family), (keytree and quote(keytree) or None) 241 | ) 242 | self.family = family 243 | self.keytree = keytree 244 | 245 | def process_response(self, response): 246 | result = response.items.get(_RESULT_KEY) 247 | if result.value == '0': 248 | raise AGIDBError("Unable to delete family from database: family=%(family)r, keytree=%(keytree)r" % { 249 | 'family': self.family, 250 | 'keytree': self.keytree or '', 251 | }, response.items) 252 | 253 | 254 | class DatabaseGet(_Action): 255 | """ 256 | Retrieves the value of the specified family/key entry from Asterisk's database. 257 | 258 | `AGIAppError` is raised on failure. 259 | 260 | `AGIDBError` is raised if the key could not be found or if some other database problem 261 | occurs. 262 | """ 263 | check_hangup = False 264 | 265 | def __init__(self, family, key): 266 | _Action.__init__(self, 'DATABASE GET', quote(family), quote(key)) 267 | self.family = family 268 | self.key = key 269 | 270 | def process_response(self, response): 271 | result = response.items.get(_RESULT_KEY) 272 | if result.value == '0': 273 | raise AGIDBError("Key not found in database: family=%(family)r, key=%(key)r" % { 274 | 'family': self.family, 275 | 'key': self.key, 276 | }, response.items) 277 | elif result.value == '1': 278 | return result.data 279 | 280 | raise AGIDBError("Unable to query database: family=%(family)r, key=%(key)r, result=%(result)r" % { 281 | 'family': self.family, 282 | 'key': self.key, 283 | 'result': result.value, 284 | }, response.items) 285 | 286 | 287 | class DatabasePut(_Action): 288 | """ 289 | Inserts or updates value of the specified family/key entry in Asterisk's database. 290 | 291 | `AGIAppError` is raised on failure. 292 | 293 | `AGIDBError` is raised if the key could not be inserted or if some other database problem 294 | occurs. 295 | """ 296 | 297 | def __init__(self, family, key, value): 298 | _Action.__init__(self, 'DATABASE PUT', quote(family), quote(key), quote(value)) 299 | self.family = family 300 | self.key = key 301 | self.value = value 302 | 303 | def process_response(self, response): 304 | result = response.items.get(_RESULT_KEY) 305 | if result.value == '0': 306 | raise AGIDBError("Unable to store value in database: family=%(family)r, key=%(key)r, value=%(value)r" % { 307 | 'family': self.family, 308 | 'key': self.key, 309 | 'value': self.value, 310 | }, response.items) 311 | 312 | 313 | class Exec(_Action): 314 | """ 315 | Executes an arbitrary Asterisk `application` with the given `options`, returning that 316 | application's output. 317 | 318 | `options` is an optional sequence of arguments, with any double-quote characters or commas 319 | explicitly escaped. 320 | 321 | `AGIAppError` is raised if the application could not be executed. 322 | """ 323 | check_hangup = False 324 | 325 | def __init__(self, application, options=()): 326 | self._application = application 327 | options = ','.join((str(o or '') for o in options)) 328 | _Action.__init__(self, 'EXEC', self._application, (options and quote(options)) or '') 329 | 330 | def process_response(self, response): 331 | result = response.items.get(_RESULT_KEY) 332 | if result.value == '-2': 333 | raise AGIAppError("Unable to execute application '%(application)r'" % { 334 | 'application': self._application, 335 | }, response.items) 336 | return response.raw[7:] # Everything after 'result=' 337 | 338 | 339 | class GetData(_Action): 340 | """ 341 | See also `ControlStreamFile`, `GetOption`, `StreamFile`. 342 | 343 | Plays back the specified file, which is the `filename` of the file to be played, either in 344 | an Asterisk-searched directory or as an absolute path, without extension. ('myfile.wav' 345 | would be specified as 'myfile', to allow Asterisk to choose the most efficient encoding, 346 | based on extension, for the channel) 347 | 348 | `timeout` is the number of milliseconds to wait between DTMF presses or following the end 349 | of playback if no keys were pressed to interrupt playback prior to that point. It defaults 350 | to 2000. 351 | 352 | `max_digits` is the number of DTMF keypresses that will be accepted. It defaults to 255. 353 | 354 | The value returned is a tuple consisting of (dtmf_keys:str, timeout:bool). '#' is always 355 | interpreted as an end-of-event character and will never be present in the output. 356 | 357 | `AGIAppError` is raised on failure, most commonly because no keys, aside from '#', were 358 | entered. 359 | """ 360 | 361 | def __init__(self, filename, timeout=2000, max_digits=255): 362 | _Action.__init__(self, 363 | 'GET DATA', quote(filename), quote(timeout), quote(max_digits) 364 | ) 365 | 366 | def process_response(self, response): 367 | result = response.items.get(_RESULT_KEY) 368 | return (result.value, result.data == 'timeout') 369 | 370 | 371 | class GetFullVariable(_Action): 372 | """ 373 | Returns a `variable` associated with this channel, with full expression-processing. 374 | 375 | The value of the requested variable is returned as a string. If the variable is 376 | undefined, `None` is returned. 377 | 378 | `AGIAppError` is raised on failure. 379 | """ 380 | check_hangup = False 381 | 382 | def __init__(self, variable): 383 | _Action.__init__(self, 'GET FULL VARIABLE', quote(variable)) 384 | 385 | def process_response(self, response): 386 | result = response.items.get(_RESULT_KEY) 387 | if result.value == '1': 388 | return result.data 389 | return None 390 | 391 | 392 | class GetOption(_Action): 393 | """ 394 | See also `ControlStreamFile`, `GetData`, `StreamFile`. 395 | 396 | Plays back the specified file, which is the `filename` of the file to be played, either in 397 | an Asterisk-searched directory or as an absolute path, without extension. ('myfile.wav' 398 | would be specified as 'myfile', to allow Asterisk to choose the most efficient encoding, 399 | based on extension, for the channel) 400 | 401 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 402 | of possibly mixed ints and strings. Playback ends immediately when one is received. 403 | 404 | `timeout` is the number of milliseconds to wait following the end of playback if no keys 405 | were pressed to interrupt playback prior to that point. It defaults to 2000. 406 | 407 | The value returned is a tuple consisting of (dtmf_key:str, offset:int), where the offset is 408 | the number of milliseconds that elapsed since the start of playback, or None if playback 409 | completed successfully or the sample could not be opened. 410 | 411 | `AGIAppError` is raised on failure, most commonly because the channel was 412 | hung-up. 413 | """ 414 | 415 | def __init__(self, filename, escape_digits='', timeout=2000): 416 | escape_digits = _process_digit_list(escape_digits) 417 | _Action.__init__(self, 418 | 'GET OPTION', quote(filename), 419 | quote(escape_digits), quote(timeout) 420 | ) 421 | 422 | def process_response(self, response): 423 | result = response.items.get(_RESULT_KEY) 424 | if not result.value == '0': 425 | dtmf_character = _convert_to_char(result.value, response.items) 426 | offset = _convert_to_int(response.items) 427 | return (dtmf_character, offset) 428 | return None 429 | 430 | 431 | class GetVariable(_Action): 432 | """ 433 | Returns a `variable` associated with this channel. 434 | 435 | The value of the requested variable is returned as a string. If the variable is 436 | undefined, `None` is returned. 437 | 438 | `AGIAppError` is raised on failure. 439 | """ 440 | check_hangup = False 441 | 442 | def __init__(self, variable): 443 | _Action.__init__(self, 'GET VARIABLE', quote(variable)) 444 | 445 | def process_response(self, response): 446 | result = response.items.get(_RESULT_KEY) 447 | if result.value == '1': 448 | return result.data 449 | return None 450 | 451 | 452 | class Hangup(_Action): 453 | """ 454 | Hangs up this channel or, if `channel` is set, the named channel. 455 | 456 | `AGIAppError` is raised on failure. 457 | """ 458 | 459 | def __init__(self, channel=None): 460 | _Action.__init__(self, 'HANGUP', (channel and quote(channel) or None)) 461 | 462 | 463 | class Noop(_Action): 464 | """ 465 | Does nothing. 466 | 467 | Good for testing the connection to the Asterisk server, like a ping, but 468 | not useful for much else. If you wish to log information through 469 | Asterisk, use the `verbose` method instead. 470 | 471 | `AGIAppError` is raised on failure. 472 | """ 473 | 474 | def __init__(self): 475 | _Action.__init__(self, 'NOOP') 476 | 477 | 478 | class ReceiveChar(_Action): 479 | """ 480 | Receives a single character of text from a supporting channel, discarding anything else in 481 | the character buffer. 482 | 483 | `timeout` is the number of milliseconds to wait for a character to be received, defaulting 484 | to infinite. 485 | 486 | The value returned is a tuple of the form (char:str, timeout:bool), with the timeout element 487 | indicating whether the function returned because of a timeout, which may result in an empty 488 | string. `None` is returned if the channel does not support text. 489 | 490 | `AGIAppError` is raised on failure. 491 | """ 492 | 493 | def __init__(self, timeout=0): 494 | _Action.__init__(self, 'RECEIVE CHAR', quote(timeout)) 495 | 496 | def process_response(self, response): 497 | result = response.items.get(_RESULT_KEY) 498 | if not result.value == '0': 499 | return (_convert_to_char(result.value, response.items), result.data == 'timeout') 500 | return None 501 | 502 | 503 | class ReceiveText(_Action): 504 | """ 505 | Receives a block of text from a supporting channel. 506 | 507 | `timeout` is the number of milliseconds to wait for text to be received, defaulting 508 | to infinite. Presumably, the first block received is immediately returned in full. 509 | 510 | The value returned is a string. 511 | 512 | `AGIAppError` is raised on failure. 513 | """ 514 | 515 | def __init__(self, timeout=0): 516 | _Action.__init__(self, 'RECEIVE TEXT', quote(timeout)) 517 | 518 | def process_response(self, response): 519 | result = response.items.get(_RESULT_KEY) 520 | return result.value 521 | 522 | 523 | class RecordFile(_Action): 524 | """ 525 | Records audio to the specified file, which is the `filename` of the file to be written, 526 | defaulting to Asterisk's sounds path or an absolute path, without extension. ('myfile.wav' 527 | would be specified as 'myfile') `format` is one of the following, which sets the extension 528 | and encoding, with WAV being the default: 529 | 530 | - FORMAT_SLN 531 | - FORMAT_G723 532 | - FORMAT_G729 533 | - FORMAT_GSM 534 | - FORMAT_ALAW 535 | - FORMAT_ULAW 536 | - FORMAT_VOX 537 | - FORMAT_WAV: PCM16 538 | 539 | The filename may also contain the special string '%d', which Asterisk will replace with an 540 | auto-incrementing number, with the resulting filename appearing in the 'RECORDED_FILE' 541 | channel variable. 542 | 543 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 544 | of possibly mixed ints and strings. Playback ends immediately when one is received. 545 | 546 | `timeout` is the number of milliseconds to wait following the end of playback if no keys 547 | were pressed to end recording prior to that point. By default, it waits forever. 548 | 549 | `sample_offset` may be used to jump an arbitrary number of milliseconds into the audio data. 550 | 551 | `beep`, if `True`, the default, causes an audible beep to be heard when recording begins. 552 | 553 | `silence`, if given, is the number of seconds of silence to allow before terminating 554 | recording early. 555 | 556 | The value returned is a tuple consisting of (dtmf_key:str, offset:int, timeout:bool), where 557 | the offset is the number of milliseconds that elapsed since the start of playback dtmf_key 558 | may be the empty string if no key was pressed, and timeout is `False` if recording ended due 559 | to another condition (DTMF or silence). 560 | 561 | The raising of `AGIResultHangup` is another condition that signals a successful recording, 562 | though it also means the user hung up. 563 | 564 | `AGIAppError` is raised on failure, most commonly because the destination file isn't 565 | writable. 566 | """ 567 | 568 | def __init__(self, filename, format=FORMAT_WAV, escape_digits='', timeout=-1, sample_offset=0, beep=True, 569 | silence=None): 570 | escape_digits = _process_digit_list(escape_digits) 571 | _Action.__init__(self, 572 | 'RECORD FILE', quote(filename), quote(format), 573 | quote(escape_digits), quote(timeout), quote(sample_offset), 574 | (beep and quote('beep') or None), 575 | (silence and quote('s=' + str(silence)) or None) 576 | ) 577 | 578 | def process_response(self, response): 579 | result = response.items.get(_RESULT_KEY) 580 | offset = _convert_to_int(response.items) 581 | 582 | if result.data == 'randomerror': 583 | raise AGIAppError("Unknown error occurred %(ms)i into recording: %(error)s" % { 584 | 'ms': offset, 585 | 'error': result.value, 586 | }) 587 | elif result.data == 'timeout': 588 | return ('', offset, True) 589 | elif result.data == 'dtmf': 590 | return (_convert_to_char(result.value, response.items), offset, False) 591 | return ('', offset, True) # Assume a timeout if any other result data is received. 592 | 593 | 594 | class _SayAction(_Action): 595 | """ 596 | A specialised subclass of `_Action` that provides behaviour common to several children. 597 | 598 | Synthesises speech on a channel. This abstracts the commonalities between the "SAY ?" 599 | subclasses. 600 | 601 | `say_type` is the type of command to be issued. 602 | 603 | `argument` is the argument to be synthesised. 604 | 605 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 606 | of possibly mixed ints and strings. Playback ends immediately when one is received. 607 | 608 | `AGIAppError` is raised on failure, most commonly because the channel was 609 | hung-up. 610 | """ 611 | 612 | def __init__(self, say_type, argument, escape_digits, *args): 613 | escape_digits = _process_digit_list(escape_digits) 614 | _Action.__init__(self, 615 | 'SAY ' + say_type, quote(argument), quote(escape_digits), *args 616 | ) 617 | 618 | def process_response(self, response): 619 | result = response.items.get(_RESULT_KEY) 620 | 621 | if not result.value == '0': 622 | return _convert_to_char(result.value, response.items) 623 | return None 624 | 625 | 626 | class SayAlpha(_SayAction): 627 | """ 628 | Reads an alphabetic string of `characters`. 629 | 630 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 631 | of possibly mixed ints and strings. Playback ends immediately when one is received and it is 632 | returned. If nothing is recieved, `None` is returned. 633 | 634 | `AGIAppError` is raised on failure, most commonly because the channel was 635 | hung-up. 636 | """ 637 | 638 | def __init__(self, characters, escape_digits=''): 639 | characters = _process_digit_list(characters) 640 | _SayAction.__init__(self, 'ALPHA', characters, escape_digits) 641 | 642 | 643 | class SayDate(_SayAction): 644 | """ 645 | Reads the date associated with `seconds` since the UNIX Epoch. If not given, the local time 646 | is used. 647 | 648 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 649 | of possibly mixed ints and strings. Playback ends immediately when one is received and it is 650 | returned. If nothing is recieved, `None` is returned. 651 | 652 | `AGIAppError` is raised on failure, most commonly because the channel was 653 | hung-up. 654 | """ 655 | 656 | def __init__(self, seconds=None, escape_digits=''): 657 | if seconds is None: 658 | seconds = int(time.time()) 659 | _SayAction.__init__(self, 'DATE', seconds, escape_digits) 660 | 661 | 662 | class SayDatetime(_SayAction): 663 | """ 664 | Reads the datetime associated with `seconds` since the UNIX Epoch. If not given, the local 665 | time is used. 666 | 667 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 668 | of possibly mixed ints and strings. Playback ends immediately when one is received and it is 669 | returned. If nothing is recieved, `None` is returned. 670 | 671 | `format` defaults to `"ABdY 'digits/at' IMp"`, but may be a string with any of the following 672 | meta-characters (or single-quote-escaped sound-file references): 673 | 674 | - A: Day of the week 675 | - B: Month (Full Text) 676 | - m: Month (Numeric) 677 | - d: Day of the month 678 | - Y: Year 679 | - I: Hour (12-hour format) 680 | - H: Hour (24-hour format) 681 | - M: Minutes 682 | - p: AM/PM 683 | - Q: Shorthand for Today, Yesterday or ABdY 684 | - R: Shorthand for HM 685 | - S: Seconds 686 | - T: Timezone 687 | 688 | `timezone` may be a string in standard UNIX form, like 'America/Edmonton'. If `format` is 689 | undefined, `timezone` is ignored and left to default to the system's local value. 690 | 691 | `AGIAppError` is raised on failure, most commonly because the channel was 692 | hung-up. 693 | """ 694 | 695 | def __init__(self, seconds=None, escape_digits='', format=None, timezone=None): 696 | if seconds is None: 697 | seconds = int(time.time()) 698 | if not format: 699 | timezone = None 700 | _SayAction.__init__(self, 701 | 'DATETIME', seconds, escape_digits, 702 | (format and quote(format) or None), (timezone and quote(timezone) or None) 703 | ) 704 | 705 | 706 | class SayDigits(_SayAction): 707 | """ 708 | Reads a numeric string of `digits`. 709 | 710 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 711 | of possibly mixed ints and strings. Playback ends immediately when one is received and it is 712 | returned. If nothing is recieved, `None` is returned. 713 | 714 | `AGIAppError` is raised on failure, most commonly because the channel was 715 | hung-up. 716 | """ 717 | 718 | def __init__(self, digits, escape_digits=''): 719 | digits = _process_digit_list(digits) 720 | _SayAction.__init__(self, 'DIGITS', digits, escape_digits) 721 | 722 | 723 | class SayNumber(_SayAction): 724 | """ 725 | Reads a `number` naturally. 726 | 727 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 728 | of possibly mixed ints and strings. Playback ends immediately when one is received and it is 729 | returned. If nothing is recieved, `None` is returned. 730 | 731 | `AGIAppError` is raised on failure, most commonly because the channel was 732 | hung-up. 733 | """ 734 | 735 | def __init__(self, number, escape_digits=''): 736 | number = _process_digit_list(number) 737 | _SayAction.__init__(self, 'NUMBER', number, escape_digits) 738 | 739 | 740 | class SayPhonetic(_SayAction): 741 | """ 742 | Reads a phonetic string of `characters`. 743 | 744 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 745 | of possibly mixed ints and strings. Playback ends immediately when one is received and it is 746 | returned. If nothing is received, `None` is returned. 747 | 748 | `AGIAppError` is raised on failure, most commonly because the channel was 749 | hung-up. 750 | """ 751 | 752 | def __init__(self, characters, escape_digits=''): 753 | characters = _process_digit_list(characters) 754 | _SayAction.__init__(self, 'PHONETIC', characters, escape_digits) 755 | 756 | 757 | class SayTime(_SayAction): 758 | """ 759 | Reads the time associated with `seconds` since the UNIX Epoch. If not given, the local 760 | time is used. 761 | 762 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 763 | of possibly mixed ints and strings. Playback ends immediately when one is received and it is 764 | returned. If nothing is received, `None` is returned. 765 | 766 | `AGIAppError` is raised on failure, most commonly because the channel was 767 | hung-up. 768 | """ 769 | 770 | def __init__(self, seconds=None, escape_digits=''): 771 | if seconds is None: 772 | seconds = int(time.time()) 773 | _SayAction.__init__(self, 'TIME', seconds, escape_digits) 774 | 775 | 776 | class SendImage(_Action): 777 | """ 778 | Sends the specified image, which is the `filename` of the file to be presented, either in 779 | an Asterisk-searched directory or as an absolute path, without extension. ('myfile.png' 780 | would be specified as 'myfile', to allow Asterisk to choose the most efficient encoding, 781 | based on extension, for the channel) 782 | 783 | `AGIAppError` is raised on failure. 784 | """ 785 | 786 | def __init__(self, filename): 787 | _Action.__init__(self, 'SEND FILE', quote(filename)) 788 | 789 | 790 | class SendText(_Action): 791 | """ 792 | Sends the specified `text` on a supporting channel. 793 | 794 | `AGIAppError` is raised on failure. 795 | """ 796 | 797 | def __init__(self, text): 798 | _Action.__init__(self, 'SEND TEXT', quote(text)) 799 | 800 | 801 | class SetAutohangup(_Action): 802 | """ 803 | Instructs Asterisk to hang up the channel after the given number of `seconds` have elapsed. 804 | 805 | Calling this function with `seconds` set to 0, the default, will disable auto-hangup. 806 | 807 | `AGIAppError` is raised on failure. 808 | """ 809 | 810 | def __init__(self, seconds=0): 811 | _Action.__init__(self, 'SET AUTOHANGUP', quote(seconds)) 812 | 813 | 814 | class SetCallerid(_Action): 815 | """ 816 | Sets the called ID (`number` and, optionally, `name`) of Asterisk on this channel. 817 | 818 | `AGIAppError` is raised on failure. 819 | """ 820 | 821 | def __init__(self, number, name=None): 822 | if name: # Escape it 823 | name = '\\"%(name)s\\"' % { 824 | 'name': name, 825 | } 826 | else: # Make sure it's the empty string 827 | name = '' 828 | number = "%(name)s<%(number)s>" % { 829 | 'name': name, 830 | 'number': number, 831 | } 832 | _Action.__init__(self, 'SET CALLERID', quote(number)) 833 | 834 | 835 | class SetContext(_Action): 836 | """ 837 | Sets the context for Asterisk to use upon completion of this AGI instance. 838 | 839 | No context-validation is performed; specifying an invalid context will cause the call to 840 | terminate unexpectedly. 841 | 842 | `AGIAppError` is raised on failure. 843 | """ 844 | 845 | def __init__(self, context): 846 | _Action.__init__(self, 'SET CONTEXT', quote(context)) 847 | 848 | 849 | class SetExtension(_Action): 850 | """ 851 | Sets the extension for Asterisk to use upon completion of this AGI instance. 852 | 853 | No extension-validation is performed; specifying an invalid extension will cause the call to 854 | terminate unexpectedly. 855 | 856 | `AGIAppError` is raised on failure. 857 | """ 858 | 859 | def __init__(self, extension): 860 | _Action.__init__(self, 'SET EXTENSION', quote(extension)) 861 | 862 | 863 | class SetMusic(_Action): 864 | """ 865 | Enables or disables music-on-hold for this channel, per the state of the `on` argument. 866 | 867 | If specified, `moh_class` identifies the music-on-hold class to be used. 868 | 869 | `AGIAppError` is raised on failure. 870 | """ 871 | 872 | def __init__(self, on, moh_class=None): 873 | _Action.__init__(self, 874 | 'SET MUSIC', quote(on and 'on' or 'off'), 875 | (moh_class and quote(moh_class) or None) 876 | ) 877 | 878 | 879 | class SetPriority(_Action): 880 | """ 881 | Sets the priority for Asterisk to use upon completion of this AGI instance. 882 | 883 | No priority-validation is performed; specifying an invalid priority will cause the call to 884 | terminate unexpectedly. 885 | 886 | `AGIAppError` is raised on failure. 887 | """ 888 | 889 | def __init__(self, priority): 890 | _Action.__init__(self, 'SET PRIORITY', quote(priority)) 891 | 892 | 893 | class SetVariable(_Action): 894 | """ 895 | Sets the variable identified by `name` to `value` on the current channel. 896 | 897 | `AGIAppError` is raised on failure. 898 | """ 899 | 900 | def __init__(self, name, value): 901 | _Action.__init__(self, 'SET VARIABLE', quote(name), quote(value)) 902 | 903 | 904 | class StreamFile(_Action): 905 | """ 906 | See also `ControlStreamFile`, `GetData`, `GetOption`. 907 | 908 | Plays back the specified file, which is the `filename` of the file to be played, either in 909 | an Asterisk-searched directory or as an absolute path, without extension. ('myfile.wav' 910 | would be specified as 'myfile', to allow Asterisk to choose the most efficient encoding, 911 | based on extension, for the channel) 912 | 913 | `escape_digits` may optionally be a list of DTMF digits, specified as a string or a sequence 914 | of possibly mixed ints and strings. Playback ends immediately when one is received. 915 | 916 | `sample_offset` may be used to jump an arbitrary number of milliseconds into the audio data. 917 | 918 | The value returned is a tuple consisting of (dtmf_key:str, offset:int), where the offset is 919 | the number of milliseconds that elapsed since the start of playback, or None if playback 920 | completed successfully or the sample could not be opened. 921 | 922 | `AGIAppError` is raised on failure, most commonly because the channel was 923 | hung-up. 924 | """ 925 | 926 | def __init__(self, filename, escape_digits='', sample_offset=0): 927 | escape_digits = _process_digit_list(escape_digits) 928 | _Action.__init__(self, 929 | 'STREAM FILE', quote(filename), 930 | quote(escape_digits), quote(sample_offset) 931 | ) 932 | 933 | def process_response(self, response): 934 | result = response.items.get(_RESULT_KEY) 935 | if not result.value == '0': 936 | dtmf_character = _convert_to_char(result.value, response.items) 937 | offset = _convert_to_int(response.items) 938 | return (dtmf_character, offset) 939 | return None 940 | 941 | 942 | class TDDMode(_Action): 943 | """ 944 | Sets the TDD transmission `mode` on supporting channels, one of the following: 945 | 946 | - TDD_ON 947 | - TDD_OFF 948 | - TDD_MATE 949 | 950 | `True` is returned if the mode is set, `False` if the channel isn't capable, and 951 | `AGIAppError` is raised if a problem occurs. According to documentation from 2006, 952 | all non-capable channels will cause an exception to occur. 953 | """ 954 | 955 | def __init__(self, mode): 956 | _Action.__init__(self, 'TDD MODE', mode) 957 | 958 | def process_response(self, response): 959 | result = response.items.get(_RESULT_KEY) 960 | return result.value == '1' 961 | 962 | 963 | class Verbose(_Action): 964 | """ 965 | Causes Asterisk to process `message`, logging it to console or disk, 966 | depending on whether `level` is greater-than-or-equal-to Asterisk's 967 | corresponding verbosity threshold. 968 | 969 | `level` is one of the following, defaulting to LOG_INFO: 970 | 971 | - LOG_DEBUG 972 | - LOG_INFO 973 | - LOG_WARN 974 | - LOG_ERROR 975 | - LOG_CRITICAL 976 | 977 | `AGIAppError` is raised on failure. 978 | """ 979 | 980 | def __init__(self, message, level=LOG_INFO): 981 | _Action.__init__(self, 'VERBOSE', quote(message), quote(level)) 982 | 983 | 984 | class WaitForDigit(_Action): 985 | """ 986 | Waits for up to `timeout` milliseconds for a DTMF keypress to be received, returning that 987 | value. By default, this function blocks indefinitely. 988 | 989 | If no DTMF key is pressed, `None` is returned. 990 | 991 | `AGIAppError` is raised on failure, most commonly because the channel was 992 | hung-up. 993 | """ 994 | 995 | def __init__(self, timeout=-1): 996 | _Action.__init__(self, 'WAIT FOR DIGIT', quote(timeout)) 997 | 998 | def process_response(self, response): 999 | result = response.items.get(_RESULT_KEY) 1000 | if not result.value == '0': 1001 | return _convert_to_char(result.value, response.items) 1002 | return None 1003 | 1004 | 1005 | # Exceptions 1006 | ############################################################################### 1007 | class AGIDBError(AGIAppError): 1008 | """ 1009 | Indicates that Asterisk encountered an error while interactive with its 1010 | database. 1011 | """ 1012 | -------------------------------------------------------------------------------- /pystrix/agi/fastagi.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.agi.fagi 3 | ================ 4 | 5 | Provides classes that expose methods for communicating with Asterisk from a 6 | FastAGI (TCP socket) context. 7 | 8 | Usage 9 | ----- 10 | 11 | Usage of this module is provided in the examples directory of the source 12 | distribution. 13 | 14 | Legal 15 | ----- 16 | 17 | This file is part of pystrix. 18 | pystrix is free software; you can redistribute it and/or modify 19 | it under the terms of the GNU Lesser General Public License as published 20 | by the Free Software Foundation; either version 3 of the License, or 21 | (at your option) any later version. 22 | 23 | This program is distributed in the hope that it will be useful, 24 | but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | GNU Lesser General Public License for more details. 27 | 28 | You should have received a copy of the GNU General Public License and 29 | GNU Lesser General Public License along with this program. If not, see 30 | . 31 | 32 | (C) Ivrnet, inc., 2011 33 | 34 | Authors: 35 | 36 | - Neil Tallim 37 | """ 38 | import cgi 39 | import platform 40 | import socket 41 | import subprocess 42 | import threading 43 | from pystrix.agi.agi_core import * 44 | from pystrix.agi.agi_core import _AGI 45 | 46 | try: 47 | import socketserver 48 | except ModuleNotFoundError: 49 | import SocketServer as socketserver 50 | 51 | 52 | class _ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): 53 | """ 54 | Provides a variant of the TCPServer that spawns a new thread to handle each 55 | request. 56 | """ 57 | 58 | @staticmethod 59 | def get_somaxconn(): 60 | """ 61 | Returns the value of SOMAXCONN configured in the system. 62 | """ 63 | # determine the OS appropriate management informations base (MIB) 64 | # name to determine SOMAXCONN 65 | system = platform.system() 66 | if "Linux" == system: 67 | sysctl_mib_somaxconn = "net.core.somaxconn" 68 | sysctl_output_delimiter = "=" 69 | elif "Darwin" == system: 70 | sysctl_mib_somaxconn = "kern.ipc.somaxconn" 71 | sysctl_output_delimiter = ":" 72 | else: 73 | raise NotImplementedError( 74 | "Determining SOMAXCONN is not implemented for {} system.".format(system) 75 | ) 76 | # run the cmd to determine the SOMAXCONN 77 | cmd_result = subprocess.check_output(["sysctl", sysctl_mib_somaxconn]) 78 | 79 | # parse the output of the cmd to return the value of SOMAXCONN 80 | return int(cmd_result.decode().split(sysctl_output_delimiter)[-1].strip()) 81 | 82 | def __init__(self, *args, **kwargs): 83 | # adjust request queue size to a saner value for modern systems 84 | # further adjustments are automatically picked up for kernel 85 | # settings on server start 86 | self.request_queue_size = max(socket.SOMAXCONN, self.get_somaxconn()) 87 | self.allow_reuse_address = True 88 | super().__init__(*args, **kwargs) 89 | 90 | 91 | class _AGIClientHandler(socketserver.StreamRequestHandler): 92 | """ 93 | Handles TCP connections. 94 | """ 95 | def handle(self): 96 | """ 97 | Creates an instance of an AGI-interface object and passes it to a pre-specified callable, 98 | selected by matching the request parameters against a series of regular expressions. 99 | """ 100 | agi_instance = FastAGI(self.rfile, self.wfile, debug=self.server.debug) 101 | 102 | (path, kwargs) = self._extract_query_elements(agi_instance) 103 | args = self._extract_positional_args(agi_instance) 104 | 105 | (handler, match) = self.server.get_script_handler(path) 106 | if handler: 107 | handler(agi_instance, args, kwargs, match, path) 108 | 109 | def _extract_positional_args(self, agi_instance): 110 | """ 111 | Pulls the 'agi_arg_x' values out of the AGI instance to make them easier to process, since 112 | the specification by which they're supplied may change in the future. 113 | """ 114 | env = agi_instance.get_environment() 115 | keys = sorted((int(key[8:]) for key in env if key.startswith('agi_arg_'))) 116 | return tuple((env['agi_arg_%i' % key] for key in keys)) 117 | 118 | def _extract_query_elements(self, agi_instance): 119 | """ 120 | Provides the path string and a dictionary of keyword arguments passed along with the AGI 121 | request. Arguments are supplied as a list, since the same parameter may be specified 122 | multiple times. 123 | """ 124 | tokens = (agi_instance.get_environment().get('agi_network_script') or '/').split('?', 1) 125 | path = tokens[0] 126 | if len(tokens) == 1: 127 | return (path, {}) 128 | return (path, cgi.urlparse.parse_qs(tokens[1])) 129 | 130 | class FastAGIServer(_ThreadedTCPServer): 131 | """ 132 | Provides a FastAGI TCP server to handle requests from Asterisk servers. 133 | """ 134 | debug = False #Used to enable various printouts for library development 135 | _default_script_handler = None #A script-handler to use if nothing else matched 136 | _script_handlers = None #A list of regex/callable pairs to use when determining how to handle an AGI request 137 | _script_handlers_lock = None #A lock used to prevent race conditions on the handlers list 138 | 139 | def __init__(self, interface='127.0.0.1', port=4573, daemon_threads=True, debug=False): 140 | """ 141 | Creates the server and binds the client-handler callable. 142 | 143 | `interface` is the address of the interface on which to listen; defaults 144 | to localhost, but may be any interface on the host or `'0.0.0.0'` for 145 | all. `port` is the TCP port on which to listen. 146 | 147 | `daemon_threads` indicates whether any threads spawned to handle 148 | requests should be killed if the main thread dies. (Generally a good 149 | idea to avoid hung calls keeping the process alive forever) 150 | 151 | `debug` should only be turned on for library development. 152 | """ 153 | _ThreadedTCPServer.__init__(self, (interface, port), _AGIClientHandler) 154 | self.debug = debug 155 | self.daemon_threads = daemon_threads 156 | self._script_handlers = [] 157 | self._script_handlers_lock = threading.Lock() 158 | 159 | def clear_script_handlers(self): 160 | """ 161 | Empties the list of script handlers, allowing it to be repopulated. The default handler is 162 | not cleared by this action; to clear it, call `register_script_handler(None, None)`. 163 | """ 164 | with self._script_handlers_lock: 165 | self._script_handlers = [] 166 | 167 | def get_script_handler(self, script_path): 168 | """ 169 | Provides the callable specified to handle requests received by this 170 | FastAGI server and the result of matching, as a tuple. 171 | 172 | `script_path` is the path received from Asterisk. 173 | """ 174 | with self._script_handlers_lock: 175 | for (regex, handler) in self._script_handlers: 176 | match = None 177 | if isinstance(regex, str): 178 | match = re.match(regex, script_path) 179 | else: 180 | match = regex.match(script_path) 181 | if match: 182 | return (handler, match) 183 | 184 | return (self._default_script_handler, None) 185 | 186 | def register_script_handler(self, regex, handler): 187 | """ 188 | Registers the given `handler`, which is a callable that accepts an AGI object used to 189 | communicate with the Asterisk channel, a tuple containing any positional arguments, a 190 | dictionary containing any keyword arguments (values are enumerated in a list), the match 191 | object (may be `None`), and the original script address as a string. 192 | 193 | Handlers are resolved by `regex`, which may be a regular expression object or a string, 194 | match in the order in which they were supplied, so provide more specific qualifiers first. 195 | 196 | The special `regex` value `None` sets the default handler, invoked when every comparison 197 | fails; this is preferable to adding a catch-all handler in case the list is changed at 198 | runtime. Setting the default handler to `None` disables the catch-all, which will typically 199 | make Asterisk just drop the call. 200 | """ 201 | with self._script_handlers_lock: 202 | if regex is None: 203 | self._default_script_handler = handler 204 | return 205 | 206 | #Ensure that the regex hasn't been registered before 207 | for (old_regex, old_handler) in self._script_handlers: 208 | if old_regex == regex: 209 | return 210 | 211 | #Add the handler to the end of the list 212 | self._script_handlers.append((regex, handler)) 213 | 214 | def unregister_script_handler(self, regex): 215 | """ 216 | Removes a specific script-handler from the list, given the same `regex` object used to 217 | register it initially. 218 | 219 | This function should only be used when a specific handler is no longer useful; if you want 220 | to re-introduce handlers, consider using `clear_script_handlers()` and re-adding all 221 | handlers in the desired order. 222 | """ 223 | with self._script_handlers_lock: 224 | for (i, (old_regex, old_handler)) in enumerate(self._script_handlers): 225 | if old_regex == regex: 226 | self._script_handlers.pop(i) 227 | break 228 | 229 | class FastAGI(_AGI): 230 | """ 231 | An interface to Asterisk, exposing request-response functions for 232 | synchronous management of the call associated with this channel. 233 | """ 234 | def __init__(self, rfile, wfile, debug=False): 235 | """ 236 | Associates I/O with `rfile` and `wfile`. 237 | 238 | `debug` should only be turned on for library development. 239 | """ 240 | self._rfile = rfile 241 | self._wfile = wfile 242 | 243 | _AGI.__init__(self, debug) 244 | 245 | -------------------------------------------------------------------------------- /pystrix/ami/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.ami 3 | =========== 4 | 5 | Provides a library suitable for interacting with an Asterisk server using the 6 | Asterisk Management Interface (AMI) protocol. 7 | 8 | Usage 9 | ----- 10 | 11 | Importing this package is recommended over importing individual modules. 12 | 13 | Legal 14 | ----- 15 | 16 | This file is part of pystrix. 17 | pystrix is free software; you can redistribute it and/or modify 18 | it under the terms of the GNU Lesser General Public License as published 19 | by the Free Software Foundation; either version 3 of the License, or 20 | (at your option) any later version. 21 | 22 | This program is distributed in the hope that it will be useful, 23 | but WITHOUT ANY WARRANTY; without even the implied warranty of 24 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 | GNU Lesser General Public License for more details. 26 | 27 | You should have received a copy of the GNU General Public License and 28 | GNU Lesser General Public License along with this program. If not, see 29 | . 30 | 31 | (C) Ivrnet, inc., 2011 32 | 33 | Authors: 34 | 35 | - Neil Tallim 36 | """ 37 | from pystrix.ami.ami import ( 38 | RESPONSE_GENERIC, EVENT_GENERIC, 39 | KEY_ACTION, KEY_ACTIONID, KEY_EVENT, KEY_RESPONSE, 40 | Manager, 41 | Error, ManagerError, ManagerSocketError, 42 | ) 43 | 44 | from pystrix.ami import core 45 | from pystrix.ami import dahdi 46 | from pystrix.ami import app_confbridge 47 | from pystrix.ami import app_meetme 48 | 49 | # Register events 50 | from pystrix.ami import core_events 51 | from pystrix.ami import dahdi_events 52 | from pystrix.ami import app_confbridge_events 53 | from pystrix.ami import app_meetme_events 54 | 55 | from pystrix.ami.ami import (_EVENT_REGISTRY, _EVENT_REGISTRY_REV) 56 | for module in ( 57 | core_events, dahdi_events, 58 | app_confbridge_events, app_meetme_events, 59 | ): 60 | for event in (e for e in dir(module) if not e.startswith('_')): 61 | class_object = getattr(module, event) 62 | _EVENT_REGISTRY[event] = class_object 63 | _EVENT_REGISTRY_REV[class_object] = event 64 | del _EVENT_REGISTRY 65 | del _EVENT_REGISTRY_REV 66 | 67 | -------------------------------------------------------------------------------- /pystrix/ami/app_confbridge.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.ami.app_confbridge 3 | ========================== 4 | 5 | Provides classes meant to be fed to a `Manager` instance's `send_action()` function. 6 | 7 | Specifically, this module provides implementations for features specific to the ConfBridge 8 | application. 9 | 10 | Legal 11 | ----- 12 | 13 | This file is part of pystrix. 14 | pystrix is free software; you can redistribute it and/or modify 15 | it under the terms of the GNU Lesser General Public License as published 16 | by the Free Software Foundation; either version 3 of the License, or 17 | (at your option) any later version. 18 | 19 | This program is distributed in the hope that it will be useful, 20 | but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | GNU Lesser General Public License for more details. 23 | 24 | You should have received a copy of the GNU General Public License and 25 | GNU Lesser General Public License along with this program. If not, see 26 | . 27 | 28 | (C) Ivrnet, inc., 2011 29 | 30 | Authors: 31 | 32 | - Neil Tallim 33 | 34 | The requests and events implemented by this module follow the definitions provided by 35 | https://wiki.asterisk.org/ 36 | """ 37 | from pystrix.ami.ami import (_Request, ManagerError) 38 | from pystrix.ami import core_events 39 | from pystrix.ami import app_confbridge_events 40 | from pystrix.ami import generic_transforms 41 | 42 | class ConfbridgeKick(_Request): 43 | """ 44 | Kicks a participant from a ConfBridge room. 45 | """ 46 | def __init__(self, conference, channel): 47 | """ 48 | `channel` is the channel to be kicked from `conference`. 49 | """ 50 | _Request.__init__(self, 'ConfbridgeKick') 51 | self['Conference'] = conference 52 | self['Channel'] = channel 53 | 54 | class ConfbridgeList(_Request): 55 | """ 56 | Lists all participants in a ConfBridge room. 57 | 58 | A series of 'ConfbridgeList' events follow, with one 'ConfbridgeListComplete' event at the end. 59 | """ 60 | _aggregates = (app_confbridge_events.ConfbridgeList_Aggregate,) 61 | _synchronous_events_list = (app_confbridge_events.ConfbridgeList,) 62 | _synchronous_events_finalising = (app_confbridge_events.ConfbridgeListComplete,) 63 | 64 | def __init__(self, conference): 65 | """ 66 | `conference` is the identifier of the bridge. 67 | """ 68 | _Request.__init__(self, 'ConfbridgeList') 69 | self['Conference'] = conference 70 | 71 | class ConfbridgeListRooms(_Request): 72 | """ 73 | Lists all ConfBridge rooms. 74 | 75 | A series of 'ConfbridgeListRooms' events follow, with one 'ConfbridgeListRoomsComplete' event at 76 | the end. 77 | """ 78 | _aggregates = (app_confbridge_events.ConfbridgeListRooms_Aggregate,) 79 | _synchronous_events_list = (app_confbridge_events.ConfbridgeListRooms,) 80 | _synchronous_events_finalising = (app_confbridge_events.ConfbridgeListRoomsComplete,) 81 | 82 | def __init__(self): 83 | _Request.__init__(self, 'ConfbridgeListRooms') 84 | 85 | class ConfbridgeLock(_Request): 86 | """ 87 | Locks a ConfBridge room, disallowing access to non-administrators. 88 | """ 89 | def __init__(self, conference): 90 | """ 91 | `conference` is the identifier of the bridge. 92 | """ 93 | _Request.__init__(self, 'ConfbridgeLock') 94 | self['Conference'] = conference 95 | 96 | class ConfbridgeUnlock(_Request): 97 | """ 98 | Unlocks a ConfBridge room, allowing access to non-administrators. 99 | """ 100 | def __init__(self, conference): 101 | """ 102 | `conference` is the identifier of the bridge. 103 | """ 104 | _Request.__init__(self, 'ConfbridgeUnlock') 105 | self['Conference'] = conference 106 | 107 | class ConfbridgeMoHOn(_Request): 108 | """ 109 | Forces MoH to a participant in a ConfBridge room. 110 | 111 | This action does not mute audio coming from the participant. 112 | 113 | Depends on . 114 | """ 115 | def __init__(self, conference, channel): 116 | """ 117 | `channel` is the channel to which MoH should be started in `conference`. 118 | """ 119 | _Request.__init__(self, 'ConfbridgeMoHOn') 120 | self['Conference'] = conference 121 | self['Channel'] = channel 122 | 123 | class ConfbridgeMoHOff(_Request): 124 | """ 125 | Stops forcing MoH to a participant in a ConfBridge room. 126 | 127 | This action does not unmute audio coming from the participant. 128 | 129 | Depends on . 130 | """ 131 | def __init__(self, conference, channel): 132 | """ 133 | `channel` is the channel to which MoH should be stopped in `conference`. 134 | """ 135 | _Request.__init__(self, 'ConfbridgeMoHOff') 136 | self['Conference'] = conference 137 | self['Channel'] = channel 138 | 139 | class ConfbridgeMute(_Request): 140 | """ 141 | Mutes a participant in a ConfBridge room. 142 | """ 143 | def __init__(self, conference, channel): 144 | """ 145 | `channel` is the channel to be muted in `conference`. 146 | """ 147 | _Request.__init__(self, 'ConfbridgeMute') 148 | self['Conference'] = conference 149 | self['Channel'] = channel 150 | 151 | class ConfbridgeUnmute(_Request): 152 | """ 153 | Unmutes a participant in a ConfBridge room. 154 | """ 155 | def __init__(self, conference, channel): 156 | """ 157 | `channel` is the channel to be unmuted in `conference`. 158 | """ 159 | _Request.__init__(self, 'ConfbridgeUnmute') 160 | self['Conference'] = conference 161 | self['Channel'] = channel 162 | 163 | class ConfbridgePlayFile(_Request): 164 | """ 165 | Plays a file to individuals or an entire conference. 166 | 167 | Note: This implementation is built upon the not-yet-accepted patch under 168 | https://issues.asterisk.org/jira/browse/ASTERISK-19571 169 | """ 170 | def __init__(self, file, conference, channel=None): 171 | """ 172 | `file`, resolved like other Asterisk media, is played to `conference` 173 | or, if specified, a specific `channel` therein. 174 | """ 175 | _Request.__init__(self, 'ConfbridgePlayFile') 176 | self['Conference'] = conference 177 | if channel: 178 | self['Channel'] = channel 179 | self['File'] = file 180 | 181 | class ConfbridgeStartRecord(_Request): 182 | """ 183 | Starts recording a ConfBridge conference. 184 | 185 | A 'VarSet' event will be generated to indicate the absolute path of the recording. To identify 186 | it, match its 'Channel' key against "ConfBridgeRecorder/conf-?-...", where "..." is 187 | Asterisk-generated identification data that can be discarded and "?" is the room ID. The 188 | 'Variable' key must be "MIXMONITOR_FILENAME", with the 'Value' key holding the file's path. 189 | """ 190 | _synchronous_events_finalising = (core_events.VarSet,) 191 | 192 | def __init__(self, conference, filename=None): 193 | """ 194 | `conference` is the room to be recorded, and `filename`, optional, is the path, 195 | Asterisk-resolved or absolute, of the file to write. 196 | """ 197 | _Request.__init__(self, 'ConfbridgeStartRecord') 198 | self['Conference'] = conference 199 | if filename: 200 | self['RecordFile'] = filename 201 | 202 | class ConfbridgeStopRecord(_Request): 203 | """ 204 | Stops recording a ConfBridge conference. 205 | 206 | A 'Hangup' event will be generated when the recorder detaches from the conference. To identify 207 | it, match its 'Channel' key against "ConfBridgeRecorder/conf-?-...", where "..." is 208 | Asterisk-generated identification data that can be discarded and "?" is the room ID. 209 | """ 210 | _synchronous_events_finalising = (core_events.Hangup,) 211 | 212 | def __init__(self, conference): 213 | """ 214 | `conference` is the room being recorded. 215 | """ 216 | _Request.__init__(self, 'ConfbridgeStopRecord') 217 | self['Conference'] = conference 218 | 219 | class ConfbridgeSetSingleVideoSrc(_Request): 220 | """ 221 | Sets the video source for the conference to a single channel's stream. 222 | """ 223 | def __init__(self, conference, channel): 224 | """ 225 | `channel` is the video source in `conference`. 226 | """ 227 | _Request.__init__(self, 'ConfbridgeSetSingleVideoSource') 228 | self['Conference'] = conference 229 | self['Channel'] = channel 230 | 231 | -------------------------------------------------------------------------------- /pystrix/ami/app_confbridge_events.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.ami.app_confbridge_events 3 | ================================= 4 | 5 | Provides defnitions and filtering rules for events that may be raised by Asterisk's ConfBridge 6 | module. 7 | 8 | Legal 9 | ----- 10 | 11 | This file is part of pystrix. 12 | pystrix is free software; you can redistribute it and/or modify 13 | it under the terms of the GNU Lesser General Public License as published 14 | by the Free Software Foundation; either version 3 of the License, or 15 | (at your option) any later version. 16 | 17 | This program is distributed in the hope that it will be useful, 18 | but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | GNU Lesser General Public License for more details. 21 | 22 | You should have received a copy of the GNU General Public License and 23 | GNU Lesser General Public License along with this program. If not, see 24 | . 25 | 26 | (C) Ivrnet, inc., 2011 27 | 28 | Authors: 29 | 30 | - Neil Tallim 31 | 32 | The events implemented by this module follow the definitions provided by 33 | http://www.asteriskdocs.org/ and https://wiki.asterisk.org/ 34 | """ 35 | from pystrix.ami.ami import (_Aggregate, _Event) 36 | from pystrix.ami import generic_transforms 37 | 38 | class ConfbridgeEnd(_Event): 39 | """ 40 | Indicates that a ConfBridge has ended. 41 | 42 | - 'Conference' : The room's identifier 43 | """ 44 | 45 | class ConfbridgeJoin(_Event): 46 | """ 47 | Indicates that a participant has joined a ConfBridge room. 48 | 49 | `NameRecordingPath` blocks on 50 | 51 | - 'CallerIDname' (optional) : The name, on supporting channels, of the participant 52 | - 'CallerIDnum' : The (often) numeric address of the participant 53 | - 'Channel' : The channel that joined 54 | - 'Conference' : The identifier of the room that was joined 55 | - 'NameRecordingPath' (optional) : The path at which the user's name-recording is kept 56 | - 'Uniqueid' : An Asterisk unique value 57 | """ 58 | 59 | class ConfbridgeLeave(_Event): 60 | """ 61 | Indicates that a participant has left a ConfBridge room. 62 | 63 | - 'CallerIDname' (optional) : The name, on supporting channels, of the participant 64 | - 'CallerIDnum' : The (often) numeric address of the participant 65 | - 'Channel' : The channel that left 66 | - 'Conference' : The identifier of the room that was left 67 | - 'Uniqueid' : An Asterisk unique value 68 | """ 69 | 70 | class ConfbridgeList(_Event): 71 | """ 72 | Describes a participant in a ConfBridge room. 73 | 74 | - 'Admin' : 'Yes' or 'No' 75 | - 'CallerIDNum' : The (often) numeric address of the participant 76 | - 'CallerIDName' (optional) : The name of the participant on supporting channels 77 | - 'Channel' : The Asterisk channel in use by the participant 78 | - 'Conference' : The room's identifier 79 | - 'MarkedUser' : 'Yes' or 'No' 80 | - 'NameRecordingPath' (optional) : The path at which the user's name-recording is kept 81 | """ 82 | def process(self): 83 | """ 84 | Translates the 'Admin' and 'MarkedUser' headers' values into bools. 85 | """ 86 | (headers, data) = _Event.process(self) 87 | 88 | generic_transforms.to_bool(headers, ('Admin', 'MarkedUser',), truth_value='Yes') 89 | 90 | return (headers, data) 91 | 92 | class ConfbridgeListComplete(_Event): 93 | """ 94 | Indicates that all participants in a ConfBridge room have been enumerated. 95 | 96 | - 'ListItems' : The number of items returned prior to this event 97 | """ 98 | def process(self): 99 | """ 100 | Translates the 'ListItems' header's value into an int, or -1 on failure. 101 | """ 102 | (headers, data) = _Event.process(self) 103 | 104 | generic_transforms.to_int(headers, ('ListItems',), -1) 105 | 106 | return (headers, data) 107 | 108 | class ConfbridgeListRooms(_Event): 109 | """ 110 | Describes a ConfBridge room. 111 | 112 | And, yes, it's plural in Asterisk, too. 113 | 114 | - 'Conference' : The room's identifier 115 | - 'Locked' : 'Yes' or 'No' 116 | - 'Marked' : The number of marked users 117 | - 'Parties' : The number of participants 118 | """ 119 | def process(self): 120 | """ 121 | Translates the 'Marked' and 'Parties' headers' values into ints, or -1 on failure. 122 | 123 | Translates the 'Locked' header's value into a bool. 124 | """ 125 | (headers, data) = _Event.process(self) 126 | 127 | generic_transforms.to_bool(headers, ('Locked',), truth_value='Yes') 128 | generic_transforms.to_int(headers, ('Marked', 'Parties',), -1) 129 | 130 | return (headers, data) 131 | 132 | class ConfbridgeListRoomsComplete(_Event): 133 | """ 134 | Indicates that all ConfBridge rooms have been enumerated. 135 | 136 | - 'ListItems' : The number of items returned prior to this event 137 | """ 138 | def process(self): 139 | """ 140 | Translates the 'ListItems' header's value into an int, or -1 on failure. 141 | """ 142 | (headers, data) = _Event.process(self) 143 | 144 | generic_transforms.to_int(headers, ('ListItems',), -1) 145 | 146 | return (headers, data) 147 | 148 | class ConfbridgeStart(_Event): 149 | """ 150 | Indicates that a ConfBridge has started. 151 | 152 | - 'Conference' : The room's identifier 153 | """ 154 | 155 | class ConfbridgeTalking(_Event): 156 | """ 157 | Indicates that a participant has started or stopped talking. 158 | 159 | - 'Channel' : The Asterisk channel in use by the participant 160 | - 'Conference' : The room's identifier 161 | - 'TalkingStatus' : 'on' or 'off' 162 | - 'Uniqueid' : An Asterisk unique value 163 | """ 164 | def process(self): 165 | """ 166 | Translates the 'TalkingStatus' header's value into a bool. 167 | """ 168 | (headers, data) = _Event.process(self) 169 | 170 | generic_transforms.to_bool(headers, ('TalkingStatus',), truth_value='on') 171 | 172 | return (headers, data) 173 | 174 | 175 | #List-aggregation events 176 | #################################################################################################### 177 | #These define non-Asterisk-native event-types that collect multiple events (cases where multiple 178 | #events are generated in response to a single action) and emit the bundle as a single message. 179 | 180 | class ConfbridgeList_Aggregate(_Aggregate): 181 | """ 182 | Emitted after all conference participants have been received in response to a ConfbridgeList 183 | request. 184 | 185 | Its members consist of ConfbridgeList events. 186 | 187 | It is finalised by ConfbridgeListComplete. 188 | """ 189 | _name = "ConfbridgeList_Aggregate" 190 | 191 | _aggregation_members = (ConfbridgeList,) 192 | _aggregation_finalisers = (ConfbridgeListComplete,) 193 | 194 | def _finalise(self, event): 195 | self._check_list_items_count(event, 'ListItems') 196 | return _Aggregate._finalise(self, event) 197 | 198 | class ConfbridgeListRooms_Aggregate(_Aggregate): 199 | """ 200 | Emitted after all conference rooms have been received in response to a ConfbridgeListRooms 201 | request. 202 | 203 | Its members consist of ConfbridgeListRooms events. 204 | 205 | It is finalised by ConfbridgeListRoomsComplete. 206 | """ 207 | _name = "ConfbridgeListRooms_Aggregate" 208 | 209 | _aggregation_members = (ConfbridgeListRooms,) 210 | _aggregation_finalisers = (ConfbridgeListRoomsComplete,) 211 | 212 | def _finalise(self, event): 213 | self._check_list_items_count(event, 'ListItems') 214 | return _Aggregate._finalise(self, event) 215 | 216 | -------------------------------------------------------------------------------- /pystrix/ami/app_meetme.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.ami.app_meetme 3 | ====================== 4 | 5 | Provides classes meant to be fed to a `Manager` instance's `send_action()` function. 6 | 7 | Specifically, this module provides implementations for features specific to the Meetme 8 | application. 9 | 10 | Legal 11 | ----- 12 | 13 | This file is part of pystrix. 14 | pystrix is free software; you can redistribute it and/or modify 15 | it under the terms of the GNU Lesser General Public License as published 16 | by the Free Software Foundation; either version 3 of the License, or 17 | (at your option) any later version. 18 | 19 | This program is distributed in the hope that it will be useful, 20 | but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | GNU Lesser General Public License for more details. 23 | 24 | You should have received a copy of the GNU General Public License and 25 | GNU Lesser General Public License along with this program. If not, see 26 | . 27 | 28 | (C) Ivrnet, inc., 2011 29 | 30 | Authors: 31 | 32 | - Neil Tallim 33 | 34 | The requests and events implemented by this module follow the definitions provided by 35 | http://www.asteriskdocs.org/ and https://wiki.asterisk.org/ 36 | """ 37 | from pystrix.ami.ami import (_Request, ManagerError) 38 | from pystrix.ami import app_meetme_events 39 | from pystrix.ami import generic_transforms 40 | 41 | class MeetmeList(_Request): 42 | """ 43 | Lists all participants in all (or one) conferences. 44 | 45 | A series of 'MeetmeList' events follow, with one 'MeetmeListComplete' event at the end. 46 | 47 | Note that if no conferences are active, the response will indicate that it was not successful, 48 | per https://issues.asterisk.org/jira/browse/ASTERISK-16812 49 | """ 50 | _aggregates = (app_meetme_events.MeetmeList_Aggregate,) 51 | _synchronous_events_list = (app_meetme_events.MeetmeList,) 52 | _synchronous_events_finalising = (app_meetme_events.MeetmeListComplete,) 53 | 54 | def __init__(self, conference=None): 55 | """ 56 | `conference` is the optional identifier of the bridge. 57 | """ 58 | _Request.__init__(self, 'MeetmeList') 59 | if not conference is None: 60 | self['Conference'] = conference 61 | 62 | class MeetmeListRooms(_Request): 63 | """ 64 | Lists all conferences. 65 | 66 | A series of 'MeetmeListRooms' events follow, with one 'MeetmeListRoomsComplete' event at the 67 | end. 68 | """ 69 | _aggregates = (app_meetme_events.MeetmeListRooms_Aggregate,) 70 | _synchronous_events_list = (app_meetme_events.MeetmeListRooms,) 71 | _synchronous_events_finalising = (app_meetme_events.MeetmeListRoomsComplete,) 72 | 73 | def __init__(self): 74 | _Request.__init__(self, 'MeetmeListRooms') 75 | 76 | class MeetmeMute(_Request): 77 | """ 78 | Mutes a participant in a Meetme bridge. 79 | 80 | Requires call 81 | """ 82 | def __init__(self, meetme, usernum): 83 | """ 84 | `meetme` is the identifier of the bridge and `usernum` is the participant ID of the user to 85 | be muted, which is associated with a channel by the 'MeetmeJoin' event. If successful, this 86 | request will trigger a 'MeetmeMute' event. 87 | """ 88 | _Request.__init__(self, 'MeetmeMute') 89 | self['Meetme'] = meetme 90 | self['Usernum'] = usernum 91 | 92 | class MeetmeUnmute(_Request): 93 | """ 94 | Unmutes a participant in a Meetme bridge. 95 | 96 | Requires call 97 | """ 98 | def __init__(self, meetme, usernum): 99 | """ 100 | `meetme` is the identifier of the bridge and `usernum` is the participant ID of the user to 101 | be unmuted, which is associated with a channel by the 'MeetmeJoin' event. If successful, 102 | this request will trigger a 'MeetmeMute' event. 103 | """ 104 | _Request.__init__(self, 'MeetmeUnmute') 105 | self['Meetme'] = meetme 106 | self['Usernum'] = usernum 107 | 108 | -------------------------------------------------------------------------------- /pystrix/ami/app_meetme_events.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.ami.app_meetme_events 3 | ============================= 4 | 5 | Provides defnitions and filtering rules for events that may be raised by Asterisk's Meetme module. 6 | 7 | Legal 8 | ----- 9 | 10 | This file is part of pystrix. 11 | pystrix is free software; you can redistribute it and/or modify 12 | it under the terms of the GNU Lesser General Public License as published 13 | by the Free Software Foundation; either version 3 of the License, or 14 | (at your option) any later version. 15 | 16 | This program is distributed in the hope that it will be useful, 17 | but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | GNU Lesser General Public License for more details. 20 | 21 | You should have received a copy of the GNU General Public License and 22 | GNU Lesser General Public License along with this program. If not, see 23 | . 24 | 25 | (C) Ivrnet, inc., 2011 26 | 27 | Authors: 28 | 29 | - Neil Tallim 30 | 31 | The events implemented by this module follow the definitions provided by 32 | http://www.asteriskdocs.org/ and https://wiki.asterisk.org/ 33 | """ 34 | from pystrix.ami.ami import (_Aggregate, _Event) 35 | from pystrix.ami import generic_transforms 36 | 37 | class MeetmeJoin(_Event): 38 | """ 39 | Indicates that a user has joined a Meetme bridge. 40 | 41 | - 'Channel' : The channel that was bridged 42 | - 'Meetme' : The ID of the Meetme bridge, typically a number formatted as a string 43 | - 'Uniqueid' : An Asterisk unique value 44 | - 'Usernum' : The bridge-specific participant ID assigned to the channel 45 | """ 46 | 47 | class MeetmeList(_Event): 48 | """ 49 | Describes a participant in a Meetme room. 50 | 51 | - 'Admin' : 'Yes' or 'No' 52 | - 'CallerIDNum' : The (often) numeric address of the participant 53 | - 'CallerIDName' (optional) : The name of the participant on supporting channels 54 | - 'Channel' : The Asterisk channel in use by the participant 55 | - 'Conference' : The room's identifier 56 | - 'ConnectedLineNum' : unknown 57 | - 'ConnectedLineName' : unknown 58 | - 'MarkedUser' : 'Yes' or 'No' 59 | - 'Muted' : "By admin", "By self", "No" 60 | - 'Role' : "Listen only", "Talk only", "Talk and listen" 61 | - 'Talking' : 'Yes', 'No', or 'Not monitored' 62 | - 'UserNumber' : The ID of the participant in the conference 63 | """ 64 | def process(self): 65 | """ 66 | Translates the 'Admin' and 'MarkedUser' headers' values into bools. 67 | 68 | Translates the 'Talking' header's value into a bool, or `None` if not monitored. 69 | 70 | Translates the 'UserNumber' header's value into an int, or -1 on failure. 71 | """ 72 | (headers, data) = _Event.process(self) 73 | 74 | talking = headers.get('Talking') 75 | if talking == 'Yes': 76 | headers['Talking'] = True 77 | elif talking == 'No': 78 | headers['Talking'] = False 79 | else: 80 | headers['Talking'] = None 81 | 82 | generic_transforms.to_bool(headers, ('Admin', 'MarkedUser',), truth_value='Yes') 83 | generic_transforms.to_int(headers, ('UserNumber',), -1) 84 | 85 | return (headers, data) 86 | 87 | class MeetmeListComplete(_Event): 88 | """ 89 | Indicates that all participants in a Meetme query have been enumerated. 90 | 91 | - 'ListItems' : The number of items returned prior to this event 92 | """ 93 | def process(self): 94 | """ 95 | Translates the 'ListItems' header's value into an int, or -1 on failure. 96 | """ 97 | (headers, data) = _Event.process(self) 98 | 99 | generic_transforms.to_int(headers, ('ListItems',), -1) 100 | 101 | return (headers, data) 102 | 103 | class MeetmeListRooms(_Event): 104 | """ 105 | Describes a Meetme room. 106 | 107 | And, yes, it's plural in Asterisk, too. 108 | 109 | - 'Activity' : The duration of the conference 110 | - 'Conference' : The room's identifier 111 | - 'Creation' : 'Dynamic' or 'Static' 112 | - 'Locked' : 'Yes' or 'No' 113 | - 'Marked' : The number of marked users, but not as an integer: 'N/A' or %.4d 114 | - 'Parties' : The number of participants 115 | """ 116 | def process(self): 117 | """ 118 | Translates the 'Parties' header's value into an int, or -1 on failure. 119 | 120 | Translates the 'Locked' header's value into a bool. 121 | """ 122 | (headers, data) = _Event.process(self) 123 | 124 | generic_transforms.to_bool(headers, ('Locked',), truth_value='Yes') 125 | generic_transforms.to_int(headers, ('Parties',), -1) 126 | 127 | return (headers, data) 128 | 129 | class MeetmeListRoomsComplete(_Event): 130 | """ 131 | Indicates that all Meetme rooms have been enumerated. 132 | 133 | - 'ListItems' : The number of items returned prior to this event 134 | """ 135 | def process(self): 136 | """ 137 | Translates the 'ListItems' header's value into an int, or -1 on failure. 138 | """ 139 | (headers, data) = _Event.process(self) 140 | 141 | generic_transforms.to_int(headers, ('ListItems',), -1) 142 | 143 | return (headers, data) 144 | 145 | class MeetmeMute(_Event): 146 | """ 147 | Indicates that a user has been muted in a Meetme bridge. 148 | 149 | - 'Channel' : The channel that was muted 150 | - 'Meetme' : The ID of the Meetme bridge, typically a number formatted as a string 151 | - 'Status' : 'on' or 'off', depending on whether the user was muted or unmuted 152 | - 'Uniqueid' : An Asterisk unique value 153 | - 'Usernum' : The participant ID of the user that was affected 154 | """ 155 | def process(self): 156 | """ 157 | Translates the 'Status' header's value into a bool. 158 | """ 159 | (headers, data) = _Event.process(self) 160 | 161 | generic_transforms.to_bool(headers, ('Status',), truth_value='on') 162 | 163 | return (headers, data) 164 | 165 | 166 | #List-aggregation events 167 | #################################################################################################### 168 | #These define non-Asterisk-native event-types that collect multiple events (cases where multiple 169 | #events are generated in response to a single action) and emit the bundle as a single message. 170 | 171 | class MeetmeList_Aggregate(_Aggregate): 172 | """ 173 | Emitted after all participants have been received in response to a MeetmeList request. 174 | 175 | Its members consist of MeetmeList events. 176 | 177 | It is finalised by MeetmeListComplete. 178 | """ 179 | _name = "MeetmeList_Aggregate" 180 | 181 | _aggregation_members = (MeetmeList,) 182 | _aggregation_finalisers = (MeetmeListComplete,) 183 | 184 | def _finalise(self, event): 185 | self._check_list_items_count(event, 'ListItems') 186 | return _Aggregate._finalise(self, event) 187 | 188 | class MeetmeListRooms_Aggregate(_Aggregate): 189 | """ 190 | Emitted after all participants have been received in response to a MeetmeListRooms request. 191 | 192 | Its members consist of MeetmeListRooms events. 193 | 194 | It is finalised by MeetmeListRoomsComplete. 195 | """ 196 | _name = "MeetmeListRooms_Aggregate" 197 | 198 | _aggregation_members = (MeetmeListRooms,) 199 | _aggregation_finalisers = (MeetmeListRoomsComplete,) 200 | 201 | def _finalise(self, event): 202 | self._check_list_items_count(event, 'ListItems') 203 | return _Aggregate._finalise(self, event) 204 | 205 | -------------------------------------------------------------------------------- /pystrix/ami/dahdi.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.ami.dahdi 3 | ================= 4 | 5 | Provides classes meant to be fed to a `Manager` instance's `send_action()` function. 6 | 7 | Specifically, this module provides implementations for features specific to the DAHDI technology. 8 | 9 | Legal 10 | ----- 11 | 12 | This file is part of pystrix. 13 | pystrix is free software; you can redistribute it and/or modify 14 | it under the terms of the GNU Lesser General Public License as published 15 | by the Free Software Foundation; either version 3 of the License, or 16 | (at your option) any later version. 17 | 18 | This program is distributed in the hope that it will be useful, 19 | but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 21 | GNU Lesser General Public License for more details. 22 | 23 | You should have received a copy of the GNU General Public License and 24 | GNU Lesser General Public License along with this program. If not, see 25 | . 26 | 27 | (C) Ivrnet, inc., 2011 28 | 29 | Authors: 30 | 31 | - Neil Tallim 32 | 33 | The requests implemented by this module follow the definitions provided by 34 | https://wiki.asterisk.org/ 35 | """ 36 | from pystrix.ami.ami import (_Request, ManagerError) 37 | from pystrix.ami import dahdi_events 38 | from pystrix.ami import generic_transforms 39 | 40 | class DAHDIDNDoff(_Request): 41 | """ 42 | Sets a DAHDI channel's DND status to off. 43 | """ 44 | def __init__(self, dahdi_channel): 45 | """ 46 | `dahdi_channel` is the channel to modify. 47 | """ 48 | _Request.__init__(self, 'DAHDIDNDoff') 49 | self['DAHDIChannel'] = dahdi_channel 50 | 51 | class DAHDIDNDon(_Request): 52 | """ 53 | Sets a DAHDI channel's DND status to on. 54 | """ 55 | def __init__(self, dahdi_channel): 56 | """ 57 | `dahdi_channel` is the channel to modify. 58 | """ 59 | _Request.__init__(self, 'DAHDIDNDon') 60 | self['DAHDIChannel'] = dahdi_channel 61 | 62 | class DAHDIDialOffhook(_Request): 63 | """ 64 | Dials a number on an off-hook DAHDI channel. 65 | """ 66 | def __init__(self, dahdi_channel, number): 67 | """ 68 | `dahdi_channel` is the channel to use and `number` is the number to dial. 69 | """ 70 | _Request.__init__(self, 'DAHDIDialOffhook') 71 | self['DAHDIChannel'] = dahdi_channel 72 | self['Number'] = number 73 | 74 | class DAHDIHangup(_Request): 75 | """ 76 | Hangs up a DAHDI channel. 77 | """ 78 | def __init__(self, dahdi_channel): 79 | """ 80 | `dahdi_channel` is the channel to hang up. 81 | """ 82 | _Request.__init__(self, 'DAHDIHangup') 83 | self['DAHDIChannel'] = dahdi_channel 84 | 85 | class DAHDIRestart(_Request): 86 | """ 87 | Fully restarts all DAHDI channels. 88 | """ 89 | def __init__(self): 90 | _Request.__init__(self, 'DAHDIRestart') 91 | 92 | class DAHDIShowChannels(_Request): 93 | """ 94 | Provides the current status of all (or one) DAHDI channels through a series of 95 | 'DAHDIShowChannels' events, ending with a 'DAHDIShowChannelsComplete' event. 96 | """ 97 | _aggregates = (dahdi_events.DAHDIShowChannels_Aggregate,) 98 | _synchronous_events_list = (dahdi_events.DAHDIShowChannels,) 99 | _synchronous_events_finalising = (dahdi_events.DAHDIShowChannelsComplete,) 100 | 101 | def __init__(self, dahdi_channel=None): 102 | _Request.__init__(self, 'DAHDIShowChannels') 103 | if not dahdi_channel is None: 104 | self['DAHDIChannel'] = dahdi_channel 105 | 106 | -------------------------------------------------------------------------------- /pystrix/ami/dahdi_events.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.ami.dahdi_events 3 | ======================== 4 | 5 | Provides defnitions and filtering rules for events that may be raised by Asterisk's DAHDI module. 6 | 7 | Legal 8 | ----- 9 | 10 | This file is part of pystrix. 11 | pystrix is free software; you can redistribute it and/or modify 12 | it under the terms of the GNU Lesser General Public License as published 13 | by the Free Software Foundation; either version 3 of the License, or 14 | (at your option) any later version. 15 | 16 | This program is distributed in the hope that it will be useful, 17 | but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | GNU Lesser General Public License for more details. 20 | 21 | You should have received a copy of the GNU General Public License and 22 | GNU Lesser General Public License along with this program. If not, see 23 | . 24 | 25 | (C) Ivrnet, inc., 2011 26 | 27 | Authors: 28 | 29 | - Neil Tallim 30 | 31 | The events implemented by this module follow the definitions provided by 32 | http://www.asteriskdocs.org/ and https://wiki.asterisk.org/ 33 | """ 34 | from pystrix.ami.ami import (_Aggregate, _Event) 35 | from pystrix.ami import generic_transforms 36 | 37 | class DAHDIShowChannels(_Event): 38 | """ 39 | Describes the current state of a DAHDI channel. 40 | 41 | Yes, the event's name is pluralised. 42 | 43 | - 'AccountCode': unknown (not present if the DAHDI channel is down) 44 | - 'Alarm': unknown 45 | - 'Channel': The channel being described (not present if the DAHDI channel is down) 46 | - 'Context': The Asterisk context associated with the channel 47 | - 'DAHDIChannel': The ID of the DAHDI channel 48 | - 'Description': unknown 49 | - 'DND': 'Disabled' or 'Enabled' 50 | - 'Signalling': A lexical description of the current signalling state 51 | - 'SignallingCode': A numeric description of the current signalling state 52 | - 'Uniqueid': unknown (not present if the DAHDI channel is down) 53 | """ 54 | def process(self): 55 | """ 56 | Translates the 'DND' header's value into a bool. 57 | 58 | Translates the 'DAHDIChannel' and 'SignallingCode' headers' values into ints, or -1 on 59 | failure. 60 | """ 61 | (headers, data) = _Event.process(self) 62 | 63 | generic_transforms.to_bool(headers, ('DND',), truth_value='Enabled') 64 | generic_transforms.to_int(headers, ('DAHDIChannel', 'SignallingCode',), -1) 65 | 66 | return (headers, data) 67 | 68 | class DAHDIShowChannelsComplete(_Event): 69 | """ 70 | Indicates that all DAHDI channels have been described. 71 | 72 | - 'Items': The number of items returned prior to this event 73 | """ 74 | def process(self): 75 | """ 76 | Translates the 'Items' header's value into an int, or -1 on failure. 77 | """ 78 | (headers, data) = _Event.process(self) 79 | 80 | generic_transforms.to_int(headers, ('Items',), -1) 81 | 82 | return (headers, data) 83 | 84 | 85 | #List-aggregation events 86 | #################################################################################################### 87 | #These define non-Asterisk-native event-types that collect multiple events (cases where multiple 88 | #events are generated in response to a single action) and emit the bundle as a single message. 89 | 90 | class DAHDIShowChannels_Aggregate(_Aggregate): 91 | """ 92 | Emitted after all DAHDI channels have been enumerated in response to a DAHDIShowChannels 93 | request. 94 | 95 | Its members consist of DAHDIShowChannels events. 96 | 97 | It is finalised by DAHDIShowChannelsComplete. 98 | """ 99 | _name = "DAHDIShowChannels_Aggregate" 100 | 101 | _aggregation_members = (DAHDIShowChannels,) 102 | _aggregation_finalisers = (DAHDIShowChannelsComplete,) 103 | 104 | def _finalise(self, event): 105 | self._check_list_items_count(event, 'Items') 106 | return _Aggregate._finalise(self, event) 107 | 108 | -------------------------------------------------------------------------------- /pystrix/ami/generic_transforms.py: -------------------------------------------------------------------------------- 1 | """ 2 | pystrix.ami.generic_transforms 3 | ============================== 4 | 5 | Provides generic functions for translating data received from Asterisk into Python data-types. 6 | 7 | Legal 8 | ----- 9 | 10 | This file is part of pystrix. 11 | pystrix is free software; you can redistribute it and/or modify 12 | it under the terms of the GNU Lesser General Public License as published 13 | by the Free Software Foundation; either version 3 of the License, or 14 | (at your option) any later version. 15 | 16 | This program is distributed in the hope that it will be useful, 17 | but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | GNU Lesser General Public License for more details. 20 | 21 | You should have received a copy of the GNU General Public License and 22 | GNU Lesser General Public License along with this program. If not, see 23 | . 24 | 25 | (C) Neil Tallim, 2013 26 | 27 | Authors: 28 | 29 | - Neil Tallim 30 | """ 31 | import sys 32 | 33 | 34 | # identify string type in a python 2 and 3 compatible manner 35 | string_type = str if sys.version_info[0] >= 3 else basestring 36 | 37 | 38 | def to_bool(dictionary, keys, truth_value=None, truth_function=(lambda x:bool(x)), preprocess=(lambda x:x)): 39 | for key in keys: 40 | if truth_value: 41 | dictionary[key] = dictionary.get(key) == truth_value 42 | else: 43 | try: 44 | dictionary[key] = truth_function(preprocess(dictionary.get(key))) 45 | except Exception: 46 | dictionary[key] = False 47 | 48 | 49 | def to_float(dictionary, keys, failure_value, preprocess=(lambda x:x)): 50 | for key in keys: 51 | try: 52 | dictionary[key] = float(preprocess(dictionary.get(key))) 53 | except Exception: 54 | dictionary[key] = failure_value 55 | 56 | 57 | def to_int(dictionary, keys, failure_value, preprocess=(lambda x:x)): 58 | for key in keys: 59 | try: 60 | dictionary[key] = int(preprocess(dictionary.get(key))) 61 | except Exception: 62 | dictionary[key] = failure_value 63 | 64 | 65 | def add_result(dictionary, key, result_map): 66 | if dictionary[key] in result_map: 67 | dictionary['Result'] = result_map[dictionary[key]] 68 | 69 | 70 | def string_to_bytes(value, encoding="utf-8", errors="strict"): 71 | if isinstance(value, string_type): 72 | return value.encode(encoding, errors) 73 | return value 74 | 75 | 76 | def bytes_to_string(value, encoding="utf-8", errors="strict"): 77 | if not isinstance(value, string_type): 78 | return value.decode(encoding, errors) 79 | return value 80 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Deployment script for pystrix. 4 | """ 5 | 6 | from pystrix import VERSION 7 | 8 | from setuptools import setup 9 | import os 10 | 11 | 12 | CLASSIFIERS = [ 13 | 'Intended Audience :: Developers', 14 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 15 | 'Operating System :: OS Independent', 16 | 'Programming Language :: Python', 17 | 'Programming Language :: Python :: 2', 18 | 'Programming Language :: Python :: 2.7', 19 | 'Programming Language :: Python :: 3', 20 | 'Programming Language :: Python :: 3.4', 21 | 'Programming Language :: Python :: 3.5', 22 | 'Programming Language :: Python :: 3.6', 23 | 'Topic :: Communications :: Telephony' 24 | ] 25 | 26 | README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() 27 | 28 | # allow setup.py to be run from any path 29 | os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) 30 | 31 | setup( 32 | author='Marta Solano', 33 | author_email='marta.solano@ivrtechnology.com', 34 | name='pystrix', 35 | version=VERSION, 36 | description='Python bindings for Asterisk Manager Interface and Asterisk Gateway Interface', 37 | long_description=README, 38 | url='https://github.com/IVRTech/pystrix', 39 | license='GNU General Public License', 40 | platforms=['OS Independent'], 41 | classifiers=CLASSIFIERS, 42 | packages=[ 43 | 'pystrix', 44 | 'pystrix.agi', 45 | 'pystrix.ami', 46 | ] 47 | ) 48 | --------------------------------------------------------------------------------