Example #1
0
def delete_channel(channel_id: str, request: Request, response: Response):

    # Clean delete channel
    Channel.objects(_id=channel_id).update(set__status='deleted')

    # Return response
    return {"msg": "deleted!"}
Example #2
0
 def get_channel(channel_name):
     if Channel.exists(channel_name):
         channel = Channel.get(channel_name)
     else:
         channel = Channel(channel_name)
         channel.save()
     return channel
Example #3
0
 def _handle_privmsg_to_channel(self, message, receiver, user):
     if not Channel.exists(receiver):
         return
     channel = Channel.get(receiver)
     msg_content = message.parameters[-1]
     message = "[%s] <%s>: %s" % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M'), user.nickname, msg_content)
     self._message(channel.name, message)
Example #4
0
    def from_user(self, mask, o=None, *_):
        # TODO: If the "o" parameter is passed only operators are returned
        # according to the <mask> supplied.
        # TODO: If there is a list of parameters supplied
        # with a WHO message, a RPL_ENDOFWHO MUST be sent
        # after processing each list item with <name> being
        # the item.

        resp = []
        if Channel.exists(mask):
            channel = Channel.get(mask)
            for channel_user in channel.users:
                resp.append(
                    RPL_WHOREPLY(self.actor, channel_user, str(channel))
                )
        else:
            if mask == '0':
                mask = '*'
            parser = abnf.wildcard(mask)
            for user in User.all():
                # TODO: add check for servername
                if any([abnf.parse(str, parser)
                        for str
                        in [user.hostname, user.realname, user.nickname]]):
                    resp.append(RPL_WHOREPLY(self.actor, user, mask))
        #resp.append(RPL_ENDOFWHO(self.user, str(channel)))
        return resp
Example #5
0
 def from_user(self, receivers=None, text=None, *_):
     if receivers is None:
         return ERR_NORECIPIENT(self.command, self.actor)
     if text is None:
         return ERR_NOTEXTTOSEND(self.actor)
     resp = []
     # TODO: check for ERR_TOOMANYTARGETS
     for receiver in receivers.split(','):
         if Channel.exists(receiver):
             users = [user
                      for user in Channel.get(receiver).users
                      if user is not self.user]
             resp.append(M(
                 ActorCollection(users),
                 self.command, str(receiver), text,
                 prefix=str(self.user)))
         elif User.exists(receiver):
             resp.append(M(
                 Actor.by_user(User.get(receiver)),
                 self.command, str(receiver), text,
                 prefix=str(self.user)))
         # TODO: Implement wildcards
         # TODO: check for ERR_WILDTOPLEVEL, RPL_AWAY, ERR_NOTOPLEVEL
         else:
             resp.append(ERR_NOSUCHNICK(receiver, self.actor))
     return resp
Example #6
0
def create_channel(channel_payload: ChannelType, request: Request,
                   response: Response):

    # Get logged in user
    user = auth_module.get_me(request=request)

    if user is None:
        return {"msg": "access denied!"}

    # Channel fields
    channel = Channel()
    channel.name = channel_payload.name
    channel.summary = channel_payload.summary
    channel.tags = channel_payload.tags
    channel.admins = [user.get("_id")]

    # Channel cover
    cover = Photo()
    cover._id = uuid.uuid4()
    cover.filename = "path-filename"
    cover.path = "path-photo"
    channel.cover = cover

    channel.save()

    return {"msg": "create channel route!"}
Example #7
0
 def post(self, *args, **kwargs):
     try:
         data = json.loads(self.request.body)
         channel = yield self.db.Channel.find_one({"_id": data["_id"]})
         if channel:
             c = Channel(_id=channel['_id'], body=data)
             channel = c.get()
         yield self.db.Channel.save(channel)
     except:
         self.write_response("", status=0)
         get_traceback()
Example #8
0
 def post(self, *args, **kwargs):
     try:
         data = json.loads(self.request.body)     #将json格式文件变成字典
         c = Channel(data['_id'], body=data)
         channel = c.get()
         yield self.db.Channel.insert(channel)
         self.write_response("")
     except Exception as e:
         print e
         self.write_response("", status=0, error="channel 添加失败")
         get_traceback()
