예제 #1
0
 def process_default(self, event):
     subprocess.call([
         "pandoc",
         md,
         "-f",
         "markdown",
         "-t",
         "html",
         "-s",
         "-o",
         html,
         "-c",
         "/css/latex-style.css",
         "--mathjax",
     ])
     chrome = Chromote()
     Chromote(host="localhost", port=9222)
     tab = chrome.tabs[0]
     tab.set_url('http://localhost:8080')
     tab.reload()
     bash(
         'pandoc {} --latex-engine=xelatex -o {}/pdf/{}.pdf --variable mainfont="CMU Serif" --variable sansfont="CMU Sans Serif" --variable monofont="CMU Typewriter Text"'
         .format(md, way_to_pdf_save, file_name))
     bash("cp text.md {}/md/{}.md".format(way_to_pdf_save, file_name))
     bash("cp index.html {}/html/{}.html".format(way_to_pdf_save,
                                                 file_name))
예제 #2
0
def get_tab():
    try:
        chrome = Chromote()
    except:
        subprocess.Popen(["google-chrome", "--remote-debugging-port=9222"])
        time.sleep(5)
        chrome = Chromote()
    for t in chrome.tabs:
        if t.url == args.hangouts_url:
            return t
    return chrome.tabs[0]
예제 #3
0
    def connect(self):
        try:
            self.browser = Chromote(host="localhost", port=9222)
        except requests.exceptions.ConnectionError:
            self.browser = Chromote(host="localhost", port=9222, internet_explorer=True)
        kodi.log("connected to %s: %s" % (self.browser.browsertype, self.browser))

        while not self.stop_event.check():
            try:
                self.tab = next(tab for tab, title, url in self.browser.tabs if url != "about:blank" and "file://" not in url)
                break
            except StopIteration:
                xbmc.sleep(200)
        self.tab.connect_websocket()
        kodi.log("websocket connected: %s" % self.tab.url)
예제 #4
0
    def __init__(self, start_url=None, **kwargs):
        super().__init__(**kwargs)

        # TODO : actually return ports to _free_ports
        try:
            self.chromote_port = XWrapChromium._free_ports.pop()
        except IndexError:
            self.chromote_port = XWrapChromium._next_port
            XWrapChromium._next_port += 1

        chromium_command = [
            CHROMIUM_BIN,
            '--incognito',
            '--bwsi',
            '--kiosk',
            '--no-default-browser-check',
            '--no-first-run',
            '--no-session-id',
            '--new-window',
            '--user-data-dir=/tmp/chromote{}'.format(self.chromote_port),
            '--remote-debugging-port={}'.format(self.chromote_port),
            '--class=XWrap{}'.format(self.chromote_port),
            start_url or 'about:blank',
        ]

        print(chromium_command)

        self.process = subprocess.Popen(chromium_command)
        self.xdisplay = Display()
        self.xroot = self.xdisplay.screen().root

        # TODO : don't block everything while waiting.. also make it adaptable to non-chromium? (no probably not)
        self.xwindow = None  # set to None first so update_window(..) doesn't break if fired early by Kivy.
        self.xwindow = awaitish(lambda: self.find_chromium())
        self.xwindow.unmap()

        self.chromote = Chromote('localhost', self.chromote_port)

        print('Found Window: {}'.format(self.xwindow.id))
        self.update_xwindow()
        self.bind(pos=self.__class__.handle_move,
                  size=self.__class__.handle_resize)

        Clock.schedule_interval(self.check_visible, 1 / 10.0)
        print_xlib_tree(self.xdisplay.screen().root)

        kroot = self.parent
        self.kivy_root = None

        while kroot:
            if isinstance(kroot, WindowBase):
                self.kivy_root = kroot
                kroot.bind(pos=self.__class__.handle_move,
                           size=self.__class__.handle_resize)
                break

            kroot = kroot.parent
