Beispiel #1
0
def bookiesports_sync():
    if not Config.get("advanced_features", default=False):
        raise Exception("Sync currently disabled")

    form = SynchronizationForm()

    if form.validate_on_submit():
        flash("Blockchain has been synchronized with bookiesports and a new proposal has been created, ready to be broadcasted")
        Node().sync(Config.get("connection", "use"))
        return redirect(url_for("pending_operations"))
    else:
        form.chain_id.data = Config.get("connection", "use") + ":" + Node().get_node().rpc.chain_params["chain_id"]
        form.bookiesports_name.data = Config.get("connection", "use")
        try:
            bookieSports = BookieSports(
                chain=form.bookiesports_name.data
            )
            form.bookiesports_name.data = form.bookiesports_name.data + ":" + bookieSports.index.get("chain_id", None)

            if bookieSports.index.get("chain_id", None) is not None and\
                (bookieSports.index["chain_id"] == "*" or
                 bookieSports.index["chain_id"] == Node().get_node().rpc.chain_params["chain_id"]):
                if Node().isInSync(Config.get("connection", "use")):
                    form.status.data = "In sync!"
                else:
                    form.status.data = "NOT in sync! Needs syncing!"
            else:
                flash("Your bookiesports name and chain id do not match. Please make sure that the alias you use for the key connection.use within config-bos-mint.yaml matches the corresponding chain", category="error")
                form.status.data = "Your bookiesports name and chain id do not match."
                delattr(form, "submit")

        except AssertionError:
            flash("BookieSports uses the aliases " + str(BookieSports.list_chains()) + ", please use the same aliases in the key connection.use within config-bos-mint.yaml", category="error")
            delattr(form, "submit")

    return render_template_menuinfo('generic.html', **locals())
Beispiel #2
0
    def __init__(
        self,
        sports_folder=None,
        network=None,
        proposing_account=None,
        approving_account=None,
        *args,
        **kwargs
    ):
        """ Let's load all the data from the folder and its subfolders
        """
        kwargs.pop("proposer", None)  # Do not forward proposer
        kwargs.pop("approver", None)  # Do not forward approver
        BlockchainInstance.__init__(self, *args, **kwargs)

        # self._cwd = os.path.dirname(os.path.realpath(__file__))
        self._cwd = os.getcwd()

        if not self.proposing_account and proposing_account:
            self.proposing_account = proposing_account
        elif self.proposing_account:
            pass
        elif "default_account" in config:
            proposing_account = config["default_account"]
        else:
            log.error("No proposing account known")
            raise Exception("No proposing account known!")

        if not self.approving_account and approving_account:
            self.approving_account = approving_account
        elif self.approving_account:
            pass
        elif "default_account" in config:
            approving_account = config["default_account"]
        else:
            log.error("No approving account known")
            raise Exception("No approving account known!")

        # We define two transaction buffers
        if not Lookup.direct_buffer:
            self.clear_direct_buffer()
        if not Lookup.proposal_buffer:
            self.clear_proposal_buffer()

        # Do not reload sports if already stored in data
        if (
            not Lookup.data or
            (sports_folder and Lookup.sports_folder != sports_folder) or
            (network and Lookup._network_name != network)
        ):
            # Load sports
            self._bookiesports = BookieSports(
                network=network,
                sports_folder=sports_folder
            )
            Lookup.sports_folder = sports_folder
            Lookup._network_name = network
            self.data["sports"] = self._bookiesports

            # Ensure that the node is on the right network
            sports_chain_id = self._bookiesports.chain_id
            node_chain_id = self.blockchain.rpc.chain_params["chain_id"]
            assert sports_chain_id == "*" or sports_chain_id == node_chain_id, "You are connecting to {} while network {} requires {}".format(
                node_chain_id, network, sports_chain_id
            )

        # This variable tracks internal retriggers.
        # Internal retriggers are used when the backend claims an operation
        # exists already. Then, we will call update() again which might cause
        # recursion. To prevent that, we only allow retriggers **once**.
        self._retriggered = False
        self._retriggered_kwargs = dict()
Beispiel #3
0
 def test_bookiesports(self):
     # Validation happens inside
     BookieSports()
Beispiel #4
0
 def test_list_chains(self):
     networks = BookieSports.list_chains()
     self.assertIn("alice", networks)
     self.assertIn("beatrice", networks)
     self.assertIn("charlie", networks)
