예제 #1
0
 def on_join(self, channel_name):
     if not channel_name.startswith('#'):
         emit('error', {'message': 'Channel name should start with a #'})
         return
     channel = Channel.get(channel_name)
     if current_user.is_authenticated:
         if channel is None:
             channel = Channel(channel_name)
             db.session.add(channel)
         if channel not in current_user.channels:
             current_user.channels.append(channel)
             join_room(channel_name)
         current_user.last_channel = channel
         db.session.commit()
         data = {
             'channel': {
                 'name': channel_name
             },
             'user': current_user.name
         }
     else:
         if channel is None:
             data = {'channel': None}
         else:
             join_room(channel_name)
             data = {'channel': {'name': channel_name}}
     emit('channel-joined', data, room=channel_name, include_self=True)
예제 #2
0
 def on_message(self, channel_name, message, message_hash=None):
     channel = Channel.get(channel_name)
     if channel is None:
         emit('error', {
             'message':
             'You have to join a channel before writing something.'
         })
         return
     emit('message-sent')
     if message_hash is None:
         message_hash = calculate_hash(current_user.id, message)
         data = {
             'channel': channel_name,
             'message': message,
             'user': current_user.name,
             'hash': message_hash
         }
         emit('message', data, room=channel_name, include_self=True)
     else:
         if verify_hash(current_user.id, message_hash):
             data = {'hash': message_hash, 'message': message}
             emit('message-edited',
                  data,
                  room=channel_name,
                  include_self=True)
         else:
             emit('error', {'message': 'Hash verification failed.'})
예제 #3
0
def get_channel():
    from models import Channel

    try:
        return Channel.get(Channel.username == SELF_CHANNEL_USERNAME)
    except Channel.DoesNotExist:
        return False
예제 #4
0
    def execute(self):
        channel = Channel.get(self.request.channel_id)
        pattern = Pattern.get(channel.current_mode)
        pattern_data = pattern.get_pattern_data(len(channel.members))

        self.response.update({
            "pattern": pattern_data,
        })
예제 #5
0
    def execute(self):
        channel = Channel.get(self.request.channel_id)
        pattern = self.request.pattern

        pattern = get_pattern_data(pattern, len(channel.members))

        package = SyncPackage(channel=channel, pattern=pattern)
        channel.push_to_all(package.data, member_index=True)
예제 #6
0
    def execute(self):
        channel = Channel.get(self.request.channel_id)
        if channel.current_mode != self.request.mode_id:
            channel.current_mode = self.request.mode_id
            pattern = Pattern.get(channel.current_mode)
            pattern_data = pattern.get_pattern_data(len(channel.members))

            package = SyncPackage(channel=channel, pattern=pattern_data)
            channel.push_to_all(package.data, member_index=True)
예제 #7
0
 def execute(self):
     logger.debug("QuitChannel begin")
     user = User.get(self.request.client_id)
     if not user.channel:
         raise UserIsNotInAnyChannel
     channel = Channel.get(user.channel.channel_id)
     channel.quit(user.client_id)
     user.channel = None
     User.update(user)
     logger.debug("QuitChannel end")
예제 #8
0
def updateInfo(key, gogo_id):
    channel = Channel.get(key)
    programs = list(Program.gql("WHERE channel = :channel", channel = channel))
    for p in programs:
        p.delete()
    for day in range(1,8): #iterate week
        logging.info('updating info of ' + channel.name)
        try:
            updatePrograms(channel, day, gogo_id)
        except Exception, e:
            logging.error('error happened, while updating: ' + e.message)
예제 #9
0
    def execute(self):
        channel = Channel.get(self.request.channel_id)
        channel.now_playing_song_id = self.request.song_id
        channel.song_play_time = self.request.song_play_time
        channel.server_start_time = (time.time() * 1000)
        channel.playing = True
        Channel.update(channel)

        package = SyncPackage(channel=channel)
        channel.push_to_all(package.data)
        self.response.update(package.data)
        self.response.update({'cmd': self.cmd_id})
예제 #10
0
 def on_part(self, channel_name):
     channel = Channel.get(channel_name)
     if channel not in current_user.channels:
         emit('error', {
             'message': 'You cannot leave a channel that you didn\'t join.'
         })
         return
     current_user.channels.remove(channel)
     db.session.commit()
     data = {'channel': {'name': channel_name}, 'user': current_user.name}
     emit('channel-parted', data, room=channel_name, include_self=True)
     leave_room(channel_name)