Example #9
0
def update_channel(channel_payload: ChannelType, channel_id: str,
                   request: Request, response: Response, action: str):

    # Get logged in user
    user = auth_module.get_me(request=request)

    if user is None:
        response.status_code = status.HTTP_401_UNAUTHORIZED
        return util_module.generate_response_context(status=403,
                                                     error='access denied!',
                                                     data=None)

    if action == 'update':

        # Check ownership
        if not Channel.objects(pk=channel_id,
                               admins__contains=user.get("_id")):
            response.status_code = status.HTTP_403_FORBIDDEN
            return util_module.generate_response_context(
                status=403, error='access denied! now owner', data=None)

        # Update
        Channel.objects(_id=channel_id).update(
            set__name=channel_payload.name,
            set__summary=channel_payload.summary,
            set__tags=channel_payload.tags)

        # Retrun success response
        return {"msg": 'updated'}

    if action == 'follow':

        # Add new follower
        Channel.objects(pk=channel_id).update(
            add_to_set__followers=[user.get("_id")])

        return {"msg": "follow channel"}

    if action == 'unfollow':

        # Add new follower
        Channel.objects(pk=channel_id).update(pull__followers=user.get("_id"))

        return {"msg": "unfollow channel"}

    if action == 'delete':

        # Clean delete channel
        Channel.objects(_id=channel_id).update(set__status='deleted')

        # Return response
        return {"msg": "deleted!"}

    if action == 'add-admin':

        return {"case": "assign admin to channel"}

    # No action was provided
    return {"msg": "provide action query parameter!"}
Example #10
0
def ch_put(name):
    infos = request.json
    if infos is None or infos == '':
        return error_view(400, "missing parameter")

    if not Channel.exists(name):
        return error_view(404, f"channel {name} not found")

    ch = Channel.get(name)
    ch.update(infos)

    return ch_admin_put_view(ch)
 def setUp(self):
     self.full_intersection_rect = pygame.Rect(0, 0, 768, 768)
     self.inner_intersection_rect = pygame.Rect(280, 280, 210, 210)
     self.default_channel = Channel()
     self.default_car = random_car(
         name=1,
         initial_speed=20,
         full_intersection=self.full_intersection_rect,
         channel=self.default_channel,
         inner_intersection=self.inner_intersection_rect,
         lane=0,
         intention='s')
Example #12
0
def register():
    name = request.form.get('name')
    icon = request.form.get('icon')

    if not name:
        return to_error_json("name is required")
    elif Channel.query.filter(Channel.name == name).first() is not None:
        return to_error_json("name {} is already in use".format(name))

    channel = Channel(name=name, icon=icon)
    db.session.add(channel)
    db.session.commit()
    return jsonify(channel.dict(True))
 def test_second_at_charge_leave(self):
     channel = Channel()
     car1 = Car(name=1, lane=0, intention='l', channel=channel)
     do_round([car1], channel)
     car1.enter_intersection()
     for i in range(4):
         do_round([car1], channel)
     self.assertTrue(car1.is_supervisor())
     car2 = Car(name=2, lane=1, intention='l', channel=channel)
     do_round([car1, car2], channel)
     car2.enter_intersection()
     car3 = Car(name=3, lane=2, intention='s', channel=channel)
     do_round([car1, car2, car3], channel)
     car3.enter_intersection()
     car4 = Car(name=4, lane=2, intention='r', channel=channel)
     do_round([car1, car2, car3, car4], channel)
     car4.enter_intersection()
     # follow lists:
     # 1: []
     # 2: [1]
     # 3: [2]
     # 4: [3]
     channel.do_round()
     for car in [car1, car2, car3, car4]:
         self.assertEqual([1, 2], [car.get_supervisor_car(), car.get_second_at_charge()])
     # Before car 2 leaves
     self.assertEqual([], list(car1.get_following_cars().keys()))
     self.assertEqual([1], list(car2.get_following_cars().keys()))
     self.assertEqual([2], list(car3.get_following_cars().keys()))
     self.assertEqual([3], list(car4.get_following_cars().keys()))
     for car in [car1, car2, car3, car4]:
         self.assertEqual({4}, car.get_leaf_cars())
     do_round([car1, car2, car3, car4], channel)
     car2.leave_inner_intersection()
     do_round([car1, car2, car3, car4], channel)
     for car in [car1, car3, car4]:
         self.assertEqual([1, 3], [car.get_supervisor_car(), car.get_second_at_charge()])
     self.assertEqual([1, None], [car2.get_supervisor_car(), car2.get_second_at_charge()])
     self.assertTrue(car1.is_supervisor())
     self.assertTrue(car3.is_second_at_charge())
     self.assertFalse(car4.is_supervisor())
     self.assertFalse(car4.is_second_at_charge())
     for car in [car1, car2, car3, car4]:
         self.assertTrue(2 not in car.get_graph())
         for node in car.get_graph().values():
             self.assertTrue(2 not in node.get_follow_list())
     # After
     self.assertEqual([], list(car1.get_following_cars().keys()))
     self.assertEqual([1], list(car2.get_following_cars().keys()))
     self.assertEqual([], list(car3.get_following_cars().keys()))
     self.assertEqual([3], list(car4.get_following_cars().keys()))
