├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── stale.yml └── workflows │ └── pythonpackage.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .readthedocs.yml ├── CHANGELOG ├── CODE_OF_CONDUCT.md ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── docs ├── .DS_Store ├── Makefile ├── _static │ └── logo.png ├── apis.rst ├── apis │ ├── modules.rst │ ├── pyshorteners.rst │ └── pyshorteners.shorteners.rst ├── conf.py ├── contributing.rst └── index.rst ├── example.py ├── pyshorteners ├── __init__.py ├── base.py ├── exceptions.py └── shorteners │ ├── __init__.py │ ├── adfly.py │ ├── bitly.py │ ├── chilpit.py │ ├── clckru.py │ ├── cuttly.py │ ├── dagd.py │ ├── gitio.py │ ├── isgd.py │ ├── nullpointer.py │ ├── osdb.py │ ├── owly.py │ ├── post.py │ ├── qpsru.py │ ├── shortcm.py │ ├── tinycc.py │ └── tinyurl.py ├── setup.cfg ├── setup.py └── tests ├── __init__.py ├── test_adfly.py ├── test_base.py ├── test_bitly.py ├── test_chilpit.py ├── test_clckru.py ├── test_cuttly.py ├── test_dagd.py ├── test_isgd.py ├── test_nullpointer.py ├── test_osdb.py ├── test_owly.py ├── test_post.py ├── test_qpsru.py ├── test_shortcm.py ├── test_tinycc.py └── test_tinyurl.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. 13 | 2. 14 | 15 | **Expected behavior** 16 | A clear and concise description of what you expected to happen. 17 | 18 | 19 | **Desktop (please complete the following information):** 20 | - OS: [e.g. iOS] 21 | - Version [e.g. 22] 22 | 23 | 24 | **Additional context** 25 | Add any other context about the problem here. 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 60 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 7 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - pinned 8 | - security 9 | # Label to use when marking an issue as stale 10 | staleLabel: wontfix 11 | # Comment to post when marking an issue as stale. Set to `false` to disable 12 | markComment: > 13 | This issue has been automatically marked as stale because it has not had 14 | recent activity. It will be closed if no further activity occurs. Thank you 15 | for your contributions. 16 | # Comment to post when closing a stale issue. Set to `false` to disable 17 | closeComment: false 18 | -------------------------------------------------------------------------------- /.github/workflows/pythonpackage.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | max-parallel: 4 11 | matrix: 12 | python-version: [3.6, 3.7, 3.8] 13 | 14 | steps: 15 | - uses: actions/checkout@v1 16 | - name: Set up Python ${{ matrix.python-version }} 17 | uses: actions/setup-python@v1 18 | with: 19 | python-version: ${{ matrix.python-version }} 20 | - name: Install dependencies and run tests 21 | run: | 22 | python -m pip install --upgrade pip 23 | make test 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | Pipfile.lock 28 | Pipfile 29 | .mypy_cache 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *,cover 50 | .hypothesis/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv/ 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | 93 | # Rope project settings 94 | .ropeproject 95 | 96 | # PyCharm 97 | .idea/ 98 | 99 | # pytest cache 100 | .pytest_cache/ 101 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/psf/black 5 | rev: 19.3b0 6 | hooks: 7 | - id: black 8 | -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | sphinx: 3 | configuration: docs/conf.py 4 | formats: [] 5 | python: 6 | version: 3.7 7 | install: 8 | - method: pip 9 | path: . 10 | extra_requirements: 11 | - docs 12 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | 1.0.0 2 | ===== 3 | * Major release, see docs for complete overview 4 | 5 | 6 | 0.6.0 7 | ===== 8 | 9 | Breaking changes on the shorteners classes 10 | 11 | * Removing the `Shortener` class on the Shortener classes. Check the README for the new examples 12 | * Adding wp-a.co Shortener #40 13 | 14 | 15 | 0.5.8 16 | ===== 17 | * Fix goog.gl shortener 18 | 19 | 0.5.5 20 | ===== 21 | * Add timeout kwarg #9 22 | 23 | 0.5.3 24 | ===== 25 | * add `debug` kwarg on Shortener class 26 | * implemented `total_clicks` method on BaseShortener class. 27 | * implemented `total_clicks` on BitlyShortener 28 | * change BitlyShortener `short` and `expand` to use GET requests 29 | * BitlyShortener only requires `bitly_token` for shortening/expading/analytics 30 | * 100% Coverage :smiley: 31 | 32 | 33 | 0.5.2 34 | ===== 35 | * Fix import shortcut 36 | * add `_get` and `_post` helper methods on BaseShortener 37 | 38 | 39 | 0.5.1 40 | ===== 41 | * add import shortcut 42 | 43 | 0.5 44 | === 45 | 46 | * tests running now with pytest 47 | * fix some py3 issues 48 | * Remove GenericExpander in favor of new BaseShortener class 49 | * All shorteners now must inherit from BaseShortener 50 | 51 | 0.4.2 52 | ===== 53 | 54 | * Goo.gl now needs an `api_key` in order to short and expand urls 55 | * Bit.ly now needs an extra `bitly_token` in order to short and expand urls 56 | 57 | 0.4 58 | === 59 | * Ow.ly shortener added 60 | * Readability shortener added 61 | 62 | 0.3 63 | === 64 | * Add GenericExpander 65 | 66 | 0.2.10 67 | ====== 68 | 69 | 70 | 0.2.8 71 | ===== 72 | * Remove Dot.tk API 73 | * Add Senta.la API 74 | * Add qr_code methor on Shortener class 75 | * add shorten and expanded properties on Shortener class 76 | 77 | 0.2.7 78 | ===== 79 | * Add custom exceptions 80 | * Add Is.gd API (Issue #7) 81 | * Fix import Shortener on __init__.py 82 | * add show_current_apis function 83 | 84 | 0.2.6 85 | ===== 86 | 87 | * Add Dot.Tk shortener API support 88 | 89 | 0.2.5 90 | ===== 91 | 92 | * Python 3 support 93 | 94 | 0.2.4 95 | 0.2.3 96 | ===== 97 | 98 | * Add kwargs on short, expand functions, fixing the credentials params 99 | * Add Adfly shortener 100 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ellisonleao@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: test 2 | test: develop 3 | @python setup.py test 4 | 5 | .PHONY: develop 6 | develop: 7 | @pip install -e .[dev] 8 | pre-commit install 9 | 10 | .PHONY: docs 11 | docs: 12 | @pip install -e .[docs] 13 | $(MAKE) --directory=docs/ html 14 | 15 | clean-build: 16 | rm -fr build/ 17 | rm -fr dist/ 18 | rm -fr *.egg-info 19 | rm -fr *.egg 20 | 21 | clean-pyc: 22 | find . -name '*.pyc' -exec rm -f {} + 23 | find . -name '*.pyo' -exec rm -f {} + 24 | find . -name '*~' -exec rm -f {} + 25 | find . -name '__pycache__' -exec rm -fr {} + 26 | 27 | .PHONY: dist 28 | dist: 29 | @pip install twine 30 | @python setup.py sdist 31 | 32 | .PHONY: upload-test 33 | upload-test: dist 34 | @python -m twine upload --repository-url https://test.pypi.org/legacy/ dist/* 35 | 36 | upload: dist 37 | @python -m twine upload dist/* 38 | 39 | 40 | .PHONY: clean-pyc clean-build clean 41 | clean: clean-build clean-pyc 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 |    logo
3 | pyshorteners 4 |

5 | 6 |
7 | 8 |

9 |    Travis 10 |     11 |    Download stats 12 |