예제 #11
0
 def step(self, *args, **kwargs):
     try:
         is_approved = True
         is_sent = False
         is_deleted = False
         self.channel = Channel.get(Channel.id == self.channel_id)
         if self.channel.is_subscribed is False:
             return None
         for response in list(Response.select().where(
             (Response.is_approved == is_approved)
                 & (Response.is_sent == is_sent)
                 & (Response.is_deleted == is_deleted)
                 & (Response.to_channel == self.channel))):
             response_text = response.text
             response_text = self.__format_response_text(
                 response.to_user, response_text)
             if self.profanity_filter_on is True:
                 response_text = lib.utilities.scrub_profanity(
                     response_text)
             query_params = {
                 'channel': self.channel.slack_id,
                 'text': response_text,
                 'parse': 'full',
                 'linknames': 1,
                 'unfurl_links': 'true',
                 'unfult_media': 'true',
                 'username': self.bot_slack_name
             }
             if hasattr(slackotron_settings, 'BOT_ICON_URL'):
                 query_params['icon_url'] = self.bot_icon_url
             if hasattr(slackotron_settings, 'BOT_ICON_EMOJI'):
                 query_params['icon_emoji'] = self.bot_icon_emoji
             g = self.locker.make_lock_generator('response')
             try:
                 g.next()
                 response_json = self.slack.send_message(query_params)
                 if response_json is not None:
                     response.text = response_text
                     response.is_sent = True
                     response.slack_timestamp = response_json['timestamp']
                     response.save()
                     self.info(response)
             except Exception as e:
                 self.error(e.__class__.__name__)
                 self.error(e)
             finally:
                 g.next()
     except Exception as e:
         self.error(e.__class__.__name__)
         self.error(e)
         traceback.print_exc()
예제 #12
0
 def add_bot(self, channel, name):
     channel = channel.lower()
     name = name.lower()
     try:
         Bot.get(Bot.name == name)
     except peewee.DoesNotExist:
         pass  # this seems really unpythonic somehow
     else:
         raise KeyError('Bot already exists')
     try:
         chan_o = Channel.get(Channel.name == channel)
     except peewee.DoesNotExist:
         chan_o = Channel.create(name=channel)
     Bot.create(name=name,
                channel=chan_o)
예제 #13
0
def get_channel(channel_id: str):

    try:
        channel = Channel.get(Channel.channel_id == channel_id)
        channel_ = model_to_dict(channel)
        videos = Video.select().where(Video.channel == channel)
        videos_ = []
        for v in videos:
            videos_.append(model_to_dict(v))
        channel_['videos'] = videos_
        channel_['status'] = 'success'
        return channel_
    except BaseException as e:
        print(e)
        return {
            'status': 'not found',
        }
예제 #14
0
 def _run(self):
     SlackChannelPublisher.lock.acquire()
     try:
         is_approved = True
         is_sent = False
         is_deleted = False
         with Channel.database().transaction():
             self.channel = Channel.get(Channel.id == self.channel.get_id())
             for response in list(Response.select().where(
                 (Response.is_approved == is_approved)
                     & (Response.is_sent == is_sent)
                     & (Response.is_deleted == is_deleted)
                     & (Response.to_channel == self.channel))):
                 response_text = response.text
                 response_text = self.__format_response_text(
                     response.to_user, response_text)
                 if self.channel.is_secure is True:
                     response_text = utilities.scrub_profanity(
                         response_text)
                 query_params = {
                     'channel': self.channel.slack_id,
                     'text': response_text,
                     'parse': 'full',
                     'linknames': 1,
                     'unfurl_links': 'true',
                     'unfult_media': 'true',
                     'username': self.bot_name
                 }
                 if hasattr(slackotron_settings, 'BOT_ICON_URL'):
                     query_params['icon_url'] = self.bot_icon_url
                 if hasattr(slackotron_settings, 'BOT_ICON_EMOJI'):
                     query_params['icon_emoji'] = self.bot_icon_emoji
                 response_json = self.slack.send_message(query_params)
                 if response_json is not None:
                     response.text = response_text
                     response.is_sent = True
                     response.slack_timestamp = response_json['timestamp']
                     response.save()
                     self.info('Outgoing response:')
                     self.info(response)
     except Exception as e:
         self.error(e.__class__.__name__)
         self.error(e)
         traceback.print_exc()
     finally:
         SlackChannelPublisher.lock.release()
