예제 #1
0
def random_char(game: str):
    try:
        Roster.default(game)
    except FileNotFoundError:
        return f"<h1>Server Error</h1><h2>Unknown game '{game}'</h2>"
    dists = Roster.distributions(game)
    return render_template('index.html', game=game, dists=dists)
예제 #2
0
    def _build_roster(self):
        roster = Roster()

        for i, player in enumerate(self.player_pool):
            if self._player_is_included(i):
                roster.add_player(player)

        return roster
예제 #3
0
  def _build_roster(self):
    roster = Roster()

    for i, player in enumerate(self.player_pool):
      if self._player_is_included(i):
        roster.add_player(player)

    return roster
예제 #4
0
 def initialize_threads(self):
     """ Initializes io threads"""
     super().initialize_threads()
     self.dashboard_interval = int(self.ping_interval * 2)
     self.topic_fastclock_pub = self.publish_topics[Global.FASTCLOCK]
     self.topic_dashboard_pub = self.publish_topics[Global.DASHBOARD]
     self.topic_node_pub = self.publish_topics[Global.NODE]
     self.topic_ping_sub = self.subscribed_topics[Global.PING]
     # print("!!! ping sub: "+self.topic_ping_sub)
     self.topic_sensor_sub = self.subscribed_topics[Global.SENSOR]
     self.topic_backup_sub = self.subscribed_topics[Global.BACKUP]
     # print("!!! backup sub: "+self.topic_backup_sub)
     if Global.CONFIG in self.config:
         if Global.OPTIONS in self.config[Global.CONFIG]:
             if Global.TIME in self.config[Global.CONFIG][Global.OPTIONS]:
                 if Global.FAST in self.config[Global.CONFIG][
                         Global.OPTIONS][Global.TIME]:
                     if Global.RATIO in self.config[Global.CONFIG][
                             Global.OPTIONS][Global.TIME][Global.FAST]:
                         self.fast_ratio = int(
                             self.config[Global.CONFIG][Global.OPTIONS][
                                 Global.TIME][Global.FAST][Global.RATIO])
                     if Global.INTERVAL in self.config[Global.CONFIG][
                             Global.OPTIONS][Global.TIME][Global.FAST]:
                         self.fast_interval = int(
                             self.config[Global.CONFIG][Global.OPTIONS][
                                 Global.TIME][Global.FAST][Global.INTERVAL])
             if Global.PING in self.config[Global.CONFIG][Global.OPTIONS]:
                 self.ping_interval = self.config[Global.CONFIG][
                     Global.OPTIONS][Global.PING]
             if Global.BACKUP in self.config[Global.CONFIG][Global.OPTIONS]:
                 self.backup_path = self.config[Global.CONFIG][
                     Global.OPTIONS][Global.BACKUP]
     self.roster = Roster(self.log_queue,
                          file_path=Global.DATA + "/" + Global.ROSTER +
                          ".json")
     self.switches = Switches(self.log_queue,
                              file_path=Global.DATA + "/" +
                              Global.SWITCHES + ".json")
     self.warrants = Warrants(self.log_queue,
                              file_path=Global.DATA + "/" +
                              Global.WARRANTS + ".json")
     self.signals = Signals(self.log_queue,
                            file_path=Global.DATA + "/" + Global.SIGNALS +
                            ".json")
     self.layout = Layout(self.log_queue,
                          file_path=Global.DATA + "/" + Global.LAYOUT +
                          ".json")
     self.dashboard = Dashboard(self.log_queue,
                                file_path=Global.DATA + "/" +
                                Global.DASHBOARD + ".json")
     self.sensors = Sensors(self.log_queue,
                            file_path=Global.DATA + "/" + Global.SENSORS +
                            ".json")
예제 #5
0
  def handle_media_ready(self, client, data):
    '''Announce self to the NDN network when the local user has media ready (i.e. get permission fo use microphone and/or camera)

    Args:
      client : local user
      data : media_ready message from local user
    '''
    if self.client is None:
      PeetsServerFactory.__logger.debug('register client %s', client.id)
      self.client = client
      # announce self in NDN
      self.roster = Roster('/ndn/broadcast/' + self.chatroom, self.peets_msg_callback, lambda: self.client.local_user)
      self.local_status_callback('Running')
    else:
      PeetsServerFactory.__logger.debug("Join message from: %s, but we already have a client: %s", client.id, self.client.id)
