Skip to content

Instantly share code, notes, and snippets.

@zhiyue
Forked from Chairo/down_torrents.py
Last active August 29, 2015 14:11
Show Gist options
  • Save zhiyue/51b456ab3d2391e3219c to your computer and use it in GitHub Desktop.
Save zhiyue/51b456ab3d2391e3219c to your computer and use it in GitHub Desktop.
# -*- coding:utf-8 -*-
import requests, os, hashlib
from pymongo import Connection #引入Mongo支持
#连接Mongo
mongo = Connection(host='127.0.0.1', port=27017)
db = mongo.bt #连接bt这个数据库,没有会自动新建
#保存下载的BT种子
def save_file_to_disk(content, info_hash):
_temp = file_path(info_hash)
_path = os.path.abspath('%s/%s'%('torrents', _temp['path']))
_file_name = _temp['file_name']
open('%s/%s'%(_path, _file_name), 'wb').write(content)
return _temp
#获取BT种子保存的文件路径
def file_path(info_hash):
_md5 = hashlib.md5(info_hash).hexdigest()
check_path(_md5[0:2])
check_path('%s/%s/'%(_md5[0:2], _md5[2:5]))
return {'path':'%s/%s/'%(_md5[0:2], _md5[2:5]), 'file_name':'%s.torrent'%_md5}
#检查文件夹是否存在
def check_path(path):
if not os.path.exists(os.path.abspath('%s/%s'%('torrents', path))):
os.mkdir(os.path.abspath('%s/%s'%('torrents', path)))
#下载BT文件
def get_file(info_hash):
_url = 'http://torrage.com/torrent/%s.torrent'%info_hash.upper()
try:
_content = requests.get(_url, timeout=3).content
if 'File not found' not in _content:
_path = save_file_to_disk(_content, info_hash)
db.info_hash.update({'info_hash':info_hash}, {'$set':{'download':1,'file_path':'%s/%s/%s'%('torrents',_path.get('path'), _path.get('file_name'))}}, upsert=False, multi=True)
except:
db.info_hash.remove({'info_hash':info_hash})
#遍历Mongo下载BT种子
def down_bt():
#使用find命令获取所有没有下载过的数据
for item in db.info_hash.find({"download": {"$exists": False}}, fields={'info_hash':True,'_id':False}):
get_file(item.get('info_hash'))
if __name__ == "__main__":
down_bt()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment