Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mr-js committed Nov 15, 2023
0 parents commit 8cf3f2c
Show file tree
Hide file tree
Showing 7 changed files with 307 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
152 changes: 152 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Mr. JS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# netstream
Parallel asynchronous network requests via tor proxy

## Usage
Simply feed all page urls to the Netstream module[^1] and it will start a parallel asynchronous process to load the required resources

## Examples
```python
from netstream import Netstream

urls = [fr'https://ya.ru', fr'http://jsonip.com']
ns = Netstream()
data = ns.run(targets=urls)
complete = f'{100*ns.received/ns.total:.0f}' if ns.total else 0
print(f'result {complete}% (errors {ns.total-ns.received}) ')
print(f'{data}')
```
## Remarks
Netstream used Tor Browser resources.
[^1]: Tor browser must be running and active at this time
104 changes: 104 additions & 0 deletions netstream/netstream.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import sys
import os
import traceback
import requests
import asyncio
import aiohttp
from aiohttp_socks import ProxyType, ProxyConnector, ChainProxyConnector
from fake_useragent import UserAgent
from timeit import default_timer
import logging
import datetime
from dataclasses import dataclass
from dataclasses import field
import codecs
import tomllib


# logging: netstream.log or netstream.log + console
# logging.basicConfig(handlers=[logging.FileHandler(os.path.join('netstream.log'), 'w', 'utf-8')], level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d.%m.%y %H:%M:%S')
logging.basicConfig(handlers=[logging.StreamHandler(), logging.FileHandler(os.path.join('netstream.log'), 'w', 'utf-8')], level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d.%m.%y %H:%M:%S')


class Netstream():
def __init__(self):
self.data = dict()
self.total = 0
self.received = 0
self.status = 'init'
self.started = default_timer()
try:
with open('netstream.toml', 'rb') as f:
config = tomllib.load(f)
self.proxy = config['connection']['proxy']
self.timeout = config['connection']['timeout']
self.attemps = config['connection']['attemps']
self.status = 'ready'
except * (FileNotFoundError, KeyError) as e:
e.add_note('Configuration file not correct! Please try again.')
logging.error(e.__notes__[0])
self.status = 'config error'


def finish(self):
time_total = f'{default_timer() - self.started:1.2f}s'
logging.info(f'finished at {time_total}')


async def get_page(self, client, target):
async with client.get(target) as response:
if response.status != 200:
return ''
return await response.read()


async def get_data(self, target):
attemp = 0
loop = asyncio.get_running_loop()
while (attemp < self.attemps):
attemp += 1
timeout = aiohttp.ClientTimeout(total=self.timeout)
connector = ProxyConnector.from_url(self.proxy)
headers = {'User-Agent': UserAgent().chrome}
async with aiohttp.ClientSession(loop=loop, headers=headers, connector=connector, timeout=timeout) as client:
logging.debug(f'receiving page data: {target} ({attemp}/{self.attemps})')
try:
data = await self.get_page(client, target)
if data:
self.data[target] = data.decode('utf-8')
logging.debug(f'!received page data: {target} ({attemp}/{self.attemps})')
self.received += 1
break
else:
self.data[target] = ''
except:
## logging.debug(traceback.format_exc())
...


async def start(self, targets):
logging.info(f'started')
await asyncio.gather(*(self.get_data(target) for target in targets))


def run(self, targets):
if self.status != 'ready':
logging.warning(f'Netstream not ready')
else:
self.total = len(targets)
asyncio.run(self.start(targets))
self.finish()
return self.data


def main():
urls = [fr'https://ya.ru', fr'http://jsonip.com']
ns = Netstream()
data = ns.run(targets=urls)
complete = f'{100*ns.received/ns.total:.0f}' if ns.total else 0
logging.info(f'result {complete}% (errors {ns.total-ns.received}) ')
logging.debug(f'{data}')


if __name__ == "__main__":
main()
4 changes: 4 additions & 0 deletions netstream/netstream.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[connection]
proxy = 'socks5://127.0.0.1:9150'
attemps = 10
timeout = 3
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
aiohttp==3.8.5
aiohttp-socks==0.8.0
fake-useragent==1.2.1
requests==2.31.0

0 comments on commit 8cf3f2c

Please sign in to comment.