예제 #6
0
    def test_nearest_in_partition(self, positions_and_item):
        positions, (position, character) = positions_and_item
        roster = Roster.partitioned(
            positions,
            area_containing(positions),
            partition_func=character_colour,
        )

        partition_key = "blue"

        assume(
            any(char.colour == partition_key and char != character
                for (_, char) in positions.items()))

        nearest = roster.nearest_to(position, key=partition_key)
        assert nearest is not None
        nearest_position, nearest_character = nearest.position, nearest.character

        assert nearest_position != position
        assert nearest_character != character

        best_distance = min((p - position).distance
                            for p, c in positions.items()
                            if c != character and c.colour == partition_key)
        assert best_distance == (nearest_position - position).distance
예제 #7
0
 def _assemble_roster(self):
     """Assemble a roster for this team."""
     # Prepare some variables that we'll need
     roster_order = ('P', 'C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF')
     lineup = []
     available_players = list(self.players)
     # Assemble starters
     for position_to_slot in roster_order:
         available_players_at_that_position = [
             p for p in available_players if p.position == position_to_slot
         ]
         best_available_at_that_position = max(
             available_players_at_that_position,
             key=lambda player: self.scout.grade(prospect=player,
                                                 position=position_to_slot))
         lineup.append(best_available_at_that_position)
         available_players.remove(best_available_at_that_position)
     # Assemble bullpen and bench
     bullpen = []
     bench = []
     for bench_player in available_players:
         if bench_player.position == 'P':
             bullpen.append(bench_player)
         else:
             bench.append(bench_player)
     # Instantiate and set a Roster object
     self.roster = Roster(lineup=tuple(lineup),
                          bullpen=tuple(bullpen),
                          bench=tuple(bench))
예제 #8
0
    def test_preserves_instigator(self, instigator, target):
        positions = {Point(0, 0): instigator, Point(1, 1): target}

        roster = Roster.for_mapping(positions, area_containing(positions))
        paint = ChangeCharacter(instigator, Point(1, 1), paint_blue)
        new_roster = paint.next_roster(roster)
        assert new_roster.character_at(Point(0, 0)) is instigator
예제 #9
0
 def test_move_of_non_existent_character(self, character,
                                         non_existent_character):
     roster = Roster.for_mapping({Point(0, 0): character},
                                 Area(Point(0, 0), Point(5, 5)))
     move = Move(non_existent_character, Point(1, 1), Point(2, 1))
     with pytest.raises(ValueError):
         move.next_roster(roster)
예제 #10
0
    def test_move_to_occupied_position(self, mover, obstacle):
        positions = {Point(0, 0): mover, Point(1, 1): obstacle}

        roster = Roster.for_mapping(positions, area_containing(positions))
        move = Move(mover, Point(0, 0), Point(1, 1))
        with pytest.raises(ValueError):
            move.next_roster(roster)
예제 #11
0
def post_install():
    # Retrieve the auth code from the request params
    auth_code = request.args['code']
    name = request.args['state'].split(' ')

    first_name = name[0]

    if len(name) == 3:
        last_name = name[2]
        first_name += ' ' + name[1]
    else:
        last_name = name[1]

    client = slack.WebClient(token="")

    # Request the auth tokens from Slack
    response = client.oauth_access(client_id=client_id,
                                   client_secret=client_secret,
                                   code=auth_code)

    # Save the token to an to data store for later use
    person = {
        'access_token': response['access_token'],
        'user_id': response['user_id'],
    }

    employees.update({
        'first_name': first_name,
        'last_name': last_name
    }, {'$set': person},
                     upsert=False)

    r = Roster("password.json", "EAST")
    r.setOutOfQueue()

    #set the user to Out of Queue if it is their OOQ day
    completed = employees.find_one({
        'first_name': first_name,
        'last_name': last_name
    })
    choose_command.apply_async(args=("run", response['user_id']),
                               queue="commands")

    return "Auth complete! You will receive a notification on your Out of Queue day, and your status will be updated! \n\n Please check out #sup-ooq for discussion"
예제 #12
0
 def setUp(self):
   roster_data = {"players" : [
                   {"name" : "Kalpesh Shah", "skill" : 3, "division": "West"},
                   {"name" : "Larry Ward", "skill" : 3, "division": "West"},
                   {"name" : "Justin Long", "skill" : 3, "division": "East"},
                   {"name" : "Joe Au", "skill" : 2, "division": "East"},
                   {"name" : "Kevin Dahl", "skill" : 2, "division": "West"},
                   {"name" : "Maria Bates", "skill" : 1, "division": "East"}
                 ]}
   self.roster = Roster(roster_data)