예제 #5
0
파일: test.py 프로젝트: iiSeymour/chromote
def test_chromote():
    from chromote import Chromote

    chrome = Chromote()

    tab0 = chrome.tabs[0]

    sites = [
        'https://github.com',
        'http://stackoverflow.com',
    ]

    tab0.set_url(sites[0])
    print(tab0)

    tab1 = chrome.add_tab(sites[1])
    print(tab1)
    chrome.close_tab(tab1)

    tab2 = chrome.add_tab()
    print(tab2)
예제 #6
0
    def runJob(self):

        self.chromeBrowser = Chromote()
        self.tab = self.chromeBrowser.tabs[0]
        self.loadSeeds('seeds.txt')
        logging.info('Starting harvest')
        seedCount = 0
        for seed in self.seedList:
            seedCount = seedCount + 1
            print('{} of {}'.format(seedCount, self.numberOfSeeds))
            logging.info('{}'.format(seed))
            self.tab.set_url(seed)
            time.sleep(10)
        self.shutdown()
예제 #7
0
def get_tabs():
    urls = []
    exclude_list = [
        'br-analytics.ru', 'docs.google.com', 'mail.google.com', 'vk.com',
        'www.loveradio.ru'
    ]

    tabs = Chromote(host="localhost", port=9222)
    for tab in tabs:
        clean_path = urlsplit(tab.url)
        base_url = clean_path.netloc
        if base_url not in exclude_list:
            urls.append(tab.url)
    return urls
예제 #8
0
def do_somt(func, m):
    try:
        ch = Chromote()
        for i in ch.tabs:
            if i.url.startswith('https://vk.com/'):
                if func == 'play':
                    soup = BeautifulSoup(str(i.html), 'lxml')
                    soup = soup.find(class_='head_nav_item_player')
                    soup = soup.find(id="top_audio_player")
                    if len(soup.get('class')) == 2:
                        i.evaluate('getAudioPlayer().play()')
                        send(m, 'Музыка играет')
                    else:
                        i.evaluate('getAudioPlayer().pause()')
                        send(m, 'Музыка приостановлена')
                else:
                    i.evaluate(func)
                return True
        return False
    except BaseException as e:
        print(str(e))
예제 #9
0
def main(argv=None):
    # set signal handler
    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)

    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
            raise Usage(msg)
        # more code, unchanged
        # os.system("google-chrome")
        proc = Popen("google-chrome", shell=True, stdout=PIPE, stderr=STDOUT)
        sleep(1)
        chrome = Chromote()
        tab = chrome.tabs[0]
        tab.set_url(
            'http://127.0.0.1:8080/examples/servlets/servlet/HelloWorldExample'
        )
        while True:
            tab.reload()
            sleep(9)
예제 #10
0
def test_chromote():
    from chromote import Chromote

    chrome = Chromote()

    tab0 = chrome.tabs[0]

    sites = [
        'https://github.com',
        'http://stackoverflow.com',
    ]

    tab0.set_url(sites[0])
    print(tab0)

    tab1 = chrome.add_tab(sites[1])
    print(tab1)
    chrome.close_tab(tab1)

    tab2 = chrome.add_tab()
    print(tab2)