Example #14
0
def ch_delete(name):
    if name == Channel.DEFAULT:
        return error_view(403, f"cannot modify default channel")

    if not Channel.exists(name):
        return error_view(404, f"channel {name} not found")

    ch = Channel.get(name)
    user_channel_list = UserChannel.list_from_channel(ch.name)
    for user_ch in user_channel_list:
        user_ch.delete()

    ch.delete()

    return ch_admin_delete_view(ch)
def simulate_stop_before_crash(first_car_speed=10.0,
                               first_lane=0,
                               first_intention='s',
                               iterations=1000,
                               collision_x=335,
                               collision_y=345):
    screen_width = 768
    screen, background, intersection_background, font = init_graphic_environment(
        screen_width, 768)
    channel = Channel()
    first_car = random_car(name=1,
                           initial_speed=first_car_speed,
                           acceleration_rate=5,
                           full_intersection=full_intersection_rect,
                           channel=channel,
                           inner_intersection=inner_intersection_rect,
                           lane=first_lane,
                           intention=first_intention,
                           create_sensor_flag=True)
    simulation_car = SimulationCar(first_car)
    ticks = simulation_car.get_ticks_to_goal(collision_x, collision_y)
    print(ticks)
    for i in range(iterations):
        screen.blit(background, (0, 0))
        screen.blit(intersection_background, (0, 0))
        screen.blit(simulation_car.rotated_image, simulation_car.screen_car)
        pygame.display.update(screen.get_rect())
        simulation_car.update()
        if simulation_car.collision_with_point(collision_x, collision_y):
            print('Collision with point: ' + str(i))
        if i > 140:
            print(simulation_car.get_ticks_to_goal(collision_x, collision_y))
            print(simulation_car.collision_with_point(collision_x,
                                                      collision_y))
    pygame.display.quit()