예제 #13
0
    def test_changes_target(self, instigator):
        target = Character(colour="red")
        positions = {Point(0, 0): instigator, Point(1, 1): target}

        roster = Roster.for_mapping(positions, area_containing(positions))
        paint = ChangeCharacter(instigator, Point(1, 1), paint_blue)
        new_roster = paint.next_roster(roster)

        new_character = new_roster.character_at(Point(1, 1))
        assert new_character is not None
        assert new_character.colour == "blue"
예제 #14
0
    def test_move_out_of_bounds(self, area_and_positions, new_position):
        area, positions = area_and_positions
        position, character = next(iter(positions.items()))

        assume(new_position not in area)

        roster = Roster.for_mapping(positions, area)
        move = Move(character, position, new_position)

        with pytest.raises(ValueError):
            move.next_roster(roster)
예제 #15
0
    def test_write_roster(self):
        with Roster("Jones_2019.xlsx") as r:
            john = r.get_student("Johnny Carson")
            for assignment, grade in [(3, 90), (6, 94), (9, 92)]:
                john["grades"][assignment] = grade
            self.assertTrue(r.class_average() == 616.6 / 7)
            r.save("Jones_2019_Updated.xlsx")

        wb = load_workbook("Jones_2019_Updated.xlsx")
        self.assertTrue(wb.get_sheet_by_name("Student_1")["B12"].value == 94)
        wb.close()
예제 #16
0
class TestRoster(unittest.TestCase):
  def setUp(self):
    roster_data = {"players" : [
                    {"name" : "Kalpesh Shah", "skill" : 3, "division": "West"},
                    {"name" : "Larry Ward", "skill" : 3, "division": "West"},
                    {"name" : "Justin Long", "skill" : 3, "division": "East"},
                    {"name" : "Joe Au", "skill" : 2, "division": "East"},
                    {"name" : "Kevin Dahl", "skill" : 2, "division": "West"},
                    {"name" : "Maria Bates", "skill" : 1, "division": "East"}
                  ]}
    self.roster = Roster(roster_data)

  def tearDown(self):
    self.roster = None

  def test_roster_has_player_data(self):
    self.assertEqual('Kalpesh Shah', self.roster.get_players()[0].name)

  def test_roster_size(self):
    self.assertEqual(6, self.roster.get_count())

  def test_get_division_peers_count(self):
    peers = self.roster.get_division_peers(self.roster.get_players()[0])
    self.assertEqual(2, len(peers))

  def test_get_division_peers_division(self):
    player_1 = self.roster.get_players()[0]
    peers = self.roster.get_division_peers(player_1)
    for peer in peers:
      self.assertEqual(player_1.division, peer.division)
예제 #17
0
def refresh():
    rost = Roster("password.json", "EAST")
    rost.setEmployees()
    rost.setOutOfQueue()
    s = SlackBot()
    s.refreshOOQ()
    print(f"Refresh Complete! Value of inTraining: {s.inTraining}")
예제 #18
0
    def test_character_moves(self, positions_and_item, move_vector):
        positions, (position, character) = positions_and_item
        new_position = position + move_vector

        all_positions = list(positions) + [new_position]

        assume(not any(pos == new_position for pos, _ in positions.items()))
        roster = Roster.for_mapping(positions, area_containing(all_positions))
        move = Move(character, position, new_position)

        next_roster = move.next_roster(roster)

        assert next_roster.character_at(new_position) == character
예제 #19
0
def create_new_roster():
    clear_screen()
    name = input("Enter the name of your new program >> ")
    strengths = None
    while not strengths:
        strengths = input("""
Enter your string strengths. For example,
for 8 First Violins, 6 Seconds, 5 Violas, 4 Cellos and 3 Basses,
type "8 6 5 4 3" (max 30 players per section).
>> """)
        strengths = convert_input_to_int(strengths, 1, 30, 5)

    return Roster(strengths, name)
예제 #20
0
    def test_read_roster(self):
        with Roster("Jones_2019.xlsx") as r:
            student_names = r.get_student_names()
            self.assertTrue(len(student_names) == 7)
            self.assertTrue("Robert Waters" in student_names)

            catherine = r.get_student("Catherine Hitchens")
            self.assertTrue(catherine["id"] == 3)
            self.assertTrue(isinstance(catherine["grades"], pandas.Series))
            self.assertTrue(len(catherine["grades"]) == 10)
            self.assertTrue(catherine["grades"][4] == 86)

            self.assertTrue(r.class_average() == 614.1 / 7)