예제 #11
0
def main():
    print(
        ' ______     ______     __    __     ______   __  __     ______     __  __     ______     ______    \n/\\  __ \\   /\\  == \\   /\\ "-./  \\   /\\  ___\\ /\\ \\/\\ \\   /\\  ___\\   /\\ \\/ /    /\\  ___\\   /\\  == \\   \n\\ \\  __ \\  \\ \\  __<   \\ \\ \\-./\\ \\  \\ \\  __\\ \\ \\ \\_\\ \\  \\ \\ \\____  \\ \\  _"-.  \\ \\  __\\   \\ \\  __<   \n \\ \\_\\ \\_\\  \\ \\_\\ \\_\\  \\ \\_\\ \\ \\_\\  \\ \\_\\    \\ \\_____\\  \\ \\_____\\  \\ \\_\\ \\_\\  \\ \\_____\\  \\ \\_\\ \\_\\ \n  \\/_/\\/_/   \\/_/ /_/   \\/_/  \\/_/   \\/_/     \\/_____/   \\/_____/   \\/_/\\/_/   \\/_____/   \\/_/ /_/ \n ______     __  __    \n/\\  == \\   /\\ \\_\\ \\   \n\\ \\  __<   \\ \\____ \\  \n \\ \\_____\\  \\/\\_____\\ \n  \\/_____/   \\/_____/ \n __    __     ______     __         ______     __   __     __  __     ______     __         __        \n/\\ "-./  \\   /\\  ___\\   /\\ \\       /\\  __ \\   /\\ "-.\\ \\   /\\ \\_\\ \\   /\\  ___\\   /\\ \\       /\\ \\       \n\\ \\ \\-./\\ \\  \\ \\  __\\   \\ \\ \\____  \\ \\ \\/\\ \\  \\ \\ \\-.  \\  \\ \\  __ \\  \\ \\  __\\   \\ \\ \\____  \\ \\ \\____  \n \\ \\_\\ \\ \\_\\  \\ \\_____\\  \\ \\_____\\  \\ \\_____\\  \\ \\_\\\\"\\_\\  \\ \\_\\ \\_\\  \\ \\_____\\  \\ \\_____\\  \\ \\_____\\ \n  \\/_/  \\/_/   \\/_____/   \\/_____/   \\/_____/   \\/_/ \\/_/   \\/_/\\/_/   \\/_____/   \\/_____/   \\/_____/ \n')
    log("ARM_Fucker by MelonHell запущен")
    global port, chrome
    port = random.randint(1000, 9999)
    log(f"Порт дебаггера: {port}")

    login_data = None

    try:
        with open(configFileName, "r") as f:
            jsonData = json.load(f)
            if "login" in jsonData and "password" in jsonData:
                log("Обнаружен сохранёный пароль. Автоматическая авторизация")
                login = jsonData["login"]
                password = jsonData["password"]
                login_data = login, password
    except:
        pass

    use_theme = input("Хош ахуеную кастомную тему? Y/n: ")

    if os.path.exists("ARM_Student.exe"):
        subprocess.Popen(f"ARM_Student.exe --remote-debugging-port={port}")
    elif os.path.exists("ARM_Student/ARM_Student.exe"):
        subprocess.Popen(f"ARM_Student/ARM_Student.exe --remote-debugging-port={port}")
    else:
        log("Авроры нэма чёт, закинь эту хуйню в папку с авророй")
        time.sleep(5)
        return;

    # WAIT AVRORA
    isStarted = False
    for i in range(10):
        if isStarted:
            continue
        log(f"Ожидание запуска этой поеботы. Попытка {i + 1} из 10")
        try:
            chrome = Chromote(port=port)
            isStarted = True
        except:
            pass
    if not isStarted:
        log("ОШИБКА! Аврора не запустилась. Завершение скрипта")
        return
    log("Заебись! Вроде запустилось")
    global tab
    tab = chrome.tabs[0]

    for i in range(100):
        if login_data is not None:
            continue
        log("Ожидание входа")
        tab.evaluate(scripts.buttonJs)
        att_idUser = json.loads(tab.evaluate(scripts.getIdUser))
        att_password = json.loads(tab.evaluate(scripts.getPassword))
        if att_idUser['result']['result']['type'] == 'string' and att_password['result']['result']['type'] == 'string':
            login = att_idUser['result']['result']['value']
            password = att_password['result']['result']['value']
            login_data = login, password
            with open(configFileName, "w") as f:
                json.dump({"login": login, "password": password}, f)
            log("Пароль сохранён")

    log("Авторизация")
    tab.set_url(f"https://mirea2.aco-avrora.ru/student/?ArmUserId={login_data[0]}&ArmUserPassword={login_data[1]}")

    log("Ждем 5 сек")
    time.sleep(5)
    log("Выполнение основного скрипта")
    tab.evaluate(scripts.mainScript)
    if use_theme in ["", "Y", "y", "1"]:
        log("Применяем мою ахуительную тему")
        tab.evaluate(scripts.insertCss)
    log("АХУЕТЬ ОНО РАБОТАЕТ! Наверное..")
    log("Переход в режим консоли, если она тебе нахуй не нужна, можешь смело закрывать эту хуйню")
    while True:
        console(input("> "))
