Repository: Datalux/Osintgram Branch: master Commit: c8ba1f0ae119 Files: 18 Total size: 161.7 KB Directory structure: gitextract_mi80brfi/ ├── .dockerignore ├── .github/ │ └── workflows/ │ └── lint_python.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── doc/ │ ├── CHANGELOG.md │ └── COMMANDS.md ├── docker-compose.yml ├── docker_reqs.txt ├── main.py ├── requirements.txt └── src/ ├── Osintgram.py ├── artwork.py ├── config.py ├── hikercli.py └── printcolors.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ .github .img doc output .dockerignore .gitignore Docker-compose.yml Dockerfile LICENSE Makefile README.md ================================================ FILE: .github/workflows/lint_python.yml ================================================ name: lint_python on: [pull_request, push] jobs: lint_python: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install bandit black codespell flake8 isort mypy pytest pyupgrade safety - run: bandit -r . || true - run: black --check . || true - run: codespell --ignore-words-list="followings" --quiet-level=2 - run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - run: isort --check-only --profile black . || true - run: pip install -r requirements.txt - run: mypy --ignore-missing-imports . - run: pytest . || true - run: pytest --doctest-modules . || true - run: shopt -s globstar && pyupgrade --py36-plus **/*.py || true - run: safety check ================================================ FILE: .gitignore ================================================ __pycache__/ output/ **/*.pyc **/*.json venv/ credentials.ini settings.json ================================================ FILE: Dockerfile ================================================ FROM python:3.9.2-alpine3.13 as build WORKDIR /wheels RUN apk add --no-cache \ ncurses-dev \ build-base COPY docker_reqs.txt /opt/osintgram/requirements.txt RUN pip3 wheel -r /opt/osintgram/requirements.txt FROM python:3.9.2-alpine3.13 WORKDIR /home/osintgram RUN adduser -D osintgram COPY --from=build /wheels /wheels COPY --chown=osintgram:osintgram requirements.txt /home/osintgram/ RUN pip3 install -r requirements.txt -f /wheels \ && rm -rf /wheels \ && rm -rf /root/.cache/pip/* \ && rm requirements.txt COPY --chown=osintgram:osintgram src/ /home/osintgram/src COPY --chown=osintgram:osintgram main.py /home/osintgram/ COPY --chown=osintgram:osintgram config/ /home/osintgram/config USER osintgram ENTRYPOINT ["python", "main.py"] ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: Makefile ================================================ SHELL := /bin/bash setup: @echo -e "\e[34m####### Setup for Osintgram #######\e[0m" @[ -d config ] || mkdir config || exit 1 @echo -n "{}" > config/settings.json @read -p "Instagram Username: " uservar; \ read -sp "Instagram Password: " passvar; \ echo -en "[Credentials]\nusername = $$uservar\npassword = $$passvar" > config/credentials.ini || exit 1 @echo "" @echo -e "\e[32mSetup Successful - config/credentials.ini created\e[0m" run: @echo -e "\e[34m######## Building and Running Osintgram with Docker-compose ########\e[0m" @[ -d config ] || { echo -e "\e[31mConfig folder not found! Please run 'make setup' before running this command.\e[0m"; exit 1; } @echo -e "\e[34m[#] Killing old docker processes\e[0m" @docker-compose rm -fs || exit 1 @echo -e "\e[34m[#] Building docker container\e[0m" @docker-compose build || exit 1 @read -p "Target Username: " username; \ docker-compose run --rm osintgram $$username build-run-testing: @echo -e "\e[34m######## Building and Running Osintgram with Docker-compose for Testing/Debugging ########\e[0m" @[ -d config ] || { echo -e "\e[31mConfig folder not found! Please run 'make setup' before running this command.\e[0m"; exit 1; } @echo -e "\e[34m[#] Killing old docker processes\e[0m" @docker-compose rm -fs || exit 1 @echo -e "\e[34m[#] Building docker container\e[0m" @docker-compose build || exit 1 @echo -e "\e[34m[#] Running docker container in detached mode\e[0m" @docker-compose run --name osintgram-testing -d --rm --entrypoint "sleep infinity" osintgram || exit 1 @echo -e "\e[32m[#] osintgram-test container is now Running!\e[0m" cleanup-testing: @echo -e "\e[34m######## Cleanup Build-run-testing Container ########\e[0m" @docker-compose down @echo -e "\e[32m[#] osintgram-test container has been removed\e[0m" ================================================ FILE: README.md ================================================ # Osintgram 🔎📸 [![version-1.3](https://img.shields.io/badge/version-1.3-green)](https://github.com/Datalux/Osintgram/releases/tag/1.3) [![GPLv3](https://img.shields.io/badge/license-GPLv3-blue)](https://img.shields.io/badge/license-GPLv3-blue) [![Python3](https://img.shields.io/badge/language-Python3-red)](https://img.shields.io/badge/language-Python3-red) [![Telegram](https://img.shields.io/badge/Telegram-Channel-blue.svg)](https://t.me/osintgram) [![Docker](https://img.shields.io/badge/Docker-Supported-blue)](https://img.shields.io/badge/Docker-Supported-blue) Osintgram is an **OSINT** tool on Instagram to collect, analyze, and run reconnaissance.

Disclaimer: **FOR EDUCATIONAL PURPOSE ONLY! The contributors do not assume any responsibility for the use of this tool.** $${\color{red}Warning:}$$ It is advisable to **not** use your own/primary account when using this tool. $${\color{red}Warning:}$$ If you fork the project and add your instagram credentials to you home repository do not upload them to github. You can disable uploading a certain file by adding it to ignore list. ## Tools and Commands 🧰 Osintgram offers an interactive shell to perform analysis on Instagram account of any users by its nickname. You can get: ```text - addrs Get all registered addressed by target photos - captions Get user's photos captions - comments Get total comments of target's posts - followers Get target followers - followings Get users followed by target - fwersemail Get email of target followers - fwingsemail Get email of users followed by target - fwersnumber Get phone number of target followers - fwingsnumber Get phone number of users followed by target - hashtags Get hashtags used by target - info Get target info - likes Get total likes of target's posts - mediatype Get user's posts type (photo or video) - photodes Get description of target's photos - photos Download user's photos in output folder - propic Download user's profile picture - stories Download user's stories - tagged Get list of users tagged by target - wcommented Get a list of user who commented target's photos - wtagged Get a list of user who tagged target ``` You can find detailed commands usage [here](doc/COMMANDS.md). [**Latest version**](https://github.com/Datalux/Osintgram/releases/tag/1.3) | [Commands](doc/COMMANDS.md) | [CHANGELOG](doc/CHANGELOG.md) ## FAQ 1. **Can I access the contents of a private profile?** No, you cannot get information on private profiles. You can only get information from a public profile or a profile you follow. The tools that claim to be successful are scams! 2. **What is and how I can bypass the `challenge_required` error?** The `challenge_required` error means that Instagram notice a suspicious behavior on your profile, so needs to check if you are a real person or a bot. To avoid this you should follow the suggested link and complete the required operation (insert a code, confirm email, etc) ## Installation ⚙️ 1. Fork/Clone/Download this repo `git clone https://github.com/Datalux/Osintgram.git` 2. Navigate to the directory `cd Osintgram` 3. Create a virtual environment for this project `python3 -m venv venv` 4. Load the virtual environment - On Windows Powershell: `.\venv\Scripts\activate.ps1` - On Linux and Git Bash: `source venv/bin/activate` 5. Run `pip install -r requirements.txt` 6. Open the `credentials.ini` file in the `config` folder and write your Instagram account username and password in the corresponding fields. Or use `hikerapi_token` from https://hikerapi.com/tokens (first 100 requests are free after registration and confirmation of your tg) Alternatively, you can run the `make setup` command to populate this file for you. 7. Run the main.py script in one of three ways * As an interactive prompt `python3 main.py ` * Or execute your command straight away `python3 main.py --command ` * Or execute using HikerAPI token via env `HIKERAPI_TOKEN= python3 main.py -c ` ### Use Osintgram v2 (beta) You can use Osintgram2 beta just switching to `v2` [branch](https://github.com/Datalux/Osintgram/tree/v2). The v2 has some improvements and is faster with a new command execution interface. Try it just running `git checkout v2`. ## Docker Quick Start 🐳 This section will explain how you can quickly use this image with `Docker` or `Docker-compose`. ### Prerequisites Before you can use either `Docker` or `Docker-compose`, please ensure you do have the following prerequisites met. 1. **Docker** installed - [link](https://docs.docker.com/get-docker/) 2. **Docker-composed** installed (if using Docker-compose) - [link](https://docs.docker.com/compose/install/) 3. **Credentials** configured - This can be done manually or by running the `make setup` command from the root of this repo **Important**: Your container will fail if you do not do step #3 and configure your credentials ### Docker If docker is installed you can build an image and run this as a container. Build: ```bash docker build -t osintgram . ``` Run: ```bash docker run --rm -it -v "$PWD/output:/home/osintgram/output" osintgram ``` - The `` is the Instagram account you wish to use as your target for recon. - The required `-i` flag enables an interactive terminal to use commands within the container. [docs](https://docs.docker.com/engine/reference/commandline/run/#assign-name-and-allocate-pseudo-tty---name--it) - The required `-v` flag mounts a volume between your local filesystem and the container to save to the `./output/` folder. [docs](https://docs.docker.com/engine/reference/commandline/run/#mount-volume--v---read-only) - The optional `--rm` flag removes the container filesystem on completion to prevent cruft build-up. [docs](https://docs.docker.com/engine/reference/run/#clean-up---rm) - The optional `-t` flag allocates a pseudo-TTY which allows colored output. [docs](https://docs.docker.com/engine/reference/run/#foreground) ### Using `docker-compose` You can use the `docker-compose.yml` file this single command: ```bash docker-compose run osintgram ``` Where `target` is the Instagram target for recon. Alternatively, you may run `docker-compose` with the `Makefile`: `make run` - Builds and Runs with compose. Prompts for a `target` before running. ### Makefile (easy mode) For ease of use with Docker-compose, a `Makefile` has been provided. Here is a sample work flow to spin up a container and run `osintgram` with just two commands! 1. `make setup` - Sets up your Instagram credentials 2. `make run` - Builds and Runs a osintgram container and prompts for a target Sample workflow for development: 1. `make setup` - Sets up your Instagram credentials 2. `make build-run-testing` - Builds an Runs a container without invoking the `main.py` script. Useful for an `it` Docker session for development 3. `make cleanup-testing` - Cleans up the testing container created from `build-run-testing` ## Development version 💻 To use the development version with the latest feature and fixes just switch to `development` branch using Git: `git checkout development` and update to last version using: `git pull origin development` ## Updating ⬇️ To update Osintgram with the stable release just pull the latest commit using Git. 1. Make sure you are in the master branch running: `git checkout master` 2. Download the latest version: `git pull origin master` ## Contributing 💡 You can propose a feature request opening an issue or a pull request. Here is a list of Osintgram's contributors: ## External library 🔗 [Instagram API](https://github.com/ping/instagram_private_api) ================================================ FILE: doc/CHANGELOG.md ================================================ # Changelog ## [1.3](https://github.com/Datalux/Osintgram/releases/tag/1.3) **Enhancements** - Artwork refactoring (#149) - Added command line mode (#155) - Added output limiter (#201) **Bug fixes** - Losing collected data (#156) - JSON user info (#202) - Issue #198 (#200) - Issue #204 (12e730e) ## [1.2](https://github.com/Datalux/Osintgram/releases/tag/1.2) **Enhancements** - Added virtual environment (#126) - Removed some typos (#129, #118) - Added new configuration (#125) - Added new `commentdata` command (#131) - Added Docker support (#141) **Bug fixes** - Fix bug #138 (fc2a6be) - SSL certificate error (#136) ## [1.1](https://github.com/Datalux/Osintgram/releases/tag/1.1) **Enhancements** - Improved command parser (#86) - Improved errors handling (8bd1abc) - Add new line when input command is empty (f5211eb) - Added new commands to catch phone number of users (#111) - Added support for Windows (#100) **Bug fixes** - Fix commands output limit bug (#87) - Fix setting target with "." in username (9082990) - Readline installing error (#94 ) ## [1.0.1](https://github.com/Datalux/Osintgram/releases/tag/1.0.1) **Bug fixes** - Set itself as target by param ## [1.0](https://github.com/Datalux/Osintgram/releases/tag/1.0) **Enhancements** - Set itself as target (#53) - Get others info from user (`info` command): - Whats'App number (if available) - City Name (if available) - Address Street (if available) - Contact phone number (if available) **Bug fixes** - Fix login issue (#79, #80, #81) ## [0.9](https://github.com/Datalux/Osintgram/releases/tag/0.9) **Enhancements** - Send a follow request if user not following target (#44) - Added new `fwingsemail` command (#50) - Added autocomplete with TAB (07e0fe8) **Bug fixes** - Decoding error of response [bug #46] (f9c5f73) - `stories` command not working (#49) ## [0.8](https://github.com/Datalux/Osintgram/releases/tag/0.8) **Enhancements** - Added `wtagged` command (#38) - Added `fwersemail` command (#40) - Access private profiles if you following targets (#37) - Added more info in `info` command (#36) **Bug fixes** - Minor bug fix in `addrs` commands (9b9086a) ## [0.7](https://github.com/Datalux/Osintgram/releases/tag/0.7) **Enhancements** - banner now show target ID (#30) - persistent login (#33) - error handler (85e390b) - added CTRL+C handler (c2c3c3e) **Bug fixes** - fix likes and comments posts counter bug (44b7534) ## [0.6](https://github.com/Datalux/Osintgram/releases/tag/0.6) **Enhancements** - new `wcommented` command (#27) - new `target` command - added json dump also for captions command - added options as arguments (#24) - new Instagram APIs (#26) **Bug fixes** - fix empty addrs bug (#12) ## [0.5](https://github.com/Datalux/Osintgram/releases/tag/0.5) **Enhancements** - added JSON export feature **Bug fixes** - Fix #2 ## [0.4](https://github.com/Datalux/Osintgram/releases/tag/0.4) **Enhancements** - added `stories` command (#8) - added `target` command (#9) **Bug fixes** - added a check if the target has a private profile to avoid tool crash (#10) - fixed `tagged` bug (#5) ## [0.3](https://github.com/Datalux/Osintgram/releases/tag/0.3) **Enhancements** - added `photos` command - added `captions` command - added `mediatype` command - added `propic` command ## 0.2 **Enhancements** - write in file the output of commands ## 0.1 **Initial release** ================================================ FILE: doc/COMMANDS.md ================================================ # Commands list and usage ``` - addrs Get all registered addressed by target photos - captions Get user's photos captions - commentdata Get a list of all the comments on the target's posts - comments Get total comments of target's posts - followers Get target followers - followings Get users followed by target - fwersemail Get email of target followers - fwingsemail Get email of users followed by target - hashtags Get hashtags used by target - info Get target info - likes Get total likes of target's posts - mediatype Get user's posts type (photo or video) - photodes Get description of target's photos - photos Download user's photos in output folder - propic Download user's profile picture - stories Download user's stories - tagged Get list of users tagged by target - wcommented Get a list of user who commented target's photos - wtagged Get a list of user who tagged target ``` ### addrs Return a list with address (GPS) tagged by target in his photos. The list has post, address and date fields. ### captions Return a list of all captions used by target in his photos. ### comments Return the total number of comments in target's posts ### exit Exit from Osintgram ### FILE Can set preference to save commands output in output folder. It save output in `_.txt` file. With `FILE=y` you can enable saving in file. With `FILE=n` you can disable saving in file. ### followers Return a list with target followers with id, nickname and full name ### followings Return a list with users followed by target with id, nickname and full name ### fwersemail Return a list of emails of target followers ### fwingsemail Return a list of emails of user followed by target ### fwersnumber Return a list of phone number of target followers ### fwingsnumber Return a list of phone number of user followed by target ### hashtags Return a list with all hashtag used by target in his photos ### info Show target info like: - id - full name - biography - followed - follow - is business account? - business category (if target has business account) - is verified? - business email (if available) - HD profile picture url - connected Facebook page (if available) - Whats'App number (if available) - City Name (if available) - Address Street (if available) - Contact phone number (if available) ### JSON Can set preference to export commands output as JSON in output folder. It save output in `_.JSON` file. With `JSON=y` you can enable JSON exporting. With `JSON=n` you can disable JSON exporting. ### likes Return the total number of likes in target's posts ### list (or help) Show all commands available. ### mediatype Return the number of photos and video shared by target ### photodes Return a list with the description of the content of target's photos ### photos Download all target's photos in output folder. When you run the command, script ask you how many photos you want to download. Type ENTER to download all photos available or type a number to choose how many photos you want download. ``` Run a command: photos How many photos you want to download (default all): ``` ### propic Download target profile picture (HD if is available) ### stories Download all target's stories in output folder. ## tagged Return a list of users tagged by target with ID, username and full name ## wcommented Return a list of users who commented target's photos sorted by number of comments ## wtagged Return a list of users who tagged target sorted by number of photos ================================================ FILE: docker-compose.yml ================================================ version: '3.7' services: osintgram: container_name: osintgram build: . volumes: - ./output:/home/osintgram/output ================================================ FILE: docker_reqs.txt ================================================ requests-toolbelt==0.9.1 geopy>=2.0.0 prettytable==0.7.2 instagram-private-api==1.6.0 gnureadline>=8.0.0 hikerapi==1.7.1 ================================================ FILE: main.py ================================================ #!/usr/bin/env python3 import os import sys import signal import argparse from src import artwork, config from src import printcolors as pc from src.hikercli import HikerCLI, hk from src.Osintgram import Osintgram is_windows = False try: import gnureadline except: is_windows = True import pyreadline def printlogo(): pc.printout(artwork.ascii_art, pc.YELLOW) pc.printout("\nVersion 1.1 - Developed by Giuseppe Criscione", pc.YELLOW) pc.printout( f"\nHikerAPI {hk.__version__} https://hikerapi.com/help/about\n\n", pc.YELLOW ) pc.printout("Type 'list' to show all allowed commands\n") pc.printout("Type 'FILE=y' to save results to files like '_.txt (default is disabled)'\n") pc.printout("Type 'FILE=n' to disable saving to files'\n") pc.printout("Type 'JSON=y' to export results to a JSON files like '_.json (default is " "disabled)'\n") pc.printout("Type 'JSON=n' to disable exporting to files'\n") def cmdlist(): pc.printout("FILE=y/n\t") print("Enable/disable output in a '_.txt' file'") pc.printout("JSON=y/n\t") print("Enable/disable export in a '_.json' file'") pc.printout("addrs\t\t") print("Get all registered addressed by target photos") pc.printout("cache\t\t") print("Clear cache of the tool") pc.printout("captions\t") print("Get target's photos captions") pc.printout("commentdata\t") print("Get a list of all the comments on the target's posts") pc.printout("comments\t") print("Get total comments of target's posts") pc.printout("followers\t") print("Get target followers") pc.printout("followings\t") print("Get users followed by target") pc.printout("fwersemail\t") print("Get email of target followers") pc.printout("fwingsemail\t") print("Get email of users followed by target") pc.printout("fwersnumber\t") print("Get phone number of target followers") pc.printout("fwingsnumber\t") print("Get phone number of users followed by target") pc.printout("hashtags\t") print("Get hashtags used by target") pc.printout("info\t\t") print("Get target info") pc.printout("likes\t\t") print("Get total likes of target's posts") pc.printout("mediatype\t") print("Get target's posts type (photo or video)") pc.printout("photodes\t") print("Get description of target's photos") pc.printout("photos\t\t") print("Download target's photos in output folder") pc.printout("propic\t\t") print("Download target's profile picture") pc.printout("stories\t\t") print("Download target's stories") pc.printout("tagged\t\t") print("Get list of users tagged by target") pc.printout("target\t\t") print("Set new target") pc.printout("wcommented\t") print("Get a list of user who commented target's photos") pc.printout("wtagged\t\t") print("Get a list of user who tagged target") def signal_handler(sig, frame): pc.printout("\nGoodbye!\n", pc.RED) sys.exit(0) def completer(text, state): options = [i for i in commands if i.startswith(text)] if state < len(options): return options[state] else: return None def _quit(): pc.printout("Goodbye!\n", pc.RED) sys.exit(0) signal.signal(signal.SIGINT, signal_handler) if is_windows: pyreadline.Readline().parse_and_bind("tab: complete") pyreadline.Readline().set_completer(completer) else: gnureadline.parse_and_bind("tab: complete") gnureadline.set_completer(completer) parser = argparse.ArgumentParser(description='Osintgram is a OSINT tool on Instagram. It offers an interactive shell ' 'to perform analysis on Instagram account of any users by its nickname ') parser.add_argument('id', type=str, # var = id help='username') parser.add_argument('-C','--cookies', help='clear\'s previous cookies', action="store_true") parser.add_argument('-j', '--json', help='save commands output as JSON file', action='store_true') parser.add_argument('-f', '--file', help='save output in a file', action='store_true') parser.add_argument('-c', '--command', help='run in single command mode & execute provided command', action='store') parser.add_argument('-o', '--output', help='where to store photos', action='store') args = parser.parse_args() if config.getHikerToken(): api = HikerCLI(args.id, args.file, args.json, args.command, args.output, args.cookies) else: api = Osintgram(args.id, args.file, args.json, args.command, args.output, args.cookies) commands = { 'list': cmdlist, 'help': cmdlist, 'quit': _quit, 'exit': _quit, 'addrs': api.get_addrs, 'cache': api.clear_cache, 'captions': api.get_captions, "commentdata": api.get_comment_data, 'comments': api.get_total_comments, 'followers': api.get_followers, 'followings': api.get_followings, 'fwersemail': api.get_fwersemail, 'fwingsemail': api.get_fwingsemail, 'fwersnumber': api.get_fwersnumber, 'fwingsnumber': api.get_fwingsnumber, 'hashtags': api.get_hashtags, 'info': api.get_user_info, 'likes': api.get_total_likes, 'mediatype': api.get_media_type, 'photodes': api.get_photo_description, 'photos': api.get_user_photo, 'propic': api.get_user_propic, 'stories': api.get_user_stories, 'tagged': api.get_people_tagged_by_user, 'target': api.change_target, 'wcommented': api.get_people_who_commented, 'wtagged': api.get_people_who_tagged } signal.signal(signal.SIGINT, signal_handler) if is_windows: pyreadline.Readline().parse_and_bind("tab: complete") pyreadline.Readline().set_completer(completer) else: gnureadline.parse_and_bind("tab: complete") gnureadline.set_completer(completer) if not args.command: printlogo() while True: if args.command: cmd = args.command _cmd = commands.get(args.command) else: signal.signal(signal.SIGINT, signal_handler) if is_windows: pyreadline.Readline().parse_and_bind("tab: complete") pyreadline.Readline().set_completer(completer) else: gnureadline.parse_and_bind("tab: complete") gnureadline.set_completer(completer) pc.printout("Run a command: ", pc.YELLOW) cmd = input() _cmd = commands.get(cmd) if _cmd: _cmd() elif cmd == "FILE=y": api.set_write_file(True) elif cmd == "FILE=n": api.set_write_file(False) elif cmd == "JSON=y": api.set_json_dump(True) elif cmd == "JSON=n": api.set_json_dump(False) elif cmd == "": print("") else: pc.printout("Unknown command\n", pc.RED) if args.command: break ================================================ FILE: requirements.txt ================================================ requests-toolbelt==0.9.1 geopy>=2.0.0 prettytable==0.7.2 instagram-private-api==1.6.0 gnureadline>=8.0.0; platform_system != "Windows" pyreadline==2.1; platform_system == "Windows" hikerapi==1.7.1 ================================================ FILE: src/Osintgram.py ================================================ import datetime import json import sys import urllib import os import codecs from pathlib import Path import httpx import ssl ssl._create_default_https_context = ssl._create_unverified_context from geopy.geocoders import Nominatim from instagram_private_api import Client as AppClient from instagram_private_api import ClientCookieExpiredError, ClientLoginRequiredError, ClientError, ClientThrottledError from prettytable import PrettyTable from src import printcolors as pc from src import config class Osintgram: api = None api2 = None geolocator = Nominatim(user_agent="http") user_id = None target_id = None is_private = True following = False target = "" writeFile = False jsonDump = False cli_mode = False output_dir = "output" def __init__(self, target, is_file, is_json, is_cli, output_dir, clear_cookies): self.output_dir = output_dir or self.output_dir u = config.getUsername() p = config.getPassword() self.clear_cookies(clear_cookies) self.cli_mode = is_cli if not is_cli: print("\nAttempt to login...") self.login(u, p) self.setTarget(target) self.writeFile = is_file self.jsonDump = is_json def clear_cookies(self,clear_cookies): if clear_cookies: self.clear_cache() def setTarget(self, target): self.target = target user = self.get_user(target) self.target_id = user['id'] self.is_private = user['is_private'] self.following = self.check_following() self.__printTargetBanner__() self.output_dir = self.output_dir + "/" + str(self.target) Path(self.output_dir).mkdir(parents=True, exist_ok=True) def __get_feed__(self): data = [] result = self.api.user_feed(str(self.target_id)) data.extend(result.get('items', [])) next_max_id = result.get('next_max_id') while next_max_id: results = self.api.user_feed(str(self.target_id), max_id=next_max_id) data.extend(results.get('items', [])) next_max_id = results.get('next_max_id') return data def __get_comments__(self, media_id): comments = [] result = self.api.media_comments(str(media_id)) comments.extend(result.get('comments', [])) next_max_id = result.get('next_max_id') while next_max_id: results = self.api.media_comments(str(media_id), max_id=next_max_id) comments.extend(results.get('comments', [])) next_max_id = results.get('next_max_id') return comments def __printTargetBanner__(self): pc.printout("\nLogged as ", pc.GREEN) pc.printout(self.api.username, pc.CYAN) pc.printout(". Target: ", pc.GREEN) pc.printout(str(self.target), pc.CYAN) pc.printout(" [" + str(self.target_id) + "]") if self.is_private: pc.printout(" [PRIVATE PROFILE]", pc.BLUE) if self.following: pc.printout(" [FOLLOWING]", pc.GREEN) else: pc.printout(" [NOT FOLLOWING]", pc.RED) print('\n') def change_target(self): pc.printout("Insert new target username: ", pc.YELLOW) line = input() self.setTarget(line) return def get_addrs(self): if self.check_private_profile(): return pc.printout("Searching for target localizations...\n") data = self.__get_feed__() locations = {} for post in data: if 'location' in post and post['location'] is not None: if 'lat' in post['location'] and 'lng' in post['location']: lat = post['location']['lat'] lng = post['location']['lng'] locations[str(lat) + ', ' + str(lng)] = post.get('taken_at') address = {} for k, v in locations.items(): details = self.geolocator.reverse(k) unix_timestamp = datetime.datetime.fromtimestamp(v) address[details.address] = unix_timestamp.strftime('%Y-%m-%d %H:%M:%S') sort_addresses = sorted(address.items(), key=lambda p: p[1], reverse=True) if len(sort_addresses) > 0: t = PrettyTable() t.field_names = ['Post', 'Address', 'time'] t.align["Post"] = "l" t.align["Address"] = "l" t.align["Time"] = "l" pc.printout("\nWoohoo! We found " + str(len(sort_addresses)) + " addresses\n", pc.GREEN) i = 1 json_data = {} addrs_list = [] for address, time in sort_addresses: t.add_row([str(i), address, time]) if self.jsonDump: addr = { 'address': address, 'time': time } addrs_list.append(addr) i = i + 1 if self.writeFile: file_name = self.output_dir + "/" + self.target + "_addrs.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['address'] = addrs_list json_file_name = self.output_dir + "/" + self.target + "_addrs.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_captions(self): if self.check_private_profile(): return pc.printout("Searching for target captions...\n") captions = [] data = self.__get_feed__() counter = 0 try: for item in data: if "caption" in item: if item["caption"] is not None: text = item["caption"]["text"] captions.append(text) counter = counter + 1 sys.stdout.write("\rFound %i" % counter) sys.stdout.flush() except AttributeError: pass except KeyError: pass json_data = {} if counter > 0: pc.printout("\nWoohoo! We found " + str(counter) + " captions\n", pc.GREEN) file = None if self.writeFile: file_name = self.output_dir + "/" + self.target + "_captions.txt" file = open(file_name, "w") for s in captions: print(s + "\n") if self.writeFile: file.write(s + "\n") if self.jsonDump: json_data['captions'] = captions json_file_name = self.output_dir + "/" + self.target + "_followings.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) if file is not None: file.close() else: pc.printout("Sorry! No results found :-(\n", pc.RED) return def get_total_comments(self): if self.check_private_profile(): return pc.printout("Searching for target total comments...\n") comments_counter = 0 posts = 0 data = self.__get_feed__() for post in data: comments_counter += post['comment_count'] posts += 1 if self.writeFile: file_name = self.output_dir + "/" + self.target + "_comments.txt" file = open(file_name, "w") file.write(str(comments_counter) + " comments in " + str(posts) + " posts\n") file.close() if self.jsonDump: json_data = { 'comment_counter': comments_counter, 'posts': posts } json_file_name = self.output_dir + "/" + self.target + "_comments.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) pc.printout(str(comments_counter), pc.MAGENTA) pc.printout(" comments in " + str(posts) + " posts\n") def get_comment_data(self): if self.check_private_profile(): return pc.printout("Retrieving all comments, this may take a moment...\n") data = self.__get_feed__() _comments = [] t = PrettyTable(['POST ID', 'ID', 'Username', 'Comment']) t.align["POST ID"] = "l" t.align["ID"] = "l" t.align["Username"] = "l" t.align["Comment"] = "l" for post in data: post_id = post.get('id') comments = self.api.media_n_comments(post_id) for comment in comments: t.add_row([post_id, comment.get('user_id'), comment.get('user').get('username'), comment.get('text')]) comment = { "post_id": post_id, "user_id":comment.get('user_id'), "username": comment.get('user').get('username'), "comment": comment.get('text') } _comments.append(comment) print(t) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_comment_data.txt" with open(file_name, 'w') as f: f.write(str(t)) f.close() if self.jsonDump: file_name_json = self.output_dir + "/" + self.target + "_comment_data.json" with open(file_name_json, 'w') as f: f.write("{ \"Comments\":[ \n") f.write('\n'.join(json.dumps(comment) for comment in _comments) + ',\n') f.write("]} ") def get_followers(self): if self.check_private_profile(): return pc.printout("Searching for target followers...\n") _followers = [] followers = [] rank_token = AppClient.generate_uuid() data = self.api.user_followers(str(self.target_id), rank_token=rank_token) _followers.extend(data.get('users', [])) next_max_id = data.get('next_max_id') while next_max_id: sys.stdout.write("\rCatched %i followers" % len(_followers)) sys.stdout.flush() results = self.api.user_followers(str(self.target_id), rank_token=rank_token, max_id=next_max_id) _followers.extend(results.get('users', [])) next_max_id = results.get('next_max_id') print("\n") for user in _followers: u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followers.append(u) t = PrettyTable(['ID', 'Username', 'Full Name']) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" json_data = {} followings_list = [] for node in followers: t.add_row([str(node['id']), node['username'], node['full_name']]) if self.jsonDump: follow = { 'id': node['id'], 'username': node['username'], 'full_name': node['full_name'] } followings_list.append(follow) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_followers.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followers'] = followers json_file_name = self.output_dir + "/" + self.target + "_followers.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) def get_followings(self): if self.check_private_profile(): return pc.printout("Searching for target followings...\n") _followings = [] followings = [] rank_token = AppClient.generate_uuid() data = self.api.user_following(str(self.target_id), rank_token=rank_token) _followings.extend(data.get('users', [])) next_max_id = data.get('next_max_id') while next_max_id: sys.stdout.write("\rCatched %i followings" % len(_followings)) sys.stdout.flush() results = self.api.user_following(str(self.target_id), rank_token=rank_token, max_id=next_max_id) _followings.extend(results.get('users', [])) next_max_id = results.get('next_max_id') print("\n") for user in _followings: u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) t = PrettyTable(['ID', 'Username', 'Full Name']) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" json_data = {} followings_list = [] for node in followings: t.add_row([str(node['id']), node['username'], node['full_name']]) if self.jsonDump: follow = { 'id': node['id'], 'username': node['username'], 'full_name': node['full_name'] } followings_list.append(follow) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_followings.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followings'] = followings_list json_file_name = self.output_dir + "/" + self.target + "_followings.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) def get_hashtags(self): if self.check_private_profile(): return pc.printout("Searching for target hashtags...\n") hashtags = [] counter = 1 texts = [] data = self.api.user_feed(str(self.target_id)) texts.extend(data.get('items', [])) next_max_id = data.get('next_max_id') while next_max_id: results = self.api.user_feed(str(self.target_id), max_id=next_max_id) texts.extend(results.get('items', [])) next_max_id = results.get('next_max_id') for post in texts: if post['caption'] is not None: caption = post['caption']['text'] for s in caption.split(): if s.startswith('#'): hashtags.append(s.encode('UTF-8')) counter += 1 if len(hashtags) > 0: hashtag_counter = {} for i in hashtags: if i in hashtag_counter: hashtag_counter[i] += 1 else: hashtag_counter[i] = 1 ssort = sorted(hashtag_counter.items(), key=lambda value: value[1], reverse=True) file = None json_data = {} hashtags_list = [] if self.writeFile: file_name = self.output_dir + "/" + self.target + "_hashtags.txt" file = open(file_name, "w") for k, v in ssort: hashtag = str(k.decode('utf-8')) print(str(v) + ". " + hashtag) if self.writeFile: file.write(str(v) + ". " + hashtag + "\n") if self.jsonDump: hashtags_list.append(hashtag) if file is not None: file.close() if self.jsonDump: json_data['hashtags'] = hashtags_list json_file_name = self.output_dir + "/" + self.target + "_hashtags.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user_info(self): try: endpoint = 'users/{user_id!s}/full_detail_info/'.format(**{'user_id': self.target_id}) content = self.api._call_api(endpoint) data = content['user_detail']['user'] pc.printout("[ID] ", pc.GREEN) pc.printout(str(data['pk']) + '\n') pc.printout("[FULL NAME] ", pc.RED) pc.printout(str(data['full_name']) + '\n') pc.printout("[BIOGRAPHY] ", pc.CYAN) pc.printout(str(data['biography']) + '\n') pc.printout("[FOLLOWED] ", pc.BLUE) pc.printout(str(data['follower_count']) + '\n') pc.printout("[FOLLOW] ", pc.GREEN) pc.printout(str(data['following_count']) + '\n') pc.printout("[BUSINESS ACCOUNT] ", pc.RED) pc.printout(str(data['is_business']) + '\n') if data['is_business']: if not data['can_hide_category']: pc.printout("[BUSINESS CATEGORY] ") pc.printout(str(data['category']) + '\n') pc.printout("[VERIFIED ACCOUNT] ", pc.CYAN) pc.printout(str(data['is_verified']) + '\n') if 'public_email' in data and data['public_email']: pc.printout("[EMAIL] ", pc.BLUE) pc.printout(str(data['public_email']) + '\n') pc.printout("[HD PROFILE PIC] ", pc.GREEN) pc.printout(str(data['hd_profile_pic_url_info']['url']) + '\n') if 'fb_page_call_to_action_id' in data and data['fb_page_call_to_action_id']: pc.printout("[FB PAGE] ", pc.RED) pc.printout(str(data['connected_fb_page']) + '\n') if 'whatsapp_number' in data and data['whatsapp_number']: pc.printout("[WHATSAPP NUMBER] ", pc.GREEN) pc.printout(str(data['whatsapp_number']) + '\n') if 'city_name' in data and data['city_name']: pc.printout("[CITY] ", pc.YELLOW) pc.printout(str(data['city_name']) + '\n') if 'address_street' in data and data['address_street']: pc.printout("[ADDRESS STREET] ", pc.RED) pc.printout(str(data['address_street']) + '\n') if 'contact_phone_number' in data and data['contact_phone_number']: pc.printout("[CONTACT PHONE NUMBER] ", pc.CYAN) pc.printout(str(data['contact_phone_number']) + '\n') if self.jsonDump: user = { 'id': data['pk'], 'full_name': data['full_name'], 'biography': data['biography'], 'edge_followed_by': data['follower_count'], 'edge_follow': data['following_count'], 'is_business_account': data['is_business'], 'is_verified': data['is_verified'], 'profile_pic_url_hd': data['hd_profile_pic_url_info']['url'] } if 'public_email' in data and data['public_email']: user['email'] = data['public_email'] if 'fb_page_call_to_action_id' in data and data['fb_page_call_to_action_id']: user['connected_fb_page'] = data['fb_page_call_to_action_id'] if 'whatsapp_number' in data and data['whatsapp_number']: user['whatsapp_number'] = data['whatsapp_number'] if 'city_name' in data and data['city_name']: user['city_name'] = data['city_name'] if 'address_street' in data and data['address_street']: user['address_street'] = data['address_street'] if 'contact_phone_number' in data and data['contact_phone_number']: user['contact_phone_number'] = data['contact_phone_number'] json_file_name = self.output_dir + "/" + self.target + "_info.json" with open(json_file_name, 'w') as f: json.dump(user, f) except ClientError as e: print(e) pc.printout("Oops... " + str(self.target) + " non exist, please enter a valid username.", pc.RED) pc.printout("\n") exit(2) def get_total_likes(self): if self.check_private_profile(): return pc.printout("Searching for target total likes...\n") like_counter = 0 posts = 0 data = self.__get_feed__() likes = [int(p["like_count"]) for p in data] posts = len(likes) like_counter = sum(likes) min_ = min(likes) max_ = max(likes) avg = int(like_counter / posts) result = f" likes in {posts} posts (min: {min_}, max: {max_}, avg: {avg})\n" if self.writeFile: file_name = self.output_dir + "/" + self.target + "_likes.txt" file = open(file_name, "w") file.write(str(like_counter) + result) file.close() if self.jsonDump: json_data = { "like_counter": like_counter, "posts": posts, "min": min_, "max": max_, "avg": avg, } json_file_name = self.output_dir + "/" + self.target + "_likes.json" with open(json_file_name, "w") as f: json.dump(json_data, f) pc.printout(str(like_counter), pc.MAGENTA) pc.printout(result) def get_media_type(self): if self.check_private_profile(): return pc.printout("Searching for target captions...\n") counter = 0 photo_counter = 0 video_counter = 0 data = self.__get_feed__() for post in data: if "media_type" in post: if post["media_type"] == 1: photo_counter = photo_counter + 1 elif post["media_type"] == 2: video_counter = video_counter + 1 counter = counter + 1 sys.stdout.write("\rChecked %i" % counter) sys.stdout.flush() sys.stdout.write(" posts") sys.stdout.flush() if counter > 0: if self.writeFile: file_name = self.output_dir + "/" + self.target + "_mediatype.txt" file = open(file_name, "w") file.write(str(photo_counter) + " photos and " + str(video_counter) + " video posted by target\n") file.close() pc.printout("\nWoohoo! We found " + str(photo_counter) + " photos and " + str(video_counter) + " video posted by target\n", pc.GREEN) if self.jsonDump: json_data = { "photos": photo_counter, "videos": video_counter } json_file_name = self.output_dir + "/" + self.target + "_mediatype.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_people_who_commented(self): if self.check_private_profile(): return pc.printout("Searching for users who commented...\n") data = self.__get_feed__() users = [] for post in data: comments = self.__get_comments__(post['id']) for comment in comments: if not any(u['id'] == comment['user']['pk'] for u in users): user = { 'id': comment['user']['pk'], 'username': comment['user']['username'], 'full_name': comment['user']['full_name'], 'counter': 1 } users.append(user) else: for user in users: if user['id'] == comment['user']['pk']: user['counter'] += 1 break if len(users) > 0: ssort = sorted(users, key=lambda value: value['counter'], reverse=True) json_data = {} t = PrettyTable() t.field_names = ['Comments', 'ID', 'Username', 'Full Name'] t.align["Comments"] = "l" t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" for u in ssort: t.add_row([str(u['counter']), u['id'], u['username'], u['full_name']]) print(t) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_users_who_commented.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['users_who_commented'] = ssort json_file_name = self.output_dir + "/" + self.target + "_users_who_commented.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_people_who_tagged(self): if self.check_private_profile(): return pc.printout("Searching for users who tagged target...\n") posts = [] result = self.api.usertag_feed(self.target_id) posts.extend(result.get('items', [])) next_max_id = result.get('next_max_id') while next_max_id: results = self.api.user_feed(str(self.target_id), max_id=next_max_id) posts.extend(results.get('items', [])) next_max_id = results.get('next_max_id') if len(posts) > 0: pc.printout("\nWoohoo! We found " + str(len(posts)) + " photos\n", pc.GREEN) users = [] for post in posts: if not any(u['id'] == post['user']['pk'] for u in users): user = { 'id': post['user']['pk'], 'username': post['user']['username'], 'full_name': post['user']['full_name'], 'counter': 1 } users.append(user) else: for user in users: if user['id'] == post['user']['pk']: user['counter'] += 1 break ssort = sorted(users, key=lambda value: value['counter'], reverse=True) json_data = {} t = PrettyTable() t.field_names = ['Photos', 'ID', 'Username', 'Full Name'] t.align["Photos"] = "l" t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" for u in ssort: t.add_row([str(u['counter']), u['id'], u['username'], u['full_name']]) print(t) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_users_who_tagged.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['users_who_tagged'] = ssort json_file_name = self.output_dir + "/" + self.target + "_users_who_tagged.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_photo_description(self): if self.check_private_profile(): return content = httpx.get("https://www.instagram.com/" + str(self.target) + "/?__a=1") data = content.json() dd = data['graphql']['user']['edge_owner_to_timeline_media']['edges'] if len(dd) > 0: pc.printout("\nWoohoo! We found " + str(len(dd)) + " descriptions\n", pc.GREEN) count = 1 t = PrettyTable(['Photo', 'Description']) t.align["Photo"] = "l" t.align["Description"] = "l" json_data = {} descriptions_list = [] for i in dd: node = i.get('node') descr = node.get('accessibility_caption') t.add_row([str(count), descr]) if self.jsonDump: description = { 'description': descr } descriptions_list.append(description) count += 1 if self.writeFile: file_name = self.output_dir + "/" + self.target + "_photodes.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['descriptions'] = descriptions_list json_file_name = self.output_dir + "/" + self.target + "_descriptions.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user_photo(self): if self.check_private_profile(): return limit = -1 if self.cli_mode: user_input = "" else: pc.printout("How many photos you want to download (default all): ", pc.YELLOW) user_input = input() try: if user_input == "": pc.printout("Downloading all photos available...\n") else: limit = int(user_input) pc.printout("Downloading " + user_input + " photos...\n") except ValueError: pc.printout("Wrong value entered\n", pc.RED) return data = [] counter = 0 result = self.api.user_feed(str(self.target_id)) data.extend(result.get('items', [])) next_max_id = result.get('next_max_id') while next_max_id: results = self.api.user_feed(str(self.target_id), max_id=next_max_id) data.extend(results.get('items', [])) next_max_id = results.get('next_max_id') try: for item in data: if counter == limit: break if "image_versions2" in item: counter = counter + 1 url = item["image_versions2"]["candidates"][0]["url"] photo_id = item["id"] end = self.output_dir + "/" + self.target + "_" + photo_id + ".jpg" urllib.request.urlretrieve(url, end) sys.stdout.write("\rDownloaded %i" % counter) sys.stdout.flush() else: carousel = item["carousel_media"] for i in carousel: if counter == limit: break counter = counter + 1 url = i["image_versions2"]["candidates"][0]["url"] photo_id = i["id"] end = self.output_dir + "/" + self.target + "_" + photo_id + ".jpg" urllib.request.urlretrieve(url, end) sys.stdout.write("\rDownloaded %i" % counter) sys.stdout.flush() except AttributeError: pass except KeyError: pass sys.stdout.write(" photos") sys.stdout.flush() pc.printout("\nWoohoo! We downloaded " + str(counter) + " photos (saved in " + self.output_dir + " folder) \n", pc.GREEN) def get_user_propic(self): try: endpoint = 'users/{user_id!s}/full_detail_info/'.format(**{'user_id': self.target_id}) content = self.api._call_api(endpoint) data = content['user_detail']['user'] if "hd_profile_pic_url_info" in data: URL = data["hd_profile_pic_url_info"]['url'] else: #get better quality photo items = len(data['hd_profile_pic_versions']) URL = data["hd_profile_pic_versions"][items-1]['url'] if URL != "": end = self.output_dir + "/" + self.target + "_propic.jpg" urllib.request.urlretrieve(URL, end) pc.printout("Target propic saved in output folder\n", pc.GREEN) else: pc.printout("Sorry! No results found :-(\n", pc.RED) except ClientError as e: error = json.loads(e.error_response) print(error['message']) print(error['error_title']) exit(2) def get_user_stories(self): if self.check_private_profile(): return pc.printout("Searching for target stories...\n") data = self.api.user_reel_media(str(self.target_id)) counter = 0 if data['items'] is not None: # no stories avaibile counter = data['media_count'] for i in data['items']: story_id = i["id"] if i["media_type"] == 1: # it's a photo url = i['image_versions2']['candidates'][0]['url'] end = self.output_dir + "/" + self.target + "_" + story_id + ".jpg" urllib.request.urlretrieve(url, end) elif i["media_type"] == 2: # it's a gif or video url = i['video_versions'][0]['url'] end = self.output_dir + "/" + self.target + "_" + story_id + ".mp4" urllib.request.urlretrieve(url, end) if counter > 0: pc.printout(str(counter) + " target stories saved in output folder\n", pc.GREEN) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_people_tagged_by_user(self): pc.printout("Searching for users tagged by target...\n") ids = [] username = [] full_name = [] post = [] counter = 1 data = self.__get_feed__() try: for i in data: if "usertags" in i: c = i.get('usertags').get('in') for cc in c: if cc.get('user').get('pk') not in ids: ids.append(cc.get('user').get('pk')) username.append(cc.get('user').get('username')) full_name.append(cc.get('user').get('full_name')) post.append(1) else: index = ids.index(cc.get('user').get('pk')) post[index] += 1 counter = counter + 1 except AttributeError as ae: pc.printout("\nERROR: an error occurred: ", pc.RED) print(ae) print("") pass if len(ids) > 0: t = PrettyTable() t.field_names = ['Posts', 'Full Name', 'Username', 'ID'] t.align["Posts"] = "l" t.align["Full Name"] = "l" t.align["Username"] = "l" t.align["ID"] = "l" pc.printout("\nWoohoo! We found " + str(len(ids)) + " (" + str(counter) + ") users\n", pc.GREEN) json_data = {} tagged_list = [] for i in range(len(ids)): t.add_row([post[i], full_name[i], username[i], str(ids[i])]) if self.jsonDump: tag = { 'post': post[i], 'full_name': full_name[i], 'username': username[i], 'id': ids[i] } tagged_list.append(tag) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_tagged.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['tagged'] = tagged_list json_file_name = self.output_dir + "/" + self.target + "_tagged.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user(self, username): try: content = self.api.username_info(username) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_user_id.txt" file = open(file_name, "w") file.write(str(content['user']['pk'])) file.close() user = dict() user['id'] = content['user']['pk'] user['is_private'] = content['user']['is_private'] return user except ClientError as e: pc.printout('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(e.msg, e.code, e.error_response), pc.RED) error = json.loads(e.error_response) if 'message' in error: print(error['message']) if 'error_title' in error: print(error['error_title']) if 'challenge' in error: print("Please follow this link to complete the challenge: " + error['challenge']['url']) sys.exit(2) def set_write_file(self, flag): if flag: pc.printout("Write to file: ") pc.printout("enabled", pc.GREEN) pc.printout("\n") else: pc.printout("Write to file: ") pc.printout("disabled", pc.RED) pc.printout("\n") self.writeFile = flag def set_json_dump(self, flag): if flag: pc.printout("Export to JSON: ") pc.printout("enabled", pc.GREEN) pc.printout("\n") else: pc.printout("Export to JSON: ") pc.printout("disabled", pc.RED) pc.printout("\n") self.jsonDump = flag def login(self, u, p): try: settings_file = "config/settings.json" if not os.path.isfile(settings_file): # settings file does not exist print(f'Unable to find file: {settings_file!s}') # login new self.api = AppClient(auto_patch=True, authenticate=True, username=u, password=p, on_login=lambda x: self.onlogin_callback(x, settings_file)) else: with open(settings_file) as file_data: cached_settings = json.load(file_data, object_hook=self.from_json) # print('Reusing settings: {0!s}'.format(settings_file)) # reuse auth settings self.api = AppClient( username=u, password=p, settings=cached_settings, on_login=lambda x: self.onlogin_callback(x, settings_file)) except (ClientCookieExpiredError, ClientLoginRequiredError) as e: print(f'ClientCookieExpiredError/ClientLoginRequiredError: {e!s}') # Login expired # Do relogin but use default ua, keys and such self.api = AppClient(auto_patch=True, authenticate=True, username=u, password=p, on_login=lambda x: self.onlogin_callback(x, settings_file)) except ClientError as e: pc.printout('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(e.msg, e.code, e.error_response), pc.RED) error = json.loads(e.error_response) pc.printout(error['message'], pc.RED) pc.printout(": ", pc.RED) pc.printout(e.msg, pc.RED) pc.printout("\n") if 'challenge' in error: print("Please follow this link to complete the challenge: " + error['challenge']['url']) exit(9) def to_json(self, python_object): if isinstance(python_object, bytes): return {'__class__': 'bytes', '__value__': codecs.encode(python_object, 'base64').decode()} raise TypeError(repr(python_object) + ' is not JSON serializable') def from_json(self, json_object): if '__class__' in json_object and json_object['__class__'] == 'bytes': return codecs.decode(json_object['__value__'].encode(), 'base64') return json_object def onlogin_callback(self, api, new_settings_file): cache_settings = api.settings with open(new_settings_file, 'w') as outfile: json.dump(cache_settings, outfile, default=self.to_json) # print('SAVED: {0!s}'.format(new_settings_file)) def check_following(self): if str(self.target_id) == self.api.authenticated_user_id: return True endpoint = 'users/{user_id!s}/full_detail_info/'.format(**{'user_id': self.target_id}) return self.api._call_api(endpoint)['user_detail']['user']['friendship_status']['following'] def check_private_profile(self): if self.is_private and not self.following: pc.printout("Impossible to execute command: user has private profile\n", pc.RED) send = input("Do you want send a follow request? [Y/N]: ") if send.lower() == "y": self.api.friendships_create(self.target_id) print("Sent a follow request to target. Use this command after target accepting the request.") return True return False def get_fwersemail(self): if self.check_private_profile(): return followers = [] try: pc.printout("Searching for emails of target followers... this can take a few minutes\n") rank_token = AppClient.generate_uuid() data = self.api.user_followers(str(self.target_id), rank_token=rank_token) for user in data.get('users', []): u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followers.append(u) next_max_id = data.get('next_max_id') while next_max_id: sys.stdout.write("\rCatched %i followers email" % len(followers)) sys.stdout.flush() results = self.api.user_followers(str(self.target_id), rank_token=rank_token, max_id=next_max_id) for user in results.get('users', []): u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followers.append(u) next_max_id = results.get('next_max_id') print("\n") results = [] pc.printout("Do you want to get all emails? y/n: ", pc.YELLOW) value = input() if value == str("y") or value == str("yes") or value == str("Yes") or value == str("YES"): value = len(followers) elif value == str(""): print("\n") return elif value == str("n") or value == str("no") or value == str("No") or value == str("NO"): while True: try: pc.printout("How many emails do you want to get? ", pc.YELLOW) new_value = int(input()) value = new_value - 1 break except ValueError: pc.printout("Error! Please enter a valid integer!", pc.RED) print("\n") return else: pc.printout("Error! Please enter y/n :-)", pc.RED) print("\n") return for follow in followers: user = self.api.user_info(str(follow['id'])) if 'public_email' in user['user'] and user['user']['public_email']: follow['email'] = user['user']['public_email'] if len(results) > value: break results.append(follow) except ClientThrottledError as e: pc.printout("\nError: Instagram blocked the requests. Please wait a few minutes before you try again.", pc.RED) pc.printout("\n") if len(results) > 0: t = PrettyTable(['ID', 'Username', 'Full Name', 'Email']) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" t.align["Email"] = "l" json_data = {} for node in results: t.add_row([str(node['id']), node['username'], node['full_name'], node['email']]) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_fwersemail.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followers_email'] = results json_file_name = self.output_dir + "/" + self.target + "_fwersemail.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_fwingsemail(self): if self.check_private_profile(): return followings = [] try: pc.printout("Searching for emails of users followed by target... this can take a few minutes\n") rank_token = AppClient.generate_uuid() data = self.api.user_following(str(self.target_id), rank_token=rank_token) for user in data.get('users', []): u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) next_max_id = data.get('next_max_id') while next_max_id: results = self.api.user_following(str(self.target_id), rank_token=rank_token, max_id=next_max_id) for user in results.get('users', []): u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) next_max_id = results.get('next_max_id') results = [] pc.printout("Do you want to get all emails? y/n: ", pc.YELLOW) value = input() if value == str("y") or value == str("yes") or value == str("Yes") or value == str("YES"): value = len(followings) elif value == str(""): print("\n") return elif value == str("n") or value == str("no") or value == str("No") or value == str("NO"): while True: try: pc.printout("How many emails do you want to get? ", pc.YELLOW) new_value = int(input()) value = new_value - 1 break except ValueError: pc.printout("Error! Please enter a valid integer!", pc.RED) print("\n") return else: pc.printout("Error! Please enter y/n :-)", pc.RED) print("\n") return for follow in followings: sys.stdout.write("\rCatched %i followings email" % len(results)) sys.stdout.flush() user = self.api.user_info(str(follow['id'])) if 'public_email' in user['user'] and user['user']['public_email']: follow['email'] = user['user']['public_email'] if len(results) > value: break results.append(follow) except ClientThrottledError as e: pc.printout("\nError: Instagram blocked the requests. Please wait a few minutes before you try again.", pc.RED) pc.printout("\n") print("\n") if len(results) > 0: t = PrettyTable(['ID', 'Username', 'Full Name', 'Email']) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" t.align["Email"] = "l" json_data = {} for node in results: t.add_row([str(node['id']), node['username'], node['full_name'], node['email']]) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_fwingsemail.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followings_email'] = results json_file_name = self.output_dir + "/" + self.target + "_fwingsemail.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_fwingsnumber(self): if self.check_private_profile(): return try: pc.printout("Searching for phone numbers of users followed by target... this can take a few minutes\n") followings = [] rank_token = AppClient.generate_uuid() data = self.api.user_following(str(self.target_id), rank_token=rank_token) for user in data.get('users', []): u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) next_max_id = data.get('next_max_id') while next_max_id: results = self.api.user_following(str(self.target_id), rank_token=rank_token, max_id=next_max_id) for user in results.get('users', []): u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) next_max_id = results.get('next_max_id') results = [] pc.printout("Do you want to get all phone numbers? y/n: ", pc.YELLOW) value = input() if value == str("y") or value == str("yes") or value == str("Yes") or value == str("YES"): value = len(followings) elif value == str(""): print("\n") return elif value == str("n") or value == str("no") or value == str("No") or value == str("NO"): while True: try: pc.printout("How many phone numbers do you want to get? ", pc.YELLOW) new_value = int(input()) value = new_value - 1 break except ValueError: pc.printout("Error! Please enter a valid integer!", pc.RED) print("\n") return else: pc.printout("Error! Please enter y/n :-)", pc.RED) print("\n") return for follow in followings: sys.stdout.write("\rCatched %i followings phone numbers" % len(results)) sys.stdout.flush() user = self.api.user_info(str(follow['id'])) if 'contact_phone_number' in user['user'] and user['user']['contact_phone_number']: follow['contact_phone_number'] = user['user']['contact_phone_number'] if len(results) > value: break results.append(follow) except ClientThrottledError as e: pc.printout("\nError: Instagram blocked the requests. Please wait a few minutes before you try again.", pc.RED) pc.printout("\n") print("\n") if len(results) > 0: t = PrettyTable(['ID', 'Username', 'Full Name', 'Phone']) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" t.align["Phone number"] = "l" json_data = {} for node in results: t.add_row([str(node['id']), node['username'], node['full_name'], node['contact_phone_number']]) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_fwingsnumber.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followings_phone_numbers'] = results json_file_name = self.output_dir + "/" + self.target + "_fwingsnumber.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_fwersnumber(self): if self.check_private_profile(): return followings = [] try: pc.printout("Searching for phone numbers of users followers... this can take a few minutes\n") rank_token = AppClient.generate_uuid() data = self.api.user_following(str(self.target_id), rank_token=rank_token) for user in data.get('users', []): u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) next_max_id = data.get('next_max_id') while next_max_id: results = self.api.user_following(str(self.target_id), rank_token=rank_token, max_id=next_max_id) for user in results.get('users', []): u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) next_max_id = results.get('next_max_id') results = [] pc.printout("Do you want to get all phone numbers? y/n: ", pc.YELLOW) value = input() if value == str("y") or value == str("yes") or value == str("Yes") or value == str("YES"): value = len(followings) elif value == str(""): print("\n") return elif value == str("n") or value == str("no") or value == str("No") or value == str("NO"): while True: try: pc.printout("How many phone numbers do you want to get? ", pc.YELLOW) new_value = int(input()) value = new_value - 1 break except ValueError: pc.printout("Error! Please enter a valid integer!", pc.RED) print("\n") return else: pc.printout("Error! Please enter y/n :-)", pc.RED) print("\n") return for follow in followings: sys.stdout.write("\rCatched %i followers phone numbers" % len(results)) sys.stdout.flush() user = self.api.user_info(str(follow['id'])) if 'contact_phone_number' in user['user'] and user['user']['contact_phone_number']: follow['contact_phone_number'] = user['user']['contact_phone_number'] if len(results) > value: break results.append(follow) except ClientThrottledError as e: pc.printout("\nError: Instagram blocked the requests. Please wait a few minutes before you try again.", pc.RED) pc.printout("\n") print("\n") if len(results) > 0: t = PrettyTable(['ID', 'Username', 'Full Name', 'Phone']) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" t.align["Phone number"] = "l" json_data = {} for node in results: t.add_row([str(node['id']), node['username'], node['full_name'], node['contact_phone_number']]) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_fwersnumber.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followings_phone_numbers'] = results json_file_name = self.output_dir + "/" + self.target + "_fwerssnumber.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_comments(self): if self.check_private_profile(): return pc.printout("Searching for users who commented...\n") data = self.__get_feed__() users = [] for post in data: comments = self.__get_comments__(post['id']) for comment in comments: print(comment['text']) # if not any(u['id'] == comment['user']['pk'] for u in users): # user = { # 'id': comment['user']['pk'], # 'username': comment['user']['username'], # 'full_name': comment['user']['full_name'], # 'counter': 1 # } # users.append(user) # else: # for user in users: # if user['id'] == comment['user']['pk']: # user['counter'] += 1 # break if len(users) > 0: ssort = sorted(users, key=lambda value: value['counter'], reverse=True) json_data = {} t = PrettyTable() t.field_names = ['Comments', 'ID', 'Username', 'Full Name'] t.align["Comments"] = "l" t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" for u in ssort: t.add_row([str(u['counter']), u['id'], u['username'], u['full_name']]) print(t) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_users_who_commented.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['users_who_commented'] = ssort json_file_name = self.output_dir + "/" + self.target + "_users_who_commented.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def clear_cache(self): try: f = open("config/settings.json",'w') f.write("{}") pc.printout("Cache Cleared.\n",pc.GREEN) except FileNotFoundError: pc.printout("Settings.json don't exist.\n",pc.RED) finally: f.close() ================================================ FILE: src/artwork.py ================================================ ascii_art = r""" ________ .__ __ \_____ \ _____|__| _____/ |_ ________________ _____ / | \ / ___/ |/ \ __\/ ___\_ __ \__ \ / \ / | \\___ \| | | \ | / /_/ > | \// __ \| Y Y \ \_______ /____ >__|___| /__| \___ /|__| (____ /__|_| / \/ \/ \/ /_____/ \/ \/ """ ================================================ FILE: src/config.py ================================================ import os import configparser import sys from src import printcolors as pc try: config = configparser.ConfigParser(interpolation=None) config.read("config/credentials.ini") except FileNotFoundError: pc.printout('Error: file "config/credentials.ini" not found!\n', pc.RED) sys.exit(0) except Exception as e: pc.printout("Error: {}\n".format(e), pc.RED) sys.exit(0) def getUsername(): try: username = config["Credentials"]["username"] if username == '': pc.printout('Error: "username" field cannot be blank in "config/credentials.ini"\n', pc.RED) sys.exit(0) return username except KeyError: pc.printout('Error: missing "username" field in "config/credentials.ini"\n', pc.RED) sys.exit(0) def getPassword(): try: password = config["Credentials"]["password"] if password == '': pc.printout('Error: "password" field cannot be blank in "config/credentials.ini"\n', pc.RED) sys.exit(0) return password except KeyError: pc.printout('Error: missing "password" field in "config/credentials.ini"\n', pc.RED) sys.exit(0) def getHikerToken(): return config["Credentials"].get("hikerapi_token") or os.getenv("HIKERAPI_TOKEN") ================================================ FILE: src/hikercli.py ================================================ import datetime import json import sys import urllib import codecs from pathlib import Path import ssl ssl._create_default_https_context = ssl._create_unverified_context from geopy.geocoders import Nominatim from hikerapi import Client as AppClient from hikerapi import __version__ as hk from prettytable import PrettyTable from src import printcolors as pc from src import config class HikerCLI: api = None api2 = None geolocator = Nominatim(user_agent="http") user_id = None target_id = None is_private = True following = False target = "" writeFile = False jsonDump = False cli_mode = False output_dir = "output" def __init__(self, target, is_file, is_json, is_cli, output_dir, clear_cookies): self.output_dir = output_dir or self.output_dir access_key = config.getHikerToken() self.cli_mode = is_cli if not is_cli: print("\nConnect to HikerAPI...") self.api = AppClient(token=access_key) self.setTarget(target) self.writeFile = is_file self.jsonDump = is_json def setTarget(self, target): self.target = target self.user = self.get_user(target) self.target_id = self.user["pk"] self.is_private = self.user["is_private"] self.__printTargetBanner__() self.output_dir = self.output_dir + "/" + str(self.target) Path(self.output_dir).mkdir(parents=True, exist_ok=True) def __get_feed__(self, limit=-1): data = [] next_page_id = "" while True: pc.printout("@", pc.CYAN) result = self.api.user_medias_v2(self.target_id, page_id=next_page_id) data.extend(result.get("response", {}).get("items", [])) next_page_id = result.get("next_page_id") if limit > -1 and len(data) >= limit: break if not next_page_id: break return data def __get_comments__(self, media_id, limit=-1): data = [] next_page_id = "" while True: pc.printout("@", pc.CYAN) try: result = self.api.media_comments_v2(media_id, page_id=next_page_id) except Exception as e: msg = str(e) pc.printout(msg, pc.RED) if "Entries not found" in msg: return data raise e data.extend(result.get("response", {}).get("comments", [])) next_page_id = result.get("next_page_id") if limit > -1 and len(data) >= limit: break if not next_page_id: break return data def __printTargetBanner__(self): pc.printout("Target: ", pc.GREEN) pc.printout(str(self.target), pc.CYAN) pc.printout(" [" + str(self.target_id) + "]") if self.is_private: pc.printout(" [PRIVATE PROFILE]", pc.BLUE) print("\n") def change_target(self): pc.printout("Insert new target username: ", pc.YELLOW) line = input() self.setTarget(line) return def get_addrs(self): if self.check_private_profile(): return pc.printout("Searching for target localizations...\n") data = self.__get_feed__() locations = {} for post in data: if "location" in post and post["location"] is not None: if "lat" in post["location"] and "lng" in post["location"]: lat = post["location"]["lat"] lng = post["location"]["lng"] locations[str(lat) + ", " + str(lng)] = post.get("taken_at") address = {} for k, v in locations.items(): details = self.geolocator.reverse(k) unix_timestamp = datetime.datetime.fromtimestamp(v) address[details.address] = unix_timestamp.strftime("%Y-%m-%d %H:%M:%S") sort_addresses = sorted(address.items(), key=lambda p: p[1], reverse=True) if len(sort_addresses) > 0: t = PrettyTable() t.field_names = ["Post", "Address", "Time"] t.align["Post"] = "l" t.align["Address"] = "l" t.align["Time"] = "l" pc.printout( "\nWoohoo! We found " + str(len(sort_addresses)) + " addresses\n", pc.GREEN, ) i = 1 json_data = {} addrs_list = [] for address, time in sort_addresses: t.add_row([str(i), address, time]) if self.jsonDump: addr = {"address": address, "time": time} addrs_list.append(addr) i = i + 1 if self.writeFile: file_name = self.output_dir + "/" + self.target + "_addrs.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data["address"] = addrs_list json_file_name = self.output_dir + "/" + self.target + "_addrs.json" with open(json_file_name, "w") as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_captions(self): if self.check_private_profile(): return pc.printout("Searching for target captions...\n") captions = [] data = self.__get_feed__() counter = 0 try: for item in data: if "caption" in item: if item["caption"] is not None: text = item["caption"]["text"] captions.append(text) counter = counter + 1 sys.stdout.write("\rFound %i" % counter) sys.stdout.flush() except AttributeError: pass except KeyError: pass json_data = {} if counter > 0: pc.printout("\nWoohoo! We found " + str(counter) + " captions\n", pc.GREEN) file = None if self.writeFile: file_name = self.output_dir + "/" + self.target + "_captions.txt" file = open(file_name, "w") for s in captions: print(s + "\n") if self.writeFile: file.write(s + "\n") if self.jsonDump: json_data["captions"] = captions json_file_name = ( self.output_dir + "/" + self.target + "_followings.json" ) with open(json_file_name, "w") as f: json.dump(json_data, f) if file is not None: file.close() else: pc.printout("Sorry! No results found :-(\n", pc.RED) return def get_total_comments(self): if self.check_private_profile(): return pc.printout("Searching for target total comments...\n") data = self.__get_feed__() comments = [int(p["comment_count"]) for p in data] posts = len(comments) comments_counter = sum(comments) min_ = min(comments) max_ = max(comments) avg = int(comments_counter / posts) result = f" comments in {posts} posts (min: {min_}, max: {max_}, avg: {avg})\n" if self.writeFile: file_name = self.output_dir + "/" + self.target + "_comments.txt" file = open(file_name, "w") file.write( str(comments_counter) + " comments in " + str(posts) + " posts\n" ) file.close() if self.jsonDump: json_data = {"comment_counter": comments_counter, "posts": posts} json_file_name = self.output_dir + "/" + self.target + "_comments.json" with open(json_file_name, "w") as f: json.dump(json_data, f) pc.printout(str(comments_counter), pc.MAGENTA) pc.printout(result) def get_comment_data(self): if self.check_private_profile(): return pc.printout("Retrieving all comments, this may take a moment...\n") data = self.__get_feed__() _comments = [] t = PrettyTable(["POST ID", "ID", "Username", "Comment"]) t.align["POST ID"] = "l" t.align["ID"] = "l" t.align["Username"] = "l" t.align["Comment"] = "l" for post in data: post_id = post.get("id") comments = self.__get_comments__(post_id) for comment in comments: comment = { "post_id": post_id, "user_id": comment.get("user_id"), "username": comment.get("user", {}).get("username"), "comment": comment.get("text"), } t.add_row( [ post_id, comment["user_id"], comment["username"], comment["comment"], ] ) _comments.append(comment) print(t) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_comment_data.txt" with open(file_name, "w") as f: f.write(str(t)) f.close() if self.jsonDump: file_name_json = self.output_dir + "/" + self.target + "_comment_data.json" with open(file_name_json, "w") as f: f.write('{ "Comments":[ \n') f.write("\n".join(json.dumps(comment) for comment in _comments) + ",\n") f.write("]} ") def get_followers(self): if self.check_private_profile(): return pc.printout("Searching for target followers...\n") followers = [] next_page_id = "" while True: pc.printout("@", pc.CYAN) result = self.api.user_followers_v2(self.target_id, page_id=next_page_id) followers.extend(result.get("response", {}).get("users", [])) next_page_id = result.get("next_page_id") if not next_page_id: break print("\n") t = PrettyTable(["ID", "Username", "Full Name"]) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" items = [] for user in followers: u = { "id": user["pk"], "username": user["username"], "full_name": user["full_name"], "profile_pic_url": user["profile_pic_url"], "is_private": user["is_private"], "is_verified": user["is_verified"], } t.add_row([str(u["id"]), u["username"], u["full_name"]]) if self.jsonDump: items.append(u) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_followers.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data = {"followers": items} json_file_name = self.output_dir + "/" + self.target + "_followers.json" with open(json_file_name, "w") as f: json.dump(json_data, f) print(t) def get_followings(self): if self.check_private_profile(): return pc.printout("Searching for target followings...\n") following = [] next_page_id = "" while True: pc.printout("@", pc.CYAN) result = self.api.user_following_v2(self.target_id, page_id=next_page_id) following.extend(result.get("response", {}).get("users", [])) next_page_id = result.get("next_page_id") if not next_page_id: break print("\n") t = PrettyTable(["ID", "Username", "Full Name"]) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" items = [] for user in following: u = { "id": user["pk"], "username": user["username"], "full_name": user["full_name"], "profile_pic_url": user["profile_pic_url"], "is_private": user["is_private"], "is_verified": user["is_verified"], } t.add_row([str(u["id"]), u["username"], u["full_name"]]) if self.jsonDump: items.append(u) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_followings.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data = {"followings": items} json_file_name = self.output_dir + "/" + self.target + "_followings.json" with open(json_file_name, "w") as f: json.dump(json_data, f) print(t) def get_hashtags(self): if self.check_private_profile(): return pc.printout("Searching for target hashtags...\n") data = self.__get_feed__() hashtags = [] for post in data: if post["caption"] is not None: caption = post["caption"]["text"] for s in caption.split(): if s.startswith("#"): hashtags.append(s) if len(hashtags) > 0: hashtag_counter = {} for i in hashtags: if i in hashtag_counter: hashtag_counter[i] += 1 else: hashtag_counter[i] = 1 ssort = sorted( hashtag_counter.items(), key=lambda value: value[1], reverse=True ) file = None hashtags_list = [] if self.writeFile: file_name = self.output_dir + "/" + self.target + "_hashtags.txt" file = open(file_name, "w") print() for hashtag, v in ssort: line = f"{v}. {hashtag}" print(line) if self.writeFile: file.write(f"{line}\n") if self.jsonDump: hashtags_list.append(hashtag) if file is not None: file.close() if self.jsonDump: json_data = {"hashtags": hashtags_list} json_file_name = self.output_dir + "/" + self.target + "_hashtags.json" with open(json_file_name, "w") as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user_info(self): data = self.user pc.printout("[ID] ", pc.GREEN) pc.printout(str(data["pk"]) + "\n") pc.printout("[FULL NAME] ", pc.RED) pc.printout(str(data["full_name"]) + "\n") pc.printout("[BIOGRAPHY] ", pc.CYAN) pc.printout(str(data["biography"]) + "\n") pc.printout("[FOLLOWED] ", pc.BLUE) pc.printout(str(data["follower_count"]) + "\n") pc.printout("[FOLLOW] ", pc.GREEN) pc.printout(str(data["following_count"]) + "\n") pc.printout("[MEDIA] ", pc.CYAN) pc.printout(str(data["media_count"]) + "\n") pc.printout("[BUSINESS ACCOUNT] ", pc.RED) pc.printout(str(data["is_business"]) + "\n") if data["is_business"]: if not data["can_hide_category"]: pc.printout("[BUSINESS CATEGORY] ") pc.printout(str(data["category"]) + "\n") pc.printout("[VERIFIED ACCOUNT] ", pc.CYAN) pc.printout(str(data["is_verified"]) + "\n") if "public_email" in data and data["public_email"]: pc.printout("[EMAIL] ", pc.BLUE) pc.printout(str(data["public_email"]) + "\n") pc.printout("[HD PROFILE PIC] ", pc.GREEN) pc.printout(str(data["hd_profile_pic_url_info"]["url"]) + "\n") if "fb_page_call_to_action_id" in data and data["fb_page_call_to_action_id"]: pc.printout("[FB PAGE] ", pc.RED) pc.printout(str(data["connected_fb_page"]) + "\n") if "whatsapp_number" in data and data["whatsapp_number"]: pc.printout("[WHATSAPP NUMBER] ", pc.GREEN) pc.printout(str(data["whatsapp_number"]) + "\n") if "city_name" in data and data["city_name"]: pc.printout("[CITY] ", pc.YELLOW) pc.printout(str(data["city_name"]) + "\n") if "address_street" in data and data["address_street"]: pc.printout("[ADDRESS STREET] ", pc.RED) pc.printout(str(data["address_street"]) + "\n") if "contact_phone_number" in data and data["contact_phone_number"]: pc.printout("[CONTACT PHONE NUMBER] ", pc.CYAN) pc.printout(str(data["contact_phone_number"]) + "\n") if self.jsonDump: user = { "id": data["pk"], "full_name": data["full_name"], "biography": data["biography"], "edge_followed_by": data["follower_count"], "edge_follow": data["following_count"], "is_business_account": data["is_business"], "is_verified": data["is_verified"], "profile_pic_url_hd": data["hd_profile_pic_url_info"]["url"], } if "public_email" in data and data["public_email"]: user["email"] = data["public_email"] if ( "fb_page_call_to_action_id" in data and data["fb_page_call_to_action_id"] ): user["connected_fb_page"] = data["fb_page_call_to_action_id"] if "whatsapp_number" in data and data["whatsapp_number"]: user["whatsapp_number"] = data["whatsapp_number"] if "city_name" in data and data["city_name"]: user["city_name"] = data["city_name"] if "address_street" in data and data["address_street"]: user["address_street"] = data["address_street"] if "contact_phone_number" in data and data["contact_phone_number"]: user["contact_phone_number"] = data["contact_phone_number"] json_file_name = self.output_dir + "/" + self.target + "_info.json" with open(json_file_name, "w") as f: json.dump(user, f) def get_total_likes(self): if self.check_private_profile(): return pc.printout("Searching for target total likes...\n") data = self.__get_feed__() likes = [int(p["like_count"]) for p in data] posts = len(likes) like_counter = sum(likes) min_ = min(likes) max_ = max(likes) avg = int(like_counter / posts) result = f" likes in {posts} posts (min: {min_}, max: {max_}, avg: {avg})\n" if self.writeFile: file_name = self.output_dir + "/" + self.target + "_likes.txt" file = open(file_name, "w") file.write(str(like_counter) + result) file.close() if self.jsonDump: json_data = { "like_counter": like_counter, "posts": posts, "min": min_, "max": max_, "avg": avg, } json_file_name = self.output_dir + "/" + self.target + "_likes.json" with open(json_file_name, "w") as f: json.dump(json_data, f) pc.printout(f"\n{like_counter}", pc.MAGENTA) pc.printout(result) def get_media_type(self): if self.check_private_profile(): return pc.printout("Searching for target captions...\n") counter = 0 photo_counter = 0 video_counter = 0 data = self.__get_feed__() for post in data: if "media_type" in post: if post["media_type"] == 1: photo_counter = photo_counter + 1 elif post["media_type"] == 2: video_counter = video_counter + 1 counter = counter + 1 sys.stdout.write("\rChecked %i" % counter) sys.stdout.flush() sys.stdout.write(" posts") sys.stdout.flush() if counter > 0: if self.writeFile: file_name = self.output_dir + "/" + self.target + "_mediatype.txt" file = open(file_name, "w") file.write( str(photo_counter) + " photos and " + str(video_counter) + " video posted by target\n" ) file.close() pc.printout( "\nWoohoo! We found " + str(photo_counter) + " photos and " + str(video_counter) + " video posted by target\n", pc.GREEN, ) if self.jsonDump: json_data = {"photos": photo_counter, "videos": video_counter} json_file_name = self.output_dir + "/" + self.target + "_mediatype.json" with open(json_file_name, "w") as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_people_who_commented(self): if self.check_private_profile(): return pc.printout("Searching for users who commented...\n") data = self.__get_feed__() users = [] for post in data: comments = self.__get_comments__(post["id"]) for comment in comments: if not any(u["id"] == comment["user"]["pk"] for u in users): user = { "id": comment["user"]["pk"], "username": comment["user"]["username"], "full_name": comment["user"]["full_name"], "counter": 1, } users.append(user) else: for user in users: if user["id"] == comment["user"]["pk"]: user["counter"] += 1 break if len(users) > 0: ssort = sorted(users, key=lambda value: value["counter"], reverse=True) json_data = {} t = PrettyTable() t.field_names = ["Comments", "ID", "Username", "Full Name"] t.align["Comments"] = "l" t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" for u in ssort: t.add_row([str(u["counter"]), u["id"], u["username"], u["full_name"]]) print(t) if self.writeFile: file_name = ( self.output_dir + "/" + self.target + "_users_who_commented.txt" ) file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data["users_who_commented"] = ssort json_file_name = ( self.output_dir + "/" + self.target + "_users_who_commented.json" ) with open(json_file_name, "w") as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_people_who_tagged(self): if self.check_private_profile(): return pc.printout("Searching for users who tagged target...\n") posts = [] next_page_id = "" while True: pc.printout("@", pc.CYAN) resp = self.api.user_tag_medias_v2(self.target_id, page_id=next_page_id) posts.extend(resp.get("response", {}).get("items", [])) next_page_id = resp.get("next_page_id") if not next_page_id: break if len(posts) > 0: pc.printout(f"\nWoohoo! We found {len(posts)} medias\n", pc.GREEN) users = {} for post in posts: tag = post["user"] pk = tag["pk"] if pk in users: users[pk]["counter"] += 1 continue users[pk] = { "id": pk, "username": tag["username"], "full_name": tag["full_name"], "counter": 1, } users = users.values() ssort = sorted(users, key=lambda value: value["counter"], reverse=True) t = PrettyTable() t.field_names = ["Medias", "ID", "Username", "Full Name"] t.align["Medias"] = "l" t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" for u in ssort: t.add_row([str(u["counter"]), u["id"], u["username"], u["full_name"]]) print(t) if self.writeFile: file_name = ( self.output_dir + "/" + self.target + "_users_who_tagged.txt" ) file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data = {"users_who_tagged": ssort} json_file_name = ( self.output_dir + "/" + self.target + "_users_who_tagged.json" ) with open(json_file_name, "w") as f: json.dump(json_data, f) else: pc.printout("\nSorry! No results found :-(\n", pc.RED) def get_photo_description(self): if self.check_private_profile(): return pc.printout("Instagram has disabled this functionality.\n", pc.RED) def get_user_photo(self): if self.check_private_profile(): return limit = -1 pc.printout("How many photos you want to download (default all): ", pc.YELLOW) user_input = input() try: if user_input.lower() in ("", "all"): pc.printout("Downloading all photos available...\n") else: limit = int(user_input) pc.printout(f"Downloading {user_input} photos...\n") except ValueError: pc.printout("Wrong value entered\n", pc.RED) return data = self.__get_feed__(limit=limit) print() counter = 0 for item in data: if "image_versions2" in item: if limit > -1 and counter >= limit: break counter += 1 url = item["image_versions2"]["candidates"][0]["url"] photo_id = item["id"] end = self.output_dir + "/" + self.target + "_" + photo_id + ".jpg" urllib.request.urlretrieve(url, end) sys.stdout.write("\rDownloaded %i" % counter) sys.stdout.flush() else: carousel = item["carousel_media"] for i in carousel: if limit > -1 and counter >= limit: break counter += 1 url = i["image_versions2"]["candidates"][0]["url"] photo_id = i["id"] end = self.output_dir + "/" + self.target + "_" + photo_id + ".jpg" urllib.request.urlretrieve(url, end) sys.stdout.write("\rDownloaded %i" % counter) sys.stdout.flush() pc.printout( f"\nWoohoo! We downloaded {counter} medias (saved in {self.output_dir} folder) \n", pc.GREEN, ) def get_user_propic(self): data = self.user if "hd_profile_pic_url_info" in data: url = data["hd_profile_pic_url_info"]["url"] else: # get better quality photo items = len(data["hd_profile_pic_versions"]) url = data["hd_profile_pic_versions"][items - 1]["url"] if url != "": end = self.output_dir + "/" + self.target + "_propic.jpg" urllib.request.urlretrieve(url, end) pc.printout("Target propic saved in output folder\n", pc.GREEN) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user_stories(self): if self.check_private_profile(): return pc.printout("Searching for target stories...\n") data = self.api.user_stories_v2(self.target_id) counter = 0 if data["reel"]: # no stories avaibile items = data["reel"].get("items", []) counter = len(items) for i in items: pc.printout("@", pc.CYAN) story_id = i["id"] if i["media_type"] == 1: # photo url = i["image_versions2"]["candidates"][0]["url"] end = self.output_dir + "/" + self.target + "_" + story_id + ".jpg" urllib.request.urlretrieve(url, end) elif i["media_type"] == 2: # video url = i["video_versions"][0]["url"] end = self.output_dir + "/" + self.target + "_" + story_id + ".mp4" urllib.request.urlretrieve(url, end) if counter > 0: pc.printout( f"\n{counter} target stories saved in output folder\n", pc.GREEN ) else: pc.printout("\nSorry! No results found :-(\n", pc.RED) def get_people_tagged_by_user(self): pc.printout("Searching for users tagged by target...\n") pks = [] username = [] full_name = [] tagged = [] counter = 1 data = self.__get_feed__() for post in data: usertags = post.get("usertags", []) for tag in usertags: u = tag.get("user", {}) if u["pk"] not in pks: pks.append(u["pk"]) username.append(u["username"]) full_name.append(u["full_name"]) tagged.append(1) else: index = pks.index(u["pk"]) tagged[index] += 1 counter += 1 if len(pks) > 0: t = PrettyTable() t.field_names = ["Posts", "Full Name", "Username", "ID"] t.align["Posts"] = "l" t.align["Full Name"] = "l" t.align["Username"] = "l" t.align["ID"] = "l" pc.printout( f"\nWoohoo! We found {len(pks)} ({counter}) users\n", pc.GREEN, ) json_data = {} tagged_list = [] for i in range(len(pks)): t.add_row([tagged[i], full_name[i], username[i], str(pks[i])]) if self.jsonDump: tag = { "post": tagged[i], "full_name": full_name[i], "username": username[i], "id": pks[i], } tagged_list.append(tag) if self.writeFile: file_name = self.output_dir + "/" + self.target + "_tagged.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data["tagged"] = tagged_list json_file_name = self.output_dir + "/" + self.target + "_tagged.json" with open(json_file_name, "w") as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user(self, username): data = self.api.user_by_username_v2(username) if "error" in data: pc.printout( "Oops... {error}\n".format(**data), pc.RED, ) exit(2) elif "detail" in data: pc.printout( f"Oops... {self.target} non exist, please enter a valid username ({data['detail']})\n", pc.RED, ) exit(2) user = data["user"] if self.writeFile: file_name = self.output_dir + "/" + self.target + "_user_id.txt" file = open(file_name, "w") file.write(str(user["pk"])) file.close() return user def set_write_file(self, flag): if flag: pc.printout("Write to file: ") pc.printout("enabled", pc.GREEN) pc.printout("\n") else: pc.printout("Write to file: ") pc.printout("disabled", pc.RED) pc.printout("\n") self.writeFile = flag def set_json_dump(self, flag): if flag: pc.printout("Export to JSON: ") pc.printout("enabled", pc.GREEN) pc.printout("\n") else: pc.printout("Export to JSON: ") pc.printout("disabled", pc.RED) pc.printout("\n") self.jsonDump = flag def to_json(self, python_object): if isinstance(python_object, bytes): return { "__class__": "bytes", "__value__": codecs.encode(python_object, "base64").decode(), } raise TypeError(repr(python_object) + " is not JSON serializable") def from_json(self, json_object): if "__class__" in json_object and json_object["__class__"] == "bytes": return codecs.decode(json_object["__value__"].encode(), "base64") return json_object def check_private_profile(self): if self.is_private: pc.printout( "Impossible to execute command: user has private profile\n", pc.RED ) return True return False def get_contact_info( self, func, from_key, to_key, json_key, file_name, title, field, help_text ): if self.check_private_profile(): return items = [] pc.printout(f"{help_text}... this can take a few minutes\n") next_page_id = "" while True: pc.printout("@", pc.CYAN) result = func(self.target_id, page_id=next_page_id) items.extend(result.get("response", {}).get("users", [])) next_page_id = result.get("next_page_id") if not next_page_id: break print("\n") pc.printout( f"Do you want to get all {title} (for {len(items)} users)? y/n: ", pc.YELLOW ) value = input() if value.lower() in ["y", "yes"]: value = len(items) elif value == "": print("\n") return elif value.lower() in ["n", "no"]: while True: try: pc.printout(f"How many {title} do you want to get? ", pc.YELLOW) new_value = int(input()) value = new_value - 1 break except ValueError: pc.printout("Error! Please enter a valid integer!", pc.RED) print("\n") continue else: pc.printout("Error! Please enter y/n :-)", pc.RED) print("\n") return results = [] for follow in items: pc.printout("@", pc.CYAN) user = self.api.user_by_id_v2(follow["pk"]) if item := user["user"].get(from_key): follow[to_key] = item results.append(follow) if len(results) > value: break if len(results) > 0: t = PrettyTable(["ID", "Username", "Full Name", field]) t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" t.align[field] = "l" for node in results: t.add_row( [str(node["id"]), node["username"], node["full_name"], node[to_key]] ) if self.writeFile: file_name = self.output_dir + "/" + self.target + f"_{file_name}.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data = {json_key: results} json_file_name = ( self.output_dir + "/" + self.target + f"_{file_name}.json" ) with open(json_file_name, "w") as f: json.dump(json_data, f) print(t) else: pc.printout("\nSorry! No results found :-(\n", pc.RED) def get_fwersemail(self): return self.get_contact_info( self.api.user_followers_v2, from_key="public_email", to_key="email", json_key="followers_email", file_name="_fwersemail", title="emails", field="Email", help_text="Searching for emails of target followers", ) def get_fwingsemail(self): return self.get_contact_info( self.api.user_following_v2, from_key="public_email", to_key="email", json_key="followings_email", file_name="_fwingsemail", title="emails", field="Email", help_text="Searching for emails of users followed by target", ) def get_fwersnumber(self): return self.get_contact_info( self.api.user_followers_v2, from_key="contact_phone_number", to_key="contact_phone_number", json_key="followers_phone_numbers", file_name="_fwersnumber", title="phone numbers", field="Phone", help_text="Searching for phone numbers of users followers", ) def get_fwingsnumber(self): return self.get_contact_info( self.api.user_following_v2, from_key="contact_phone_number", to_key="contact_phone_number", json_key="followings_phone_numbers", file_name="_fwingsnumber", title="phone numbers", field="Phone", help_text="Searching for phone numbers of users followed by target", ) def get_comments(self): if self.check_private_profile(): return pc.printout("Searching for users who commented...\n") data = self.__get_feed__() users = [] for post in data: comments = self.__get_comments__(post["id"]) for comment in comments: print(comment["text"]) # if not any(u['id'] == comment['user']['pk'] for u in users): # user = { # 'id': comment['user']['pk'], # 'username': comment['user']['username'], # 'full_name': comment['user']['full_name'], # 'counter': 1 # } # users.append(user) # else: # for user in users: # if user['id'] == comment['user']['pk']: # user['counter'] += 1 # break if len(users) > 0: ssort = sorted(users, key=lambda value: value["counter"], reverse=True) t = PrettyTable() t.field_names = ["Comments", "ID", "Username", "Full Name"] t.align["Comments"] = "l" t.align["ID"] = "l" t.align["Username"] = "l" t.align["Full Name"] = "l" for u in ssort: t.add_row([str(u["counter"]), u["id"], u["username"], u["full_name"]]) print(t) if self.writeFile: file_name = ( self.output_dir + "/" + self.target + "_users_who_commented.txt" ) file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data = {"users_who_commented": ssort} json_file_name = ( self.output_dir + "/" + self.target + "_users_who_commented.json" ) with open(json_file_name, "w") as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def clear_cache(self): pc.printout("Cache is already empty.\n", pc.GREEN) ================================================ FILE: src/printcolors.py ================================================ import sys BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) def has_colours(stream): if not (hasattr(stream, "isatty") and stream.isatty): return False try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: return False has_colours = has_colours(sys.stdout) def printout(text, colour=WHITE): if has_colours: seq = "\x1b[1;%dm" % (30 + colour) + text + "\x1b[0m" sys.stdout.write(seq) else: sys.stdout.write(text) sys.stdout.flush()