예제 #21
0
def main(): 
    f = Field('30x50 yards ', 'grass')
    all_players = Roster()
    r = all_players.roster
    tourney = Tournament()
    divided_teams = tourney.make_teams(r)
    # # print(test)
    winner = tourney.compute_winner()

    print("These are the teams:\n")
    for t in range(len(divided_teams)):
        print("{}\n".format(divided_teams[t]))

    print("The winner is: \033[1;32m{}\033[0m".format(winner))
예제 #22
0
def class_average(ctx, filename="Jones_2019.xlsx"):
    """
        Runs Roster.class_average()

        Parameters
        ---------
        ctx
            The context parameter required by invoke tasks.

        filename
            Name of excel file to get class average from
    """
    with Roster(filename) as r:
        print(r.class_average())
예제 #23
0
def get_student_names(ctx, filename="Jones_2019.xlsx"):
    """
        Runs Roster.get_student_names()

        Parameters
        ---------
        ctx
            The context parameter required by invoke tasks.

        filename
            Name of excel file to get student names from
    """
    with Roster(filename) as r:
        print(r.get_student_names())
예제 #24
0
    def test_zombie_approaches_human(self):
        zombie = default_zombie()
        human = default_human()

        characters = {Point(0, 0): zombie, Point(2, 2): human}
        area = Area(Point(0, 0), Point(3, 3))
        roster = Roster.partitioned(characters,
                                    area=area,
                                    partition_func=LifeState.for_character)

        roster = Tick(roster).next()

        assert sorted(roster.positions) == [(Point(1, 1), zombie),
                                            (Point(2, 2), human)]
예제 #25
0
 def test_viewpoint_multiple_characters(self, char1, char2):
     roster = Roster.for_mapping(
         {
             Point(1, 1): char1,
             Point(2, 0): char2
         },
         area=Area(Point(0, 0), Point(3, 3)),
     )
     viewpoint = Viewpoint(Point(0, 1), roster)
     assert viewpoint.occupied_points_in(
         BoundingBox.range(1)) == {Vector(1, 0)}
     assert viewpoint.occupied_points_in(BoundingBox.range(5)) == {
         Vector(1, 0),
         Vector(2, -1),
     }
예제 #26
0
def main():
    """Main function.

    Sets up some example students, then prints the intro email.
    """
    students = [
        Student('Alice', '*****@*****.**'),
        Student('Bob', '*****@*****.**'),
        Student('Mel', '*****@*****.**'),
    ]
    roster = Roster(students, 'David')

    intro_email = write_intro_email(roster)

    print(intro_email)
예제 #27
0
def rosters(draw,
            inhabitants=st.one_of(st.builds(default_human),
                                  st.builds(default_zombie))):
    width, height = draw(world_dimensions), draw(world_dimensions)
    assume(width > 0)
    assume(height > 0)
    area = Area(Point(0, 0), Point(width, height))
    points = st.builds(
        Point,
        st.integers(min_value=0, max_value=width - 1),
        st.integers(min_value=0, max_value=height - 1),
    )
    characters = draw(st.dictionaries(points, inhabitants))
    return Roster.partitioned(characters,
                              area=area,
                              partition_func=LifeState.for_character)
예제 #28
0
 def __init__(self, position, name, players, n_players, player_csv, load=None):
     self.roster = []
     self.mutex = threading.Lock()
     self.cond = threading.Condition(threading.Lock()) 
     self.players = players
     self.starred_players = []
     for player in self.players:
         if player.stared == 1:
             self.starred_players.append(player)
     self.allplayers = copy.copy(players)
     max_name = 10
     self.done = 0
     for player in players:
         if len(player.name) > max_name:
             max_name = len(player.name)
     self.maxnamelen = max_name
     self.user_pos = (position - 1)
     self.round = 0
     self.rd_pick = 0
     self.total_pick = 1
     self.n_rosters = n_players
     self.selections = []
     filname = 'logs/draft/Draft_' + time.strftime('%m_%d_%y') + '.log'
     self.logger = draftlogging.Logger(filname)
     filname = 'logs/picks/Draft_picks' + time.strftime('%m_%d_%y_%H_%M_%S') + '.log'
     self.picklogger = filname
     with open(self.picklogger, 'w+') as f:
         #ensure it is empty
         pass
     self.player_csv = player_csv
     self.user_name = name
     for i in range(1, (self.n_rosters+1)):
         if i == position:
             ros_str = name
         else:
             ros_str = "comp%d"%(i)
         roster = Roster(i, ros_str, self.player_csv, self.logger)
         if i == (self.user_pos+1):
             self.user_roster = roster
         self.roster.append(roster)
     if load != None:
         str =  "loading draft"
         self.logger.logg(str, 1)
     self.current_roster = self.roster[0]
     self.remaining_picks = (self.n_rosters * self.roster[0].max_players)
     self.turn_ts = time.time()
     self.started = 0