Example #16
0
def user_channel_post(channel_name, username):
    new_user_channel = None
    try:
        contact = request.args.get('contact')
        if contact is None or contact == '':
            return error_view(400, "invalid contact")

        channel = Channel.get(channel_name)
        user = User.get(username)

        if UserChannel.exists(user.username, channel.name):
            return error_view(500, "this channel is already linked")

        new_user_channel = UserChannel.new(user.username, channel.name, contact)
        new_user_channel.insert()

        template = CHANNEL_VERIFY_TEMPLATE
        template.set_format(token=new_user_channel.token, channel=channel.name)
        send(contact, channel, template)

        return user_ch_created_view(new_user_channel)

    except (MailSendingError, TelegramSendingError):
        if new_user_channel is not None:
            new_user_channel.delete()

        return error_view(500, "error sending token to this contact")
 def test_info_messages(self):
     channel = Channel()
     sup_car = Car(name=1, lane=0, intention='s',
                   channel=channel, pos_x=1, pos_y=1)
     second_car = Car(name=2, lane=1, intention='s',
                      channel=channel, pos_x=2, pos_y=2)
     normal_car = Car(name=3, lane=3, intention='l',
                      channel=channel, pos_x=3, pos_y=3)
     # Car 1 enters
     do_round([sup_car], channel)
     sup_car.enter_intersection()
     self.assertTrue(1 in sup_car.get_leaf_cars())
     # Car 2 enters and Car 1 becomes supervisor, Car 1 sends info message before Car 2 enters
     do_round([sup_car, second_car], channel)
     second_car.enter_intersection()
     # Car 3 enters and Car2 receives WelcomeMessage and Second At Charge, Car 1 and Car 2 send Info
     # before Car 3 enters
     do_round([sup_car, second_car, normal_car], channel)
     # Check leaf cars update
     self.assertEqual({2}, sup_car.get_leaf_cars())
     self.assertEqual({2}, second_car.get_leaf_cars())
     # Check info message from sup_car and follow lists
     self.assertEqual({}, sup_car.get_following_cars())
     self.assertEqual([1], list(second_car.get_following_cars().keys()))
     self.assertEqual(1, second_car.get_following_cars()[1]['pos_x'])
     normal_car.enter_intersection()
     # Car 3 receives Welcome Message
     do_round([sup_car, second_car, normal_car], channel)
     self.assertEqual({3}, sup_car.get_leaf_cars())
     self.assertEqual({3}, second_car.get_leaf_cars())
     self.assertEqual({3}, normal_car.get_leaf_cars())
     self.assertEqual([1], list(second_car.get_following_cars().keys()))
     self.assertEqual([2], list(normal_car.get_following_cars().keys()))
     self.assertTrue(2, normal_car.get_following_cars()[2]['pos_x'])
Example #18
0
def check_channel(id, json=True, attempts=MAX_DEFAULT_ATTEMPTS):
    if not check_request_key(request): return 'Unauthorized', 401
    logger.debug("Checking channel: %s", id)
    # get the channel info
    channel = db.get_channel(int(id))
    # get the attempts parameter
    if not (request.json is None) and 'attempts' in request.json:
        attempts = request.json['attempts']
    logger.debug("Attempts: %s", attempts)
    attempts = int(attempts)
    # check the channel url
    logger.debug("Checking channel url: %s", channel['url'])
    result = m3uchecker.check_link(channel['url'], attempts)
    logger.debug("Result: %s", result)
    print(result)

    # save the result
    last_check = int(time.mktime(datetime.datetime.now().timetuple())) * 1000
    newChannel = Channel(position=channel['position'],
                         name=channel['name'],
                         metadata=channel.get('metadata', ''),
                         url=channel['url'],
                         checked=result,
                         last_check=last_check)
    db.update_channel(int(id), newChannel)

    if json:
        return jsonify({'checked': result, 'last_check': last_check})
    else:
        return result
 def test_destination_lane(self):
     channel = Channel()
     car1 = random_car(name=1,
                       initial_speed=20,
                       full_intersection=self.full_intersection_rect,
                       channel=channel,
                       inner_intersection=self.inner_intersection_rect,
                       lane=0,
                       intention='s')
     car2 = random_car(name=1,
                       initial_speed=20,
                       full_intersection=self.full_intersection_rect,
                       channel=channel,
                       inner_intersection=self.inner_intersection_rect,
                       lane=0,
                       intention='l')
     car3 = random_car(name=1,
                       initial_speed=20,
                       full_intersection=self.full_intersection_rect,
                       channel=channel,
                       inner_intersection=self.inner_intersection_rect,
                       lane=0,
                       intention='r')
     self.assertEqual(2, car1.destination_lane())
     self.assertEqual(3, car2.destination_lane())
     self.assertEqual(1, car3.destination_lane())
Example #20
0
 def test_list(self):
     Channel._list = MagicMock(
         return_value=[channel_email, channel_telegram])
     ch_list = Channel.list()
     self.assertEqual(len(ch_list), 2)
     self.assertEqual(ch_list[0].type, channel_email['type'])
     self.assertEqual(ch_list[1].type, channel_telegram['type'])
