Beispiel #1
0
    def main(self):

       parser = OptionParser()
       parser.add_option("-c", "--config", dest="config", help="config file", metavar="FILE", default=None)
       parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False)
       parser.add_option("-l", "--log-level", dest="log_level", default='info', help="set logging level [%default]")
       parser.add_option("-s", "--summary", dest="summary", default=None, help="optional summary of picture")
       parser.add_option("-u", "--uploaders", dest="uploaders", default=[], action="append", help="enable specific uploaders")
       parser = parser

       (options, args) = parser.parse_args()

       configure_logging(options.log_level)

       # Mute boto unless we're verbose
       if options.verbose == False:
            logging.getLogger('boto').setLevel(logging.CRITICAL)
            logging.getLogger('requests').setLevel(logging.CRITICAL)


       opts = config.GetScreenshotOptions(options.config)
       for k, v in opts.__dict__.iteritems():
            self.log.debug("%s: %s", k, v)

       app = Screenshot(opts)

       shortname = None
       if len(args) > 0:
        shortname = args[0]
       summary = options.summary
       opts.summary = options.summary
       #opts.uploaders = options.uploaders

        
       app.take_screenshot(shortname, summary)
Beispiel #2
0
def screenshot(args):
    """Take a screenshot and upload it to Dropbox."""
    from screenshot import Screenshot

    screenshot = Screenshot(args.mode)

    screenshot.capture()

    c.handle_files([screenshot.path], [screenshot.filename], args.share)
Beispiel #3
0
 def __init__(self):
     """
     The constructor function of the main server.
     """
     self.streamer_socket = socket.socket()
     self.online_users = {}  # {socket: display resolution}.
     self.communicator = Communicator()
     self.screenshot = Screenshot()
     self.running = True
Beispiel #4
0
def screenshot(args):
    """Take a screenshot and upload it to Dropbox."""
    from screenshot import Screenshot

    screenshot = Screenshot(args.mode)

    screenshot.capture()

    c.handle_files([screenshot.path], [screenshot.filename], args.share)
Beispiel #5
0
    def screenshots(self):
        '''
        Take screenshots of all the pages in sitemap.
        '''
        if not os.path.exists(Sitemap.screenshot_dir):
            os.makedirs(Sitemap.screenshot_dir)

        cookies_list = []
        for (key, value) in self.cookies.items():
            cookies_list.append(key + '=' + value)

        urls = []
        for url in self.sitemap.keys():
            if not self.skipscreenshot \
               or self.skipscreenshot not in url:
                urls.append(url)
                self.sitemap[url]['image'] = os.path.join(
                    Sitemap.screenshot_dir, url.pretty() + '.png')
        screenshot = Screenshot(path=Sitemap.screenshot_dir)
        screenshot.screenshot(urls, cookies_list)
Beispiel #6
0
    def main(self):

       parser = OptionParser()
       parser.add_option("-c", "--config", dest="config", help="config file", metavar="FILE", default=None)
       parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False)
       parser.add_option("-l", "--log-level", dest="log_level", default='', help="set logging level [%default]")
       parser.add_option("-s", "--summary", dest="summary", default=None, help="optional summary of picture")
       parser.add_option("-u", "--uploaders", dest="uploaders", default=[], action="append", help="enable specific uploaders")
       parser.add_option("-f", "--filename", dest="filename", default=None, help="use this file (or http address) instead of capturing")
       parser = parser

       (options, args) = parser.parse_args()

       if options.log_level != '':
            configure_logging(options.log_level)

       # Mute boto unless we're verbose
       if options.verbose == False:
            logging.getLogger('boto').setLevel(logging.CRITICAL)
            logging.getLogger('requests').setLevel(logging.CRITICAL)


       opts = config.GetScreenshotOptions(options.config)
       for k, v in opts.__dict__.iteritems():
            self.log.debug("%s: %s", k, v)

       opts.filename = options.filename
       app = Screenshot(opts, configure_logging)

       shortname = None
       if len(args) > 0:
        shortname = args[0]
       summary = options.summary
       opts.summary = options.summary
       #opts.uploaders = options.uploaders

        
       meta = app.take_screenshot(shortname, summary)

       d  = meta.to_dict()
       print json.dumps(d, indent=4, sort_keys=True)