예제 #29
0
    def __init__(
        self,
        area: Area,
        population: Iterable[Optional[Character]],
        barriers: Barriers = Barriers.NONE,
    ):
        character_positions = (p for p in area if not barriers.occupied(p))

        starting_positions = {
            point: character
            for point, character in zip(character_positions, population)
            if character is not None
        }

        self._roster = Roster.partitioned(
            starting_positions,
            area=area,
            partition_func=LifeState.for_character)
예제 #30
0
    def test_delete_roster_student(self):
        student_count = 0
        with Roster("Jones_2019.xlsx") as r:
            student_count = len(r.get_student_names())
            self.assertTrue(student_count == 7)
            self.assertTrue(r.get_student("William Thomas")["id"] == 5)
            r.delete_student("Allen Dalton")
            student_count = len(r.get_student_names())
            self.assertTrue(student_count == 6)
            self.assertTrue(r.get_student("William Thomas")["id"] == 4)
            r.save("Jones_2019_Reduced.xlsx")

        wb = load_workbook("Jones_2019_Reduced.xlsx")
        sheet_names = wb.get_sheet_names()
        self.assertTrue(len(sheet_names) == 7)
        self.assertTrue(sheet_names[0] == "Roster")
        self.assertTrue(sheet_names[-1] == "Student_6")
        self.assertTrue(wb.get_sheet_by_name("Student_3")["B7"].value == 92)
        wb.close()
예제 #31
0
 def test_init(self):
     nshiftsperday = 3
     qualified = ["Q1", "Q2", "Q3"]
     regular = ["R1", "R2", "R3", "R4", "R5"]
     monthno = 5
     year = 2019
     roster = Roster(nshiftsperday, qualified, regular, monthno, year)
     self.assertEqual(roster.nshiftsperday, nshiftsperday)
     self.assertEqual(roster.qualified, qualified)
     self.assertEqual(roster.regular, regular)
     self.assertEqual(roster.monthno, monthno)
     self.assertEqual(roster.year, year)
     self.assertEqual(roster.ndays, ndays(monthno, year))
     self.assertEqual(len(roster.arr), ndays(monthno, year))
     self.assertEqual(len(roster.arr[0]), nshiftsperday)
     for iday in range(0, roster.ndays):
         for ishift in range(0, roster.nshiftsperday):
             self.assertEqual(roster.arr[iday][ishift], "")
     return roster
예제 #32
0
def get_student(ctx, student_identifier, filename="Jones_2019.xlsx"):
    """
        Runs Roster.get_student_()

        Parameters
        ---------
        ctx
            The context parameter required by invoke tasks.

        student_identifier
            Either a full name as a string, or a student ID as an int

        filename
            Name of excel file to get the student
    """
    with Roster(filename) as r:
        if _is_intstring(student_identifier):
            print(r.get_student(int(student_identifier)))
        else:
            print(r.get_student(student_identifier))
예제 #33
0
def daily():
    rost = Roster("password.json", "EAST")
    rost.setEmployees()
    rost.setOutOfQueue()

    s = SlackBot()
    print("From cron.py")
    print(s.inTraining)

    if s.inTraining:
        for engineer in s.inTraining:
            s.setStatus(engineer)

    s.msgOutOfQueue()
    s.msgAllStaff()