Example #21
0
 def test_get_telegram(self):
     name = channel_telegram['_key']
     Channel._get = MagicMock(return_value=channel_telegram)
     ch = Channel.get(name)
     self.assertEqual(ch.name, name)
     self.assertEqual(ch.infos.bot_token,
                      channel_telegram['infos']['bot_token'])
Example #22
0
 def play_channel(self, channel, play_index):
     log.debug('Playing channel: {0}'.format(channel.id))
     self.channel = Channel(channel.to_dict())
     self.channel.play_index = play_index
     url = self.channel.streamurls[play_index]
     log.debug('Selected url: {0}'.format(url))
     url_components = urlparse(url)
     app = QApplication.instance()
     if app.protocol_plugins.get(url_components.scheme, None):
         protocol_class = app.protocol_plugins[url_components.scheme]
         log.debug('Using {0} to process {1}'.format(protocol_class.name, url))
         try:
             self.protocol = protocol_class(self)
             self.protocol.protocol_ready.connect(self.protocol_ready)
             self.protocol.protocol_error.connect(self.protocol_error)
             self.protocol.load_url(url, channel.args(url))
         except ProtocolException as e:
             log.error(e.message)
             QMessageBox.critical(
                 self,
                 self.tr("Error playing channel"),
                 self.tr("Protocol crashed with error: {0}").format(e.message)
             )
             self.playback_error.emit(self.channel)
             self.channel = None
     else:
         log.error('No suitable protocol found for {0}'.format(url))
Example #23
0
def get_users_in_voice_channels(voice_channels):
    active_users = []
    for voice_channel in voice_channels:
        if not(Channel.exist(voice_channel.id)):
            for user in voice_channel.members:
                active_users.append(user)
    return active_users
Example #24
0
def alert_all_process(dn_list):
    """
    Sent the DN list to all registered Users
    :param dn_list: the DN list to send
    :return:
    """

    data = []
    for dn in dn_list:
        data.append([
            dn['domain_name'],
            dn['last_ip_address'],
            dn['current_ip_address'],
        ])

    columns = ['Domain name', 'Last IP address', 'Current IP address']
    df = pandas.DataFrame(data=data, columns=columns)

    # fixme
    template = ALERT_LIST_TEMPLATE
    template.set_format(url_alerts="/alerts",
                        url_channels="/channels",
                        table=df.to_markdown(index=False))

    # fixme
    # users = User.list()
    users = [User.get("user")]
    for u in users:
        if u.role != UserRole.USER.value and u.role != UserRole.ADMIN.value:
            continue

        user_channels = UserChannel.list_from_username(u.username)
        for u_ch in user_channels:
            channel = Channel.get(u_ch.channel_name)
            send(u_ch.contact, channel, template)
Example #25
0
def sms_factory(faker):
    return {
        'phone': faker.phone_number(),
        'text': faker.text(),
        'channel_id': Channel.first().id,
        'direction': False
    }
 def test_enter_intersection(self):
     channel = Channel()
     car = random_car(name=1,
                      initial_speed=20,
                      full_intersection=self.full_intersection_rect,
                      channel=channel,
                      inner_intersection=self.inner_intersection_rect,
                      lane=0,
                      intention='s')
     self.assertFalse(car.get_inside_full_rectangle())
     self.assertFalse(car.inside_full_intersection())
     self.assertTrue(car not in channel.get_cars())
     for _ in range(25):
         do_round([car], channel)
     self.assertTrue(car in channel.get_cars())
     self.assertTrue(car.get_inside_full_rectangle())
     self.assertTrue(car.inside_full_intersection())
Example #27
0
def init_db():
    with app.app_context():
        db.create_all()
        default_channel = {
            'name': '大厅',
            'description': '没有描述',
        }
        Channel(default_channel).save()
Example #28
0
async def get_channel_records(skip: int, take: int):
    collection = get_channel_collection()

    results = []

    async for channel in collection.find({}).skip(skip).limit(take):
        results.append(Channel(**channel))
    return results
Example #29
0
def delete_channels():
    name = request.form.get('name')
    admin_key = request.form.get('admin_key')

    if name is None:
        return to_error_json("name is missing")
    elif admin_key is None:
        return to_error_json("admin key is missing")

    channel = Channel.query.filter(Channel.name == name,
                                   Channel.admin_key == admin_key).first()

    if channel is not None:
        Channel.delete(channel)
        return to_success_json("Channel Deleted")
    else:
        return to_error_json("Channel or admin key mismatch")