예제 #15
0
 def _initialize_channels_and_users(self):
   self.info('Loading channels and users...')
   channel_id_to_name_map, channel_name_to_id_map = \
       self.slack.channel_id_name_maps()
   with self.database_manager.transaction():
     for k, v in channel_id_to_name_map.items():
       is_direct = True if k.startswith('D0') else False
       try:
         channel = Channel.get(
             Channel.slack_id == k
         )
         channel.slack_name = v
         channel.is_direct = is_direct
         channel.save()
       except Channel.DoesNotExist:
         channel = Channel.create(
             slack_name=v,
             slack_id=k,
             is_direct=is_direct
         )
       except Exception as e:
         self.error(e)
       channel_members = self.slack.channel_members(channel.slack_name)
       for channel_member in channel_members:
         is_slackbot = True if channel_member[1] == 'USLACKBOT' else False
         try:
           user = User.get(
               User.slack_name == channel_member[1],
               User.slack_id == channel_member[0],
               User.is_slackbot == is_slackbot
           )
         except User.DoesNotExist:
           user = User.create(
               slack_name=channel_member[1],
               slack_id=channel_member[0],
               is_slackbot=is_slackbot
           )
         except Exception as e:
           self.error(e)
         try:
           ChannelUserRelationship.create(
               channel=channel,
               user=user
           )
         except:
           pass
예제 #16
0
 def _run_once(self, *_, **kwargs):
   try:
     rmq_message = kwargs.get('rmq_message', '{}') or '{}'
     rmq_message = json.loads(rmq_message)
     if len(rmq_message) == 0:
       return None
     channel = Channel.get(
         Channel.id == rmq_message['channel_id']  # noqa pylint:disable=no-member
     )
     if channel.is_subscribed is False:
       return None
     user = User.get(
         User.id == rmq_message['user_id']  # noqa pylint:disable=no-member
     )
     message = Message.get(
         Message.id == rmq_message['message_id']  # noqa pylint:disable=no-member
     )
     plugin_name = rmq_message['plugin_name']
     plugin_response = rmq_message['plugin_response']
     if len(plugin_name) == 0:
       return None
     if len(plugin_response) == 0:
       return None
     is_approved = True if channel.is_secure is False \
         else False
     response = Response(
         text=plugin_response,
         from_plugin=plugin_name,
         in_response_to=message,
         to_channel=channel,
         to_user=user,
         is_approved=is_approved,
         is_sent=False,
     )
     lock_generator = self.locker.make_lock_generator('response')
     try:
       lock_generator.next()
       response.save()
     except Exception as error:
       self.error(error)
     finally:
       lock_generator.next()
   except Exception as error:
     self.error(error)
     return None
예제 #17
0
 def _process_rmq_message(self, rmq_message):
   try:
     rmq_message = json.loads(rmq_message)
     channel = Channel.get(
         Channel.id == rmq_message['channel_id']
     )
     user = User.get(
         User.id == rmq_message['user_id']
     )
     message = Message.get(
         Message.id == rmq_message['message_id']
     )
     plugin_name = rmq_message['plugin_name']
     plugin_response = rmq_message['plugin_response']
     return channel, user, message, plugin_name, plugin_response
   except Exception as e:
     self.error(e)
     return None, None, None, None, None
예제 #18
0
    def execute(self):
        user = User.get(self.request.client_id)

        if user.channel:
            if user.channel.channel_id == long(self.request.channel_id):
                logger.debug("User already in this channel")
                self.construct_response(user.channel)
                return
            logger.debug("User in another channel, please quit first")
            raise PleaseQuitChannel()

        channel = Channel.get(self.request.channel_id)
        logger.debug("Got the channel")
        channel.members[user.client_id] = user
        logger.debug("Update the members of channel.")
        user.channel = channel
        Channel.update(channel)
        self.construct_response(user.channel)