Beispiel #7
0
def add_screenshot(game_id):
    if request.method == "GET":
        return render_template("add_screenshot.html", game=db.get_game(game_id))
    if "img" in request.files:
        img = request.files["img"]
        valid_ext = [".jpg", ".png"]
        img_name = None
        if img.filename[len(img.filename)-4:] in valid_ext:
            img_name = images.save(img)
            db.insert_screenshot(Screenshot(img_name,current_user.id,game_id,request.form.get("caption"),str(datetime.utcnow())))
            return render_template("add_screenshot_result.html", success=True, img_name=img_name, game_id=game_id)
        else:
            return render_template("add_screenshot_result.html", success=False, img_name=img_name, game_id=game_id)
    def get_screenshot(self, shot_id):
        self.connect()

        statement = "SELECT SCREENSHOTS.NAME, SCREENSHOTS.USER_ID, CAPTION, DATE_ADDED, LIKES, DISLIKES, SCREENSHOTS.GAME_ID, GAMES.TITLE, USERS.NAME FROM (USERS JOIN (SCREENSHOTS JOIN GAMES ON SCREENSHOTS.GAME_ID=GAMES.GAME_ID) ON USERS.USER_ID=SCREENSHOTS.USER_ID) WHERE SHOT_ID=%s"
        data = (str(shot_id), )
        query = statement, data
        self.query_database(query)
        name, user_id, caption, date_added, likes, dislikes, game_id, game_title, user_name = self.cursor.fetchone(
        )
        shot = Screenshot(name, user_id, game_id, caption, date_added, likes,
                          dislikes, shot_id, game_title, user_name)
        self.disconnect()

        return shot
    def get_screenshots_of_game(self, game_id, cur_user_id):
        self.connect()
        statement = "SELECT SCREENSHOTS.NAME, SCREENSHOTS.GAME_ID, CAPTION, DATE_ADDED, LIKES, DISLIKES, SHOT_ID, USERS.NAME FROM (SCREENSHOTS JOIN USERS ON ((SCREENSHOTS.USER_ID=USERS.USER_ID) AND (SCREENSHOTS.GAME_ID=%s))) ORDER BY DATE_ADDED DESC"
        data = (str(game_id), )
        query = statement, data
        self.query_database(query)
        sss = []
        for row in self.cursor:
            name, user_id, caption, date_added, likes, dislikes, shot_id, user_name = row
            sss.append(
                Screenshot(name, user_id, game_id, caption, date_added, likes,
                           dislikes, shot_id, None, user_name))

        for shot in sss:
            shot.liked_from_current = self.get_like_of_user(
                shot.id, cur_user_id, "SCREENSHOTS")
            shot.disliked_from_current = self.get_dislike_of_user(
                shot.id, cur_user_id, "SCREENSHOTS")
        self.disconnect()
        return sss
Beispiel #10
0
import sys

from PyQt5.QtWidgets import QApplication

from screenshot import Screenshot

if __name__ == '__main__':
    app = QApplication(sys.argv)
    s = Screenshot()
    s.app = app
    s.capture('http://chungtoimuontudo2.wordpress.com',
              'chungtoimuontudo2.png')
    sys.exit(app.exec_())