Example #30
0
    def generate_channels(self):
        num_channels = randint(100, 200)
        for i in range(0, num_channels):
            self.channels.append(Channel(i, name="Channel %d" % i, description="Description of channel %d" % i))

        if CREATE_MY_CHANNEL:
            # Pick one of these channels as your channel
            self.my_channel = randint(0, len(self.channels) - 1)
Example #31
0
def chats(name, n):
    page_size = 10
    chats = Channel.findByName(name).chats.offset(n *
                                                  page_size).limit(page_size)
    for i in chats:
        print(i.content)
    next_page_url = '/channel/{}/chats/{}'.format(name, n + 1)
    return render_template('message.html', chats=chats, url=next_page_url)
Example #32
0
    def from_user(self, receivers=None, text=None, *_):
        if receivers is None:
            return ERR_NORECIPIENT(self.command, self.actor)
        if text is None:
            return ERR_NOTEXTTOSEND(self.actor)
        resp = []
        # TODO: check for ERR_TOOMANYTARGETS
        for receiver in receivers.split(','):
            if Channel.exists(receiver):
                channel_log = '%s/%s.log' % (config.get(
                    'server', 'channel_log_dir'), receiver.replace('#', ''))
                # if not PrivmsgCommand.channel_log_files.get(channel_log):
                #     PrivmsgCommand.channel_log_files[channel_log] = open(channel_log,'a')
                # PrivmsgCommand.channel_log_files[channel_log].write("%s::%s::%s::%s\n" % (
                #         time.time(), time.strftime('%Y-%m-%d %H:%I:%S'), self.user.nickname, text
                # ))
                # PrivmsgCommand.channel_log_files[channel_log].flush()
                with open(channel_log, 'a') as f:
                    f.write("%s::%s::%s::%s\n" %
                            (time.time(), time.strftime('%Y-%m-%d %H:%I:%S'),
                             self.user.nickname, text))
                    f.flush()

                users = [
                    user for user in Channel.get(receiver).users
                    if user is not self.user
                ]
                resp.append(
                    M(ActorCollection(users),
                      self.command,
                      str(receiver),
                      text,
                      prefix=str(self.user)))
            elif User.exists(receiver):
                resp.append(
                    M(Actor.by_user(User.get(receiver)),
                      self.command,
                      str(receiver),
                      text,
                      prefix=str(self.user)))
            # TODO: Implement wildcards
            # TODO: check for ERR_WILDTOPLEVEL, RPL_AWAY, ERR_NOTOPLEVEL
            else:
                resp.append(ERR_NOSUCHNICK(receiver, self.actor))
        return resp
 def setUp(self):
     self.intention_list = ['l', 's', 'r']
     self.ticks = 15
     self.channel = Channel()
     self.test_case = {1: {'lane': 0, 'intention': 's', 'tick': 0},
                       2: {'lane': 0, 'intention': 'l', 'tick': 1},
                       3: {'lane': 3, 'intention': 'l', 'tick': 3},
                       4: {'lane': 1, 'intention': 'r', 'tick': 5},
                       5: {'lane': 2, 'intention': 's', 'tick': 7}}
Example #34
0
def text(message):
    """Sent by a client when the user entered a new message.
    The message is sent to all people in the room."""
    # room = message.get('channel')
    message['type'] = 'message'
    message['username'] = current_user().username
    message['avatar'] = current_user().avatar
    room = message.get('channel', Channel.default_channel().name)
    print(message)
    # Channel.findByName(room).save_chat(Chat(message))
    chat = {
        'content': message.get('content', ''),
        'user': current_user(),
        'channel': Channel.findByName(room),
    }
    Chat(chat).save()
    join_room(room)
    emit('message', message, broadcast=True)
Example #35
0
 def get(self):
        
     all_channels = Channel.query_all()
     
     for channel in all_channels:
         
         channel_id = channel.channel_id
         logging.info('Queing task a channel update task from updateAllChannels - {}'.format(channel_id))
         handler = EnqueueTaskHandler()
         task_response = handler.post(channel_id)