예제 #34
0
파일: server.py 프로젝트: mthxx/Comms
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = str(self.request.recv(1024),"utf-8")
        self.argv = self.data.rstrip().split(',')
        
        if self.argv[0] == "get_active_log":
            log_path = self.argv[1]
            length = os.path.getsize(log_path)
            self.request.send(Server.convert_to_bytes(length))
            
            infile = open(log_path, 'r')
            self.log = infile.read()
            self.log = self.log.encode(encoding='UTF-8')
            self.log = struct.pack('>I',len(self.log)) + self.log
            self.request.sendall(self.log)
        
        elif self.argv[0] == "get_all_logs":
            self.time_stamps = ""
            for i in range(1,len(self.argv)):
                self.temp = ""
                if not os.path.exists(Config.c['LOG PATH'] + self.argv[i]):
                    f = open(Config.c['LOG PATH'] + self.argv[i], 'w')
                    f.write("Fresh Log\n\n")
                    f.close()
                self.temp = os.stat(Config.c['LOG PATH'] + self.argv[i])
                self.time_stamps += str(self.temp.st_mtime) + ","
            
            self.time_stamps = self.time_stamps.encode(encoding='UTF-8')
            self.time_stamps = struct.pack('>I',len(self.time_stamps)) + self.time_stamps
            self.request.sendall(self.time_stamps)
        
        elif self.argv[0] == "get_channels":
            channels_raw = Channels()
            self.channels = channels_raw.get_list()
            self.channel_str = ""
            for i in range(0,len(self.channels)):
                self.channel_str += self.channels[i][0] + "/"
                for j in range(0,len(self.channels[i][1])):
                    self.channel_str += self.channels[i][1][j] + ","
                if len(self.channels[i][1]) == 0:
                    self.channel_str += "none,"
                self.channel_str = self.channel_str[:-1]
                self.channel_str += "/"
                self.channel_str += self.channels[i][2] + "/"
                for j in range(0,len(self.channels[i][3])):
                    self.channel_str += self.channels[i][3][j] + ","
                if len(self.channels[i][3]) == 0:
                    self.channel_str += "none,"
                self.channel_str = self.channel_str[:-1]
                self.channel_str += "//"

            self.channel_str = self.channel_str[:-2]
            
            self.channel_str = self.channel_str.encode(encoding='UTF-8')
            self.channel_str = struct.pack('>I',len(self.channel_str)) + self.channel_str
            self.request.sendall(self.channel_str)
            #self.request.sendall(bytes(self.channel_str + "\n", "utf-8"))

        elif self.argv[0] == "get_roster":
            roster = Roster()
            self.roster_arr = roster.get_roster()
            self.roster_str = ""
            for i in range(0,len(self.roster_arr)):
                self.roster_str += self.roster_arr[i][0] + ',' + self.roster_arr[i][1] + ',' + self.roster_arr[i][2] + '/'
            
            self.roster_str = self.roster_str.encode(encoding='UTF-8')
            self.roster_str = struct.pack('>I',len(self.roster_str)) + self.roster_str
            self.request.sendall(self.roster_str)
            #self.request.sendall(bytes(self.roster_str + "\n", "utf-8"))
        
        elif self.argv[0] == "new_post":
            log_path = self.argv[1]
            log = ""
            for i in range(2,len(self.argv)):
                log += self.argv[i] + ","
            log = log[:-1]
            ts = time.time()
            st = datetime.datetime.fromtimestamp(ts).strftime('%m/%d > %H:%M >')
            log = st + ' ' + log + '\n----------\n\n'
            f = open(log_path, 'a')
            f.write(log)
            f.close()
        
        elif self.argv[0] == "whos_online":
            self.users = Online.add(self.argv[1])
            self.online_users = ""
            for i in range(0,len(self.users)):
                self.online_users += self.users[i][0] + ","
            self.request.sendall(bytes(self.online_users + "\n", "utf-8"))
예제 #35
0
파일: test.py 프로젝트: yueyoum/renren-xmpp
from twisted.internet import reactor
from twisted.words.protocols.jabber.jid import JID
from wokkel.client import XMPPClient


from echo import Echo
from roster import Roster

with open('account', 'r') as f:
    account = f.readlines()

jid = JID(account[0].rstrip('\n'))
password = account[1].rstrip('\n')

client = XMPPClient(jid, password)

echo = Echo()
roster = Roster()

roster.setHandlerParent(client)
echo.setHandlerParent(client)