예제 #19
0
 def _initialize_channels_and_users(self):
     self.info('Loading channels and users...')
     self.known_slack_channel_ids = []
     self.known_slack_user_ids = []
     with self.database_manager.transaction():
         for key, value in self.channel_id_to_name_map.items():
             is_direct = True if key.lower().startswith('d0') else False
             try:
                 channel = Channel.get(Channel.slack_id == key)
                 channel.slack_name = value
                 channel.is_direct = is_direct
                 channel.save()
             except Channel.DoesNotExist:
                 is_subscribed = True if value.lower(
                 ) == 'uslackbot' else False
                 channel = Channel.create(slack_name=value,
                                          slack_id=key,
                                          is_direct=is_direct,
                                          is_subscribed=is_subscribed)
             except Exception as error:
                 self.error(error)
                 continue
             self.known_slack_channel_ids.append(channel.slack_id)
             self.info(channel)
             channel_members = self.slack.channel_members(
                 channel.slack_name)
             for channel_member in channel_members:
                 try:
                     user = User.get(User.slack_id == channel_member[0])
                     user.slack_name = channel_member[1]
                     user.save()
                 except User.DoesNotExist:
                     user = User.create(slack_name=channel_member[1],
                                        slack_id=channel_member[0])
                 except Exception as error:
                     self.error(error)
                 try:
                     ChannelUserRelationship.create(channel=channel,
                                                    user=user)
                 except Exception:
                     pass
                 self.known_slack_user_ids.append(user.slack_id)
                 self.info(user)
예제 #20
0
 def get(self, server, channel):
     key = db.Key.from_path(Channel.kind(), '%s/%s' % (unquote(channel), server))
     channel = Channel.get(key)
     date = self.request.GET.get('date')
     if date:
         start_date = datetime.strptime(date, '%Y-%m-%d').date()
     else:
         start_date = datetime.utcnow().date()
     end_date = start_date + timedelta(days=1)
     messages = Message.all().filter('channel =', channel) \
                 .filter('timestamp >= ', start_date) \
                 .filter('timestamp < ', end_date) \
                 .order('timestamp')
     # date based pagination
     next_day = start_date + timedelta(days=1)
     if next_day > datetime.utcnow().date():
         next_day = None
     previous_day = end_date - timedelta(days=2)
     self.response.out.write(render('templates/channel.html', locals()))
     
예제 #21
0
  def step(self, *args, **kwargs):
    '''
      step(*args, **kwargs)
    '''

    try:
      self.channel = Channel.get(
          Channel.id == self.channel_id
      )
      if self.channel.is_subscribed is False:
        return []
      current_time = time.time()
      rmq_messages = []
      if (current_time - self.checked_slack_at) > self.check_slack_interval:
        self.checked_slack_at = current_time
        slack_raw_messages = self.slack.channel_messages_since(
          self.channel.slack_id,
          2
        )
        for slack_raw_message in slack_raw_messages:
          user, message, new = self._process_slack_raw_message(
              slack_raw_message
          )
          if not new:
            continue
          self.info(message)
          rmq_messages.append(
              {
                  'channel_id': self.channel.get_id(),
                  'user_id': user.get_id(),
                  'message_id': message.get_id()
              }
          )
      return rmq_messages
    except Exception as error:
      self.error(error)
      traceback.print_exc()
      return []
예제 #22
0
 def __init__(self, **kwargs):
     threading.Thread.__init__(self)
     self.stop_thread = False
     self.slack = slack_service.Slack()
     self.channel_id = kwargs['channel_id']
     self.channel = Channel.get(Channel.id == self.channel_id)
예제 #23
0
 def execute(self):
     channel = Channel.get(self.request.channel_id)
     self.response.update({
         "member_list": channel.get_members(),
     })
예제 #24
0
import channelInfo
from models import Channel

for id, channel in channelInfo.channels.items():
    print("update", channel.stationname)

    db_chan = Channel.get(shortname=channel.shortname)
    db_chan.stationname = channel.stationname
    db_chan.has_data = channel.has_data
    db_chan.primary_color = channel.primary_color
    db_chan.secondary_color = channel.secondary_color
    db_chan.save()
예제 #25
0
 def on_channel_change(self, channel_name):
     channel = Channel.get(channel_name)
     if channel is None:
         return
     current_user.last_channel = channel
     db.session.commit()