Ejemplo n.º 1
0
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")
Ejemplo n.º 2
0
    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,
            )
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
 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 
Ejemplo n.º 6
0
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))
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
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'])
Ejemplo n.º 10
0
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
Ejemplo n.º 11
0
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))
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
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)])
Ejemplo n.º 14
0
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)
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
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"])
Ejemplo n.º 17
0
 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
Ejemplo n.º 18
0
def update_blocklist():
    transmission_client = transmissionrpc.Client(
        transmission_host,
        port=transmission_port,
        user=transmission_user,
        password=transmission_password)
    transmission_client.blocklist_update()
Ejemplo n.º 19
0
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))
Ejemplo n.º 20
0
    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")
Ejemplo n.º 21
0
 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
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
0
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,
    )
Ejemplo n.º 25
0
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
Ejemplo n.º 26
0
    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)
Ejemplo n.º 27
0
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)
Ejemplo n.º 28
0
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])
Ejemplo n.º 29
0
 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),
     )
Ejemplo n.º 30
0
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"))