13 | 14 | A simple URL shortening API wrapper Python library. 15 | 16 | # Installing 17 | 18 | pip install pyshorteners 19 | 20 | # Documentation 21 | 22 | https://pyshorteners.readthedocs.io/en/latest/ 23 | -------------------------------------------------------------------------------- /docs/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ellisonleao/pyshorteners/940bde19fb594cd8b7d102c6750bb6344997aa52/docs/.DS_Store -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = pyshorteners 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/_static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ellisonleao/pyshorteners/940bde19fb594cd8b7d102c6750bb6344997aa52/docs/_static/logo.png -------------------------------------------------------------------------------- /docs/apis.rst: -------------------------------------------------------------------------------- 1 | Implemented APIs 2 | ================ 3 | 4 | Currently, `pyshorteners` implements the following APIs: 5 | 6 | Adf.ly 7 | ------ 8 | 9 | .. autoclass:: pyshorteners.shorteners.adfly.Shortener 10 | :members: 11 | :noindex: 12 | 13 | Bit.ly 14 | ------ 15 | 16 | .. autoclass:: pyshorteners.shorteners.bitly.Shortener 17 | :members: 18 | :noindex: 19 | 20 | Chilp.it 21 | -------- 22 | 23 | .. autoclass:: pyshorteners.shorteners.chilpit.Shortener 24 | :members: 25 | :noindex: 26 | 27 | 28 | Clck.ru 29 | ------- 30 | 31 | .. autoclass:: pyshorteners.shorteners.clckru.Shortener 32 | :members: 33 | :noindex: 34 | 35 | 36 | Cutt.ly 37 | ------- 38 | 39 | .. autoclass:: pyshorteners.shorteners.cuttly.Shortener 40 | :members: 41 | :noindex: 42 | 43 | 44 | Da.gd 45 | ------- 46 | 47 | .. autoclass:: pyshorteners.shorteners.dagd.Shortener 48 | :members: 49 | :noindex: 50 | 51 | 52 | Git.io 53 | ------- 54 | 55 | .. autoclass:: pyshorteners.shorteners.gitio.Shortener 56 | :members: 57 | :noindex: 58 | 59 | 60 | Is.gd 61 | ------- 62 | 63 | .. autoclass:: pyshorteners.shorteners.isgd.Shortener 64 | :members: 65 | :noindex: 66 | 67 | 68 | NullPointer 69 | ----------- 70 | 71 | .. autoclass:: pyshorteners.shorteners.nullpointer.Shortener 72 | :members: 73 | :noindex: 74 | 75 | 76 | Os.db 77 | ----------- 78 | 79 | .. autoclass:: pyshorteners.shorteners.osdb.Shortener 80 | :members: 81 | :noindex: 82 | 83 | Ow.ly 84 | ----------- 85 | 86 | .. autoclass:: pyshorteners.shorteners.owly.Shortener 87 | :members: 88 | :noindex: 89 | 90 | 91 | Po.st 92 | ----------- 93 | 94 | .. autoclass:: pyshorteners.shorteners.post.Shortener 95 | :members: 96 | :noindex: 97 | 98 | 99 | Qps.ru 100 | ----------- 101 | 102 | .. autoclass:: pyshorteners.shorteners.qpsru.Shortener 103 | :members: 104 | :noindex: 105 | 106 | 107 | Short.cm 108 | ----------- 109 | 110 | .. autoclass:: pyshorteners.shorteners.shortcm.Shortener 111 | :members: 112 | :noindex: 113 | 114 | 115 | Tiny.cc 116 | ----------- 117 | 118 | .. autoclass:: pyshorteners.shorteners.tinycc.Shortener 119 | :members: 120 | :noindex: 121 | 122 | 123 | TinyURL.com 124 | ----------- 125 | 126 | .. autoclass:: pyshorteners.shorteners.tinyurl.Shortener 127 | :members: 128 | :noindex: 129 | 130 | 131 | Git.io 132 | ----------- 133 | 134 | .. autoclass:: pyshorteners.shorteners.gitio.Shortener 135 | :members: 136 | :noindex: 137 | 138 | Tiny.cc 139 | ------- 140 | 141 | .. autoclass:: pyshorteners.shorteners.tinycc.Shortener 142 | :members: 143 | :noindex: 144 | -------------------------------------------------------------------------------- /docs/apis/modules.rst: -------------------------------------------------------------------------------- 1 | pyshorteners 2 | ============ 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | pyshorteners 8 | -------------------------------------------------------------------------------- /docs/apis/pyshorteners.rst: -------------------------------------------------------------------------------- 1 | pyshorteners package 2 | ==================== 3 | 4 | .. automodule:: pyshorteners 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Subpackages 10 | ----------- 11 | 12 | .. toctree:: 13 | 14 | pyshorteners.shorteners 15 | 16 | Submodules 17 | ---------- 18 | 19 | pyshorteners.base module 20 | ------------------------ 21 | 22 | .. automodule:: pyshorteners.base 23 | :members: 24 | :undoc-members: 25 | :show-inheritance: 26 | 27 | pyshorteners.exceptions module 28 | ------------------------------ 29 | 30 | .. automodule:: pyshorteners.exceptions 31 | :members: 32 | :undoc-members: 33 | :show-inheritance: 34 | 35 | -------------------------------------------------------------------------------- /docs/apis/pyshorteners.shorteners.rst: -------------------------------------------------------------------------------- 1 | pyshorteners.shorteners package 2 | =============================== 3 | 4 | .. automodule:: pyshorteners.shorteners 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | pyshorteners.shorteners.adfly module 13 | ------------------------------------ 14 | 15 | .. automodule:: pyshorteners.shorteners.adfly 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | pyshorteners.shorteners.bitly module 21 | ------------------------------------ 22 | 23 | .. automodule:: pyshorteners.shorteners.bitly 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | pyshorteners.shorteners.chilpit module 29 | -------------------------------------- 30 | 31 | .. automodule:: pyshorteners.shorteners.chilpit 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | pyshorteners.shorteners.clckru module 37 | ------------------------------------- 38 | 39 | .. automodule:: pyshorteners.shorteners.clckru 40 | :members: 41 | :undoc-members: 42 | :show-inheritance: 43 | 44 | pyshorteners.shorteners.cuttly module 45 | ------------------------------------- 46 | 47 | .. automodule:: pyshorteners.shorteners.cuttly 48 | :members: 49 | :undoc-members: 50 | :show-inheritance: 51 | 52 | pyshorteners.shorteners.dagd module 53 | ----------------------------------- 54 | 55 | .. automodule:: pyshorteners.shorteners.dagd 56 | :members: 57 | :undoc-members: 58 | :show-inheritance: 59 | 60 | pyshorteners.shorteners.gitio module 61 | ------------------------------------ 62 | 63 | .. automodule:: pyshorteners.shorteners.gitio 64 | :members: 65 | :undoc-members: 66 | :show-inheritance: 67 | 68 | pyshorteners.shorteners.isgd module 69 | ----------------------------------- 70 | 71 | .. automodule:: pyshorteners.shorteners.isgd 72 | :members: 73 | :undoc-members: 74 | :show-inheritance: 75 | 76 | pyshorteners.shorteners.nullpointer module 77 | ------------------------------------------ 78 | 79 | .. automodule:: pyshorteners.shorteners.nullpointer 80 | :members: 81 | :undoc-members: 82 | :show-inheritance: 83 | 84 | pyshorteners.shorteners.osdb module 85 | ----------------------------------- 86 | 87 | .. automodule:: pyshorteners.shorteners.osdb 88 | :members: 89 | :undoc-members: 90 | :show-inheritance: 91 | 92 | pyshorteners.shorteners.owly module 93 | ----------------------------------- 94 | 95 | .. automodule:: pyshorteners.shorteners.owly 96 | :members: 97 | :undoc-members: 98 | :show-inheritance: 99 | 100 | pyshorteners.shorteners.post module 101 | ----------------------------------- 102 | 103 | .. automodule:: pyshorteners.shorteners.post 104 | :members: 105 | :undoc-members: 106 | :show-inheritance: 107 | 108 | pyshorteners.shorteners.qpsru module 109 | ------------------------------------ 110 | 111 | .. automodule:: pyshorteners.shorteners.qpsru 112 | :members: 113 | :undoc-members: 114 | :show-inheritance: 115 | 116 | pyshorteners.shorteners.shortcm module 117 | -------------------------------------- 118 | 119 | .. automodule:: pyshorteners.shorteners.shortcm 120 | :members: 121 | :undoc-members: 122 | :show-inheritance: 123 | 124 | pyshorteners.shorteners.tinycc module 125 | ------------------------------------- 126 | 127 | .. automodule:: pyshorteners.shorteners.tinycc 128 | :members: 129 | :undoc-members: 130 | :show-inheritance: 131 | 132 | pyshorteners.shorteners.tinyurl module 133 | -------------------------------------- 134 | 135 | .. automodule:: pyshorteners.shorteners.tinyurl 136 | :members: 137 | :undoc-members: 138 | :show-inheritance: 139 | 140 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | 11 | # If extensions (or modules to document with autodoc) are in another directory, 12 | # add these directories to sys.path here. If the directory is relative to the 13 | # documentation root, use os.path.abspath to make it absolute, like shown here. 14 | # 15 | import os 16 | import subprocess 17 | import sys 18 | sys.path.insert(0, os.path.abspath('.')) 19 | 20 | 21 | # -- Project information ----------------------------------------------------- 22 | 23 | project = 'pyshorteners' 24 | copyright = u'%d, Ellison Leão' % datetime.datetime.utcnow().year 25 | author = 'Ellison Leão' 26 | 27 | # The short X.Y version 28 | version = '1.0' 29 | # The full version, including alpha/beta/rc tags 30 | release = '1.0.0' 31 | 32 | 33 | # -- General configuration --------------------------------------------------- 34 | 35 | # If your documentation needs a minimal Sphinx version, state it here. 36 | # 37 | # needs_sphinx = '1.0' 38 | 39 | # Add any Sphinx extension module names here, as strings. They can be 40 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 41 | # ones. 42 | extensions = [ 43 | 'sphinx.ext.autodoc', 44 | 'sphinx.ext.intersphinx', 45 | 'sphinx.ext.napoleon', 46 | ] 47 | 48 | # Add any paths that contain templates here, relative to this directory. 49 | templates_path = ['_templates'] 50 | 51 | # The suffix(es) of source filenames. 52 | # You can specify multiple suffix as a list of string: 53 | # 54 | # source_suffix = ['.rst', '.md'] 55 | source_suffix = '.rst' 56 | 57 | # The master toctree document. 58 | master_doc = 'index' 59 | 60 | # The language for content autogenerated by Sphinx. Refer to documentation 61 | # for a list of supported languages. 62 | # 63 | # This is also used if you do content translation via gettext catalogs. 64 | # Usually you set "language" from the command line for these cases. 65 | language = None 66 | 67 | # List of patterns, relative to source directory, that match files and 68 | # directories to ignore when looking for source files. 69 | # This pattern also affects html_static_path and html_extra_path . 70 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 71 | 72 | # The name of the Pygments (syntax highlighting) style to use. 73 | pygments_style = 'sphinx' 74 | 75 | 76 | # -- Options for HTML output ------------------------------------------------- 77 | 78 | # The theme to use for HTML and HTML Help pages. See the documentation for 79 | # a list of builtin themes. 80 | # 81 | html_theme = 'alabaster' 82 | 83 | # Theme options are theme-specific and customize the look and feel of a theme 84 | # further. For a list of options available for each theme, see the 85 | # documentation. 86 | # 87 | html_theme_options = { 88 | 'logo': 'logo.png', 89 | 'logo_name': True, 90 | 'description': 'Python lib to handle url shortening and expanding for multiple APIs', 91 | 'github_banner': True, 92 | 'github_type': 'star', 93 | 'github_user': 'ellisonleao', 94 | 'github_repo': 'pyshorteners', 95 | 'show_powered_by': False, 96 | 'travis_button': True, 97 | 'codecov_button': True, 98 | } 99 | 100 | # Add any paths that contain custom static files (such as style sheets) here, 101 | # relative to this directory. They are copied after the builtin static files, 102 | # so a file named "default.css" will overwrite the builtin "default.css". 103 | html_static_path = ['_static'] 104 | 105 | # Custom sidebar templates, must be a dictionary that maps document names 106 | # to template names. 107 | # 108 | # The default sidebars (for documents that don't match any pattern) are 109 | # defined by theme itself. Builtin themes are using these templates by 110 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 111 | # 'searchbox.html']``. 112 | # 113 | # html_sidebars = {} 114 | 115 | 116 | # -- Options for HTMLHelp output --------------------------------------------- 117 | 118 | # Output file base name for HTML help builder. 119 | htmlhelp_basename = 'pyshortenersdoc' 120 | 121 | 122 | # -- Options for LaTeX output ------------------------------------------------ 123 | 124 | latex_elements = { 125 | # The paper size ('letterpaper' or 'a4paper'). 126 | # 127 | # 'papersize': 'letterpaper', 128 | 129 | # The font size ('10pt', '11pt' or '12pt'). 130 | # 131 | # 'pointsize': '10pt', 132 | 133 | # Additional stuff for the LaTeX preamble. 134 | # 135 | # 'preamble': '', 136 | 137 | # Latex figure (float) alignment 138 | # 139 | # 'figure_align': 'htbp', 140 | } 141 | 142 | # Grouping the document tree into LaTeX files. List of tuples 143 | # (source start file, target name, title, 144 | # author, documentclass [howto, manual, or own class]). 145 | latex_documents = [ 146 | (master_doc, 'pyshorteners.tex', 'pyshorteners Documentation', 147 | 'Ellison Leão', 'manual'), 148 | ] 149 | 150 | 151 | # -- Options for manual page output ------------------------------------------ 152 | 153 | # One entry per manual page. List of tuples 154 | # (source start file, name, description, authors, manual section). 155 | man_pages = [ 156 | (master_doc, 'pyshorteners', 'pyshorteners Documentation', 157 | [author], 1) 158 | ] 159 | 160 | 161 | # -- Options for Texinfo output ---------------------------------------------- 162 | 163 | # Grouping the document tree into Texinfo files. List of tuples 164 | # (source start file, target name, title, author, 165 | # dir menu entry, description, category) 166 | texinfo_documents = [ 167 | (master_doc, 'pyshorteners', 'pyshorteners Documentation', 168 | author, 'pyshorteners', 'One line description of project.', 169 | 'Miscellaneous'), 170 | ] 171 | 172 | 173 | # -- Extension configuration ------------------------------------------------- 174 | 175 | # Enable references to other Sphinx generated documentation websites. 176 | intersphinx_mapping = { 177 | "requests": ("http://requests.kennethreitz.org/en/master/", None) 178 | } 179 | 180 | # The number of seconds for timeout. The default is ``None``, meaning do not 181 | # timeout. 182 | intersphinx_timeout = 5 183 | subprocess.run( 184 | "sphinx-apidoc --force --module-first --output-dir apis ../pyshorteners/", check=True, shell=True 185 | ) -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | CONTRIBUTING to pyshorteners 2 | ============================ 3 | 4 | First of all, thanks for your intention to help with this project. It 5 | was built while i was learning some python magic features and it really 6 | makes me happy that you also want to be part of this. 7 | 8 | Some steps to make our lives easier: 9 | 10 | 1. Before start making any code changes, please open an issue or check 11 | if your feature/bugfix is already being handled. 12 | 2. Please always make your changes on a separated branch, you choose the 13 | name of it. 14 | 3. Please follow PEP8. 15 | 4. Make sure ``make test`` passes before sending the Pull request. 16 | 17 | Thanks for your help and let me buy you a 🍺 sometime 18 | 19 | Building a new Shortener 20 | ------------------------ 21 | 22 | If you want to build another implementation of a shortener API, you 23 | basically need to: 24 | 25 | 1. Create a new module under the ``shorteners`` folder with the 26 | shortener api name (e.g: ``adfly.py``) 27 | 2. Create a ``Shortener`` class inheriting from ``BaseShortener`` 28 | (``pyshorteners.base.BaseShortener``) 29 | 3. add the ``api_url`` property with the API url 30 | 4. Implement ``short`` and ``expand`` methods 31 | 5. You can add custom methods if you want. Just make sure to document 32 | it. 33 | 6. Add docstring for the new ``Shortener`` class following `Google 34 | Style`_ 35 | 36 | Example: 37 | 38 | .. code:: python 39 | 40 | # yourapi.py 41 | from pyshorteners.base import BaseShortener 42 | 43 | class Shortener(BaseShortener): 44 | """ 45 | Docstring 46 | """ 47 | api_url = 'http://the/link/for/the/api' 48 | 49 | def short(self, url): 50 | pass 51 | 52 | def expand(self, url): 53 | pass 54 | 55 | def custom_method(self): 56 | pass 57 | 58 | Then, to use this new shortener, just try: 59 | 60 | .. code:: python 61 | 62 | 63 | >>> import pyshorteners 64 | >>> s = Shortener() 65 | >>> s.yourapi.short('http://some.url') 66 | 'result' 67 | >>> s.yourapi.expand('http://some.url') 68 | 'result2' 69 | >>> s.yourapi.custom_method() 70 | 71 | Check out the `current implementations`_ for more info 72 | 73 | Precommit Hooks 74 | --------------- 75 | 76 | This project uses the `pre-commit`_ project to manage git pre-commit 77 | hooks, that means hooks will be run before commiting that at the moment 78 | check for pylint and black style rules. 79 | 80 | If you are following this guide and ran ``make test`` then there is 81 | nothign needed to enable this behavior, pre-commits area already 82 | installed. 83 | 84 | If you are not following this guide (you should) then you can enable 85 | pre-commit like 86 | 87 | .. code:: sh 88 | 89 | $ pip install pre-commit 90 | $ pre-commit install 91 | 92 | .. _Google Style: https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings 93 | .. _current implementations: https://github.com/ellisonleao/pyshorteners/tree/master/pyshorteners/shorteners 94 | .. _pre-commit: https://pre-commit.com 95 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to pyshorteners documentation 2 | ===================================== 3 | 4 | `pyshorteners` is a Python lib to help you short and expand urls using the most famous URL Shorteners availables. 5 | 6 | With pyshorteners , generate a short url or expand another one is as easy as typing 7 | 8 | .. code-block:: python 9 | 10 | import pyshorteners 11 | 12 | s = pyshorteners.Shortener() 13 | print(s.tinyurl.short('http://www.g1.com.br')) 14 | 15 | 16 | To install pyshorteners just grab it directly from PyPI:: 17 | 18 | pip install pyshorteners 19 | 20 | 21 | 22 | Contents 23 | -------- 24 | 25 | .. toctree:: 26 | 27 | apis 28 | contributing 29 | apis/modules.rst 30 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from pyshorteners import Shortener 3 | 4 | 5 | def hello(): 6 | s = Shortener(timeout=5) 7 | print( 8 | f""" 9 | Hello World! Testing google.com for some shorteners 10 | 11 | Results 12 | ======= 13 | - TinyURL - {s.tinyurl.short('http://www.google.com')} 14 | - Chilp.it - {s.chilpit.short('http://www.google.com')} 15 | - Clck.ru - {s.clckru.short('http://www.google.com')} 16 | - Da.gd - {s.dagd.short('http://www.google.com')} 17 | - Git.io - {s.gitio.short('https://www.github.com/ellisonleao/sharer.js')} 18 | - Is.gd - {s.isgd.short('http://www.google.com')} 19 | - NullPointer - {s.nullpointer.short('http://www.google.com')} 20 | - Osdb.link - {s.osdb.short('http://www.google.com')} 21 | - Qps.ru - {s.qpsru.short('www.google.com')} 22 | """ 23 | ) 24 | 25 | 26 | if __name__ == "__main__": 27 | hello() 28 | -------------------------------------------------------------------------------- /pyshorteners/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import importlib 3 | import pkgutil 4 | 5 | logger = logging.getLogger(__name__) 6 | __version__ = "1.0.1" 7 | __author__ = "Ellison Leão" 8 | __email__ = "ellisonleao@gmail.com" 9 | __license__ = "GPLv3" 10 | 11 | 12 | class Shortener(object): 13 | """Base Factory class to create shoreteners instances 14 | 15 | >>> s = Shortener(**kwargs) 16 | >>> instance = s.shortener_name 17 | >>> instance.short('http://www.google.com') 18 | 'http://short.url/' 19 | 20 | Available Shorteners can be seen with: 21 | 22 | >>> s = Shortener() 23 | >>> print(s.available_shorteners) 24 | """ 25 | 26 | def __init__(self, **kwargs): 27 | self.kwargs = kwargs 28 | # validate some required fields 29 | self.kwargs["debug"] = bool(kwargs.pop("debug", False)) 30 | self.kwargs["timeout"] = int(kwargs.pop("timeout", 2)) 31 | self.kwargs["verify"] = bool(kwargs.pop("verify", True)) 32 | module = importlib.import_module("pyshorteners.shorteners") 33 | self.available_shorteners = [ 34 | i.name for i in pkgutil.iter_modules(module.__path__) 35 | ] 36 | 37 | def __getattr__(self, attr): 38 | if attr not in self.available_shorteners: 39 | return self.__getattribute__(attr) 40 | 41 | # get instance of shortener class 42 | short_module = importlib.import_module( 43 | "{}.{}".format("pyshorteners.shorteners", attr) 44 | ) 45 | instance = getattr(short_module, "Shortener")(**self.kwargs) 46 | 47 | return instance 48 | -------------------------------------------------------------------------------- /pyshorteners/base.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import re 3 | 4 | from .exceptions import BadURLException, ExpandingErrorException 5 | 6 | URL_RE = re.compile( 7 | r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.]" 8 | r"[a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)" 9 | r"))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()" 10 | r'\[\]{};:\'".,<>?«»“”‘’]))' 11 | ) 12 | 13 | 14 | class BaseShortener: 15 | """Base Class for all shorteners. 16 | 17 | Keyword Args: 18 | proxies (dict, optional): Web proxy configuration for :ref:`Requests 19 | Proxies `. 20 | timeout (int, optional): Seconds before request is killed. 21 | verify (bool, str, optional): SSL Certificate verification for 22 | :ref:`Requests Verification `. 23 | 24 | Example: 25 | >>> class NewShortener(BaseShortener): 26 | ... api_url = 'http://the/link/for/the/api' 27 | ... def short(self, url): 28 | ... pass 29 | ... def expand(self, url): 30 | ... pass 31 | ... def custom_method(self): 32 | ... pass 33 | 34 | """ 35 | 36 | def __init__(self, **kwargs): 37 | for key, item in list(kwargs.items()): 38 | setattr(self, key, item) 39 | 40 | # safe check 41 | self.timeout = getattr(self, "timeout", 2) 42 | self.verify = getattr(self, "verify", True) 43 | self.proxies = getattr(self, "proxies", {}) 44 | self.cert = getattr(self, "cert", None) 45 | 46 | def _get(self, url, params=None, headers=None): 47 | """Wrap a GET request with a url check. 48 | 49 | Args: 50 | url (str): URL shortener address. 51 | 52 | Keyword Args: 53 | headers (dict): HTTP headers to add, `Requests Custom Headers`_. 54 | params (dict): URL parameters, `Requests Parameters`_. 55 | 56 | .. _Requests Custom Headers: http://requests.kennethreitz.org/en/master/user/quickstart/#custom-headers 57 | .. _Requests Parameters: http://requests.kennethreitz.org/en/master/user/quickstart/#passing-parameters-in-urls 58 | 59 | Returns: 60 | requests.Response: HTTP response. 61 | 62 | """ 63 | url = self.clean_url(url) 64 | response = requests.get( 65 | url, 66 | params=params, 67 | verify=self.verify, 68 | timeout=self.timeout, 69 | headers=headers, 70 | proxies=self.proxies, 71 | cert=self.cert, 72 | ) 73 | return response 74 | 75 | def _post(self, url, data=None, json=None, params=None, headers=None): 76 | """Wrap a POST request with a url check. 77 | 78 | Args: 79 | url (str): URL shortener address. 80 | 81 | Keyword Args: 82 | data (dict, str): Form-encoded data, `Requests POST Data`_. 83 | headers (dict): HTTP headers to add, `Requests Custom Headers`_. 84 | json (dict): Python object to JSON encode for data, `Requests 85 | POST Data`_. 86 | params (dict): URL parameters, `Requests Parameters`_. 87 | 88 | .. _Requests Custom Headers: http://requests.kennethreitz.org/en/master/user/quickstart/#custom-headers 89 | .. _Requests Parameters: http://requests.kennethreitz.org/en/master/user/quickstart/#passing-parameters-in-urls 90 | .. _Requests POST Data: http://requests.kennethreitz.org/en/master/user/quickstart/#more-complicated-post-requests 91 | 92 | Returns: 93 | requests.Response: HTTP response. 94 | 95 | """ 96 | url = self.clean_url(url) 97 | response = requests.post( 98 | url, 99 | data=data, 100 | json=json, 101 | params=params, 102 | headers=headers, 103 | timeout=self.timeout, 104 | verify=self.verify, 105 | proxies=self.proxies, 106 | cert=self.cert, 107 | ) 108 | return response 109 | 110 | def short(self, url): 111 | """Shorten URL using a shortening service. 112 | 113 | Args: 114 | url (str): URL to shorten. 115 | 116 | Raises: 117 | NotImplementedError: Subclass must override. 118 | 119 | """ 120 | raise NotImplementedError 121 | 122 | def expand(self, url): 123 | """Expand URL using a shortening service. 124 | 125 | Only visits the link, and returns the response url. 126 | 127 | Args: 128 | url (str): URL to shorten. 129 | 130 | Raises: 131 | ExpandingErrorException: URL failed to expand. 132 | 133 | """ 134 | url = self.clean_url(url) 135 | response = self._get(url) 136 | if response.ok: 137 | return response.url 138 | raise ExpandingErrorException 139 | 140 | @staticmethod 141 | def clean_url(url): 142 | """URL validation. 143 | 144 | Args: 145 | url (str): URL to shorten. 146 | 147 | Raises: 148 | BadURLException: URL is not valid. 149 | 150 | """ 151 | if not url.startswith(("http://", "https://")): 152 | url = f"http://{url}" 153 | 154 | if not URL_RE.match(url): 155 | raise BadURLException(f"{url} is not valid") 156 | 157 | return url 158 | -------------------------------------------------------------------------------- /pyshorteners/exceptions.py: -------------------------------------------------------------------------------- 1 | class ShorteningErrorException(Exception): 2 | def __init__(self, message=None): 3 | super().__init__(f'There was an error on trying to short the url: ' 4 | f'{message}') 5 | 6 | 7 | class ExpandingErrorException(Exception): 8 | def __init__(self, message=None): 9 | super().__init__(f'There was an error on trying to expand the url: ' 10 | f'{message}') 11 | 12 | 13 | class BadAPIResponseException(Exception): 14 | def __init__(self, message): 15 | super().__init__(f'Error on API Response: {message}') 16 | 17 | 18 | class BadURLException(Exception): 19 | def __init__(self, message): 20 | super().__init__(f'URL is not valid: {message}') 21 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ellisonleao/pyshorteners/940bde19fb594cd8b7d102c6750bb6344997aa52/pyshorteners/shorteners/__init__.py -------------------------------------------------------------------------------- /pyshorteners/shorteners/adfly.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from ..exceptions import ( 4 | ShorteningErrorException, 5 | BadAPIResponseException, 6 | ExpandingErrorException, 7 | ) 8 | from ..base import BaseShortener 9 | 10 | 11 | class Shortener(BaseShortener): 12 | """Adf.ly implementation. 13 | 14 | Args: 15 | api_key (str): adf.ly API key. 16 | user_id (str): adf.ly user id. 17 | domain (str, optional): Domain used upon shortening, options are: 18 | 19 | - ``ad.fly`` (default) 20 | - ``q.gs`` 21 | - ``custom.com`` 22 | - ``0`` (Random domain) 23 | 24 | type (int, optional): For advertising on the shortened link, options 25 | are: 26 | 27 | - ``1``, ``int``, ``interstitial`` - Interstitial advertising 28 | - ``2`` - No advertising 29 | - ``3``, ``banner`` - Framed Banner 30 | 31 | group_id (int, optional): API parameter `group_id`. 32 | 33 | Example: 34 | >>> import pyshorteners 35 | >>> s = pyshorteners.Shortener(api_key='YOUR_KEY', user_id='USER_ID', 36 | domain='test.us', group_id=12, type='int') 37 | >>> s.adfly.short('http://www.google.com') 38 | 'http://test.us/TEST' 39 | 40 | """ 41 | 42 | api_url = "http://api.adf.ly/v1" 43 | 44 | def short(self, url): 45 | """Short implementation for Adf.ly. 46 | 47 | Args: 48 | url (str): The URL you want to shorten. 49 | 50 | Returns: 51 | str: The shortened URL. 52 | 53 | Raises: 54 | BadAPIResponseException: If the data is malformed or we got a bad 55 | status code on API response. 56 | ShorteningErrorException: If the API Returns an error as response. 57 | 58 | """ 59 | url = self.clean_url(url) 60 | shorten_url = f"{self.api_url}/shorten" 61 | payload = { 62 | "domain": getattr(self, "domain", "adf.ly"), 63 | "advert_type": getattr(self, "type", "int"), 64 | "group_id": getattr(self, "group_id", None), 65 | "key": self.api_key, 66 | "user_id": self.user_id, 67 | "url": url, 68 | } 69 | response = self._post(shorten_url, data=payload) 70 | if not response.ok: 71 | raise BadAPIResponseException(response.content) 72 | 73 | try: 74 | data = response.json() 75 | except json.decoder.JSONDecodeError: 76 | raise BadAPIResponseException("API response could not be decoded") 77 | 78 | if data.get("errors"): 79 | errors = ",".join(i["msg"] for i in data["errors"]) 80 | raise ShorteningErrorException(errors) 81 | 82 | if not data.get("data"): 83 | raise BadAPIResponseException(response.content) 84 | 85 | return data["data"][0]["short_url"] 86 | 87 | def expand(self, url): 88 | """Expand implementation for Adf.ly. 89 | 90 | Args: 91 | url (str): The URL you want to expand. 92 | 93 | Returns: 94 | str: The expanded URL. 95 | 96 | Raises: 97 | BadAPIResponseException: If the data is malformed or we got a bad 98 | status code on API response. 99 | ExpandingErrorException: If the API Returns an error as response. 100 | 101 | """ 102 | url = self.clean_url(url) 103 | expand_url = f"{self.api_url}/expand" 104 | payload = { 105 | "domain": getattr(self, "domain", "adf.ly"), 106 | "advert_type": getattr(self, "type", "int"), 107 | "group_id": getattr(self, "group_id", None), 108 | "key": self.api_key, 109 | "user_id": self.user_id, 110 | "url": url, 111 | } 112 | response = self._post(expand_url, data=payload) 113 | if not response.ok: 114 | raise BadAPIResponseException(response.content) 115 | 116 | try: 117 | data = response.json() 118 | except json.decoder.JSONDecodeError: 119 | raise BadAPIResponseException("API response could not be decoded") 120 | 121 | if data.get("errors"): 122 | errors = ",".join(i["msg"] for i in data["errors"]) 123 | raise ExpandingErrorException(errors) 124 | 125 | if not data.get("data"): 126 | raise BadAPIResponseException(response.content) 127 | 128 | return data["data"][0]["url"] 129 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/bitly.py: -------------------------------------------------------------------------------- 1 | import json 2 | from urllib.parse import urlparse 3 | import logging 4 | 5 | from ..base import BaseShortener 6 | from ..exceptions import ( 7 | BadAPIResponseException, 8 | ExpandingErrorException, 9 | ShorteningErrorException, 10 | ) 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | class Shortener(BaseShortener): 16 | """Bit.ly shortener Implementation 17 | 18 | Args: 19 | api_key (str): bit.ly API key 20 | 21 | Example: 22 | 23 | >>> import pyshorteners 24 | >>> s = pyshorteners.Shortener(api_key='YOUR_KEY') 25 | >>> s.bitly.short('http://www.google.com') 26 | 'http://bit.ly/TEST' 27 | >>> s.bitly.expand('https://bit.ly/TEST') 28 | 'http://www.google.com' 29 | >>> s.bitly.total_clicks('https://bit.ly/TEST') 30 | 10 31 | """ 32 | 33 | api_url = "https://api-ssl.bit.ly/v4" 34 | 35 | def short(self, url): 36 | """Short implementation for Bit.ly 37 | Args: 38 | url (str): the URL you want to shorten 39 | 40 | Returns: 41 | str: The shortened URL. 42 | 43 | Raises: 44 | BadAPIResponseException: If the data is malformed or we got a bad 45 | status code on API response. 46 | ShorteningErrorException: If the API Returns an error as response 47 | """ 48 | self.clean_url(url) 49 | shorten_url = f"{self.api_url}/shorten" 50 | params = {"long_url": url} 51 | headers = {"Authorization": f"Bearer {self.api_key}"} 52 | response = self._post(shorten_url, json=params, headers=headers) 53 | if not response.ok: 54 | raise ShorteningErrorException(response.content) 55 | 56 | try: 57 | data = response.json() 58 | except json.decoder.JSONDecodeError: 59 | raise BadAPIResponseException("API response could not be decoded") 60 | 61 | return data["link"] 62 | 63 | def expand(self, url): 64 | """Expand implementation for Bit.ly 65 | Args: 66 | url (str): The URL you want to expand. 67 | 68 | Returns: 69 | str: The expanded URL. 70 | 71 | Raises: 72 | ExpandingErrorException: If the API Returns an error as response. 73 | BadAPIResponseException: If the API response can't be decoded. 74 | """ 75 | self.clean_url(url) 76 | url = "".join(urlparse(url)[1:3]) 77 | expand_url = f"{self.api_url}/expand" 78 | params = {"bitlink_id": url} 79 | headers = {"Authorization": f"Bearer {self.api_key}"} 80 | response = self._post(expand_url, json=params, headers=headers) 81 | if not response.ok: 82 | raise ExpandingErrorException(response.content) 83 | 84 | try: 85 | data = response.json() 86 | except json.decoder.JSONDecodeError: 87 | raise BadAPIResponseException("API response could not be decoded") 88 | 89 | return data["long_url"] 90 | 91 | def total_clicks(self, url): 92 | """Total clicks implementation for Bit.ly 93 | Args: 94 | url (str): the URL you want to get the total clicks count 95 | 96 | Returns: 97 | int: The total clicks count 98 | 99 | Raises: 100 | BadAPIResponseException: If the API Returns an error as response 101 | """ 102 | self.clean_url(url) 103 | url = "".join(urlparse(url)[1:3]) 104 | clicks_url = f"{self.api_url}/bitlinks/{url}/clicks" 105 | headers = {"Authorization": f"Bearer {self.api_key}"} 106 | response = self._get(clicks_url, headers=headers) 107 | if not response.ok: 108 | raise BadAPIResponseException(response.content) 109 | 110 | try: 111 | data = response.json() 112 | except json.decoder.JSONDecodeError: 113 | raise BadAPIResponseException("API response could not be decoded") 114 | 115 | total_clicks = 0 116 | try: 117 | for click in data["link_clicks"]: 118 | total_clicks += click["clicks"] 119 | except (KeyError, TypeError) as e: 120 | logger.warning("Bad value from total_clicks response: %s", e) 121 | return 0 122 | 123 | return total_clicks 124 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/chilpit.py: -------------------------------------------------------------------------------- 1 | from ..base import BaseShortener 2 | from ..exceptions import ShorteningErrorException 3 | 4 | 5 | class Shortener(BaseShortener): 6 | """ 7 | Chilp.it shortener implementation 8 | 9 | Example: 10 | 11 | >>> import pyshorteners 12 | >>> s = pyshorteners.Shortener() 13 | >>> s.chilpit.short('http://www.google.com') 14 | 'http://chilp.it/TEST' 15 | >>> s.chilpit.expand('http://chilp.it/TEST') 16 | 'http://www.google.com' 17 | """ 18 | 19 | api_url = "http://chilp.it/api.php" 20 | 21 | def short(self, url): 22 | """Short implementation for Chilp.it 23 | 24 | Args: 25 | url: the URL you want to shorten 26 | 27 | Returns: 28 | A string containing the shortened URL 29 | 30 | Raises: 31 | ShorteningErrorException: If the API returns an error as response 32 | """ 33 | response = self._get(self.api_url, params={"url": url}) 34 | if response.ok: 35 | return response.text.strip() 36 | raise ShorteningErrorException(response.content) 37 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/clckru.py: -------------------------------------------------------------------------------- 1 | from ..base import BaseShortener 2 | from ..exceptions import ShorteningErrorException 3 | 4 | 5 | class Shortener(BaseShortener): 6 | """ 7 | Clck.ru shortener implementation 8 | 9 | Example: 10 | 11 | >>> import pyshorteners 12 | >>> s = pyshorteners.Shortener() 13 | >>> s.clckru.short('http://www.google.com') 14 | 'http://clck.ru/TEST' 15 | >>> s.clckru.expand('http://clck.ru/TEST') 16 | 'http://www.google.com' 17 | 18 | """ 19 | 20 | api_url = "https://clck.ru/--" 21 | 22 | def short(self, url): 23 | """Short implementation for Clck.ru 24 | 25 | Args: 26 | url: the URL you want to shorten 27 | 28 | Returns: 29 | A string containing the shortened URL 30 | 31 | Raises: 32 | ShorteningErrorException: If the API returns an error as response 33 | """ 34 | 35 | response = self._get(self.api_url, params={"url": url}) 36 | if response.ok: 37 | return response.text.strip() 38 | raise ShorteningErrorException(response.content) 39 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/cuttly.py: -------------------------------------------------------------------------------- 1 | import json 2 | from pyshorteners.base import BaseShortener 3 | from pyshorteners.exceptions import BadAPIResponseException 4 | 5 | 6 | class Shortener(BaseShortener): 7 | """ 8 | Cutt.ly shortener implementation 9 | 10 | Args: 11 | api_key (str): cutt.ly API key 12 | 13 | Example: 14 | 15 | >>> import pyshorteners 16 | >>> s = pyshorteners.Shortener(api_key='YOUR_KEY') 17 | >>> s.cuttly.short('http://www.google.com') 18 | 'http://cutt.ly/TEST' 19 | >>> s.cuttly.expand('https://cutt.ly/TEST') 20 | 'http://www.google.com' 21 | """ 22 | 23 | api_url = "https://cutt.ly/api/api.php" 24 | STATUS_INVALID = 4 25 | 26 | def short(self, url): 27 | """Short implementation for Cutt.ly 28 | Args: 29 | url (str): the URL you want to shorten 30 | 31 | Returns: 32 | str: The shortened URL. 33 | 34 | Raises: 35 | BadAPIResponseException: If the data is malformed or we got a bad 36 | status code on API response. 37 | ShorteningErrorException: If the API Returns an error as response 38 | """ 39 | url = self.clean_url(url) 40 | response = self._get(self.api_url, params={"key": self.api_key, "short": url}) 41 | try: 42 | data = response.json() 43 | except json.decoder.JSONDecodeError: 44 | raise BadAPIResponseException( 45 | "API response is invalid ,could not be decoded" 46 | ) 47 | 48 | try: 49 | status = data["url"]["status"] 50 | except KeyError: 51 | raise BadAPIResponseException( 52 | "API response does not have the required field: status" 53 | ) 54 | 55 | if status == self.STATUS_INVALID: 56 | """According to the API Docs when a status code of 4 is returned with 57 | json an Invalid API Key is provided""" 58 | raise BadAPIResponseException("Invalid API Key") 59 | 60 | try: 61 | short_link = data["url"]["shortLink"] 62 | except KeyError: 63 | raise BadAPIResponseException( 64 | "API response does not have the required field: shortLink" 65 | ) 66 | 67 | return short_link 68 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/dagd.py: -------------------------------------------------------------------------------- 1 | from ..base import BaseShortener 2 | from ..exceptions import ShorteningErrorException, ExpandingErrorException 3 | 4 | 5 | class Shortener(BaseShortener): 6 | """ 7 | Da.gd shortener implementation 8 | 9 | Example: 10 | 11 | >>> import pyshorteners 12 | >>> s = pyshorteners.Shortener() 13 | >>> s.dagd.short('http://www.google.com') 14 | 'http://da.gd/TEST' 15 | >>> s.dagd.expand('http://da.gd/TEST') 16 | 'http://www.google.com' 17 | """ 18 | 19 | api_url = "https://da.gd/" 20 | 21 | def short(self, url): 22 | """Short implementation for Da.gd 23 | Args: 24 | url (str): the URL you want to shorten 25 | 26 | Returns: 27 | str: The shortened URL. 28 | 29 | Raises: 30 | ShorteningErrorException: If the API Returns an error as response 31 | """ 32 | url = self.clean_url(url) 33 | shorten_url = f"{self.api_url}shorten" 34 | response = self._get(shorten_url, params={"url": url}) 35 | if not response.ok: 36 | raise ShorteningErrorException(response.content) 37 | return response.text.strip() 38 | 39 | def expand(self, url): 40 | """Expand implementation for Da.gd 41 | Args: 42 | url (str): The URL you want to expand. 43 | 44 | Returns: 45 | str: The expanded URL. 46 | 47 | Raises: 48 | ExpandingErrorException: If the API Returns an error as response. 49 | """ 50 | 51 | url = self.clean_url(url) 52 | # da.gd's coshorten expects only the shorturl identifier 53 | # (i.e. the "stuff" in http://da.gd/stuff), not the full short URL. 54 | sanitized_url = url.split("da.gd/", 1)[-1] 55 | expand_url = f"{self.api_url}coshortern/{sanitized_url}" 56 | response = self._get(expand_url) 57 | if not response.ok: 58 | raise ExpandingErrorException(response.content) 59 | return response.text.strip() 60 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/gitio.py: -------------------------------------------------------------------------------- 1 | from pyshorteners.base import BaseShortener 2 | from pyshorteners.exceptions import ShorteningErrorException 3 | 4 | 5 | class Shortener(BaseShortener): 6 | """Git.io shortener Implementation 7 | 8 | Example: 9 | 10 | >>> import pyshorteners 11 | >>> s = pyshorteners.Shortener(code='12345') 12 | >>> s.gitio.short('https://github.com/TEST') 13 | 'https://git.io/12345' 14 | >>> s.gitio.expand('https://git.io/12345') 15 | 'https://github.com/TEST' 16 | """ 17 | 18 | api_url = "https://git.io" 19 | 20 | def short(self, url): 21 | """Short implementation for Git.io 22 | Only works for github urls 23 | 24 | Args: 25 | url (str): the URL you want to shorten 26 | code (str): (Optional) Custom permalink code: Eg.: test 27 | 28 | Returns: 29 | str: The shortened URL 30 | 31 | Raises: 32 | ShorteningErrorException: If the API returns an error as response 33 | """ 34 | code = None 35 | try: 36 | code = self.code 37 | except AttributeError: 38 | pass 39 | 40 | shorten_url = self.api_url 41 | data = {"url": url, "code": code} 42 | response = self._post(shorten_url, data=data) 43 | if not response.ok: 44 | raise ShorteningErrorException(response.content) 45 | 46 | if not response.headers.get("Location"): 47 | raise ShorteningErrorException(response.content) 48 | 49 | return response.headers["Location"] 50 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/isgd.py: -------------------------------------------------------------------------------- 1 | from ..base import BaseShortener 2 | from ..exceptions import ShorteningErrorException 3 | 4 | 5 | class Shortener(BaseShortener): 6 | """ 7 | Is.gd shortener implementation 8 | 9 | Example: 10 | 11 | >>> import pyshorteners 12 | >>> s = pyshorteners.Shortener() 13 | >>> s.isgd.short('http://www.google.com') 14 | 'http://is.gd/TEST' 15 | >>> s.isgd.expand('http://is.gd/TEST') 16 | 'http://www.google.com' 17 | 18 | """ 19 | 20 | api_url = "https://is.gd/create.php" 21 | 22 | def short(self, url): 23 | """Short implementation for Is.gd 24 | 25 | Args: 26 | url: the URL you want to shorten 27 | 28 | Returns: 29 | A string containing the shortened URL 30 | 31 | Raises: 32 | ShorteningErrorException: If the API returns an error as response 33 | """ 34 | 35 | url = self.clean_url(url) 36 | params = {"format": "simple", "url": url} 37 | response = self._get(self.api_url, params=params) 38 | if response.ok: 39 | return response.text.strip() 40 | raise ShorteningErrorException(response.content) 41 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/nullpointer.py: -------------------------------------------------------------------------------- 1 | from ..exceptions import ShorteningErrorException 2 | from ..base import BaseShortener 3 | 4 | 5 | class Shortener(BaseShortener): 6 | """The Null Pointer implementation 7 | 8 | Args: 9 | domain (str): Optional string for the null pointer instance to use. Default is 10 | 'https://0x0.st'. Any URL to a Null Pointer instance is supported, 11 | for example: 12 | 13 | - ``https://0x0.st`` 14 | - ``https://ttm.sh`` 15 | 16 | Example: 17 | 18 | >>> import pyshorteners 19 | >>> s = pyshorteners.Shortener(domain='https://0x0.st') 20 | >>> s.nullpointer.short('https://www.google.com') 21 | 'https://0x0.st/jU' 22 | """ 23 | 24 | def short(self, url): 25 | """Short implementation for The Null Pointer 26 | Args: 27 | url (str): the URL you want to shorten 28 | 29 | Returns: 30 | str: The shortened URL 31 | 32 | Raises: 33 | ShorteningErrorException: If the data is malformed or we got a bad 34 | status code on API response 35 | """ 36 | url = self.clean_url(url) 37 | api_url = self.clean_url(getattr(self, "domain", "https://0x0.st")) 38 | payload = {"shorten": url} 39 | 40 | response = self._post(api_url, data=payload) 41 | 42 | if not response.ok: 43 | raise ShorteningErrorException(response.content) 44 | 45 | return response.text 46 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/osdb.py: -------------------------------------------------------------------------------- 1 | from html.parser import HTMLParser 2 | 3 | from ..base import BaseShortener 4 | from ..exceptions import ShorteningErrorException 5 | 6 | 7 | class OHTMLParser(HTMLParser): 8 | def __init__(self): 9 | self.found = False 10 | self.val = None 11 | return HTMLParser.__init__(self) 12 | 13 | def handle_starttag(self, tag, attrs): 14 | attrs = dict(attrs) 15 | 16 | if "id" in attrs and attrs["id"] == "surl": 17 | self.found = True 18 | 19 | def handle_data(self, data): 20 | if not self.found: 21 | return 22 | 23 | if data.startswith("http://osdb"): 24 | self.val = data 25 | 26 | 27 | class Shortener(BaseShortener): 28 | """ 29 | Os.db shortener implementation 30 | 31 | Example: 32 | 33 | >>> import pyshorteners 34 | >>> s = pyshorteners.Shortener() 35 | >>> s.osdb.short('http://www.google.com') 36 | 'https://osdb.link/TEST' 37 | >>> s.osdb.expand('http://osdb.link/TEST') 38 | 'https://www.google.com' 39 | """ 40 | 41 | api_url = "https://osdb.link/" 42 | 43 | def short(self, url): 44 | """Short implementation for Os.db 45 | 46 | Args: 47 | url: the URL you want to shorten 48 | 49 | Returns: 50 | A string containing the shortened URL 51 | 52 | Raises: 53 | ShorteningErrorException: If the API returns an error as response 54 | """ 55 | url = self.clean_url(url) 56 | response = self._post(self.api_url, data={"url": url}) 57 | if not response.ok: 58 | raise ShorteningErrorException(response.content) 59 | p = OHTMLParser() 60 | p.feed(response.text) 61 | 62 | if not p.val: 63 | raise ShorteningErrorException("Could not find osdb.link") 64 | 65 | return p.val 66 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/owly.py: -------------------------------------------------------------------------------- 1 | from ..base import BaseShortener 2 | from ..exceptions import ( 3 | ShorteningErrorException, 4 | ExpandingErrorException, 5 | BadAPIResponseException, 6 | ) 7 | 8 | 9 | class Shortener(BaseShortener): 10 | """ 11 | Ow.ly url shortner api implementation 12 | 13 | Example: 14 | 15 | >>> import pyshorteners 16 | >>> s = pyshorteners.Shortener() 17 | >>> s.owly.short('http://www.google.com') 18 | 'http://ow.ly/TEST' 19 | >>> s.owly.expand('http://ow.ly/TEST') 20 | 'http://www.google.com' 21 | """ 22 | 23 | api_url = "http://ow.ly/api/1.1/url/" 24 | 25 | def short(self, url): 26 | """Short implementation for ow.ly. 27 | 28 | Args: 29 | url (str): The URL you want to shorten. 30 | 31 | Returns: 32 | str: The shortened URL. 33 | 34 | Raises: 35 | BadAPIResponseException: If the api response data could not get parsed. 36 | ShorteningErrorException: If the API Returns an error as response. 37 | """ 38 | 39 | url = self.clean_url(url) 40 | shorten_url = f"{self.api_url}shorten" 41 | params = {"apiKey": self.api_key, "longUrl": url} 42 | response = self._get(shorten_url, params=params) 43 | if not response.ok: 44 | raise ShorteningErrorException(response.content) 45 | 46 | data = response.json() 47 | if "results" not in data: 48 | raise BadAPIResponseException(f"API Returned wrong response: " f"{data}") 49 | 50 | return data["results"]["shortUrl"] 51 | 52 | def expand(self, url): 53 | """Expand implementation for ow.ly. 54 | 55 | Args: 56 | url (str): The URL you want to expand. 57 | 58 | Returns: 59 | str: The expanded URL. 60 | 61 | Raises: 62 | BadAPIResponseException: Bad response from the API. 63 | ExpandingErrorException: If the API Returns an error as response. 64 | """ 65 | 66 | url = self.clean_url(url) 67 | expand_url = f"{self.api_url}expand" 68 | data = {"apiKey": self.api_key, "shortUrl": url} 69 | response = self._get(expand_url, params=data) 70 | if not response.ok: 71 | raise ExpandingErrorException(response.content) 72 | 73 | data = response.json() 74 | if "results" not in data: 75 | raise BadAPIResponseException(f"API Returned wrong response: " f"{data}") 76 | 77 | return data["results"]["longUrl"] 78 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/post.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from ..base import BaseShortener 4 | from ..exceptions import ShorteningErrorException, BadAPIResponseException 5 | 6 | 7 | class Shortener(BaseShortener): 8 | """ 9 | Po.st Shortener implementation 10 | 11 | Args: 12 | api_key (str): adf.ly API key. 13 | 14 | Example: 15 | >>> import pyshorteners 16 | >>> s = pyshorteners.Shortener(api_key='YOUR_KEY') 17 | >>> s.post.short('http://www.google.com') 18 | 'http://po.st/TEST' 19 | >>> s.post.expand('http://po.st/TEST') 20 | 'http://www.google.com' 21 | 22 | """ 23 | 24 | api_url = "http://po.st/api/shorten" 25 | 26 | def short(self, url): 27 | """Short implementation for Po.st. 28 | 29 | Args: 30 | url (str): The URL you want to shorten. 31 | 32 | Returns: 33 | str: The shortened URL. 34 | 35 | Raises: 36 | BadAPIResponseException: If the data is malformed or we got a bad 37 | status code on API response. 38 | ShorteningErrorException: If the API Returns an error as response. 39 | 40 | """ 41 | url = self.clean_url(url) 42 | params = {"apiKey": self.api_key, "longUrl": url, "format": "txt"} 43 | response = self._get(self.api_url, params=params) 44 | if not response.ok: 45 | raise ShorteningErrorException(response.content) 46 | 47 | try: 48 | data = response.json() 49 | return data["short_url"] 50 | except json.decoder.JSONDecodeError: 51 | raise BadAPIResponseException("API response could not be decoded") 52 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/qpsru.py: -------------------------------------------------------------------------------- 1 | from ..base import BaseShortener 2 | from ..exceptions import ShorteningErrorException 3 | 4 | 5 | class Shortener(BaseShortener): 6 | """ 7 | Qps.ru shortener implementation 8 | 9 | Example: 10 | 11 | >>> import pyshorteners 12 | >>> s = pyshorteners.Shortener() 13 | >>> s.qpsru.short('http://www.google.com') 14 | 'http://qps.ru/TEST' 15 | >>> s.qpsru.expand('http://qps.ru/TEST') 16 | 'http://www.google.com' 17 | 18 | """ 19 | 20 | api_url = "http://qps.ru/api" 21 | 22 | def short(self, url): 23 | """Short implementation for Qps.ru 24 | 25 | Args: 26 | url: the URL you want to shorten 27 | 28 | Returns: 29 | A string containing the shortened URL 30 | 31 | Raises: 32 | ShorteningErrorException: If the API returns an error as response 33 | """ 34 | 35 | url = self.clean_url(url) 36 | response = self._get(self.api_url, params={"url": url}) 37 | if not response.ok: 38 | raise ShorteningErrorException(response.content) 39 | return response.text.strip() 40 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/shortcm.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlparse 2 | 3 | from ..base import BaseShortener 4 | from ..exceptions import ( 5 | ShorteningErrorException, 6 | ExpandingErrorException, 7 | BadURLException, 8 | ) 9 | 10 | 11 | class Shortener(BaseShortener): 12 | """Short.cm shortener Implementation 13 | 14 | Args: 15 | api_key (str): short.cm API key 16 | domain (str): which registered domain to create the link on 17 | 18 | Example: 19 | 20 | >>> import pyshorteners 21 | >>> s = pyshorteners.Shortener(api_key='YOUR_KEY') 22 | >>> s.shortcm.short('http://www.google.com') 23 | 'http://short.cm/TEST' 24 | >>> s.shortcm.expand('https://short.cm/test') 25 | 'http://www.google.com' 26 | >>> s.shortcm.expand('https://short.cm/test') 27 | 10 28 | """ 29 | 30 | api_url = "https://api.short.cm/links/" 31 | domain = "" 32 | api_key = "" 33 | 34 | def short(self, url): 35 | """Short implementation for Short.cm 36 | Args: 37 | url (str): the URL you want to shorten 38 | 39 | Returns: 40 | str: The shortened URL 41 | 42 | Raises: 43 | BadAPIResponseException: If the data is malformed or we got a bad 44 | status code on API response 45 | ShorteningErrorException: If the API Returns an error as response 46 | """ 47 | 48 | self.clean_url(url) 49 | json = {"originalURL": url, "domain": self.domain} 50 | headers = {"authorization": self.api_key} 51 | response = self._post(self.api_url, json=json, headers=headers) 52 | if response.ok: 53 | data = response.json() 54 | if "shortURL" not in data: 55 | raise ShorteningErrorException( 56 | f"API Returned wrong response: " f"{data}" 57 | ) 58 | return data["shortURL"] 59 | raise ShorteningErrorException(response.content) 60 | 61 | def expand(self, url): 62 | """Expand implementation for Short.cm 63 | Args: 64 | url: the short URL you want to expand 65 | 66 | Returns: 67 | str: The expanded URL 68 | 69 | Raises: 70 | ExpandingErrorException: If the API Returns an error as response 71 | """ 72 | expand_url = f"{self.api_url}expand" 73 | 74 | cleaned_url = self.clean_url(url) 75 | 76 | # split domain and path 77 | url_parsed = urlparse(cleaned_url) 78 | 79 | if url_parsed.hostname is None: 80 | raise BadURLException(f"{cleaned_url}") 81 | 82 | params = {"domain": url_parsed.hostname, "path": url_parsed.path.strip("/")} 83 | headers = {"authorization": self.api_key} 84 | response = self._get(expand_url, params=params, headers=headers) 85 | if response.ok: 86 | data = response.json() 87 | if "originalURL" not in data: 88 | raise ShorteningErrorException( 89 | f"API Returned wrong response: " f"{data}" 90 | ) 91 | return data["originalURL"] 92 | raise ExpandingErrorException(response.content) 93 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/tinycc.py: -------------------------------------------------------------------------------- 1 | from ..exceptions import ( 2 | ShorteningErrorException, 3 | ExpandingErrorException, 4 | BadAPIResponseException, 5 | ) 6 | from ..base import BaseShortener 7 | 8 | 9 | class Shortener(BaseShortener): 10 | """Tiny.cc implementation. 11 | 12 | Args: 13 | api_key (str): Tiny.cc API key. 14 | login (str): Tiny.cc username. 15 | 16 | Example: 17 | >>> import pyshorteners 18 | >>> s = pyshorteners.Shortener(api_key='12345', login='user') 19 | >>> s.tinycc.short('http://www.google.com') 20 | 'http://tiny.cc/6lbsez' 21 | 22 | """ 23 | 24 | api_url = "http://tiny.cc/" 25 | params = {"c": "rest_api", "version": "2.0.3", "format": "json"} 26 | headers = { 27 | "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux) Gecko/20100101 " "Firefox/61.0" 28 | } 29 | 30 | def short(self, url): 31 | """Short implementation for Tiny.cc. 32 | 33 | Args: 34 | url (str): The URL you want to shorten. 35 | 36 | Returns: 37 | str: The shortened URL. 38 | 39 | Raises: 40 | BadAPIResponseException: If the data is malformed or we got a bad 41 | status code on API response. 42 | ShorteningErrorException: If the API Returns an error as 43 | response. 44 | 45 | """ 46 | url = self.clean_url(url) 47 | params = self.params.copy() 48 | params.update( 49 | { 50 | "m": "shorten", 51 | "longUrl": url, 52 | "login": self.login, 53 | "apiKey": self.api_key, 54 | } 55 | ) 56 | response = self._get(self.api_url, params=params, headers=self.headers) 57 | if not response.ok: 58 | raise ShorteningErrorException(response.content) 59 | 60 | data = response.json() 61 | if not data.get("results"): 62 | raise ShorteningErrorException(data["errorMessage"]) 63 | 64 | return data["results"]["short_url"].strip() 65 | 66 | def expand(self, url): 67 | """Expand implementation for Tiny.cc. 68 | 69 | Args: 70 | url (str): The URL you want to expand. 71 | 72 | Returns: 73 | str: The expanded URL. 74 | 75 | Raises: 76 | ExpandingErrorException: If the API Returns an error as response. 77 | 78 | """ 79 | url = self.clean_url(url) 80 | params = self.params.copy() 81 | params.update( 82 | {"m": "expand", "longUrl": url, "login": self.login, "apiKey": self.api_key} 83 | ) 84 | response = self._get(self.api_url, params=params, headers=self.headers) 85 | if not response.ok: 86 | raise ExpandingErrorException(response.content) 87 | 88 | data = response.json() 89 | if not data.get("results"): 90 | raise ExpandingErrorException(data["errorMessage"]) 91 | 92 | return data["results"]["longUrl"].strip() 93 | 94 | def total_clicks(self, url): 95 | """How many times the shortened URL has been clicked on. 96 | 97 | Args: 98 | url (str): The shortened URL to examine. 99 | 100 | Returns: 101 | int: The number of times the shortened URL has been used. 102 | 103 | Raises: 104 | BadAPIResponseException: If the data is malformed or we got a bad 105 | status code on API response. 106 | 107 | """ 108 | url = self.clean_url(url) 109 | params = self.params.copy() 110 | params.update( 111 | { 112 | "m": "total_visits", 113 | "shortUrl": url, 114 | "login": self.login, 115 | "apiKey": self.api_key, 116 | } 117 | ) 118 | response = self._get(self.api_url, params=params, headers=self.headers) 119 | if not response.ok: 120 | raise BadAPIResponseException(response.content) 121 | 122 | data = response.json() 123 | if not data.get("results"): 124 | raise BadAPIResponseException(data["errorMessage"]) 125 | 126 | try: 127 | total_clicks = int(data["results"]["clicks"]) 128 | except (KeyError, TypeError): 129 | return 0 130 | return total_clicks 131 | -------------------------------------------------------------------------------- /pyshorteners/shorteners/tinyurl.py: -------------------------------------------------------------------------------- 1 | from ..base import BaseShortener 2 | from ..exceptions import ShorteningErrorException 3 | 4 | 5 | class Shortener(BaseShortener): 6 | """ 7 | TinyURL.com shortener implementation 8 | 9 | Example: 10 | 11 | >>> import pyshorteners 12 | >>> s = pyshorteners.Shortener() 13 | >>> s.tinyurl.short('http://www.google.com') 14 | 'http://tinyurl.com/TEST' 15 | >>> s.tinyurl.expand('http://tinyurl.com/test') 16 | 'http://www.google.com' 17 | """ 18 | 19 | api_url = "http://tinyurl.com/api-create.php" 20 | 21 | def short(self, url): 22 | """Short implementation for TinyURL.com 23 | 24 | Args: 25 | url: the URL you want to shorten 26 | 27 | Returns: 28 | A string containing the shortened URL 29 | 30 | Raises: 31 | ShorteningErrorException: If the API returns an error as response 32 | """ 33 | url = self.clean_url(url) 34 | response = self._get(self.api_url, params=dict(url=url)) 35 | if response.ok: 36 | return response.text.strip() 37 | raise ShorteningErrorException(response.content) 38 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 101 3 | ignore = F403,F401 4 | exclude=*.pyc,*.md,Makefile,LICENSE,CHANGELOG,MANIFEST.in,*.rst,docs,coverage.xml,setup.cfg,example.py 5 | 6 | [aliases] 7 | test=pytest 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # pylint: disable=C0114 3 | from setuptools import setup, find_packages 4 | 5 | import pyshorteners 6 | 7 | with open("README.md") as r: 8 | README = r.read() 9 | 10 | TESTS_REQUIRE = [ 11 | "flake8==3.7.7", 12 | "responses==0.10.6", 13 | "pytest==4.4.1", 14 | "pytest-cov==2.7.1", 15 | "codecov==2.0.15", 16 | "pytest-flake8", 17 | ] 18 | 19 | 20 | CLASSIFIERS = [ 21 | "Development Status :: 5 - Production/Stable", 22 | "Intended Audience :: Developers", 23 | "Operating System :: OS Independent", 24 | "Programming Language :: Python :: 3", 25 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 26 | "Topic :: Internet :: WWW/HTTP :: Dynamic Content", 27 | "Topic :: Software Development :: Libraries :: Python Modules", 28 | ] 29 | 30 | SHORT_DESC = "A Python lib to wrap and consume the most used shorteners APIs" 31 | 32 | setup( 33 | name="pyshorteners", 34 | version=pyshorteners.__version__, 35 | license=pyshorteners.__license__, 36 | description=SHORT_DESC, 37 | long_description=README, 38 | long_description_content_type="text/markdown", 39 | author=pyshorteners.__author__, 40 | author_email=pyshorteners.__email__, 41 | python_requires=">=3.6", 42 | url="https://github.com/ellisonleao/pyshorteners/", 43 | classifiers=CLASSIFIERS, 44 | install_requires=["requests"], 45 | setup_requires=["pytest-runner"], 46 | tests_require=TESTS_REQUIRE, 47 | packages=find_packages(exclude=["*tests*"]), 48 | extras_require={"dev": ["pre-commit"], "docs": ["sphinx"]}, 49 | ) 50 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ellisonleao/pyshorteners/940bde19fb594cd8b7d102c6750bb6344997aa52/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_adfly.py: -------------------------------------------------------------------------------- 1 | from pyshorteners import Shortener 2 | from pyshorteners.exceptions import BadAPIResponseException 3 | 4 | import responses 5 | import pytest 6 | 7 | s = Shortener(user_id="TEST", api_key="TEST_KEY") 8 | shorten = "http://ad.fly/test" 9 | expanded = "http://www.test.com" 10 | adfly = s.adfly 11 | 12 | 13 | @responses.activate 14 | def test_adfly_short_method(): 15 | # mock responses 16 | response = {"errors": [], "data": [{"short_url": shorten}]} 17 | mock_url = f"{adfly.api_url}/shorten" 18 | responses.add(responses.POST, mock_url, json=response) 19 | 20 | shorten_result = s.adfly.short(expanded) 21 | 22 | assert shorten_result == shorten 23 | 24 | 25 | @responses.activate 26 | def test_adfly_short_method_bad_response(): 27 | # mock responses 28 | mock_url = f"{adfly.api_url}/shorten" 29 | responses.add(responses.POST, mock_url, status=400) 30 | 31 | with pytest.raises(BadAPIResponseException): 32 | adfly.short(expanded) 33 | 34 | 35 | @responses.activate 36 | def test_adfly_expand_method(): 37 | # mock responses 38 | response = {"errors": [], "data": [{"url": expanded}]} 39 | mock_url = f"{adfly.api_url}/expand" 40 | responses.add(responses.POST, mock_url, json=response) 41 | 42 | expand_result = s.adfly.expand(shorten) 43 | 44 | assert expand_result == expanded 45 | 46 | 47 | @responses.activate 48 | def test_adfly_expand_method_bad_response(): 49 | # mock responses 50 | mock_url = f"{adfly.api_url}/expand" 51 | responses.add(responses.POST, mock_url, status=400) 52 | 53 | with pytest.raises(BadAPIResponseException): 54 | adfly.expand(expanded) 55 | -------------------------------------------------------------------------------- /tests/test_base.py: -------------------------------------------------------------------------------- 1 | from pyshorteners.base import BaseShortener 2 | from pyshorteners.exceptions import BadURLException, ExpandingErrorException 3 | 4 | import pytest 5 | 6 | 7 | def test_base_init_params_become_properties(): 8 | # pylint: disable=E1101 9 | shortener = BaseShortener(a=1, b=2) 10 | assert shortener.a == 1 11 | assert shortener.b == 2 12 | # check default params 13 | assert shortener.timeout == 2 14 | assert shortener.verify is True 15 | 16 | 17 | def test_base_clean_url_method(): 18 | # good 19 | url = "www.google.com" 20 | assert BaseShortener.clean_url(url) == f"http://{url}" 21 | 22 | # bad 23 | with pytest.raises(BadURLException): 24 | BaseShortener.clean_url("http://") 25 | 26 | 27 | def test_base_expand_method(): 28 | shortener = BaseShortener() 29 | url = "http://httpbin.org/get" 30 | assert shortener.expand(url) == url 31 | 32 | 33 | def test_base_expand_method_bad_response(): 34 | shortener = BaseShortener() 35 | with pytest.raises(ExpandingErrorException): 36 | shortener.expand("http://httpbin.org/status/400") 37 | 38 | 39 | def test_base_get_request_bad_url(): 40 | shortener = BaseShortener() 41 | url = "....." 42 | with pytest.raises(BadURLException): 43 | shortener._get(url) 44 | 45 | 46 | def test_base_post_request(): 47 | shortener = BaseShortener() 48 | url = "http://httpbin.org/status/200" 49 | assert shortener._post(url).status_code == 200 50 | 51 | 52 | def test_base_post_request_bad_url(): 53 | shortener = BaseShortener() 54 | url = "....." 55 | with pytest.raises(BadURLException): 56 | shortener._post(url) 57 | 58 | 59 | def test_base_short_method_raises_notimplemented(): 60 | shortener = BaseShortener() 61 | with pytest.raises(NotImplementedError): 62 | shortener.short("http://someurl") 63 | -------------------------------------------------------------------------------- /tests/test_bitly.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from urllib.parse import urlparse 3 | import json 4 | 5 | from pyshorteners import Shortener 6 | from pyshorteners.exceptions import ( 7 | ShorteningErrorException, 8 | ExpandingErrorException, 9 | BadAPIResponseException, 10 | ) 11 | 12 | import responses 13 | import pytest 14 | 15 | token = "TEST_TOKEN" 16 | s = Shortener(api_key=token) 17 | shorten = "http://bit.ly/test" 18 | expanded = "http://www.test.com" 19 | bitly = s.bitly 20 | 21 | 22 | @responses.activate 23 | def test_bitly_short_method(): 24 | # mock responses 25 | body = json.dumps({"link": shorten}) 26 | headers = {"Authorization": f"Bearer {token}"} 27 | 28 | url = f"{bitly.api_url}/shorten" 29 | responses.add( 30 | responses.POST, url, headers=headers, body=body, match_querystring=True 31 | ) 32 | 33 | shorten_result = bitly.short(expanded) 34 | 35 | assert shorten_result == shorten 36 | 37 | 38 | @responses.activate 39 | def test_bitly_short_method_bad_response(): 40 | # mock responses 41 | body = json.dumps({"link": shorten}) 42 | headers = {"Authorization": f"Bearer {token}"} 43 | 44 | url = f"{bitly.api_url}/shorten" 45 | responses.add( 46 | responses.POST, 47 | url, 48 | headers=headers, 49 | body=body, 50 | status=400, 51 | match_querystring=True, 52 | ) 53 | 54 | with pytest.raises(ShorteningErrorException): 55 | bitly.short(expanded) 56 | 57 | 58 | @responses.activate 59 | def test_bitly_expand_method(): 60 | # mock responses 61 | body = json.dumps({"long_url": expanded}) 62 | headers = {"Authorization": f"Bearer {token}"} 63 | 64 | url = f"{bitly.api_url}/expand" 65 | responses.add( 66 | responses.POST, url, headers=headers, body=body, match_querystring=True 67 | ) 68 | assert bitly.expand(shorten) == expanded 69 | 70 | 71 | @responses.activate 72 | def test_bitly_expand_method_bad_response(): 73 | # mock responses 74 | body = json.dumps({"long_url": expanded}) 75 | headers = {"Authorization": f"Bearer {token}"} 76 | 77 | url = f"{bitly.api_url}/expand" 78 | responses.add( 79 | responses.POST, 80 | url, 81 | headers=headers, 82 | body=body, 83 | status=400, 84 | match_querystring=True, 85 | ) 86 | 87 | with pytest.raises(ExpandingErrorException): 88 | bitly.expand(shorten) 89 | 90 | 91 | @responses.activate 92 | def test_bitly_total_clicks(): 93 | body = json.dumps({"link_clicks": [{"clicks": 20}]}) 94 | headers = {"Authorization": f"Bearer {token}"} 95 | url = "".join(urlparse(shorten)[1:3]) 96 | url = f"{bitly.api_url}/bitlinks/{url}/clicks" 97 | responses.add( 98 | responses.GET, url, headers=headers, body=body, match_querystring=True 99 | ) 100 | 101 | assert bitly.total_clicks(shorten) == 20 102 | 103 | 104 | @responses.activate 105 | def test_bitly_total_clicks_bad_response(): 106 | body = json.dumps({"link_clicks": [{"clicks": 20}]}) 107 | headers = {"Authorization": f"Bearer {token}"} 108 | url = "".join(urlparse(shorten)[1:3]) 109 | url = f"{bitly.api_url}/bitlinks/{url}/clicks" 110 | responses.add( 111 | responses.GET, 112 | url, 113 | headers=headers, 114 | body=body, 115 | status=400, 116 | match_querystring=True, 117 | ) 118 | with pytest.raises(BadAPIResponseException): 119 | bitly.total_clicks(shorten) 120 | -------------------------------------------------------------------------------- /tests/test_chilpit.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from pyshorteners import Shortener 4 | from pyshorteners.exceptions import ShorteningErrorException 5 | 6 | import responses 7 | import pytest 8 | 9 | s = Shortener() 10 | shorten = "http://chilp.it/test" 11 | expanded = "http://www.test.com" 12 | chil = s.chilpit 13 | 14 | 15 | @responses.activate 16 | def test_chilpit_short_method(): 17 | # mock responses 18 | params = urlencode({"url": expanded}) 19 | mock_url = f"{chil.api_url}?{params}" 20 | responses.add(responses.GET, mock_url, body=shorten, match_querystring=True) 21 | 22 | shorten_result = chil.short(expanded) 23 | 24 | assert shorten_result == shorten 25 | 26 | 27 | @responses.activate 28 | def test_chilpit_short_method_bad_response(): 29 | # mock responses 30 | params = urlencode({"url": expanded}) 31 | mock_url = f"{chil.api_url}?{params}" 32 | responses.add( 33 | responses.GET, mock_url, body=shorten, status=400, match_querystring=True 34 | ) 35 | 36 | with pytest.raises(ShorteningErrorException): 37 | chil.short(expanded) 38 | -------------------------------------------------------------------------------- /tests/test_clckru.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from pyshorteners import Shortener 4 | from pyshorteners.exceptions import ShorteningErrorException 5 | 6 | import responses 7 | import pytest 8 | 9 | s = Shortener() 10 | shorten = "http://clck.ru/test" 11 | expanded = "http://www.test.com" 12 | clck = s.clckru 13 | 14 | 15 | @responses.activate 16 | def test_clckru_short_method(): 17 | # mock responses 18 | params = urlencode({"url": expanded}) 19 | mock_url = f"{clck.api_url}?{params}" 20 | responses.add(responses.GET, mock_url, body=shorten, match_querystring=True) 21 | 22 | shorten_result = clck.short(expanded) 23 | 24 | assert shorten_result == shorten 25 | 26 | 27 | @responses.activate 28 | def test_clckru_short_method_bad_response(): 29 | # mock responses 30 | params = urlencode({"url": expanded}) 31 | mock_url = f"{clck.api_url}?{params}" 32 | responses.add( 33 | responses.GET, mock_url, body=shorten, status=400, match_querystring=True 34 | ) 35 | 36 | with pytest.raises(ShorteningErrorException): 37 | clck.short(expanded) 38 | -------------------------------------------------------------------------------- /tests/test_cuttly.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | import json 3 | 4 | from pyshorteners import Shortener 5 | from pyshorteners.exceptions import BadAPIResponseException 6 | 7 | import responses 8 | import pytest 9 | 10 | s = Shortener(api_key="TEST_KEY") 11 | url = "http://www.test.com" 12 | shorted_url = "https://cutt.ly/TEST" 13 | cuttly = s.cuttly 14 | 15 | 16 | @responses.activate 17 | def test_cuttly_short_method(): 18 | # mock responses 19 | params = urlencode({"key": cuttly.api_key, "short": url}) 20 | mock_url = f"{cuttly.api_url}?{params}" 21 | res = json.dumps({"url": {"status": 1, "shortLink": shorted_url}}) 22 | responses.add(responses.GET, mock_url, status=200, body=res, match_querystring=True) 23 | 24 | shorten_result = cuttly.short(url) 25 | 26 | assert shorten_result == shorted_url 27 | 28 | 29 | @responses.activate 30 | def test_cuttly_short_method_bad_response(): 31 | # mock responses 32 | mock_url = cuttly.api_url 33 | 34 | responses.add(responses.GET, mock_url, status=400) 35 | 36 | with pytest.raises(BadAPIResponseException): 37 | cuttly.short(url) 38 | -------------------------------------------------------------------------------- /tests/test_dagd.py: -------------------------------------------------------------------------------- 1 | from pyshorteners import Shortener 2 | from pyshorteners.exceptions import ShorteningErrorException 3 | 4 | import responses 5 | import pytest 6 | 7 | s = Shortener() 8 | shorten = "http://da.gd/test" 9 | expanded = "http://www.test.com" 10 | dagd = s.dagd 11 | 12 | 13 | @responses.activate 14 | def test_dagd_short_method(): 15 | # mock responses 16 | mock_url = f"{dagd.api_url}shorten?url={expanded}" 17 | responses.add(responses.GET, mock_url, body=shorten, match_querystring=True) 18 | 19 | shorten_result = dagd.short(expanded) 20 | 21 | assert shorten_result == shorten 22 | 23 | 24 | @responses.activate 25 | def test_dagd_short_method_bad_response(): 26 | # mock responses 27 | mock_url = f"{dagd.api_url}shorten?url={expanded}" 28 | responses.add( 29 | responses.GET, mock_url, body=shorten, status=400, match_querystring=True 30 | ) 31 | 32 | with pytest.raises(ShorteningErrorException): 33 | dagd.short(expanded) 34 | -------------------------------------------------------------------------------- /tests/test_isgd.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from pyshorteners import Shortener 4 | from pyshorteners.exceptions import ShorteningErrorException 5 | 6 | import responses 7 | import pytest 8 | 9 | s = Shortener() 10 | shorten = "https://is.gd/test" 11 | expanded = "http://www.test.com" 12 | isgd = s.isgd 13 | 14 | 15 | @responses.activate 16 | def test_isgd_short_method(): 17 | # mock responses 18 | params = urlencode({"format": "simple", "url": expanded}) 19 | mock_url = f"{isgd.api_url}?{params}" 20 | responses.add(responses.GET, mock_url, body=shorten, match_querystring=True) 21 | 22 | shorten_result = isgd.short(expanded) 23 | 24 | assert shorten_result == shorten 25 | 26 | 27 | @responses.activate 28 | def test_isgd_short_method_bad_response(): 29 | # mock responses 30 | params = urlencode({"format": "simple", "url": expanded}) 31 | mock_url = f"{isgd.api_url}?{params}" 32 | responses.add( 33 | responses.GET, mock_url, body=shorten, status=400, match_querystring=True 34 | ) 35 | 36 | with pytest.raises(ShorteningErrorException): 37 | isgd.short(expanded) 38 | -------------------------------------------------------------------------------- /tests/test_nullpointer.py: -------------------------------------------------------------------------------- 1 | from pyshorteners import Shortener 2 | from pyshorteners.exceptions import ShorteningErrorException 3 | 4 | import responses 5 | import pytest 6 | 7 | s = Shortener(domain="https://0x0.st/") 8 | shorten = "https://0x0.st/jU" 9 | expanded = "https://www.google.com" 10 | nullpointer = s.nullpointer 11 | 12 | 13 | @responses.activate 14 | def test_nullpointer_short_method(): 15 | response = shorten 16 | mock_url = nullpointer.domain 17 | responses.add(responses.POST, mock_url, body=response) 18 | 19 | shorten_result = nullpointer.short(expanded) 20 | 21 | assert shorten_result == shorten 22 | 23 | 24 | @responses.activate 25 | def test_nullpointer_short_method_bad_response(): 26 | mock_url = nullpointer.domain 27 | responses.add(responses.POST, mock_url, status=400) 28 | 29 | with pytest.raises(ShorteningErrorException): 30 | nullpointer.short(expanded) 31 | -------------------------------------------------------------------------------- /tests/test_osdb.py: -------------------------------------------------------------------------------- 1 | from pyshorteners import Shortener 2 | from pyshorteners.exceptions import ShorteningErrorException 3 | 4 | import responses 5 | import pytest 6 | 7 | s = Shortener() 8 | shorten = "http://osdb.link/test123" 9 | expanded = "http://www.test.com" 10 | osdb = s.osdb 11 | 12 | # flake8: noqa 13 | body = f"""\r\n\r\n \r\n \r\n URL shortener\r\n \r\n \r\n \r\n\t
\r\n\t\t
\r\n\t\t\t

