<commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division)

import datetime as dt
from collections import namedtuple
import requests
import re
from multiprocessing.dummy import Process as Thread
import socket
import xbmc

import websocket
from chromote import Chromote
from pykeyboard import PyKeyboard
from pymouse import PyMouse

from . import constants as const
from .utils import (uni_join, os_join)
from .xbmcwrappers import (log, settings, rpc)
from .remote import Remote


class Player(object):
    def __init__(self):
        self.exceptions = (requests.exceptions.ConnectionError, socket.error,
                           websocket.WebSocketBadStatusException)
        self.tab = None
        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)
        log.info("connected to %s: %s" % (self.browser.browsertype, self.browser))

        while True:
            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()
        log.info("websocket connected: %s" % self.tab.url)

    def cleanup(self):
        if self.browser.browsertype == "ie":
            self.browser.close_ieadapter()
            log.info("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):
        if self.tab and self.browser.browsertype == "chrome":
            focused = self.tab.evaluate('document.hasFocus()')['result']['result']['value']
            if focused:
                self.k.press_keys([self.k.control_key, "w"])
        xbmc.Player().stop()


class Session(object):
    def __init__(self):
        self.koala_playing = False

    def start(self):
        playingfile = self.get_playing_file()
        if not (playingfile["file"].startswith(uni_join(const.libpath, const.provider)) or<commit_msg>bugfix: endless loop when closing playback early<commit_after>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division)

import datetime as dt
from collections import namedtuple
import requests
import re
from multiprocessing.dummy import Process as Thread
import socket
import xbmc

import websocket
from chromote import Chromote
from pykeyboard import PyKeyboard
from pymouse import PyMouse

from . import constants as const
from .utils import (uni_join, os_join)
from .xbmcwrappers import (log, settings, rpc)
from .remote import Remote


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)
        log.info("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()
        log.info("websocket connected: %s" % self.tab.url)

    def cleanup(self):
        if self.browser.browsertype == "ie":
            self.browser.close_ieadapter()
            log.info("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):
        if self.tab and self.browser.browsertype == "chrome":
            focused = self.tab.evaluate('document.hasFocus()')['result']['result']['value']
            if focused:
                self.k.press_keys([self.k.control_key, "w"])
        xbmc.Player().stop()
        self.stopped = True


class Session(object):
    def __init__(self):
        self.koala_playing = False

    def start(self):
        playingfile = self.get_playing_file()
        if not (playingfile["file"].startswith(uni_join(const.libpath, const.provider)) or
{'fraction_non_alphanumeric': 0.11184532550171317, 'fraction_numerical': 0.00783162016642193, 'mean_word_length': 2.1838722243864432, 'pattern_counts': {'":': 12, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '456419', 'n_tokens_mistral': 2520, 'n_tokens_neox': 2384, 'n_words': 546}