def setValue(self, key, value): utils.printDebug('ANIMATOR', 'SET %s=%s' % (key, value)) try: value = int(value) except: pass if key == 'SPEED' and value in range(1, _MAX_SPEED + 1): self.config['speed'] = value elif key == 'ANIMATION' and value in range(-1, len(self.animations)): self.config['animation'] = value if value == -1: self.config['current_animation'] = uos.urandom(1)[0] % len( self.animations) else: self.config['current_animation'] = value elif key == 'LEDS' and 2 <= value and value <= _MAX_LEDS and self.config[ 'leds'] != value: tmp = self.config['leds'] self.config['leds'] = value self.forceRefreshLeds = tmp elif key == 'SECONDS_PER_ANIMATION' and value > 0: self.config['seconds_per_animation'] = value elif key == 'POWERED_ON' and (value == 0 or value == 1): self.config['powered_on'] = value self.forceRefreshColor = True self.powerOffIfNeeded() elif key == 'USE_COLOR' and (value == 0 or value == 1): self.config['use_color'] = value self.forceRefreshColor = True elif key == 'COLOR' and ure.match( "^[0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F]$", value): self.config['color'] = value self.forceRefreshColor = True
def parseRequest(self, cl): url = None params = None useHtml = False try: cl_file = cl.makefile('rwb', 0) while True: line = cl_file.readline().decode("utf-8").upper() ### TODO: fix it if not line or line == '\r\n': break if line.startswith('GET '): startPos = line.find(' ') + 1 endPos = line.rfind(' ') (url, params) = self.parseUrl(line[startPos:endPos]) useHtml = useHtml or 'HOST:' in line if url == None: utils.printDebug('SERVER', 'can not parse request') except Exception as e: while True: line = cl_file.readline().decode("utf-8").upper() ### TODO: fix it if not line or line == '\r\n': break utils.printWarn('SERVER', 'exception during parse request: %s' % str(e)) useHtml = True return (url, params, useHtml)
def process(self, cl, addr): try: utils.printDebug('SERVER', 'client connected from %s:%s' % (addr[0], addr[1])) (url, params, useHtml) = self.parseRequest(cl) if url: utils.printDebug('SERVER', 'GET %s %s (http:%s)' % (url, params, useHtml)) send = False for controller in self.controllers: response = controller.process(url, params) if response: self.sendResponse(cl, response, 200, useHtml) send = True break if not send: response = utils.jsonResponse(404, "Not found") self.sendResponse(cl, response, 404, useHtml) else: response = utils.jsonResponse(400, "Bad Request") self.sendResponse(cl, response, 400, useHtml) except Exception as e: try: utils.printWarn('SERVER', 'exception %s' % str(e)) response = utils.jsonResponse(500, "Internal Server Error") self.sendResponse(cl, response, 500, True) except Exception as e: utils.printWarn('SERVER', 'exception during sendResponse %s' % str(e))
def getAvailableReleases(showTitle, season, episode): """ Returns the available releases for the specified episode of the show. :param showTitle: Name of the show :param season: Season number {S\d\d} :param episode: Episode number {E\d\d} :returns: list of available releases for the passed episode of the show """ season_target = int(filter(str.isdigit, season)) episode_target = int(filter(str.isdigit, episode)) releases = set() main_page = getSubsPage(showTitle, season) if main_page: with requests.session() as c: response = c.get(main_page) soup = bs4.BeautifulSoup(response.text, 'html.parser') for element in soup.find_all('tr', attrs={'class':'epeven completed'}): attributes = element.find_all('td') season_fetched = int(attributes[0].text) if season_fetched == season_target: episode_fetched = int(attributes[1].text) if episode_fetched == episode_target: releases.add(attributes[4].text) utils.printDebug(str(list(releases))) return releases
def resetSpeedLimits(credentials): """ Resets all alternate speed limits and download limits for transmission-daemon. :param credentials: Credentials for transmission-daemon. """ username = credentials["username"] password = credentials["password"] verbose = True if 'verbose' in credentials else False no_alt_speed_cmd = "transmission-remote --no-alt-speed --auth={0}:{1}".format(username, password) utils.printDebug(no_alt_speed_cmd.replace(username + ':' + password, username + ':***'), verbose) response = list() returncode = 0 try: response.append(subprocess.check_output(shlex.split(no_alt_speed_cmd), stderr=subprocess.STDOUT, shell=False)) except (subprocess.CalledProcessError, TypeError) as e: response.append(e.output) returncode += e.returncode no_downlimit_cmd = "transmission-remote --no-downlimit --auth={0}:{1}".format(username, password) utils.printDebug(no_downlimit_cmd.replace(username + ':' + password, username + ':***'), verbose) try: response.append(subprocess.check_output(shlex.split(no_downlimit_cmd), stderr=subprocess.STDOUT, shell=False)) except (subprocess.CalledProcessError, TypeError) as e: response.append(e.output) returncode += e.returncode return {'returncode': returncode, 'response': response}
def update(self): secondsFromMidnight = utime.time() % SECONDS_IN_DAY state = False for (startTime, spentTime) in self.periods: startTime = self.timeToSecondsFromMidnight(startTime) if startTime <= secondsFromMidnight and secondsFromMidnight <= startTime + spentTime: state = True self.pin.value(not state) utils.printDebug("PIN_SCHEDULER", "set state %d" % state)
def sendResponse(self, cl, response, status, useHtml): utils.printDebug('SERVER', 'response status: %s' % status) utils.printDebug('SERVER', 'response: %s' % response) response = response.rstrip() + "\r\n" if useHtml: cl.send('HTTP/1.1 %d OK\r\n' % status) cl.send('Content-Type: application/javascript\r\n') cl.send('Content-Length: %d\r\n' % len(response)) cl.send('Connection: Closed\r\n') cl.send('\r\n') cl.send(response) cl.close()
def update(self): self.externalTemperatures = {} roms = self.dallas.scan() try: utils.printDebug("TEMP", "read %d dallas sensors success" % len(roms)) if roms: self.dallas.convert_temp() except Exception as e: utils.printDebug("TEMP", "dallas exception %s" % e) for rom in roms: id = "".join("{:02x}".format(c) for c in rom) temperature = self.dallas.read_temp(rom) if temperature != 85.0: self.externalTemperatures[id] = temperature
def getSubtitle(showTitle, season, episode, release): """ Downloads subtitle in English language for the specified episode of the show for the given release. :param showTitle: Name of the show :param season: Season number {S\d\d} :param episode: Episode number {E\d\d} :param release: name of the release """ # TODO return value? title_readable = showTitle.replace('_', ' '); season_target = int(filter(str.isdigit, season)) episode_target = int(filter(str.isdigit, episode)) main_page = getSubsPage(showTitle, season) if main_page: with requests.session() as c: response = c.get(main_page) soup = bs4.BeautifulSoup(response.text, 'html.parser') for element in soup.find_all('tr', attrs={'class':'epeven completed'}): attributes = element.find_all('td') season_fetched = int(attributes[0].text) if season_fetched == season_target: episode_fetched = int(attributes[1].text) if episode_fetched == episode_target: if re.compile(release, flags=re.IGNORECASE).match(attributes[4].text): link_id = attributes[9].find('a').get('href') utils.printDebug('Subtitle download link: http://www.addic7ed.com' + link_id) subtitle = c.get('http://www.addic7ed.com' + link_id, headers={'referer': main_page}) download_path, filename = utils.searchMediaDownloadPath([title_readable, season, episode, release]) if download_path == '': utils.printDebug('Subtitle is being saved to the default Download path.') download_path = os.path.expanduser('~/Downloads') if filename == '': filenames = re.findall("filename=(.+)", subtitle.headers['content-disposition']) filename = filenames[0].replace('"', '') # Replace the extension with '.srt' filename = os.path.splitext(filename)[0] + '.srt' with open(os.path.join(download_path, filename), 'wb') as code: code.write(subtitle.content) print('Subtitle is downloaded succesfully.\n(' + os.path.join(download_path, filename) + ')') break else: print('Subtitle could not be downloaded')
def addTorrent(torrent_name): """ Starts the downloading of the torrent file using transmission-daemon. :param torrent_name: Name of the torrent file to be added to torrent client. """ username = '******' password = keyring.get_password('transmission', username) if password: add_torrent_cmd = "transmission-remote -a {0} --auth=miner4:{1}".format(torrent_name, password) utils.printDebug(add_torrent_cmd.replace(password, '***'), verbose) subprocess.call(shlex.split(add_torrent_cmd), shell=False) # Since no way to pass the torrent to transmission by url, remove the torrent manually os.remove(torrent_name) else: print("transmission password could not fetched from keyring.")
def getSubsPage(showTitle, season): """ Gets the link of the available subtitles of the show. :param showTitle: Name of the show :param season: Season number {S\d\d} :returns: addic7ed.com link for the specified season of the show """ title_readable = showTitle.replace('_', ' '); season_target = int(filter(str.isdigit, season)) with requests.session() as c: response = c.get('http://www.addic7ed.com/') soup = bs4.BeautifulSoup(response.text, 'html.parser') for element in soup.find_all('option'): if re.compile(title_readable, flags=re.IGNORECASE).match(element.string): show_id = element.get('value') main_page = 'http://www.addic7ed.com/ajax_loadShow.php?show={0}&season={1}&langs=|1|&hd=1&hi=undefined'.format(show_id, season_target) utils.printDebug(main_page) return main_page else: print('Show with title \'{0}\' could not be found in addic7ed.com'.format(title_readable))
def startDownloadJob(showTitle, season, episode, releasesToDownload): """ Starts the download of the specified episode. :param showTitle: Name of the show :param season: Season number {S\d\d} :param episode: Episode number {E\d\d} :param releasesToDownload: name of the releases :returns: True if download could be executed, False otherwise """ torrent_keywords_fixed = showTitle.split('_') + [season + episode] releasesList = [r.split('.') for r in list(releasesToDownload)] utils.printDebug(str(releasesList)) torrent_file = torrent.getTorrent(torrent_keywords_fixed, releasesList, 'hdser') if torrent_file: torrent.addTorrent(torrent_file[0]) time.sleep(15) subtitledownloader.getSubtitle(showTitle, season, episode, '.'.join(torrent_file[1])) return True else: print('Torrent file cannot be found.')
def _update_working_mode(self): utils.printDebug('THERMOSTAT', 'working_mode %d' % self._config['working_mode']) utils.printDebug( 'THERMOSTAT', 'switch_force_working_mode %d' % self._config['switch_force_working_mode']) working_mode = self._config['working_mode'] or self._config[ 'switch_force_working_mode'] utils.printDebug('THERMOSTAT', 'calucalated working_mode %d' % working_mode) self._relay_pin.value(working_mode) self._led_pin.value((working_mode + 1) % 2)
def upload(self): utils.printDebug("TEMP", "start upload") for (serial, temperature) in self.externalTemperatures.items(): self.uploadTemperature(serial, temperature) utils.printDebug("TEMP", "finish upload")
def findTorrent(options): """ Returns the link of the torrent file based on the passed keywords. At the first step, the function looks for the available torrents based on the fixed keywords. Search is performed using these keywords in the same order as they are passed to the function. After that, the resulting torrents will be fitlered by the additional keywords. The keywords could be contained by the torrent name in any order. :param keywords_fixed_order: Fix ordered keywords to search in nCore. :param keywords_variable_order: Additional keywords that a torrent name should contain during an nCore search. :param category: type of torrent in nCore categories :returns: the link of torrent file """ response = list() returncode = 1 param_check = False if ('searchExpression' in options and 'username' in options and 'password' in options): param_check = True if param_check: searchExpression = options['searchExpression'] username = options['username'] password = options['password'] keywords_variable_order = options ['se'] if 'se' in options else [] category = options['category'] if 'category' in options else None upload_date_limit = options['date-after'] if 'date-after' in options else None verbose = True if 'verbose' in options else False payload_login = {'nev': username, 'pass': password, 'ne_leptessen_ki': True} # create regexp for ncore and for php page filtering keywords_fixed_order = searchExpression.split() keyword_fixed_regexp = '.*'.join(keywords_fixed_order) utils.printDebug('Search expression: ' + keyword_fixed_regexp, verbose) if category: payload_search = {'mire' : keyword_fixed_regexp, 'tipus' : category} else: payload_search = {'mire' : keyword_fixed_regexp} with requests.session() as c: login_res = c.post('https://ncore.cc/login.php', data=payload_login) if login_res.text.find('hibauzenet') == -1: returncode = 0 res = c.post('https://ncore.cc/torrents.php', data=payload_search) soup = bs4.BeautifulSoup(res.text, 'html.parser') matches = soup.find_all(lambda tag:tag.name == "a" and len(tag.attrs) == 3 and tag.has_attr("href") and tag.has_attr("title") and tag.has_attr("onclick")) if len(matches) < 1: response.append('No torrent found for the specified search criterias.') else: for item in matches: title = item.get('title') link = 'https://ncore.cc/' + item.get('href').replace('details', 'download') + '&key=13b4cafed8ce427e68854e0cc3df9aac'; upload_date = item.find_next('div', {'class' : 'box_feltoltve2'}).get_text(' ') if upload_date_limit and parse(upload_date_limit): if upload_date and parse(upload_date): if parse(upload_date_limit).replace(tzinfo=None) < parse(upload_date): response.append((title, link, upload_date)); else: response.append([title, link, upload_date]); if 0 < len(keywords_variable_order): for item in matches: for keyword_list_element in keywords_variable_order: utils.printDebug('Filter keywords: ' + str(keyword_list_element), verbose) if all(keyword in item.get('title') for keyword in keyword_list_element): response.append('Torrent found: ' + item.get('title')) torrent_link = 'https://ncore.cc/' + item.get('href').replace('details', 'download') + '&key=13b4cafed8ce427e68854e0cc3df9aac'; utils.printDebug(torrent_link, verbose) response.append([item.get('title'), torrent_link, keyword_list_element]) else: response.append('No torrent found for the specified search criterias.') else: response.append("Invalid nCore username / password.") else: response.append("Insufficient parameters.") return {'returncode': returncode, 'response': response}