Beispiel #11
0
class Streamer(object):
    """
    the server will be the "host" of the screen share,
    basically, will share his screen to all the
    clients.
    """
    def __init__(self):
        """
        The constructor function of the main server.
        """
        self.streamer_socket = socket.socket()
        self.online_users = {}  # {socket: display resolution}.
        self.communicator = Communicator()
        self.screenshot = Screenshot()
        self.running = True

    def bind_socket(self):
        """
        The function binds the server socket and starts listening
        for connections.
        """
        self.streamer_socket.bind((SERVER_IP, SERVER_PORT))
        self.streamer_socket.listen(1)
        print('================================================')
        print(f'[STREAMER] Starting server on: {SERVER_IP}:{str(SERVER_PORT)}))
        print('================================================')

    def new_user(self):
        """
        The function accepts a new connection,
        adds the user's socket to the online users dictionary
        and starts sending him screenshots.
        """
        client_socket, client_address = self.streamer_socket.accept()
        client_ip_address = client_address[0]
        self.online_users[client_socket] = DEFAULT_DISPLAY_RESOLUTION
        Thread(target=self.send_screenshots, args=[client_socket]).start()
        print('[STREAMER] New Online User [' + str(client_ip_address) + ']')

    def send_screenshots(self, user_socket):
        """

        :param user_socket: the socket to send screenshots to.
        the function sends screenshots to a user's socket.
        if there's no online user with that socket the function returns.
        """
        if user_socket in self.online_users.keys():
            while self.running:
                try:
                    user_display_resolution = self.online_users[user_socket]
                    image_data = self.screenshot.get_screenshot_data(image_resize=user_display_resolution) + IMAGE_SUFFIX
                    self.communicator.send_enc_message(image_data, False, user_socket)
                except (KeyError, socket.error):
                    self.remove_user(user_socket)
                    break
        else:
            return None

    def remove_user(self, user_socket):
        """

        :param user_socket: socket to remove from the online users dictionary.
        the function removes a user from the online users dictionary.
        """
        try:
            del self.online_users[user_socket]
            user_socket.close()
            print('[STREAMER] User has been disconnected.')
        except(KeyError, socket.error):
            pass

    def define_message_type(self, message, user_socket):
        """
        :param message: a new message the was received.
        :param user_socket: the socket that the message was received from.
        the function defines the message type and calls the wanted function.
        """
        if isinstance(message, DisplayResolutionChange):
            self.online_users[user_socket] = message.screen_resolution

    def run_server(self):
        while self.running:
            rlist, wlist, xlist = select(list(self.online_users.keys()) + [self.streamer_socket], [], [])
            for user_socket in rlist:
                if user_socket is self.streamer_socket:
                    self.new_user()
                else:
                    try:
                        message = self.communicator.get_dec_message(user_socket)
                        self.define_message_type(message, user_socket)
                    except:
                        self.remove_user(user_socket)
Beispiel #12
0
	ui = im.upload_image(path)
	os.remove(path)
	return ui.link

def get_string(x):
	if x is None:
		return ''
	else:
		return str(x)



head_text = 'Here is a screenshot of the linked page in case you cant access the page or it gets removed or you just dont want to open the page!\n'
foot_text = '\n\n-----------------------------------------------------------\nThis action was performed by a bot. Contact /u/YesIAmTheMorpheus or reply back to this message for feedback or suggestions.'

s = Screenshot()

# r = obot.login_lcb()
r = obot.login()


try:
	already_done = pickle.load('already_done.pkl')
except:
	already_done = []

while True:
	subr = r.get_subreddit('all')
	for sub in subr.get_new():
		if sub.id not in already_done:
			if not any(x in sub.url for x in ["imgur.com","reddit.com"]):
def main():
    log = LoggerItem()
    cfg = Config()

    # read in AppStream file into several Application objects
    f = gzip.open(sys.argv[1], 'rb')
    tree = ET.parse(f)
    apps = []
    for app in tree.getroot():
        a = Application(None, cfg)
        for elem in app:
            if elem.tag == 'id':
                a.set_id(elem.text)
                a.type_id = elem.get('type')
                log.update_key(a.app_id_full)
                log.write(LoggerItem.INFO, "parsing")
            elif elem.tag == 'name':
                if elem.get(XML_LANG):
                    continue
                a.names['C'] = ensure_unicode(elem.text)
            elif elem.tag == 'summary':
                if elem.get(XML_LANG):
                    continue
                a.comments['C'] = ensure_unicode(elem.text)
            elif elem.tag == 'pkgname':
                a.pkgnames.append(ensure_unicode(elem.text))
            elif elem.tag == 'appcategories':
                for elem2 in elem:
                    a.categories.append(ensure_unicode(elem2.text))
            elif elem.tag == 'keywords':
                for elem2 in elem:
                    a.keywords.append(ensure_unicode(elem2.text))
            elif elem.tag == 'url':
                a.urls[elem.get('type')] = ensure_unicode(elem.text)
            elif elem.tag == 'compulsory_for_desktop':
                a.compulsory_for_desktop.append(ensure_unicode(elem.text))
            elif elem.tag == 'project_group':
                a.project_group = ensure_unicode(elem.text)
            elif elem.tag == 'description':
                description = ''
                if len(elem._children):
                    for elem2 in elem:
                        description += elem2.text + u' '
                else:
                    description = elem.text
                a.descriptions['C'] = ensure_unicode(description)
            elif elem.tag == 'screenshots':
                if a.type_id == 'font':
                    continue
                for elem2 in elem:
                    if elem2.tag != 'screenshot':
                        continue
                    caption = None
                    for elem3 in elem2:
                        if elem3.tag == 'caption':
                            caption = elem3.text
                        elif elem3.tag == 'image':
                            if elem3.get('type') != 'source':
                                continue
                            s = Screenshot(a.app_id, None, caption)
                            s.basename = os.path.basename(elem3.text)
                            a.screenshots.append(s)
        apps.append(a)
    f.close()

    # build status page
    status = open('./screenshots/status.html', 'w')
    status.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ' +
                 'Transitional//EN" ' +
                 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
    status.write('<html xmlns="http://www.w3.org/1999/xhtml">\n')
    status.write('<head>\n')
    status.write('<meta http-equiv="Content-Type" content="text/html; ' +
                          'charset=UTF-8" />\n')
    status.write('<title>Application Data Review</title>\n')
    status.write('</head>\n')
    status.write('<body>\n')

    status.write('<h1>Executive summary</h1>\n')
    status.write('<ul>\n')

    # long descriptions
    cnt = 0
    total = len(apps)
    for app in apps:
        if len(app.descriptions) > 0:
            cnt += 1
    tmp = 100 * cnt / total
    status.write("<li>Applications in Fedora with long descriptions: %i (%i%%)</li>" % (cnt, tmp))

    # keywords
    cnt = 0
    total = len(apps)
    for app in apps:
        if len(app.keywords) > 0:
            cnt += 1
    tmp = 100 * cnt / total
    status.write("<li>Applications in Fedora with keywords: %i (%i%%)</li>" % (cnt, tmp))

    # categories
    cnt = 0
    total = len(apps)
    for app in apps:
        if len(app.categories) > 0:
            cnt += 1
    tmp = 100 * cnt / total
    status.write("<li>Applications in Fedora with categories: %i (%i%%)</li>" % (cnt, tmp))

    # screenshots
    cnt = 0
    total = len(apps)
    for app in apps:
        if len(app.screenshots) > 0:
            cnt += 1
    tmp = 100 * cnt / total
    status.write("<li>Applications in Fedora with screenshots: %i (%i%%)</li>" % (cnt, tmp))

    # project apps with appdata
    for project_group in ['GNOME', 'KDE', 'XFCE']:
        cnt = 0
        total = 0
        for app in apps:
            if app.project_group != project_group:
                continue
            total += 1
            if len(app.screenshots) > 0 or len(app.descriptions) > 0:
                cnt += 1
        tmp = 0
        if total > 0:
            tmp = 100 * cnt / total
        status.write("<li>Applications in %s with AppData: %i (%i%%)</li>" % (project_group, cnt, tmp))
    status.write('</ul>\n')

    # write applications
    status.write('<h1>Applications</h1>\n')
    for app in apps:
        if app.type_id == 'font':
            continue
        if app.type_id == 'inputmethod':
            continue
        if app.type_id == 'codec':
            continue
        log.update_key(app.app_id_full)
        log.write(LoggerItem.INFO, "writing")
        try:
            status.write(_to_utf8(_to_html(app)))
        except AttributeError, e:
            log.write(LoggerItem.WARNING, "failed to write %s: %s" % (app, str(e)))
            continue
 def update_screenshot(self):
     # checks if the window is minized and restores it, otherwise, the screenshot returns black
     winapihelper.restore_window_if_minimized(self.handle[0])
     self.screenshot = Screenshot(self.handle[0])
     self.screenshot.get_image(True)
Beispiel #15
0
class FunctionLibrary(object):
    def __init__(self, driver):
        # mobile = Mobile()
        # mobile_driver = Mobile()
        # self.mobile_driver = mobile.mobile_setConfig().driver
        self.mobile_driver = driver
        self.screenshot = Screenshot(driver, '异常截图', '')

    @excepTion
    def CheckByNameIsDisplayed(self, name):
        WebDriverWait(self.mobile_driver, 20).until(
            EC.visibility_of_element_located((By.NAME, name))).is_displayed()
        logger.info("The function checkByName By name is: %s" % name)

    @excepTion
    def ClearByname(self, name):
        element = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.NAME, name)))
        element.clear()
        logger.info("The function ClearByname By name is: %s" % name)

    @excepTion
    def ClearByID(self, element_id):
        element = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.ID, element_id)))
        element.clear()
        logger.info("The function ClearByID By element_id is: %s" % element_id)

    @excepTion
    def ClickByXpath(self, xpath):
        element = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.XPATH, xpath)))
        element.click()
        logger.info("The function ClickByXpath By name is: %s" % xpath)

    @excepTion
    def SendKeyByADB(self, content):
        os.system("adb shell input text '%s'" % content)
        logger.info("The function SendKeyByADB input: %s" % content)

    def getNumByRe(self, str1):
        import re
        model = re.compile(r"\d+")
        ss = model.findall(str1)
        s = ""
        for i in range(len(ss)):
            s += ss[i]
        return s

    def ClickByName(self, name):
        WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.NAME, name))).click()
        logger.info("The function ClickByName By name is: %s" % name)

    @excepTion
    def ClickByID(self, id):
        WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.ID, id))).click()
        logger.info("The function ClickByID By id is: %s" % id)

    @excepTion
    def ClickByClassName(self, className):
        el = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.CLASS_NAME, className)))
        el.click()
        logger.info("The function ClickByClassName By className is: %s" %
                    className)

    @excepTion
    def ClickByLinkText(self, linkText):
        '''
        根据链接文字进行点击
        '''
        el = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.LINK_TEXT, linkText)))
        el.click()
        logger.info("The function ClickByLinkText By linkText is: %s" %
                    linkText)

    @excepTion
    def ClickByUiauto(self, Uiauto):
        el = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.ANDROID_UIAUTOMATOR, Uiauto)))
        el.click()
        logger.info("The function ClickByUiauto By Uiauto is: %s" % Uiauto)

    @excepTion
    def SwipeToFindClickByName(self, name):
        for i in range(10):
            time.sleep(1)
            elements = self.mobile_driver.find_elements_by_name(name)
            if len(elements) > 0:
                elements[0].click()
                break
            else:
                if i < 9:
                    self.swipeOnScreenN(0.8, 0.8, 0.3, 0.3, 1)
        logger.info("The function SwipeToFindClickByName By name is: %s" %
                    name)

    @excepTion
    def SendKeysByID(self, element_id, content):
        element = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.ID, element_id)))
        element.clear()
        element.send_keys(content)
        logger.info("The function SendKeysByID By element_id: %s input: %s" %
                    (element_id, content))

    @excepTion
    def ClickZhangHao(self, ZhangHao):
        xpath = "//android.widget.TextView[contains(@text,\"****\")]"
        for i in range(10):
            elements = self.mobile_driver.find_elements_by_xpath(xpath)
            IsFind = False
            index = 0
            for el in elements:
                index += 1
                text = el.get_attribute("text")
                if self.IsOne(text, ZhangHao):
                    el.click()
                    IsFind = True
                    break
            if index == len(elements) and IsFind is False:
                self.swipeOnScreenN(0.8, 0.8, 0.2, 0.2, 1)

    @excepTion
    def SendKeysByXpath(self, xpath, content):
        element = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.XPATH, xpath)))
        element.clear()
        element.send_keys(content)
        logger.info("The function SendKeysByXpath By xpath: %s input: %s" %
                    (xpath, content))

    @excepTion
    def SendKeysByName(self, name, content):
        element = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.NAME, name)))
        # element.clear()
        element.send_keys(content)
        logger.info("The function SendKeysByName By name: %s input: %s" %
                    (name, content))

    @excepTion
    def SendKeysUseAdbInputText(self, content):
        '''
            只支持数字,暂未支持字母
        '''
        for i in content:
            strCmd = 'adb -s %s shell input text "%s"' % (self.udid, content)
            subprocess.Popen(strCmd,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE).stdout.readlines()

    def swipeOnScreenN(self, floatStartX, floatStartY, floatEndX, floatEndY,
                       num):
        screen = self.mobile_driver.get_window_size()
        screenWidth = screen["width"]  # 当前手机的宽度
        screenHeight = screen["height"]  # 当前手机的高度
        for i in range(num):
            self.mobile_driver.swipe(screenWidth * floatStartX,
                                     screenHeight * floatStartY,
                                     screenWidth * floatEndX,
                                     screenHeight * floatEndY)

    @excepTion
    def swipeToFindElement(self, name):
        for i in range(6):
            elements = self.mobile_driver.find_elements_by_xpath(name)
            if len(elements) > 0:
                break
            else:
                if i < 5:
                    self.swipeOnScreenN(0.9, 0.9, 0.2, 0.2, 1)

    @excepTion
    def swipeToFindElementByXpath(self, xpath):
        for i in range(6):
            elements = self.mobile_driver.find_elements_by_xpath(xpath)
            if len(elements) > 0:
                break
            else:
                if i < 5:
                    self.swipeOnScreenN(0.8, 0.8, 0.5, 0.5, 1)

    @excepTion
    def swipeToFindElementByText(self, name):
        for i in range(6):
            elements = self.mobile_driver.find_elements_by_name(name)
            if len(elements) > 0:
                break
            else:
                if i < 5:
                    self.swipeOnScreenN(0.9, 0.9, 0.2, 0.2, 1)

    @excepTion
    def waitNAME(self, name):
        '''
        等待某个ID出现,切换到新页面时填写,然后截图
        '''
        WebDriverWait(self.mobile_driver, timeout).until(
            EC.presence_of_element_located((By.NAME, name)))

    @excepTion
    def waitTime(self, wtime):
        '''
        :param time: 等待固定时长,单位/秒
        :return: 无
        '''
        time.sleep(wtime)

    def CheckContentText(self, element_id, text):
        el = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.ID, element_id)))
        content = el.get_attribute("text")
        if text in content:
            logger.info("---%s:对比数据成功---" % text)
        else:
            raise ScriptError("[Error]:结果中未找到对应text值【%s】" % text)

    @excepTion
    def CheckByText(self, element_id, text):
        el = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.ID, element_id)))
        content = el.get_attribute("text")
        if "****" in content:
            if self.IsOne(content, text) is False:
                raise ScriptError("[Error]:结果中未找到对应text值【%s】" % text)
        elif self.IsStrChangeNum(content) is True and text.isnumeric() is True:
            if self.IsNumSame(content, text) is False:
                raise ScriptError("[Error]:结果中未找到对应text值【%s】" % text)
        elif text not in content:
            raise ScriptError("[Error]:结果中未找到对应text值【%s】" % text)

    def IsOne(self, name, value):
        if value.isnumeric() is True:
            return self.IsOneNum(name, value)
        elif value.isnumeric() is False:
            return self.IsOneStr(name, value)

    def IsStrChangeNum(self, n):
        import re
        if re.search(r"[^\d,\.]", n):
            return False
        else:
            return True

    def IsNumSame(self, n1, n2):
        try:
            f1 = float(n1.replace(",", ""))
            f2 = float(n2)
            if f1 - f2 == 0:
                return True
            else:
                return False
        except Exception as e:
            funcName = sys._getframe().f_code.co_name
            self.screenshot.takeTakesScreenshot("异常截图", funcName)
            self.mobile_driver.quitDriver()
            raise ScriptError("[Error]:" + funcName + "--" + n1 + "--" + n2 +
                              "  [异常信息:%s]" % repr(e))

    def IsOneNum(self, GetStr, NewStr):
        IsSame = False
        TheStart = False
        TheEnd = False
        GetStr = GetStr.strip().split(" ")[0]
        GetStrs = "-".join(GetStr.strip()).split("-")
        NewStrs = "-".join(NewStr.strip()).split("-")
        GetStrlen = len(GetStrs)
        NewStrlen = len(NewStrs)
        for i, j in zip(range(GetStrlen), range(NewStrlen)):
            if GetStrs[0] == "*":
                TheStart = True
                break
            else:
                if GetStrs[i] != "*":
                    if GetStrs[i] != NewStrs[j]:
                        TheStart = False
                        break
                    elif GetStrs[i] == NewStrs[j]:
                        TheStart = True
                elif GetStrs[i] == "*":
                    break
        for i, j in zip(range(GetStrlen - 1, -1, -1),
                        range(NewStrlen - 1, -1, -1)):
            if GetStrs[GetStrlen - 1] == "*":
                TheEnd = True
                break
            else:
                if GetStrs[i] != "*":
                    if GetStrs[i] != NewStrs[j]:
                        TheEnd = False
                        break
                    elif GetStrs[i] == NewStrs[j]:
                        TheEnd = True
                elif GetStrs[i] == "*":
                    break
        if TheStart is True and TheEnd is True:
            IsSame = True
        return IsSame

    def IsOneStr(self, name, value):
        if name == value:
            return True
        else:
            return False

    def elementIsExist(self, name):
        # elements = WebDriverWait(self.mobile_driver, timeout).until(EC.visibility_of_all_elements_located((By.NAME, name)), name + '----对象未找到')
        elements = self.mobile_driver.find_elements_by_name(name)
        if len(elements) > 0:
            return True
        else:
            return False

    def elementIsExistByID(self, id):
        # elements = WebDriverWait(self.mobile_driver, timeout).until(EC.visibility_of_all_elements_located((By.NAME, name)), name + '----对象未找到')
        elements = self.mobile_driver.find_elements_by_name(id)
        if len(elements) > 0:
            return True
        else:
            return False

    @excepTion
    def IsExistByIdClick(self, element_id):
        elements = self.mobile_driver.find_elements_by_id(element_id)
        if len(elements) > 0:
            elements[0].click()
            logger.info("ID为%s的对象存在,已点击!" % element_id)
        else:
            logger.info("ID为%s的对象不存在!" % element_id)

    @excepTion
    def getCJJLXQ(self, details):
        '''
        :param details:
        :return:获取页面出借记录详情数据值
        '''
        element_id = "com.ygjr.ycd.debug:id/tender_detail_tv_data"
        el = WebDriverWait(self.mobile_driver, timeout).until(
            EC.visibility_of_element_located((By.ID, element_id)))
        texts = el.get_attribute('text').split()
        if details == '出借时间':
            return texts[0]
        elif details == '出借详细时间':
            return texts[1]
        elif details == '预期利率':
            return texts[2]
        elif details == '加息利率':
            return texts[3]
        elif details == '项目期限':
            return texts[4]
        elif details == '项目还款方式':
            return texts[5]
        elif details == '出借本金':
            return texts[6]
        elif details == '使用现金劵':
            return texts[7]
        elif details == '预期利息':
            return texts[8]
        elif details == '加息奖励':
            return texts[9]
        elif details == '到期时间':
            return texts[10]
        else:
            return "没有此数据项!"

    def dataCompare(self, newdata, olddata):
        if newdata == olddata:
            logger.info("数据%s和%s对比成功!" % (newdata, olddata))
        else:
            raise ScriptError("数据%s和%s对比失败!" % (newdata, olddata))

    def DateOperat(self, dater, refer, num):
        '''
        获取,根据初始日期算出多少"月"或"日"之后的日期
        :param dater:
        :param refer: "月"或"日"
        :param num: 多少天或月后
        :return: 返回计算后的日期
        '''
        LeapYearJudge = 29
        try:
            if dater[4] == "0" or dater[4] == "1":
                tempyear = int(dater[0] + dater[1] + dater[2] + dater[3])
                tempmounth = int(dater[4] + dater[5])
                tempday = int(dater[6] + dater[7])
            else:
                tempyear = int(dater.split(dater[4])[0])
                tempmounth = int(dater.split(dater[4])[1])
                tempday = int(dater.split(dater[4])[2])
            if LeapYearJudge == "29":
                Days = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            else:
                Days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            if num > 0:
                if refer == "日" or refer == "天":
                    tempday = tempday + num
                    while tempday > Days[tempmounth]:
                        tempday = tempday - Days[tempmounth]
                        tempmounth = tempmounth + 1
                        if tempmounth > 12:
                            tempmounth = tempmounth - 12
                            tempyear = tempyear + 1
                            if LeapYearJudge == "29":
                                Days = [
                                    0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31,
                                    30, 31
                                ]
                            else:
                                Days = [
                                    0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
                                    30, 31
                                ]
                elif refer == "月":
                    tempmounth = tempmounth + num
                    while tempmounth > 12:
                        tempmounth = tempmounth - 12
                        tempyear = tempyear + 1
                elif refer == "年":
                    tempyear = tempyear + num
                else:
                    print('输入格式错误')
            else:
                if refer == "天" or refer == "日":
                    tempday = tempday + num
                    print(tempday)
                    while tempday <= 0:
                        tempday = tempday + Days[tempmounth - 1]
                        tempmounth = tempmounth - 1
                        if tempmounth <= 0:
                            tempmounth = tempmounth + 12
                            tempyear = tempyear - 1
                            if LeapYearJudge == "29":
                                Days = [
                                    0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31,
                                    30, 31
                                ]
                            else:
                                Days = [
                                    0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
                                    30, 31
                                ]
                elif refer == "月":
                    tempmounth = tempmounth + num
                    while tempmounth <= 0:
                        tempmounth = tempmounth + 12
                        tempyear = tempyear - 1
                elif refer == "年":
                    tempyear = tempyear + num
                else:
                    print('输入格式错误')

            if LeapYearJudge == "29":
                Days = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            else:
                Days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            print(tempday)
            if tempday > Days[tempmounth]:
                print(Days[tempmounth])
                tempday = tempday - Days[tempmounth]
                tempmounth = tempmounth + 1
            print(tempday)
            if tempmounth > 12:
                tempmounth = tempmounth - 12
                tempyear = tempyear + 1
            if tempmounth < 10:
                mounths = "0" + str(tempmounth)
            else:
                mounths = str(tempmounth)
            if tempday < 10:
                days = "0" + str(tempday)
            else:
                days = str(tempday)
            logger.info('获取日期成功')
            return str(tempyear) + "-" + mounths + "-" + days
        except:
            logger.info('获取日期失败')