예제 #12
0
파일: run.py 프로젝트: w0de/chromote
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example script demostrating the use of Chromote to
update a remote browser periodically from a list of sites
"""

from time import sleep
from chromote import Chromote

chrome = Chromote()
print(chrome)

tab = chrome.tabs[0]

sites = [
    'https://github.com',
    'http://stackoverflow.com',
]

for site in sites:
    tab.set_url(site)
    sleep(30)
예제 #13
0
def search(port, query, maxnum=None):
    """
    Large images: tbs=isz:l
    Medium images: tbs=isz:m
    Icon sized images: tba=isz:i
    Image size larger than 400×300: tbs=isz:lt,islt:qsvga
    Image size larger than 640×480: tbs=isz:lt,islt:vga
    Image size larger than 800×600: tbs=isz:lt,islt:svga
    Image size larger than 1024×768: tbs=isz:lt,islt:xga
    Image size larger than 1600×1200: tbs=isz:lt,islt:2mp
    Image size larger than 2272×1704: tbs=isz:lt,islt:4mp
    Image sized exactly 1000×1000: tbs=isz:ex,iszw:1000,iszh:1000
    Images in full color: tbs=ic:color
    Images in black and white: tbs=ic:gray
    Images that are red: tbs=ic:specific,isc:red [orange, yellow, green, teal, blue, purple, pink, white, gray, black, brown]
    Image type Face: tbs=itp:face
    Image type Photo: tbs=itp:photo
    Image type Clipart: tbs=itp:clipart
    Image type Line drawing: tbs=itp:lineart
    Group images by subject: tbs=isg:to
    Show image sizes in search results: tbs=imgo:1
    """
    chrome = Chromote(port=port)
    tab = chrome.tabs[0]
    flags = dict(
        tbm='isch',
        # tbs='ic:color,isz:l',
        tbs='isz:lt,islt:svga',
    )
    tmpl = 'http://www.google.com/search?q={query}&{flags}'
    search_url = tmpl.format(query='+'.join(query.split(' ')),
                             flags='&'.join(
                                 [k + '=' + v for k, v in flags.items()]))
    print('Search url:', search_url)
    print(tab.set_url(search_url))
    time.sleep(1)
    # tab.reload()
    time.sleep(1)
    for i in range(5):
        tab.evaluate('window.scrollTo(0,document.body.scrollHeight);')
        print('scrolled a bit...')
        time.sleep(1)

    time.sleep(10)
    code = '''
            Array.prototype.slice.call(
                document.querySelectorAll("a.rg_l")
            ).map(
                function(elem) {
                    return elem.href;
                }
            ).join(",");
            '''
    out = tab.evaluate(code.replace('\n', ''))
    print(len(out))
    time.sleep(1)
    print(len(out))
    pprint(out)
    urls = json.loads(out)['result']['result']['value']
    pprint(urls)
    imgurls = []
    for url in urls.split(',')[:maxnum]:
        try:
            parsed_url = urlparse(url)
            if not parsed_url.path:
                continue
            # print(parsed_url)
            opts = parse_qs(parsed_url.query)
            # print(opts)
            imgurls.append(
                dict(url=opts['imgurl'][0], height=opts['h'], width=opts['w']))
        except Exception as e:
            # print('Problem with {}: {}'.format(url, e))
            pass

    def dl(url, folder):
        try:
            path = urlparse(url).path
            url_fname = os.path.split(path)[-1]
            fname = uid().hex[:8] + '-' + url_fname
            with urllib.request.urlopen(url, timeout=10) as u:
                data = u.read()
            with open(os.path.join(folder, fname), 'wb') as f:
                f.write(data)
            return True
        except Exception as e:
            print('Problem with {}: {}'.format(url, e))
            return False

    folder = slugify(query) + '-' + uid().hex[:8]
    if not os.path.exists(folder):
        os.mkdir(folder)

    with ThreadPoolExecutor(max_workers=8) as exe:
        jobs = [exe.submit(dl, x['url'], folder) for x in imgurls]
        result = [j.result() for j in jobs]

    return imgurls, tab
예제 #14
0
def open_url(url):
    chrome = Chromote()
    tab = chrome.tabs[0]
    tab.set_url(url)
예제 #15
0
파일: STTTS.py 프로젝트: matiyau/STTTS
os.chdir(pwd)

os.system("sudo fuser -k " + str(ServPort) + "/tcp")
ServTh = Thread(
    target=HTTPServer(('', ServPort), SimpleHTTPRequestHandler).serve_forever)
ServTh.start()

BrowTh = Thread(target=BrowSt)
BrowTh.start()
launchAttempts = 0
while (launchAttempts < 20):
    try:
        sleep(1)
        launchAttempts = launchAttempts + 1
        krom = Chromote()
    except:
        continue
    break

if (launchAttempts == 20):
    WelcTh.join()
    ErrMes = "Maximum Attempts Reached. Your Browser Has Either Not Started Or Has Remote Debugging Disabled"
    print(ErrMes)
    os.system('espeak "' + ErrMes + '"')

TabSTT = krom.tabs[0]
TabSTT.set_url("http://localhost:" + str(ServPort) + "/STTTS.html")
WelcTh.join()
while True:
    sleep(1)
예제 #16
0
class Player(object):
    def __init__(self, stop_event):
        self.exceptions = (StoppedException, requests.exceptions.ConnectionError, socket.error,
                           websocket.WebSocketBadStatusException, websocket.WebSocketConnectionClosedException)
        self.stop_event = stop_event
        self.browser = None
        self.tab = None
        self.k = PyKeyboard()
        self.m = PyMouse()

    def connect(self):
        try:
            self.browser = Chromote(host="localhost", port=9222)
        except requests.exceptions.ConnectionError:
            self.browser = Chromote(host="localhost", port=9222, internet_explorer=True)
        kodi.log("connected to %s: %s" % (self.browser.browsertype, self.browser))

        while not self.stop_event.check():
            try:
                self.tab = next(tab for tab, title, url in self.browser.tabs if url != "about:blank" and "file://" not in url)
                break
            except StopIteration:
                xbmc.sleep(200)
        self.tab.connect_websocket()
        kodi.log("websocket connected: %s" % self.tab.url)

    def disconnect(self):
        if self.browser and self.browser.browsertype == "ie":
            self.browser.close_ieadapter()
            kodi.log("closed ieadapter")
        if self.tab:
            self.tab.close_websocket()

    def wait_for_new_episode(self, starting_urlid):
        starting_url = self.tab.url
        while not self.stop_event.is_set:
            try:
                xbmc.sleep(1000)
                current_url = self.tab.url
                if current_url == starting_url:
                    # no url change
                    continue
                is_episode_page = re.match(r".*www.netflix.com/watch/(\d+).*", current_url)
                if not is_episode_page:
                    continue
                new_urlid = is_episode_page.group(1)
                if new_urlid != starting_urlid:
                    # new episode started
                    return new_urlid
            except KeyError:
                # loading new page
                continue
            except self.exceptions:
                # browser closed
                return None

    def playpause(self):
        self.tab.get_element_by_class_name("player-play-pause").click()

    def next(self):
        self.tab.get_element_by_class_name("player-next-episode").click()

    def forward(self):
        self.k.tap_key(self.k.right_key)

    def rewind(self):
        self.k.tap_key(self.k.left_key)

    def cont(self):
        self.m.click(x=947, y=476)
        xbmc.sleep(100)
        self.m.move(**self.corner_coors)

    def stop(self):
        xbmc.Player().stop()
        self.stop_event.set()
예제 #17
0

def write_html (data, name = "log"):
    f = open (name+".htm","w")
    #print data
    f.write (data)
    f.close


def mt_rand (low = 0, high = sys.maxint):
    """Generate a better random value
    """
    return random.randint (low, high)


chrome = Chromote()
tab = chrome.tabs[0]
tab.set_url('https://likeinsta.ru/tasks/vkontakte/subscribe/')
time.sleep(.900) # Wait for 900 milliseconds

for dotask in range(3):
    print 'dotask: ' +  str(dotask)
    r = tab.evaluate('document.querySelectorAll("a.do-task")[' + str(dotask) + '].click()')
    print r

    """
    POP-UP
    """
    time.sleep(mt_rand(8,9)) 
    all_tabs = chrome._get_tabs
    tab_popup = chrome.tabs[0]
예제 #18
0
class Player(object):
    def __init__(self):
        self.exceptions = (requests.exceptions.ConnectionError, socket.error,
                           websocket.WebSocketBadStatusException)
        self.tab = None
        self.stopped = False
        self.k = PyKeyboard()
        self.m = PyMouse()
        self.player_coord = None
        x, y = self.m.screen_size()
        self.corner_coord = {'x': x, 'y': y}
        self.middle_coord = {"x": x // 2, "y": y // 2}

    def connect(self):
        try:
            self.browser = Chromote(host="localhost", port=9222)
        except requests.exceptions.ConnectionError:
            self.browser = Chromote(host="localhost", port=9222, internet_explorer=True)
        kodi.log("connected to %s: %s" % (self.browser.browsertype, self.browser))

        while not self.stopped:
            try:
                self.tab = next(tab for tab, title, url in self.browser.tabs if url != "about:blank" and "file://" not in url)
                break
            except StopIteration:
                xbmc.sleep(50)
        self.tab.connect_websocket()
        kodi.log("websocket connected: %s" % self.tab.url)

    def cleanup(self):
        if self.browser.browsertype == "ie":
            self.browser.close_ieadapter()
            kodi.log("closed ieadapter")
        if self.tab:
            self.tab.close_websocket()

    def get_player_coord(self):
        playerelement = self.tab.get_element_by_id("playerelement")
        while not playerelement.present:
            xbmc.sleep(100)
        rect = playerelement.rect
        self.player_coord = {"x": int((rect["left"] + rect["right"]) / 2),
                             "y": int((rect["top"] + rect["bottom"]) / 2)}

    def wait_player_start(self):
        for _ in range(120):
            if "ProgressTracker" in self.tab.get_element_by_tag_name("script")["src"]:
                break
            xbmc.sleep(500)

    def wait_for_url_change(self, stored_url=None):
        stored_url = self.tab.url
        while True:
            try:
                current_url = self.tab.url
                if current_url != stored_url:
                    return current_url
            except KeyError:
                # loading new page
                continue
            except (requests.exceptions.ConnectionError, socket.error,
                    websocket.WebSocketBadStatusException):
                # browser closed
                return None
            xbmc.sleep(1000)

    def playpause(self):
        self.k.tap_key(self.k.up_key)
        self.k.tap_key(self.k.space_key)

    def forward(self):
        self.k.tap_key(self.k.right_key)

    def rewind(self):
        self.k.tap_key(self.k.left_key)

    def toggle_fullscreen(self):
        coord = self.player_coord if self.player_coord else self.middle_coord
        self.m.move(**coord)
        xbmc.sleep(200)
        self.m.click(n=2, **coord)
        self.m.move(**self.corner_coord)
        log.info("fullscreen toggled")

    def stop(self):
        xbmc.Player().stop()
        self.stopped = True