Beispiel #5
0
 def test_version(self):
     print()
     pprint(BookieSports.version())
     print()
Beispiel #6
0
 def test_beatrice(self):
     beatrice = BookieSports("beatrice")
     self.assertEqual(
         beatrice.chain_id,
         "b3f7fe1e5ad0d2deca40a626a4404524f78e65c3a48137551c33ea4e7c365672")
Beispiel #7
0
 def test_charlie(self):
     charlie = BookieSports("charlie")
     self.assertEqual(charlie.chain_id, "*")
Beispiel #8
0
 def test_alice(self):
     charlie = BookieSports("alice")
     self.assertEqual(
         charlie.chain_id,
         "6b6b5f0ce7a36d323768e534f3edb41c6d6332a541a95725b98e28d140850134")
Beispiel #9
0
 def test_fred(self):
     fred = BookieSports("fred")
     self.assertEqual(
         fred.chain_id,
         "fb6ff714f8dfcf97eef01591fc938aa97755bf641aef711b3609a94578df9e5e")
Beispiel #10
0
 def __init__(self):
     self.bookiesports = BookieSports(chainName)
     pass
Beispiel #11
0
class Cp():

    def __init__(self):
        self.bookiesports = BookieSports(chainName)
        pass

    def GetKey(self, keys):
        keys = list(keys)
        k = 0
        for key in keys:
            print(k, key)
            k = k + 1
        index = input("Enter index of key: ")
        index = int(index)
        return keys[index]

    def GetKeyParticipant(self, keys, participantDisplays):
        keys = list(keys)
        k = 0
        for key in keys:
            # print(k, participantDisplays[k])
            print(k, key)
            k = k + 1
        index = input("Enter index of key: ")
        index = int(index)
        return keys[index]

    def GetSportsList(self):
        return list(self.bookiesports.keys())

    def GetEventGroupsList(self, sport):
        eventGroupsList = self.bookiesports[sport]["eventgroups"].keys()
        eventGroupsList = list(eventGroupsList)
        return eventGroupsList

    def GetParticipants(self, sport, participantKey):
        participants = self.bookiesports[self._sport]["participants"][
                self._participantKey]["participants"]
        particpantIdentifiers = []
        participantDisplays = []
        for participant in participants:
            # particpantIdentifiers.append(participant["aliases"][0])
            participantDisplays.append(participant.values())
            # particpantIdentifiers.append(participant["identifier"])
            particpantIdentifiers.append(participant["name"]["en"])
        return particpantIdentifiers, participantDisplays

    def CliManufactureCreateIncident(self):
        self._call = INCIDENT_CALLS[0]
        self._sportsList = self.GetSportsList()
        print("")
        print("Select Sport")
        self._sport = self.GetKey(self._sportsList)
        # self._sport = self.bookiesports[self._sport]["aliases"][0]
        self._eventGroupsList = self.GetEventGroupsList(self._sport)
        print("")
        print("Select Event Group")
        self._eventGroup = self.GetKey(self._eventGroupsList)
        self._eventGroupIdentifier = self.bookiesports[self._sport][
                "eventgroups"][self._eventGroup]["identifier"]
        # self._eventGroupIdentifier = self.bookiesports[self._sport][
        # "eventgroups"][self._eventGroup]["aliases"][0]
        self._participantKey = self.bookiesports[self._sport]["eventgroups"][
                self._eventGroup]["participants"]
        self._participants, participantDisplays = self.GetParticipants(
                self._sport, self._participantKey)
        print("")
        print("Select Home Team")
        self._home = self.GetKeyParticipant(
                self._participants, participantDisplays)
        print("")
        print("Select Away Team")
        self._away = self.GetKeyParticipant(
                self._participants, participantDisplays)

        incident = dict()
        incident["call"] = self._call

        # incident["arguments"] = {
        # "whistle_start_time": "2020-08-25T22:22:45.00Z"}
        incident["id"] = dict()
        incident["id"]["sport"] = self._sport
        incident["id"]["event_group_name"] = self._eventGroupIdentifier
        # incident["id"]["event_group_name"] = self._eventGroup
        print("")
        startTime = input(
                "Enter Start Time in the format 2020-08-25T22:00:00Z :")
        startTime = date_to_string(startTime)
        incident["id"]["start_time"] = startTime
        incident["arguments"] = {"whistle_start_time": startTime}
        # incident["id"]["start_time"] = "2020-08-25T22:00:00Z"
        incident["id"]["home"] = self._home
        incident["id"]["away"] = self._away
        incident["timestamp"] = date_to_string(datetime.now(tz=timezone.utc))
        incident["arguments"]["season"] = ""

        # string = incident_to_string(incident)

        return incident

    def EventsAllSorted(self):
        print('Fetching all active events, wait a few seconds')
        eventsAll = node.getEvents("all")
        eventsAll = pd.DataFrame(eventsAll)
        if len(eventsAll) == 0:
            return None
        eventsAll = eventsAll.sort_values("start_time")
        return eventsAll

    def Event2Update(self):
        eventsAll = self.EventsAllSorted()
        if isinstance(eventsAll, type(None)):
            return None
        self._eventsAll = eventsAll
        for k in range(len(eventsAll)):
            event = eventsAll.iloc[k]
            print("")
            print(event)
            eventGroup = node.getEventGroup(event["event_group_id"])
            print(eventGroup["name"])
            sport = node.getSport(eventGroup["sport_id"])
            print(sport)
            choice = input(
                    "'U'pdate the event/'S'kip to the next event, u/s : ")
            if choice == "u":
                return event
            else:
                k = k + 1
        return None

    def HomeAway(self, homeAway):
        try:
            home, away = homeAway.split(" @ ")
        except ValueError:
            home, away = homeAway.split(" v ")
        return home, away

    def EventGroupAlias(self, sport, eventGroup):
        bookieEventGroups = self.bookiesports[sport]["eventgroups"]
        keys = list(bookieEventGroups.keys())
        for key in keys:
            if eventGroup == bookieEventGroups[key]["identifier"]:
                return bookieEventGroups[key]["aliases"][0]
        print("eventGroup Identifier NOT found: ", sport, eventGroup)

    def EventScheme(self, sport, eventGroup):
        sports = self.bookiesports[sport]
        eventGroups = sports["eventgroups"]
        for eg in eventGroups:
            if eventGroups[eg]["identifier"] == eventGroup:
                eventScheme = eventGroups[eg]
        eventScheme = eventScheme["eventscheme"]["name"]
        return eventScheme

    def CliUpdate(self):
        event = self.Event2Update()
        if isinstance(event, type(None)):
            return None
        self._event = event
        print("")
        print("Select Call")
        self._call = self.GetKey(INCIDENT_CALLS[1:-1])
        incident = dict()
        incident["call"] = self._call

        # incident["arguments"] = {
        # "whistle_start_time": "2020-08-25T22:22:45.00Z"}
        startTime = event["start_time"] + "Z"
        self._starttime = startTime
        incident["id"] = dict()
        eventGroup = rpc.get_object(event["event_group_id"])

        sport = rpc.get_object(eventGroup["sport_id"])

        # eventGroup = dict(eventGroup["name"])["identifier"]
        eventGroup = dict(eventGroup["name"])["identifier"]
        # sport = dict(sport["name"])["identifier"]
        sport = dict(sport["name"])["identifier"]
        sport = normalizer._get_sport_identifier(sport, True)
        self._sport = sport
        sportAlias = self.bookiesports[sport]["aliases"][0]

        eventGroup = normalizer._get_eventgroup_identifier(
                sport,
                eventGroup,
                startTime,
                True)

        self._eventGroup = eventGroup
        # eventGroupAlias = self.EventGroupAlias(sport, eventGroup)
        # eventGroupAlias = self.bookiesports[sport]["eventgroups"][
        # eventGroup]["aliases"][0]

        homeAway = event["name"][0][1]
        self._homeAway = homeAway
        home, away = self.HomeAway(homeAway)
        eventScheme = self.EventScheme(sport, eventGroup)
        homeAway = substitution([home, away], eventScheme)
        home, away = self.HomeAway(homeAway)

        homeAlias = normalizer._get_participant_identifier(
                sport,
                eventGroup,
                home,
                True)

        awayAlias = normalizer._get_participant_identifier(
                sport,
                eventGroup,
                away,
                True)

        # incident["id"]["event_group_name"] = eventGroupAlias
        incident["id"]["event_group_name"] = eventGroup

        incident["id"]["sport"] = sportAlias

        incident["id"]["start_time"] = startTime
        incident["arguments"] = {"whistle_start_time": startTime}
        # incident["id"]["start_time"] = "2020-08-25T22:00:00Z"

        incident["id"]["home"] = homeAlias
        incident["id"]["away"] = awayAlias
        incident["timestamp"] = date_to_string(datetime.now(tz=timezone.utc))
        incident["arguments"]["season"] = event["season"][0][1]

        if self._call == "result":
            print("")
            homeScore = input("Enter Home " + homeAlias + " Score: ")
            print("")
            awayScore = input("Enter Away " + awayAlias + " Score: ")
            incident["arguments"]["home_score"] = homeScore
            incident["arguments"]["away_score"] = awayScore

        self._incident = incident
        # string = incident_to_string(incident)

        return incident

    def Update(self):
        incident = self.CliUpdate()
        if isinstance(incident, type(None)):
            print("No incident to update")
            return None, None
        rs = []
        for potatoName in potatoNames:
            r = self.Push2bos(incident, potatoName)
            rs.append(r)
        return rs
        # r = self.Push2dp(incident)

    def Push2dp(self, incident):
        self._incident = incident
        string = incident_to_string(incident)
        self._string = string
        # normalize(string_to_incident(string), True)
        params = dict()
        params["manufacture"] = string
        params["restrict_witness_group"] = "elizabeth"
        params["token"] = "pbsabookie"
        self._params = params
        # r = requests.get(url=dps["local"], params=params)
        # return r

    def Push2bos(self, incident, providerName):
        string = incident_to_string(incident)
        self._string = string
        incident["unique_string"] = string
        incident["provider_info"] = dict()
        incident["provider_info"]["name"] = providerName
        incident["provider_info"]["pushed"] = date_to_string(
                datetime.now(tz=timezone.utc))
        self._incident = incident
        incident = normalize(incident, True)
        self._incident = incident
        logger.info(str(incident))

        # r = requests.post(url=bos["local"], json=incident)
        rng = np.random.default_rng()
        lBosApis = len(bosApis)
        ks = rng.choice(lBosApis, size=lBosApis, replace=False)
        # print(incident)
        for k in ks:
            # for api in bosApis:
            api = bosApis[k]
            # print(api)
            try:
                r = requests.post(url=api, json=incident)
                logger.info(str(api) + " : " + str(r))
                print(api, r)
            except Exception as e:
                logger.info(api + " failed " + str(e))
                print(api, ":", "failed", ":", e)
        return r

    def Create(self):
        incident = self.CliManufactureCreateIncident()
        rs = []
        for potatoName in potatoNames:
            r = self.Push2bos(incident, potatoName)
            rs.append(r)
        # r = self.Push2bos(incident, "jemshid1")
        # r2 = self.Push2bos(incident, "jemshid2")
        # r = self.Push2dp(self._incident)
        # return r, r2
        return rs

    def Choose(self):
        # print("Choose u or c:")
        print("u: Update event")
        print("c: Create event")
        choice = input("Enter your choice u/c: ")
        if choice == "u":
            self.Update()
        elif choice == "c":
            self.Create()
        else:
            print("You didn't make a relevant choice, try again")