client.startService()
reactor.run()
예제 #36
0
class PeetsServerFactory(WebSocketServerFactory):
  '''A factory class that does housing keeping job. This is needed when we use the proxy for multiple local users (each of the user would prompts the creation of a PeetsServerProtocol instance).
  Although the current usage does not support multiple local user, it's here due to historical reason and potential future needs.
  '''

  __logger = Logger.get_logger('PeetsServerFactory')
  
  def __init__(self, udp_port, nick, prefix, chatroom, url = None, protocols = [], debug = False, debugCodePaths = False):
    '''
    Args:
      udp_port (int) : The udp port to listen for WebRTC traffice.
      nick (str) : The nickname for the local user.
      prefix (str) : The prefix for the local user.
      chatroom (str) : The chatroom to join.

    Kwargs:
      url : The url for websocket server
      And other default kwargs of WebSocketServerFactory.

    A roster for the chatroom is maintained here.
    CcnxSocket created for PeetsMessages propagation if NDN.
    '''
    # super can only work with new style classes which inherits from object
    # apparently WebSocketServerFactory is old style class
    WebSocketServerFactory.__init__(self, url = url, protocols = protocols, debug = debug, debugCodePaths = debugCodePaths)
    self.handlers = {'join_room' : self.handle_join, 'send_ice_candidate' : self.handle_ice_candidate, 'send_offer' : self.handle_offer, 'media_ready' : self.handle_media_ready, 'chat_msg': self.handle_chat}
    # keep the list of local clients, first, we deal with the case where there is only one local client
    self.client = None
    # keep the list of remote users
    self.roster = None
    self.listen_port = udp_port
    self.__class__.__logger.debug('UDP-PORT=%s', str(udp_port))
    self.ccnx_socket = CcnxSocket()
    self.ccnx_socket.start()
    self.local_status_callback = lambda status: 0
    self.nick = nick
    self.prefix = prefix
    self.chatroom = chatroom

  def set_local_status_callback(self, callback):
    self.local_status_callback = callback

  def sdp_callback(self, interest, data):
    '''A callback function for incoming sdp description from remote users.

    Args:
      interest : PyCCN.UpcallInfo.Interest
      data : PyCCN.UpcallInfo.ContentObject

    Send the sdp to the frontend. If we already received the ICE candidate for the same remote user, then we also send out this ICE candidate.
    '''
    content = data.content
    offer_msg = RTCMessage.from_string(content)
    d = RTCData(socketId = self.client.id, sdp = offer_msg.data.sdp)
    # this is the answer to the local user
    answer_msg = RTCMessage('receive_answer', offer_msg.data)
    self.client.sendMessage(str(answer_msg))
    remote_user = self.roster[offer_msg.data.socketId]
    remote_user.set_sdp_sent()
    # we received ice candidate before sending answer
    if remote_user.ice_candidate_msg is not None:
      self.client.sendMessage(str(remote_user.ice_candidate_msg))

  def peets_msg_callback(self, peets_msg):
    '''A callback function to process the peets message (to be used by Roster).

    Args:
      peets_msg (PeetsMessage) : The received PeetsMessage.

    Basically, it needs to inform the status change or text chat to the front end and als fetch sdp for the new remote user if the PeetsMessage is a Join.
    '''
    remote_user = RemoteUser(peets_msg.user)
    if peets_msg.msg_type == PeetsMessage.Join or peets_msg.msg_type == PeetsMessage.Hello:
      if self.roster.has_key(remote_user.uid):
        self.__class__.__logger.debug("Redundant join message from %s", remote_user.get_sync_prefix())
        exit(0)
        return
      
      self.roster[remote_user.uid] = remote_user
      self.__class__.__logger.debug("Peets join message from remote user: %s", remote_user.get_sync_prefix())
      data = RTCData(socketId = remote_user.uid, username= remote_user.nick)
      msg = RTCMessage('new_peer_connected', data)
      self.client.sendMessage(str(msg))
      name = remote_user.get_sdp_prefix()
      
      # ask for sdp message for the new remote user
      self.ccnx_socket.send_interest(name, PeetsClosure(msg_callback = self.sdp_callback))
      

    elif peets_msg.msg_type == PeetsMessage.Leave:
      del self.roster[remote_user.uid]
      self.__class__.__logger.debug("Peets leave message from remote user: %s", remote_user.get_sync_prefix())
      data = RTCData(socketId = remote_user.uid)
      msg = RTCMessage('remove_peer_connected', data)
      self.client.sendMessage(str(msg))

    elif peets_msg.msg_type == PeetsMessage.Chat:
      data = RTCData(socketId = remote_user.uid, messages = peets_msg.extra, username = remote_user.nick)
      msg = RTCMessage('receive_chat_msg', data)
      self.client.sendMessage(str(msg))

  def unregister(self, client):
    '''Clean up when the local user quits.

    Args:
      client (PeetsServerProtocol) : the local user.
    '''

    if self.client is not None and client.id == self.client.id:
      self.local_status_callback('Stopped')
      self.handle_leave(client)
      PeetsServerFactory.__logger.debug("unregister client %s", client.id)
      self.client = None
      self.roster = None

  def process(self, client, msg):
    '''Process the message from the local user's front end.

    Args:
      client (PeetsServerProtocol) : local user.
      msg (RTCMessage) : the message from frontend.
    '''
    rtcMsg = RTCMessage.from_string(msg)
    handler = self.handlers.get(rtcMsg.eventName)
    if handler is not None:
      handler(client, rtcMsg.data)
    else:
      PeetsServerFactory.__logger.error("Unknown event name: " + rtcMsg.eventName)

  def handle_join(self, client, data):
    '''Handle join message from the frontend

    Args:
      client : local user
      data : join message from local user
    '''
    PeetsServerFactory.__logger.debug('join from client %s', client.id)

    d = RTCData(connections = [])
    msg = RTCMessage('get_peers', d)
    client.sendMessage(str(msg))
    client.local_user.nick = self.nick
    client.local_user.prefix = self.prefix

  def handle_media_ready(self, client, data):
    '''Announce self to the NDN network when the local user has media ready (i.e. get permission fo use microphone and/or camera)

    Args:
      client : local user
      data : media_ready message from local user
    '''
    if self.client is None:
      PeetsServerFactory.__logger.debug('register client %s', client.id)
      self.client = client
      # announce self in NDN
      self.roster = Roster('/ndn/broadcast/' + self.chatroom, self.peets_msg_callback, lambda: self.client.local_user)
      self.local_status_callback('Running')
    else:
      PeetsServerFactory.__logger.debug("Join message from: %s, but we already have a client: %s", client.id, self.client.id)

  def handle_leave(self, client):
    '''Clean up when local user leaves.
    
    Args:
      client : local user.
    '''
    self.roster.leave()
    sleep(1.1)
    

  # this method is local, i.e. no leak to NDN
  def handle_ice_candidate(self, client, data):
    '''Handle ice candidate from local user.

    Args:
      client : local user
      data : ice candidate message from local user.

    Whenever the local frontend ends its ice candidate, it's expecting the ice candiate from the remote end.
    We will use a fake ice candidate for the remote end to trick the frontend to use an ice candidate that points to a port that our proxy is listening to intercept webrtc traffice.
    If the SDP for remote end has not been received yet, we postpone the reply of ice candidate because WebRTC requires SDP to be set up before receiving ice candidate message.
    '''
    candidate = Candidate.from_string(data.candidate)
    if client.media_sink_ports.get(data.socketId) is None:
      port = int(candidate.port)
      client.media_sink_ports[data.socketId] = port
      client.ctrl_seqs[port] = 0
      client.remote_cids[port] = data.socketId
      if client.media_source_port is None:
        client.media_source_port = int(candidate.port)
      if client.ip is None:
        client.ip = candidate.ip
      
      candidate = Candidate(('127.0.0.1', str(self.listen_port)))
      d = RTCData(candidate = str(candidate), socketId = data.socketId)
      msg = RTCMessage('receive_ice_candidate', d)
      remote_user = self.roster[data.socketId]
      remote_user.set_ice_candidate_msg(msg)
      # sdp answer has already been sent
      if remote_user.sdp_sent:
        self.client.sendMessage(str(msg))

      
  def handle_offer(self, client, data):
    '''Handle the offer (sdp) from the front end

    Args:
      client : local user
      data : offer sdp message

    We store the offer for later use (we will use the same offer for all the PeerConnection this local user is going to establish) and also publish it to NDN.
    '''
    if client.media_source_sdp is None:
      client.media_source_sdp = data.sdp

    d = RTCData(sdp = client.media_source_sdp, socketId = client.id)
    msg = RTCMessage('receive_offer', d)

    name = client.local_user.get_sdp_prefix() 
    # publish sdp msg
    self.ccnx_socket.publish_content(name, str(msg))


    def publish(interest):
      self.ccnx_socket.publish_content(name, str(msg))

    self.ccnx_socket.register_prefix(name, PeetsClosure(incoming_interest_callback = publish))


  def has_local_client(self):
    return self.client is not None and self.roster is not None

  def handle_chat(self, client, data):
    '''Handle chat message from local user.

    Args:
      client : local user
      data : chat message from local user

    Publish the text chat message to NDN.
    '''
    msg = PeetsMessage(PeetsMessage.Chat, self.client.local_user, extra = data.messages)
    self.roster.chronos_sock.publish_string(self.client.local_user.get_sync_prefix(), self.roster.session, str(msg), StateObject.default_ttl)