Beispiel #16
0
def video_feed():
    return Response(gen(Screenshot()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
Beispiel #17
0
import sys, time, os, ast, csv
from similarity import Similarity
from wordpress import WordPressCMS
from screenshot import Screenshot

def list_to_string(obj):
    return str(obj).replace('[','').replace(']','').replace("'",'').strip()

wp = WordPressCMS(wp_path='../../../environment/wordpress/wordpress/')
screenshot = Screenshot(_dir='screenshots2')

with open('CONFLICTS_WP_SS') as f:
    CONFLICTS = ast.literal_eval(f.read())
    CONFLICTS = [
        ['a3-lazy-load', 'counterize']
        # ['comments-from-facebook', 'vk-all-in-one-expansion-unit'],
        # ['comments-from-facebook', 'disable-google-fonts'],
        # ['wp-author-date-and-meta-remover', 'comments-from-facebook'],
        # ['wp-author-date-and-meta-remover', 'vk-all-in-one-expansion-unit'],
    ]
    for conflict in CONFLICTS:
        wp.deactivate(conflict)

# capture screenshot from test page without plugins activated
default_page = '{}/default_page.png'.format(screenshot._dir)
print('capturing default page')
screenshot.capture(default_page)
print('capturing default end')

with open('visual_conflicts.csv', 'a+') as visual:
    visual_csv = csv.DictWriter(visual, fieldnames=['conflict', 'visual_effects'])
Beispiel #18
0
from vision import find_basket, find_ball, find_game_area_shift, crop_game_area, missed_shot
from control import patterns_overlap, determine_next_basket_position
from mouse import shoot, click_play_again
from debug import draw_trajectory, draw_ball, draw_basket, display_image

""" General TODOs """
# TODO: basket is found as (x, y) instead of (y, x)
# TODO: logging
# TODO: learn how to write python documentation
# TODO: important comment should be in docstrings and not as comments
# TODO: consistent use of ints for data storage

# how much to sleep between two consecutive measurements
if __name__ == '__main__':

  s = Screenshot()
  screen_and_crop = lambda: crop_game_area(s.screenshot())
  shots_hit = 0  
  pattern_length = 10
  measurement_interval = 0
  
  # shooting loop
  while True:
    
    trajectory = []
    
    # record the beggining of the pattern
    first_pattern = []
    for _ in xrange(0, pattern_length):
      img_screen = screen_and_crop()
Beispiel #19
0
import cv2

from nestopia import Nestopia
from screenshot import Screenshot
from recognizer import Recognizer
from world import World

if __name__ == '__main__':
    nestopia = Nestopia()
    nestopia.show()

    screenshot = Screenshot('Nestopia')
    world = World(nestopia)
    recognizer = Recognizer()

    try:
        while True:
            image = screenshot.take()
            state = recognizer.recognize(image)
            world.set(state)
    except KeyboardInterrupt:
        pass
class MainLoop:
    def __init__(self, order_number):
        self.pid = 0
        self.screenshot = None
        self.handle = [0, 0]
        self.finished = False
        self.successful = False
        self.order_number = order_number

    def update_screenshot(self):
        # checks if the window is minized and restores it, otherwise, the screenshot returns black
        winapihelper.restore_window_if_minimized(self.handle[0])
        self.screenshot = Screenshot(self.handle[0])
        self.screenshot.get_image(True)

    def check_if_connection_is_alive(self):
        self.pid = winapihelper.get_rdp_pid()
        return not self.pid == 0

    def close_popups(self):
        # tries to find any popups open, and then closes it
        close_button = detection.find_popup_close_button(
            self.screenshot.current_npimg)
        if close_button[0].__len__() > 0:
            winapihelper.mouse_click(self.handle[1], close_button)
            time.sleep(1)
            self.update_screenshot()
            self.close_popups()

    def go_to_main_window(self):
        # tries to go back to the main window
        if not is_valid_coords(
                detection.check_if_in_main_window(
                    self.screenshot.current_npimg)[0]):
            main_window_taskbar = \
                detection.find_main_window_in_taskbar(self.screenshot.current_npimg)
            winapihelper.mouse_click(self.handle[1], main_window_taskbar)
            time.sleep(1)
            self.update_screenshot()
            self.go_to_main_window()

    def open_print_order_window(self):
        if is_valid_coords(
                detection.check_if_order_window_is_open(
                    self.screenshot.current_npimg)):
            return

        # look for the post sell button and clicks it
        button_coords = detection.find_post_sell_button(
            self.screenshot.current_npimg)
        if is_valid_coords(button_coords[0]):
            winapihelper.mouse_click(self.handle[1], button_coords)
            time.sleep(1)
            self.update_screenshot()

            order_button_coords = detection.find_orders_button(
                self.screenshot.current_npimg)
            if is_valid_coords(order_button_coords[0]):
                winapihelper.mouse_click(self.handle[1], order_button_coords)
                time.sleep(1)
                self.update_screenshot()
            else:
                self.open_print_order_window()

            stock_manage_button_coords = detection.find_stock_manage_button(
                self.screenshot.current_npimg)
            if stock_manage_button_coords[0].__len__() > 0:
                winapihelper.mouse_click(self.handle[1],
                                         stock_manage_button_coords)
                time.sleep(1)
                self.update_screenshot()
            else:
                self.open_print_order_window()
        else:
            self.open_print_order_window()

    def print_order_routine(self):
        self.close_popups()
        # checks if the order window is already open
        if is_valid_coords(
                detection.check_if_order_window_is_open(
                    self.screenshot.current_npimg)):
            search_invoice_button = detection.find_search_invoice_button(
                self.screenshot.current_npimg, True)
            if is_valid_coords(search_invoice_button[0]):
                # we want the click to be slightly to the left, since we want to edit the
                # textbox, not click the button
                winapihelper.mouse_click(self.handle[1], search_invoice_button,
                                         (-40, 0))
                winapihelper.mouse_click(self.handle[1], search_invoice_button,
                                         (-40, 0))

                # write order number to field
                winapihelper.write_text(self.handle[1], str(self.order_number))

                # press enter, to load the order and close the popup
                winapihelper.keyboard_click(self.handle[1], win32con.VK_RETURN)
                time.sleep(.25)
                winapihelper.keyboard_click(self.handle[1], win32con.VK_RETURN)

                self.update_screenshot()

                print_button = detection.find_print_button(
                    self.screenshot.current_npimg)
                if is_valid_coords(print_button[0]):
                    winapihelper.mouse_click(self.handle[1], print_button)
                    time.sleep(1)
                    self.update_screenshot()
                else:
                    self.print_order_routine()

                print_order_button = detection.find_print_order_button(
                    self.screenshot.current_npimg)
                if is_valid_coords(print_order_button[0]):
                    winapihelper.mouse_click(self.handle[1],
                                             print_order_button)
                    time.sleep(3)
                    self.update_screenshot()
                else:
                    self.print_order_routine()

                ok_button = detection.find_ok_button(
                    self.screenshot.current_npimg)
                if is_valid_coords(ok_button[0]):
                    winapihelper.mouse_click(self.handle[1], ok_button)
                    time.sleep(2)
                    self.update_screenshot()
                else:
                    self.print_order_routine()

                # checks if the systems tells us that theres nothing to be printed
                check_if_printable = detection.check_if_cannot_print(
                    self.screenshot.current_npimg, True)
                check_if_fake_non_printable = detection.check_if_fake_cannot_print(
                    self.screenshot.current_npimg, True)
                if is_valid_coords(
                        check_if_printable[0]
                ) and not is_valid_coords(check_if_fake_non_printable):
                    self.close_popups()
                    self.finished = True
                    self.successful = True
                    return 1

                # press tab, to unselect the file type combobox
                winapihelper.keyboard_click(self.handle[1], win32con.VK_UP)
                time.sleep(2)

                save_to_file_button = detection.save_to_file_button(
                    self.screenshot.current_npimg)
                if is_valid_coords(save_to_file_button[0]):
                    winapihelper.mouse_click(self.handle[1],
                                             save_to_file_button)
                    self.close_popups()
                    self.finished = True
                    self.successful = True
                else:
                    self.print_order_routine()
            else:
                self.print_order_routine()

        else:
            self.go_to_main_window()
            self.open_print_order_window()
            self.print_order_routine()

    def open_rdp(self):
        # looks for the rdp connection
        self.check_if_connection_is_alive()
        # gets the handle based on the PID
        self.handle = winapihelper.get_handle(self.pid)
        # if theres no active rdp connections it will kill any
        # inactive windows and try to open a new one
        if self.pid == 0:
            try:
                winapihelper.kill_rdp_error_windows()
                if self.handle[0] != 0:
                    winapihelper.kill_inactive_windows()
                winapihelper.open_rdp()
                time.sleep(5)
                return False
            except psutil.AccessDenied:
                time.sleep(1)
                return False
        else:
            return True

    def run(self):
        while not self.finished:
            if not self.open_rdp():
                time.sleep(1)
            else:
                if self.handle[0] != 0:
                    self.update_screenshot()
                    is_system_open = detection.check_if_system_is_open(
                        self.screenshot.current_npimg)
                    if not is_system_open:
                        time.sleep(5)
                        if not self.open_system():
                            break

                        self.update_screenshot()

                    self.print_order_routine()
                    self.finished = True
                    self.successful = True
            time.sleep(1)
        print(self.successful)

    def open_system(self):
        coords = detection.find_program_exe(self.screenshot.current_npimg)
        if is_valid_coords(coords[0]):
            winapihelper.mouse_click(self.handle[1], coords)
            winapihelper.mouse_click(self.handle[1], coords)
            for tries in range(0, 60):
                if not detection.check_if_system_is_open(
                        self.screenshot.current_npimg):
                    print('waiting for the program to start.')
                    time.sleep(1)
                    self.update_screenshot()
                elif tries == 30:
                    winapihelper.mouse_click(self.handle[1], coords)
                    winapihelper.mouse_click(self.handle[1], coords)
                elif tries == 59:
                    self.finished = True
                    return False
                else:
                    time.sleep(3)
                    break
        return True

    def only_open_system(self):
        while self.pid == 0:
            self.open_rdp()
            if self.handle[0] != 0:
                self.update_screenshot()
                while not detection.check_if_system_is_open(
                        self.screenshot.current_npimg):
                    self.open_system()
                    time.sleep(5)
            time.sleep(1)
Beispiel #21
0
 def __init__(self, driver):
     # mobile = Mobile()
     # mobile_driver = Mobile()
     # self.mobile_driver = mobile.mobile_setConfig().driver
     self.mobile_driver = driver
     self.screenshot = Screenshot(driver, '异常截图', '')
Beispiel #22
0
    possibs += get_fives(string)
    possibs += get_fours(string)
    possibs += get_threes(string)
    r = []
    for p in possibs:
        try:
            if dict[p] == 1:
                dict[p] = 2  # already used
                words[len(p)].append(p)
                r.append(p)
        except KeyError:
            # not a word
            continue
    return r

capture = Screenshot("LonelyScreen AirPlay Receiver")
print("Press 's' when you are on the screen with the letters visible:")

while True:
    frame = capture.get_frame()
    cv2.imshow("Screen", frame)

    if cv2.waitKey(1) == ord('s'):
        cv2.destroyAllWindows()
        break

frame = cv2.cvtColor(capture.crop(frame), cv2.COLOR_BGR2GRAY)
frame = threshold(frame)
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\Moez\AppData\Local\Tesseract-OCR\tesseract.exe'

config = r'--oem 3 --psm 6'