Beispiel #12
0
class BookieLookup(object):
    """
        This class serves as the normalization entry point for incidents.
        All events / event group and participant names are replaced with the
        counterpart stored in the bookiesports package.
    """

    ALIAS_TO_SPORT = {}

    LOOKUP = BookieSports(Config.get("bookiesports_chain", default="beatrice"))

    NOT_FOUND = {}

    def _get_sport_identifier(self,
                              sport_name_in_incident,
                              errorIfNotFound=False):
        """
        Tries to find the sport in bookiesports and returns its identifier.

        :param sport_name_in_incident: name given by provider
        :type sport_name_in_incident: str
        :returns the normalized sport name
        """
        for key, sport in self.LOOKUP.items():  # @UnusedVariable
            if self._search_name_and_alias(sport_name_in_incident, sport):
                return sport["identifier"]

        BookieLookup.not_found(sport_name_in_incident)
        if errorIfNotFound:
            raise NotNormalizableException()
        return sport_name_in_incident

    def _search_name_and_alias(self,
                               search_for,
                               search_container):
        if search_container.get("aliases") and utils.search_in(
                search_for,
                search_container["aliases"]):
            return True
        if utils.search_in(search_for, search_container["name"].values()):
            return True
        if search_container.get("identifier", None) == search_for:
            return True
        return False

    def _string_to_date(self, date_string, from_or_to):
        if type(date_string) == str:
            if len(date_string) == len("YYYY/YY/YY"):
                date_string = date_string[0:4] + "-" + date_string[5:7] + "-" + date_string[8:10] + "T"
                if from_or_to == "from":
                    date_string = date_string + "00:00:00Z"
                else:
                    date_string = date_string + "23:59:59Z"
            elif len(date_string) == len("YYYY/YY/YY XX:XX:XX"):
                date_string = date_string[0:4] + "-" + date_string[5:7] + "-" + date_string[8:10] + "T" + date_string[11:19] + "Z"

        if type(date_string).__name__ == "datetime":
            return date_string
        else:
            return utils.string_to_date(date_string)

    def _start_time_within(self, eventgroup, start_date):
        if eventgroup.get("finish_date", None) is None and eventgroup.get("start_date", None) is None:
            return True

        start_date = utils.string_to_date(start_date)
        return start_date <= self._string_to_date(eventgroup["finish_date"], "to") and start_date >= self._string_to_date(eventgroup["start_date"], "from")

    def _get_eventgroup_identifier(self,
                                   sport_identifier,
                                   event_group_name_in_incident,
                                   event_start_time_in_incident,
                                   errorIfNotFound=False):
        """
        Tries to find the eventgroup in bookiesports and returns its identifier.

        :param sport_identifier: name given by provider
        :type sport_identifier: str
        :param event_group_name_in_incident: name given by provider
        :type event_group_name_in_incident: str
        :returns the normalized eventgroup name
        """
        for key, sport in self.LOOKUP.items():  # @UnusedVariable
            if sport["identifier"] == sport_identifier:
                for keyt, valuet in sport["eventgroups"].items():  # @UnusedVariable @IgnorePep8
                    if self._search_name_and_alias(
                            event_group_name_in_incident,
                            valuet) and\
                            self._start_time_within(valuet, event_start_time_in_incident):
                        return valuet["identifier"]

        BookieLookup.not_found(
            sport_identifier + "/" + event_group_name_in_incident)
        if errorIfNotFound:
            raise NotNormalizableException()
        return event_group_name_in_incident

    def _get_participant_identifier(self,
                                    sport_identifier,
                                    event_group_identifier,
                                    participant_name_in_incident,
                                    errorIfNotFound=False):
        """
        Tries to find the participant in bookiesports and returns its identifier.

        :param sport_identifier: name given by provider
        :type sport_identifier: str
        :param event_group_identifier: name given by provider
        :type event_group_identifier: str
        :param participant_name_in_incident: name given by provider
        :type participant_name_in_incident: str
        :returns the participant eventgroup name
        """
        for key, sport in self.LOOKUP.items():  # @UnusedVariable
            if sport["identifier"] == sport_identifier:
                for teamsfile, participants in sport["participants"].items():  # @UnusedVariable @IgnorePep8
                    for participant in participants["participants"]:
                        if self._search_name_and_alias(
                                participant_name_in_incident,
                                participant):
                            try:
                                return participant["identifier"]
                            except KeyError:
                                return participant["name"]["en"]

        BookieLookup.not_found(
            sport_identifier + "/" + event_group_identifier + "/" + participant_name_in_incident)
        if errorIfNotFound:
            raise NotNormalizableException()
        return participant_name_in_incident

    @staticmethod
    def not_found(key):
        BookieLookup.NOT_FOUND[key] = ""

    @staticmethod
    def normalize_incident(incident, errorIfNotFound=False):
        normalized_incident = incident.copy()
        lookup = BookieLookup()
        sport_identifier = lookup._get_sport_identifier(
            incident["id"]["sport"],
            errorIfNotFound=errorIfNotFound)
        event_group_identifier = lookup._get_eventgroup_identifier(
            sport_identifier,
            incident["id"]["event_group_name"],
            incident["id"]["start_time"],
            errorIfNotFound=errorIfNotFound)
        home_identifier = lookup._get_participant_identifier(
            sport_identifier,
            event_group_identifier,
            incident["id"]["home"],
            errorIfNotFound=errorIfNotFound)
        away_identifier = lookup._get_participant_identifier(
            sport_identifier,
            event_group_identifier,
            incident["id"]["away"],
            errorIfNotFound=errorIfNotFound)

        normalized_incident["id"]["sport"] = sport_identifier
        normalized_incident["id"]["event_group_name"] = event_group_identifier
        normalized_incident["id"]["home"] = home_identifier
        normalized_incident["id"]["away"] = away_identifier

        return normalized_incident