def cistern(): if config['require_auth']: tremote = transmissionrpc.Client( address=config['url'], port=int(config['port']), user=config['username'], password=config['password'] ) else: tremote = transmissionrpc.Client( address=config['url'], port=int(config['port']) ) click.clear() for feed in Feed.select().where(Feed.enabled == True): refresh_feed(feed) click.echo('Downloading torrents:') torrent_list = feed.torrents.select().where(Torrent.downloaded == False) if torrent_list: with click.progressbar(torrent_list) as torrents: transmission_args = {} if feed.download_dir: transmission_args['download_dir'] = feed.download_dir for torrent in torrents: tremote.add_torrent(torrent.url, **transmission_args) torrent.set_downloaded() else: click.echo("No torrents to download in this feed")
def __init__( # pylint: disable=super-init-not-called self, url: str, user: str, passwd: str, timeout: float, **kwargs: Any, ) -> None: self._init_bases(**kwargs) if transmissionrpc is None: raise RuntimeError("Required module transmissionrpc") if transmissionrpc.project == "original": self._client = transmissionrpc.Client( address=url, user=(user or None), password=(passwd or None), timeout=timeout, ) elif transmissionrpc.project == "forked": self._client = transmissionrpc.Client( host=url, username=(user or None), password=(passwd or None), timeout=timeout, )
def get_torrent_file_and_download(bot, update): url = update.message.text tc = transmissionrpc.Client() uid = update.message.from_user.id fname = str(dt.now()) + '.torrent' fpath = os.path.abspath(fname) if url.startswith('magnet'): fpath = url elif update.message.document: file_id = update.message.document.file_id torrent_file = bot.getFile(file_id) tc = transmissionrpc.Client() fpath = torrent_file.file_path else: with open(fname, 'wb') as out_stream: req = requests.get(url, stream=True) if req.headers._store.get( 'content-type')[1] == 'application/x-bittorrent': for chunk in req.iter_content(1024): out_stream.write(chunk) added_torrent = tc.add_torrent(fpath) tname = added_torrent._fields['name'][0] bot.sendMessage(uid, 'Начинаю скачивать <b>' + tname + '</b>', parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardMarkup(start_keyboard, resize_keyboard=True)) os.remove(fpath)
def connectTransmission(): # Connects to transmission and starts transmission if not already running. # Returns a transmission session object try: return transmissionrpc.Client() except transmissionrpc.error.TransmissionError as ex: if 'connection refused' in str(ex).lower(): print('Starting Transmission') # Start transmission and return control to terminal os.system('transmission-gtk &') print('Transmission Starting') unConnected = 1 # Try to connect to transmission until successful. while unConnected > 0: try: return transmissionrpc.Client() #unConnected = 0 except transmissionrpc.error.TransmissionError as ex: print('Failed to connect to Transmission. (%d times)' % unConnected) unConnected = unConnected + 1 time.sleep(1) # Sleep 1 second for sanity. else: BFun.ezLog( 'Unexpected error when connecting to transmission. Search for 1435813', ex) except Exception as ex: BFun.ezLog( 'Unexpected error when connecting to transmission. Search for 1435813a', ex)
def __init__(self, address='localhost', login=None, password=None, port=9091): try: if login and password: self._conn: trpc.Client = trpc.Client(address=address, user=login, password=password, port=port) else: self._conn: trpc.Client = trpc.Client(address=address, port=port) self._torrents, self._torrents_dict = self.get_torrents() except Exception as e: raise e
def main(): if username and password: client = transmissionrpc.Client(ip_address, port, username, password) else: client = transmissionrpc.Client(ip_address, port) for torrent in client.get_torrents(): if torrent.status == 'stopped': client.remove_torrent(torrent.id) print('{} removed'.format(torrent.id))
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Transmission sensors.""" import transmissionrpc from transmissionrpc.error import TransmissionError name = config.get(CONF_NAME) host = config.get(CONF_HOST) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) port = config.get(CONF_PORT) try: transmission = transmissionrpc.Client(host, port=port, user=username, password=password) transmission_api = TransmissionData(transmission) except TransmissionError as error: if str(error).find("401: Unauthorized"): _LOGGER.error("Credentials for Transmission client are not valid") return _LOGGER.warning("Unable to connect to Transmission client: %s:%s", host, port) raise PlatformNotReady dev = [] for variable in config[CONF_MONITORED_VARIABLES]: dev.append(TransmissionSensor(variable, transmission_api, name)) add_devices(dev, True)
def main(): tc = transmissionrpc.Client('localhost', port=9091) torrents = tc.info() ids = torrents.keys() if len(sys.argv) > 1: command = sys.argv[1] else: command = None if ids == None or len(ids) == 0: return if "start" == command: tc.start(ids) elif "stop" == command: tc.stop(ids) elif "check" != command: print "usage:" print "\ttransmission-switch start|stop|check" max_date = datetime.datetime.today() - datetime.timedelta(30) #print "max_date=", max_date removed=[] for t in torrents.values(): #print t.id, t.hashString, t.date_done, t.progress, t.ratio, t.name if t.ratio >= 30 or t.progress >= 100 and t.date_done < max_date: removed.append(t.id) #print removed if len(removed) > 0: tc.remove(removed)
def __init__(self): config = configparser.ConfigParser() config.read('config.cfg') self.tc = transmissionrpc.Client( address=config['TransmissionRPC']['server'], user=config['TransmissionRPC']['user'], password=config['TransmissionRPC']['password'])
def torrentstatusall(ip='127.0.0.1',port=9091): currentlist = [] # Setup transmission connection tc = transmissionrpc.Client(ip, port=port) # Get list of current torrents in transmission current_torrents = tc.get_torrents() # See if transmission has any torrents in it if len(current_torrents)==0 or current_torrents is None: return current_torrents # Turn torrent objects into a list of statuses for tobject in current_torrents: try: status = tobject.eta except: status = None currentlist.append({ 'hashstring':tobject.hashString, 'name':tobject.name, 'status':tobject.status, 'eta':status, }) # return list of torrents and status try: return currentlist except: return currentlist
def main(): if flagFile == True: html = getPageFromFile(startFileName) else: html = getPage(startUrl) mp3PageUrl = getMP3PageUrl(html) if flagFile == True: html = getPageFromFile(mp3PageFileName) else: html = getPage(mp3PageUrl) downloadUrl = getDownLoadUrl(html) torrent = getPage(downloadUrl, mp3PageUrl) print "downloadURL = " + downloadUrl print "refererURL = " + mp3PageUrl tc = transmissionrpc.Client(torrentServer, torrentPort, torrentUser, torrentPassword) torrents = tc.get_torrents() #for torrent in torrents: #if (torrent.status == 'seeding'): #tc.remove_torrent(torrent.id) tc.add_torrent(b64encode(torrent))
def mover(settings, allshows, tid = None): ''' The mover function is called by transmission when download is complete. It is responsible for extracting the proper video files from the set of files downloaded by the torrent, and placing them in the correct destination directory. ''' try: if tid == None: torrent_id = os.environ.get('TR_TORRENT_ID') else: torrent_id = tid print 'Torrent ID: %s' % str(torrent_id) tc = transmissionrpc.Client(settings['RPC_HOST'], port=settings['RPC_PORT'], user=settings['RPC_USER'], password=settings['RPC_PASS']) files_dict = tc.get_files() torrent_list = tc.get_torrents() files_list = [] if torrent_id != None: id_key = int(torrent_id) if id_key in files_dict.keys(): for file_key in files_dict[id_key].keys(): files_list.append(files_dict[id_key][file_key]['name']) else: print 'no id match:' for key in files_dict.keys(): print '--> %d' % key print files_list processFiles(files_list, settings, allshows) except Exception: exc_details = traceback.format_exc() print '%s' % exc_details if settings['MAIL_ENABLED']: sendMail(settings['SENDMAIL_DEST'],'An error has occurred',exc_details)
def setup_platform(hass, config, add_devices_callback, discovery_info=None): """ Sets up the transmission sensor. """ host = config.get(CONF_HOST) username = config.get(CONF_USERNAME, None) password = config.get(CONF_PASSWORD, None) port = config.get('port', 9091) name = config.get("name", "Transmission Turtle Mode") if not host: _LOGGING.error('Missing config variable %s', CONF_HOST) return False # import logging # logging.getLogger('transmissionrpc').setLevel(logging.DEBUG) transmission_api = transmissionrpc.Client(host, port=port, user=username, password=password) try: transmission_api.session_stats() except TransmissionError: _LOGGING.exception("Connection to Transmission API failed.") return False add_devices_callback([TransmissionSwitch(transmission_api, name)])
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Transmission sensors.""" import transmissionrpc from transmissionrpc.error import TransmissionError name = config.get(CONF_NAME) host = config.get(CONF_HOST) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) port = config.get(CONF_PORT) transmission_api = transmissionrpc.Client(host, port=port, user=username, password=password) try: transmission_api.session_stats() except TransmissionError: _LOGGER.exception("Connection to Transmission API failed") return False # pylint: disable=global-statement global _THROTTLED_REFRESH _THROTTLED_REFRESH = Throttle(timedelta(seconds=1))( transmission_api.session_stats) dev = [] for variable in config[CONF_MONITORED_VARIABLES]: dev.append(TransmissionSensor(variable, transmission_api, name)) add_devices(dev)
def create_rpc_client(self, config): user, password = config.get('username'), config.get('password') try: cli = transmissionrpc.Client(config['host'], config['port'], user, password) except TransmissionError as e: if isinstance(e.original, HTTPHandlerError): if e.original.code == 111: raise plugin.PluginError( "Cannot connect to transmission. Is it running?") elif e.original.code == 401: raise plugin.PluginError( "Username/password for transmission is incorrect. Cannot connect." ) elif e.original.code == 110: raise plugin.PluginError( "Cannot connect to transmission: Connection timed out." ) else: raise plugin.PluginError( "Error connecting to transmission: %s" % e.original.message) else: raise plugin.PluginError( "Error connecting to transmission: %s" % e.message) return cli
def _get_tr_client(): tr_conf = config.get_config()["transmission"] host, port = tr_conf["host"].split(":") return transmissionrpc.Client(host, port=port, user=tr_conf["user"], password=tr_conf["password"])
def establishRPC(self, client, magnet_link=None, type="magnet"): print "• Establishing connection to", client try: if client == "transmission": tc = transmissionrpc.Client(self.transmission_url.split(":")[0], port=self.transmission_url.split(":")[1], user=self.transmission_user, password=self.transmission_password) if type == "magnet": print "• Adding magnet to", client tc.add_torrent(magnet_link) else: print "• Adding torrent to", client tc.add_torrent('file://' + os.path.abspath('torrent.torrent')) elif client == "qbittorrent": qb = Client(self.qbittorrent_url) qb.login(self.qbittorrent_user, self.qbittorrent_password) if qb._is_authenticated is True: if type == "magnet": print "• Adding magnet to", client qb.download_from_link(magnet_link) else: print "• Adding torrent to", client qb.download_from_file(file('torrent.torrent')) except: traceback.print_exc() raise IOError
def update_blocklist(): transmission_client = transmissionrpc.Client( transmission_host, port=transmission_port, user=transmission_user, password=transmission_password) transmission_client.blocklist_update()
def handle_finished_download(): torrent_id = os.environ['TR_TORRENT_ID'] syslog.syslog('Beginning processing of torrent {0}'.format(torrent_id)) transmission_client = transmissionrpc.Client( transmission_host, port=transmission_port, user=transmission_user, password=transmission_password) torrent = transmission_client.get_torrent(torrent_id) # Make sure transmission called us with a completed torrent if torrent.progress != 100.0: syslog.syslog(syslog.LOG_ERR, 'Called with an incomplete torrent') sys.exit(1) if couchpotato_category in torrent.downloadDir: if not ignore_couchpotato: handle_couchpotato(torrent) elif sonarr_category in torrent.downloadDir: if not ignore_sonarr: handle_sonarr(torrent) else: handle_manual(torrent) # Immediately remove torrents that are not whitelisted (by tracker) if not whitelisted(torrent): transmission_client.remove_torrent(torrent_id) pb_notify('Removed non-whitelisted torrent {0}'.format(torrent.name))
def __init__(self, torrents, contentTypes, maxActiveTorrents, useragent, doneTasks, newTasks, ressources, Exit): """ @param urls - deque which contains the urls received from the master @param newTasks - deque which contains the urls collected by the crawlers @param ressources - ressources collected waiting for saving in sql( dict : [rType : deque of ressources,..] @param Exit - stop condition( an event share with Slave, when Slave die it is set to true ) @brief A torrent must not be recrawl ? """ Thread.__init__(self) self.torrents = torrents self.maxActiveTorrents = maxActiveTorrents self.contentTypes = contentTypes self.useragent = useragent self.doneTasks = doneTasks self.newTasks = newTasks self.ressources = ressources self.Exit = Exit self.client = transmissionrpc.Client('localhost', port=9091) self.activeTorrents = {} logging.info("TorrentHandler initialized")
def client(self): if not hasattr(self, '_client'): self._client = transmissionrpc.Client(address=self.host, port=self.port, user=self.username, password=self.password) return self._client
def __init__(self): try: self.c = transmissionrpc.Client(HOST, PORT, USER, PASSWORD) except: self.c = none #values to draw self.up = -1 self.down = -1 self.active_torrents = -1 self.nbr_of_torrents = -1 self.nbr_of_errors = -1 self.turtle_mode_active = False #create indicator self.indicator = appindicator.Indicator( "remote-transmission-applet", "transmission-tray-icon", appindicator.CATEGORY_APPLICATION_STATUS) self.indicator.set_status(appindicator.STATUS_ACTIVE) self.menu_setup() self.indicator.set_menu(self.menu) self.connected = False self.first_run = True self.connection_error_shown = True
def check_torrents(bot): tc = transmissionrpc.Client() while True: for t in tc.get_torrents(): if t.status in ('seed pending', 'seeding'): bot.sendMessage(ADMIN_ID, 'Скачал ' + t.name) time.sleep(60)
def get_transmission_client(nefarious_settings: NefariousSettings): return transmissionrpc.Client( address=nefarious_settings.transmission_host, port=nefarious_settings.transmission_port, user=nefarious_settings.transmission_user, password=nefarious_settings.transmission_pass, )
def enqueue_transmission(): max_items = 5 items_processed = 0 mongo = MongoClient(MONGO_HOST, MONGO_PORT) eztv_db = mongo['eztv'] shows_collection = eztv_db['eztv'] tc = transmissionrpc.Client("localhost", port=9091, user='******', password="******") BASE_DOWNLOAD_PATH = '/synology/jordan/Downloads/incoming_tv' download_candidates = shows_collection.find({ "parsed": True }).sort([("seeds", -1)]) for candidate in download_candidates: if items_processed >= max_items: break download_dir = BASE_DOWNLOAD_PATH + "/{}/Season {}/".format( candidate['show_title'].strip(), candidate['season'], candidate['show_title'].strip(), candidate['season'], candidate['episode']) print download_dir, candidate['seeds'] tc.add_torrent(candidate['magnet_url'], download_dir=download_dir) items_processed += 1
def run(self, config, help=None): index = load_index() try: tc = transmissionrpc.Client(config.transmission_hostname, port=config.transmission_port) except transmissionrpc.transmission.TransmissionError as e: raise errors.FatalError( "Unable to connect to a Transmission at %s:%i. %s.\n\n" "Make sure Transmission is running, the web client is " "enabled in the preferences and its details match the " "settings in config.rc. Make sure transmission-daemon is " "not running if you are trying to connect to a GUI instance." % (config.transmission_hostname, config.transmission_port, e)) tc_list = tc.list() for torrent in index.torrents: if len(torrent.data_matches) < 2: continue data_path = torrent.choose_data_path() if data_path == None: continue tc_torrent = utils.transmission_find_torrent(tc_list, torrent) if tc_torrent: tc.locate(tc_torrent.hashString, data_path) for spare_data in torrent.data_matches[1:]: path = os.path.join(spare_data[0], utils.normalise_path(torrent.name)) #path = path.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") print("%s" % path)
def dlSerie(name, season, episode): search = "{} S0{}E{}".format(name, season, episode) r_done = False while not r_done: r = requests.get( "https://extratorrent.cc/search/?search={}".format(search)) if r.status_code == 200: r_done = True name_with_point = name.replace(' ', '.') soup = bs4.BeautifulSoup(r.text, "html.parser") for element in soup.find_all('td', {'class': u'tli'}): for link in element.find_all('a'): if name in link.text or name_with_point in link.text: url = link['href'] break r_done = False while not r_done: r = requests.get("https://extratorrent.cc" + url) if r.status_code == 200: r_done = True tSoup = bs4.BeautifulSoup(r.text, "html.parser") img = tSoup.find('img', {'alt': u'Magnet link'}) torrent = img.parent['href'] print(torrent) tc = transmissionrpc.Client('localhost', port=9091, user="******", password="******") tc.add_torrent(torrent)
def tm_config(): try: tc = transmissionrpc.Client('localhost', port=9091, timeout = 3) torlist = tc.get_torrents(timeout = 3) except Exception as e: print(e) return for t in torlist: t.upload_limit = 250 if t.percentDone == 1.0 or t.sizeWhenDone < 5000000: tc.move_torrent_data(t.id, '/Volumes/Store/Downloads/t66ydone') tc.remove_torrent(t.id) if com.nowsec - t.addedDate > 3600*24*2 and t.percentDone < 0.3: tc.remove_torrent(t.id, delete_data=True) tf = sorted(t.files().items(), key=lambda d: d[1]['size']) # 按文件大小,升序 if len(tf) > 2 and tf[-2][1]['selected'] and tf[-1][1]['name'].find('hjd2048.com_') >= 0: rmids = list(t.files().keys()) rmids.remove(tf[-1][0]) tc.change_torrent(t.id, files_unwanted = rmids) for k, v in tf: if v['selected']: NAME = v['name'].upper() if v['size'] < 80000000 or NAME.find('STP') >= 0 or NAME.find('迷奸') >= 0 or NAME.find('直播') >= 0 or NAME.find('主播') >= 0 or NAME.find('.ZIP') >= 0 or NAME.find('.RAR') >= 0 or NAME.find('窺') >= 0 or NAME.find('偷') >= 0 or NAME.find('自慰') >= 0 or NAME.find('廁') >= 0 or NAME.find('韩') >= 0 or NAME.find('中年') >= 0 or NAME.find('洋') >= 0 or NAME.find('欧') >= 0 or NAME.find('醉') >= 0 or NAME.find('迷') >= 0 or NAME.find('喝多') >= 0 or NAME.find('灌') >= 0 or NAME.find('美国') >= 0 or NAME.find('水滴') >= 0: tc.change_torrent(t.id, files_unwanted = [k])
def client(self): return transmissionrpc.Client( self.srvs.settings.get(self.SETTINGS_PREFIX + ".host", "localhost"), self.srvs.settings.get(self.SETTINGS_PREFIX + ".port", 9091), self.srvs.settings.get(self.SETTINGS_PREFIX + ".username", None), self.srvs.settings.get(self.SETTINGS_PREFIX + ".password", None), )
def enqueue_transmission(): max_items = 300 mongo = MongoClient(MONGO_HOST, MONGO_PORT) yts_db = mongo['yts'] movies_collection = yts_db['movies'] print colored("MESSG:Updating Transmission", "cyan") tc = transmissionrpc.Client("localhost", port=9091, user='******',password="******") torrents = tc.get_torrents() #remove completed torrents torrents_to_remove = [] for torrent in torrents: if torrent.status in ['seeding', 'stopped']: tc.remove_torrent(torrent.hashString) torrents_to_remove.append(torrent) print colored("DELTE:","red") + "{}".format(torrent.hashString) for torrent in torrents_to_remove: torrents.remove(torrent) #add a new one(s) to replace diff = max_items - len(torrents) if(diff > 0): for i in range(0,diff): try: movie = movies_collection.find({"downloaded": False, "year": {"$gt": 1990}, 'rating':{"$gte":4}, "language": "English"}).sort([("rating", -1),("year", -1)]).limit(1)[0] except IndexError: print colored("MESSG:No Remaining Movies", "cyan") return movie['downloaded'] = True movies_collection.save(movie); tc.add_torrent(movie['magnet_url']) print colored("QUEUE:","yellow") + "({}) {} - {}".format(movie['rating'], movie['year'], movie['title'].encode("utf-8"))