Example #36
0
 def from_user(self, channel_name, topic=None, *_):
     # TODO: ERR_NOCHANMODES, ERR_CHANOPRIVSNEEDED
     if not Channel.exists(channel_name):
         return ERR_NOSUCHCHANNEL(channel_name, self.actor)
     channel = Channel.get(channel_name)
     if self.user not in channel.users:
         return ERR_NOTONCHANNEL(channel_name, self.actor)
     if topic is None:
         if channel.topic is None:
             return RPL_NOTOPIC(self.actor, channel)
         else:
             return RPL_TOPIC(self.actor, channel)
     elif topic == '':
         channel.topic = None
     else:
         channel.topic = topic
     # Forward message to others on the channel
     self.message.target = ActorCollection(channel.users)
     return self.message
Example #37
0
    def from_user(self, channels, msg='leaving', *_):
        channels = channels.split(',')

        ret = []

        for channel_name in channels:
            if not Channel.exists(channel_name):
                ret.append(ERR_NOSUCHCHANNEL(channel_name, self.actor))
                continue
            channel = Channel.get(channel_name)
            if self.user not in channel.users:
                ret.append(ERR_NOTONCHANNEL(channel_name, self.actor))
                continue
            ret.append(M(ActorCollection(channel.users),
                         'PART', str(channel), msg,
                         prefix=str(self.user)
            ))
            self.user.part(channel)

        return ret
Example #38
0
    def from_user(self, receivers=None, text=None, *_):
        if receivers is None:
            return ERR_NORECIPIENT(self.command, self.actor)
        if text is None:
            return ERR_NOTEXTTOSEND(self.actor)
        resp = []
        # TODO: check for ERR_TOOMANYTARGETS
        for receiver in receivers.split(','):
            if Channel.exists(receiver):
                channel_log = '%s/%s.log' % ( config.get('server', 'channel_log_dir'), receiver.replace('#',''))
                # if not PrivmsgCommand.channel_log_files.get(channel_log):
                #     PrivmsgCommand.channel_log_files[channel_log] = open(channel_log,'a')
                # PrivmsgCommand.channel_log_files[channel_log].write("%s::%s::%s::%s\n" % (
                #         time.time(), time.strftime('%Y-%m-%d %H:%I:%S'), self.user.nickname, text
                # ))
                # PrivmsgCommand.channel_log_files[channel_log].flush()
                with open(channel_log,'a') as f:
                    f.write("%s::%s::%s::%s\n" % (
                        time.time(), time.strftime('%Y-%m-%d %H:%I:%S'), self.user.nickname, text
                    ))
                    f.flush()

                users = [user for user in Channel.get(receiver).users if user is not self.user]
                resp.append(M(
                    ActorCollection(users),
                    self.command, str(receiver), text,
                    prefix=str(self.user)
                ))
            elif User.exists(receiver):
                resp.append(M(
                    Actor.by_user(User.get(receiver)),
                    self.command, str(receiver), text,
                    prefix=str(self.user)
                ))
            # TODO: Implement wildcards
            # TODO: check for ERR_WILDTOPLEVEL, RPL_AWAY, ERR_NOTOPLEVEL
            else:
                resp.append(ERR_NOSUCHNICK(receiver, self.actor))
        return resp
Example #39
0
def add(channel_id):
    
    # Set last_update_date to now
    last_update_date = datetime.datetime.now()
    
    # Build channel object
    channel = Channel()
    channel.key = ndb.Key(Channel, channel_id)
    
    channel.channel_id = channel_id
    channel.channel_name = 'Channel Name'
    channel.channel_link = 'https://www.youtube.com/'
    channel.last_update_date = last_update_date   
    videos = []
    channel.videos = str(videos)
    
    # Put in db
    channel.put()
    
    logging.info('Channel added! - {}'.format(channel_id))
Example #40
0
 def join_or_error(self, channel_name):
     if Channel.is_valid_name(channel_name):
         return self.join(channel_name)
     else:
         return self.no_such_channel_message(channel_name)