osdb.link

\r\n\t\t\t
\r\n\t\t\t \r\n\t\t\t \r\n\t\t\t

\r\n\t\t\t \r\n\t\t\t
\r\n\t\t\t
\t\r\n\t\t
\r\n\t
\r\n \r\n""" 14 | mock_url = osdb.api_url 15 | 16 | 17 | @responses.activate 18 | def test_tinyurl_short_method(): 19 | # mock responses 20 | responses.add(responses.POST, mock_url, body=body) 21 | 22 | shorten_result = osdb.short(expanded) 23 | assert shorten_result == shorten 24 | 25 | 26 | @responses.activate 27 | def test_tinyurl_short_bad_response(): 28 | # mock responses 29 | responses.add(responses.POST, mock_url, body=body, status=400) 30 | 31 | with pytest.raises(ShorteningErrorException): 32 | osdb.short(expanded) 33 | -------------------------------------------------------------------------------- /tests/test_owly.py: -------------------------------------------------------------------------------- 1 | import json 2 | from urllib.parse import urlencode 3 | 4 | from pyshorteners import Shortener 5 | from pyshorteners.exceptions import ShorteningErrorException, ExpandingErrorException 6 | 7 | import responses 8 | import pytest 9 | 10 | s = Shortener(api_key="TEST_KEY") 11 | shorten = "http://ow.ly/test" 12 | expanded = "http://www.test.com" 13 | owly = s.owly 14 | 15 | 16 | @responses.activate 17 | def test_owly_short_method(): 18 | # mock responses 19 | params = urlencode({"apiKey": "TEST_KEY", "longUrl": expanded}) 20 | body = json.dumps({"results": {"shortUrl": shorten}}) 21 | mock_url = f"{owly.api_url}shorten?{params}" 22 | responses.add(responses.GET, mock_url, body=body, match_querystring=True) 23 | 24 | shorten_result = owly.short(expanded) 25 | 26 | assert shorten_result == shorten 27 | 28 | 29 | @responses.activate 30 | def test_owly_short_method_bad_response(): 31 | # mock responses 32 | params = urlencode({"apiKey": "TEST_KEY", "longUrl": expanded}) 33 | body = "{'rerrsults': {'shortUrl': shorten}}" 34 | mock_url = f"{owly.api_url}shorten?{params}" 35 | responses.add(responses.GET, mock_url, body=body, match_querystring=True) 36 | 37 | with pytest.raises(json.decoder.JSONDecodeError): 38 | owly.short(expanded) 39 | 40 | 41 | @responses.activate 42 | def test_owly_short_method_bad_response_status(): 43 | # mock responses 44 | params = urlencode({"apiKey": "TEST_KEY", "longUrl": expanded}) 45 | body = "{'rerrsults': {'shortUrl': shorten}}" 46 | mock_url = f"{owly.api_url}shorten?{params}" 47 | responses.add( 48 | responses.GET, mock_url, body=body, status=400, match_querystring=True 49 | ) 50 | 51 | with pytest.raises(ShorteningErrorException): 52 | owly.short(expanded) 53 | 54 | 55 | @responses.activate 56 | def test_owly_expand_method(): 57 | # mock responses 58 | params = urlencode({"apiKey": "TEST_KEY", "shortUrl": shorten}) 59 | body = json.dumps({"results": {"longUrl": expanded}}) 60 | mock_url = f"{owly.api_url}expand?{params}" 61 | responses.add(responses.GET, mock_url, body=body, match_querystring=True) 62 | 63 | expanded_result = owly.expand(shorten) 64 | 65 | assert expanded_result == expanded 66 | 67 | 68 | @responses.activate 69 | def test_owly_expand_method_bad_response(): 70 | # mock responses 71 | params = urlencode({"apiKey": "TEST_KEY", "shortUrl": shorten}) 72 | body = "{'results': {'longUrl': ''}}" 73 | mock_url = f"{owly.api_url}expand?{params}" 74 | responses.add(responses.GET, mock_url, body=body, match_querystring=True) 75 | 76 | with pytest.raises(json.decoder.JSONDecodeError): 77 | owly.expand(shorten) 78 | 79 | 80 | @responses.activate 81 | def test_owly_expand_method_bad_status_code(): 82 | # mock responses 83 | params = urlencode({"apiKey": "TEST_KEY", "shortUrl": shorten}) 84 | body = "{'results': {'longUrl': ''}}" 85 | mock_url = f"{owly.api_url}expand?{params}" 86 | responses.add( 87 | responses.GET, mock_url, body=body, status=400, match_querystring=True 88 | ) 89 | 90 | with pytest.raises(ExpandingErrorException): 91 | owly.expand(shorten) 92 | -------------------------------------------------------------------------------- /tests/test_post.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from pyshorteners import Shortener 4 | from pyshorteners.exceptions import ShorteningErrorException 5 | 6 | import responses 7 | import pytest 8 | 9 | s = Shortener(api_key="TEST") 10 | post = s.post 11 | shorten = "http://po.st/test" 12 | expanded = "http://www.test.com" 13 | params = urlencode({"apiKey": "TEST", "longUrl": expanded, "format": "txt"}) 14 | mock_url = f"{post.api_url}?{params}" 15 | 16 | 17 | @responses.activate 18 | def test_post_short_method(): 19 | # mock responses 20 | response = {"short_url": shorten} 21 | responses.add(responses.GET, mock_url, json=response, match_querystring=True) 22 | 23 | shorten_result = post.short(expanded) 24 | assert shorten_result == shorten 25 | 26 | 27 | @responses.activate 28 | def test_post_short_bad_response(): 29 | # mock responses 30 | responses.add( 31 | responses.GET, mock_url, body=shorten, status=400, match_querystring=True 32 | ) 33 | 34 | with pytest.raises(ShorteningErrorException): 35 | post.short(expanded) 36 | -------------------------------------------------------------------------------- /tests/test_qpsru.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from pyshorteners import Shortener 4 | from pyshorteners.exceptions import ShorteningErrorException 5 | 6 | import responses 7 | import pytest 8 | 9 | s = Shortener() 10 | shorten = "http://qps.ru/test" 11 | expanded = "http://www.test.com" 12 | qp = s.qpsru 13 | 14 | 15 | @responses.activate 16 | def test_qpsru_short_method(): 17 | # mock responses 18 | params = urlencode({"url": expanded}) 19 | mock_url = f"{qp.api_url}?{params}" 20 | responses.add(responses.GET, mock_url, body=shorten, match_querystring=True) 21 | 22 | shorten_result = qp.short(expanded) 23 | 24 | assert shorten_result == shorten 25 | 26 | 27 | @responses.activate 28 | def test_qpsru_short_method_bad_response(): 29 | # mock responses 30 | params = urlencode({"url": expanded}) 31 | mock_url = f"{qp.api_url}?{params}" 32 | responses.add( 33 | responses.GET, mock_url, body=shorten, status=400, match_querystring=True 34 | ) 35 | 36 | with pytest.raises(ShorteningErrorException): 37 | qp.short(expanded) 38 | -------------------------------------------------------------------------------- /tests/test_shortcm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | 4 | import responses 5 | import pytest 6 | 7 | from pyshorteners import Shortener 8 | from pyshorteners.exceptions import ShorteningErrorException, ExpandingErrorException 9 | 10 | 11 | token = "TEST_TOKEN" 12 | domain = "short.cm" 13 | path = "test" 14 | expanded = "http://www.test.com" 15 | shorten = f"http://{domain}/{path}" 16 | s = Shortener(api_key=token, domain=domain) 17 | shortcm = s.shortcm 18 | 19 | 20 | @responses.activate 21 | def test_shortcm_short_method(): 22 | # mock responses 23 | json = {"path": path, "originalURL": expanded, "shortURL": shorten} 24 | 25 | responses.add(responses.POST, shortcm.api_url, json=json) 26 | 27 | shorten_result = shortcm.short(expanded) 28 | 29 | assert shorten_result == shorten 30 | 31 | 32 | @responses.activate 33 | def test_shortcm_short_method_bad_response(): 34 | # mock responses 35 | json = {"error": "Test error", "success": False} 36 | responses.add(responses.POST, shortcm.api_url, json=json, status=400) 37 | 38 | with pytest.raises(ShorteningErrorException): 39 | shortcm.short(expanded) 40 | 41 | 42 | @responses.activate 43 | def test_shortcm_expand_method(): 44 | # mock responses 45 | json = {"path": path, "shortURL": shorten, "originalURL": expanded} 46 | url = f"{shortcm.api_url}expand" 47 | responses.add(responses.GET, url, json=json) 48 | assert shortcm.expand(shorten) == expanded 49 | 50 | 51 | @responses.activate 52 | def test_shortcm_expand_method_bad_response(): 53 | # mock responses 54 | json = {"error": "Test error"} 55 | url = f"{shortcm.api_url}expand" 56 | responses.add(responses.GET, url, json=json, status=400) 57 | 58 | with pytest.raises(ExpandingErrorException): 59 | shortcm.expand(shorten) 60 | -------------------------------------------------------------------------------- /tests/test_tinycc.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | from pyshorteners import Shortener 4 | from pyshorteners.exceptions import ShorteningErrorException, ExpandingErrorException 5 | 6 | import responses 7 | import pytest 8 | 9 | token = "TEST_TOKEN" 10 | login = "TEST_LOGIN" 11 | api_version = "2.0.3" 12 | shorten = "http://tiny.cc/test" 13 | expanded = "http://www.test.com" 14 | s = Shortener(api_key=token, login=login) 15 | tiny = s.tinycc 16 | 17 | 18 | @responses.activate 19 | def test_tinycc_short_method(): 20 | # mock responses 21 | body = {"results": {"short_url": shorten}} 22 | params = urlencode( 23 | dict( 24 | longUrl=expanded, 25 | apiKey=token, 26 | format="json", 27 | c="rest_api", 28 | version=api_version, 29 | login=login, 30 | m="shorten", 31 | ) 32 | ) 33 | 34 | url = f"{tiny.api_url}?{params}" 35 | responses.add(responses.GET, url, json=body, match_querystring=True) 36 | 37 | shorten_result = tiny.short(expanded) 38 | 39 | assert shorten_result == shorten 40 | 41 | 42 | @responses.activate 43 | def test_tinycc_short_method_bad_response(): 44 | # mock responses 45 | body = shorten 46 | params = urlencode( 47 | dict( 48 | longUrl=expanded, 49 | apiKey=token, 50 | format="json", 51 | c="rest_api", 52 | version=api_version, 53 | login=login, 54 | m="shorten", 55 | ) 56 | ) 57 | url = f"{tiny.api_url}?{params}" 58 | responses.add(responses.GET, url, body=body, status=400, match_querystring=True) 59 | 60 | with pytest.raises(ShorteningErrorException): 61 | tiny.short(expanded) 62 | 63 | 64 | @responses.activate 65 | def test_tinycc_expand_method(): 66 | # mock responses 67 | body = {"results": {"longUrl": expanded}} 68 | params = urlencode( 69 | dict( 70 | longUrl=shorten, 71 | apiKey=token, 72 | format="json", 73 | c="rest_api", 74 | version=api_version, 75 | login=login, 76 | m="expand", 77 | ) 78 | ) 79 | url = f"{tiny.api_url}?{params}" 80 | responses.add(responses.GET, url, json=body, match_querystring=True) 81 | assert tiny.expand(shorten) == expanded 82 | 83 | 84 | @responses.activate 85 | def test_tinycc_expand_method_bad_response(): 86 | # mock responses 87 | body = expanded 88 | params = urlencode( 89 | dict( 90 | longUrl=shorten, 91 | apiKey=token, 92 | format="json", 93 | c="rest_api", 94 | version=api_version, 95 | login=login, 96 | m="expand", 97 | ) 98 | ) 99 | url = f"{tiny.api_url}?{params}" 100 | responses.add(responses.GET, url, body=body, status=400, match_querystring=True) 101 | 102 | with pytest.raises(ExpandingErrorException): 103 | tiny.expand(shorten) 104 | 105 | 106 | @responses.activate 107 | def test_tinycc_total_clicks(): 108 | body = {"results": {"clicks": 20}} 109 | params = urlencode( 110 | dict( 111 | shortUrl=shorten, 112 | apiKey=token, 113 | format="json", 114 | c="rest_api", 115 | version=api_version, 116 | login=login, 117 | m="total_visits", 118 | ) 119 | ) 120 | url = f"{tiny.api_url}?{params}" 121 | responses.add(responses.GET, url, json=body, match_querystring=True) 122 | assert tiny.total_clicks(shorten) == 20 123 | 124 | 125 | @responses.activate 126 | def test_tinycc_total_clicks_bad_response(): 127 | clicks_body = {"results": "a"} 128 | params = urlencode( 129 | dict( 130 | c="rest_api", 131 | version=api_version, 132 | format="json", 133 | apiKey=token, 134 | login=login, 135 | m="total_visits", 136 | shortUrl=shorten, 137 | ) 138 | ) 139 | url = f"{tiny.api_url}?{params}" 140 | responses.add(responses.GET, url, json=clicks_body, match_querystring=True) 141 | assert tiny.total_clicks(shorten) == 0 142 | -------------------------------------------------------------------------------- /tests/test_tinyurl.py: -------------------------------------------------------------------------------- 1 | from pyshorteners import Shortener 2 | from pyshorteners.exceptions import ShorteningErrorException 3 | 4 | import responses 5 | import pytest 6 | 7 | s = Shortener() 8 | shorten = "http://tinyurl.com/test" 9 | expanded = "http://www.test.com" 10 | tiny = s.tinyurl 11 | 12 | 13 | @responses.activate 14 | def test_tinyurl_short_method(): 15 | # mock responses 16 | mock_url = f"{tiny.api_url}?url={expanded}" 17 | responses.add(responses.GET, mock_url, body=shorten, match_querystring=True) 18 | 19 | shorten_result = tiny.short(expanded) 20 | assert shorten_result == shorten 21 | 22 | 23 | @responses.activate 24 | def test_tinyurl_short_bad_response(): 25 | # mock responses 26 | mock_url = f"{tiny.api_url}?url={expanded}" 27 | responses.add( 28 | responses.GET, mock_url, body=shorten, status=400, match_querystring=True 29 | ) 30 | 31 | with pytest.raises(ShorteningErrorException): 32 | tiny.short(expanded) 33 | --------------------------------------------------------------------------------