Skip to content

Instantly share code, notes, and snippets.

@xatier
Forked from dannvix/dmhy-magdl.py
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xatier/15845b4741961fef9190 to your computer and use it in GitHub Desktop.
Save xatier/15845b4741961fef9190 to your computer and use it in GitHub Desktop.
Command-line downloader (via magnet link) for share.dmhy.org
#!/usr/bin/env python3
# encoding: utf-8
# dmhy-magdl.py -- command-downloader for share.dmhy.org
# originally from my friend @dannvix
# modified by @xatier
# https://gist.github.com/dannvix/bcdbc83a880728f658cb
import datetime
import sys
import urllib.parse
import urllib.request
import xml.etree.ElementTree
import popcorn
# colorize the output
try:
from blessings import Terminal
except ImportError as e:
class Terminal(object):
def __getattr__(self, name):
def _missing(*args, **kwargs):
return ''.join(args)
return _missing
# globals
t = Terminal()
def query(keyword):
# query url
url = 'http://share.dmhy.org/topics/rss/rss.xml'
params = urllib.parse.urlencode(dict(keyword=keyword))
print('[+] {}?{}'.format(url, params))
req = urllib.request.Request('{}?{}'.format(url, params))
req.add_header('User-Agent', 'Chrome/27.0.1453.93')
xmldoc = urllib.request.urlopen(req).read()
# parse items
root = xml.etree.ElementTree.fromstring(xmldoc)
def _build_item(node):
# Thu, 16 Oct 2014 20:52:51 +0800
date = datetime.datetime.strptime(node.find('pubDate').text,
'%a, %d %b %Y %H:%M:%S +0800')
return dict(
title=node.find('title').text,
date=date.strftime('%Y/%m/%d %H:%M'),
magnet=node.find("enclosure[@type='application/x-bittorrent']")
.get('url'))
items = map(_build_item, root.findall('channel/item'))
items = list(filter(lambda x: x['title'], items))
idx = 0
while items[idx:idx+32]:
yield items[idx:idx+32]
idx += 32
def ask(choices):
for idx, item in enumerate(choices):
num = t.red(str(idx+1).rjust(2))
title = t.yellow(item['title'])
date = t.green(item['date'].rjust(12))
print('{}. {} {}'.format(num, date, title))
answers = input('What items do you like? (seperated by commas) [1] ')
return map(lambda x: int(x)-1, answers.split(',')) if answers else [0]
def download(items):
for item in items:
# import webbrowser
# print('Downloading... {}'.format(item['title']))
# webbrowser.open(item['magnet'])
print(item['title'])
print(item['magnet'])
print('-'*40)
popcorn.popcorn_play(item['magnet'])
if __name__ == '__main__':
if len(sys.argv) <= 1:
print('Usage: %s <keyword>'.format(sys.argv[0]))
print("Example: %s 'Fate stay night' ".format(sys.argv[1]))
sys.exit(1)
keyword = sys.argv[1]
result = query(keyword)
while True:
choices = next(result)
chosen_ids = ask(choices)
if len(choices) != 32 or chosen_ids != [0]:
break
chosens = map(lambda idx: choices[idx], chosen_ids)
download(chosens)
#!/usr/bin/env python3
import base64
import json
import urllib.request
def send_rpc(method, params):
# send json-rpc calls to popcorntime
# popcorntime configurations
url = 'http://192.168.1.111:8008/jsonrpc'
username = 'popcorn'
password = 'popcorn'
# json-rpc packer
data = '''{{
"jsonrpc": "2.0",
"method": "{}",
"params": {},
"id": 1
}}
'''.format(method, params)
print('==> : ' + data)
data = data.encode()
# basic authorization
auth_string = base64.b64encode(('{}:{}'.format(
username, password)).encode()).decode()
req = urllib.request.Request(url, data)
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', 'Basic {}'.format(auth_string))
res = urllib.request.urlopen(req)
token_dict = json.loads(res.read().decode())
print('<== : ' + str(token_dict))
def popcorn_play(magnet):
print('Sending RPC calls to popcorntime ...')
send_rpc('ping', '{}')
try:
send_rpc('ping', '{}')
except:
print("Unable to ping popcorntime")
return
send_rpc('startstream',
'''{{
"imdb_id": "",
"torrent_url": "{}",
"backdrop": "",
"subtitle": "",
"selected_subtitle": "",
"title": "",
"quality": "",
"type": ""
}}'''.format(magnet))
if __name__ == '__main__':
popcorn_play('magnet:?xt=urn:btih:AGMTNAVY5XNEB6RT35IYVSJL7YRHCTVS')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment