Skip to content

Instantly share code, notes, and snippets.

@SeyfSV
Last active October 4, 2019 17:23
Show Gist options
  • Save SeyfSV/175a45a5f6a677483a780c558f0393a8 to your computer and use it in GitHub Desktop.
Save SeyfSV/175a45a5f6a677483a780c558f0393a8 to your computer and use it in GitHub Desktop.
from urllib2 import urlopen # Python 2
from urllib2 import Request
from json import loads
from json import dumps
from .tstreamer import TStreamer
from time import sleep
from logger import Logger
class Peerflix(TStreamer):
def __init__(self, host, port=9000, base_url='torrents'):
super(Peerflix, self).__init__(host=host,
port=port,
base_url=base_url)
def add_torrent(self, infohash):
"""Add torrent.
After torrent added it's downloading started automaticaly.
Arguments:
infohash {str} -- torrent infohash
"""
json_data = dumps({'link': 'magnet:?xt=urn:btih:{}'.format(infohash)})
req = Request(self.get_url(),
json_data,
{'Content-Type': 'application/json'})
res = urlopen(req).read()
Logger.debug('torrent added {}'.format(res))
def get_videos(self, infohash):
"""Return videos list.
Arguments:
infohash {str} -- torrent infohash
Returns:
list -- list of files URLs
"""
self.add_torrent(infohash)
sleep(1) # wait before torrent downloading starts
self.stop_torrent(infohash)
# get files
json_res = urlopen(
'{}/{}'.format(self.get_url(), infohash)).read()
Logger.debug('json_res: {}'.format(json_res))
res = loads(json_res)
video_files = []
idx = 0
for video_file in res.get('files', []):
name = video_file.get('name', '')
path = video_file.get('path', '')
link = video_file.get('link', '')
idx += 1
video_files.append(self._create_file_item(idx, name, path, link))
return video_files
def stop_torrent(self, infohash):
"""Stop torrent downloading.
Arguments:
infohash {str} -- torrent infohash
"""
req = Request('{}/{}/stop'.format(self.get_url(), infohash), '')
res = urlopen(req).read()
Logger.debug('torrent_stop: {}'.format(res))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment