def _import(self, widget, data=None):
        """
        Get the categoey in which the channels will be imported.

        Convert JSON format channels to "Channel" objects.

        Add the channels to category.

        Get the channel data which are to be displayed in IconView in main
        window.

        Properly scale the image thumbnail of the channel.
        Add the channels to the Iconview in the main window.

        Close the Import Dialog Box.
        """

        all_category = Channel_Store.ALL
        if self.imported_data is not None:
            for channel in self.imported_data:
                imported_channel = Channel(self.imported_data[channel])
                all_category.add(channel, imported_channel)
                (channel_name, image_url,
                 desc) = (channel, imported_channel.get_thumbnail_url(),
                          imported_channel.get_description())
                scaled_image = graphics_util.get_scaled_image(image_url, 180)
                self.app_window.icon_list_store.append(
                    [scaled_image, channel_name, desc])
        self.box.import_box.destroy()
    def _import(self,widget,data=None):

        """
        Get the categoey in which the channels will be imported.

        Convert JSON format channels to "Channel" objects.

        Add the channels to category.

        Get the channel data which are to be displayed in IconView in main
        window.

        Properly scale the image thumbnail of the channel.
        Add the channels to the Iconview in the main window.

        Close the Import Dialog Box.
        """

        all_category = Channel_Store.ALL
        if self.imported_data is not None:
            for channel in self.imported_data:
                imported_channel = Channel(self.imported_data[channel])
                all_category.add(channel,imported_channel)
                (channel_name,image_url,desc) = (channel
                                ,imported_channel.get_thumbnail_url()
                                ,imported_channel.get_description())
                scaled_image = graphics_util.get_scaled_image(image_url,180)
                self.app_window.icon_list_store.append([scaled_image,channel_name,desc])
        self.box.import_box.destroy()
示例#3
0
    def add_channel(self, new_channel: Channel) -> None:
        def id_change_handler(channel, old_id):
            channel_path = self._root_dir / (old_id + '.json')

            del self._channels[old_id]
            self._channels[channel.id] = channel

            os.remove(str(channel_path))

        def value_change_handler(channel):
            channel_path = self._root_dir / (channel.id + '.json')

            with channel_path.open('w') as f:
                f.write(json.dumps(channel.to_dict()))

        new_channel.id_change_handler = id_change_handler
        new_channel.value_change_handler = value_change_handler
        new_channel.redirect_event_handler = lambda channel, old_id: self._redirect_event_handler(
            channel, old_id)
        new_channel.count_event_handler = lambda channel: self._count_event_handler(
            channel)

        self._channels[new_channel.id] = new_channel

        value_change_handler(new_channel)  # save to file
 def show_monitor_channel(self):  #only for testing purpose
     """
     Show default channel in Channel Iconview when app starts.
     """
     monitor_data = channel_store.get_monitor_data()
     channel = Channel(monitor_data["monitor"])
     store = Channel_Store()
     store.get_default().add(channel.name, channel)
     (name, image_url, desc) = (channel.get_name(),
                                channel.get_thumbnail_url(),
                                channel.get_description())
     scaled_image = graphics_util.get_scaled_image(image_url, 180)
     for i in range(0, 1):
         self.app_window.icon_list_store.append([scaled_image, name, desc])
    def show_monitor_channel(self):#only for testing purpose

        """
        Show default channel in Channel Iconview when app starts.
        """
        monitor_data = channel_store.get_monitor_data()
        channel = Channel(monitor_data["monitor"])
        store = Channel_Store()
        store.get_default().add(channel.name,channel)
        (name,image_url,desc) = (channel.get_name()
                                ,channel.get_thumbnail_url()
                                ,channel.get_description())
        scaled_image = graphics_util.get_scaled_image(image_url,180)
        for i in range(0,1):
            self.app_window.icon_list_store.append([scaled_image,name,desc])
示例#6
0
 def create_random_channel(self):
     # TO IMPLEMENT VIA REST
     self.create(
         Channel(name='Channel' + str(randint(0, 9999999)),
                 service_id=str(randint(0, 65535)),
                 epg_name='Epg_name_' + str(randint(0, 9999999)),
                 offset=str(randint(-23, 23)),
                 provider='Provider_' + str(randint(0, 9999999))))
示例#7
0
 def get_channels(self):
     if self.channel_cache is None:
         wd = self.app.wd
         self.open_channels_page()
         self.channel_cache = []
         for element in wd.find_elements_by_xpath(
                 "//*[@id='content']/div[2]/table/tbody/tr[.]/td[2]/a"):
             text = element.text
             id = element.get_attribute("href").split('/')[-2]
             # print "id =", id
             self.channel_cache.append(Channel(name=text, id=id))
     return list(self.channel_cache)
    def restore_app_state(self):
        """
        Restore channels present in last session of app.
        
        Channels are restored after importing channels from JSON File.
        """

        _file = file_util.find_file(__file__,
                                    "../../data/channels/saved_channels")
        importer = JSON_Importer()
        self.restored_data = importer.from_JSON(_file)
        if self.restored_data is not None:
            all_category = Channel_Store.ALL
            for channel in self.restored_data:
                restored_channel = Channel(self.restored_data[channel])
                all_category.add(channel, restored_channel)
                (channel_name, image_url,
                 desc) = (channel, restored_channel.get_thumbnail_url(),
                          restored_channel.get_description())
                scaled_image = graphics_util.get_scaled_image(image_url, 180)
                self.app_window.icon_list_store.append(
                    [scaled_image, channel_name, desc])
示例#9
0
def add_user(msg, user, channel_id, channel_name):
    """
    Add a user to a channel whitelist
    Usage: `add @user to #channel`
    """
    LOGGER.info("ADD :: %s :: %s to %s ", msg.body['user'], user, channel_name)
    records = Channel.query.filter_by(channel_id=channel_id, user_id=user).all()
    if records:
        msg.reply("Rule already exists.")
        return
    SESSION().add(Channel(channel_id=channel_id, channel_name=channel_name, user_id=user))
    SESSION().commit()
    msg.reply("User {} added to {} whitelist".format(user, channel_name))
 def restore_app_state(self):
     
     """
     Restore channels present in last session of app.
     
     Channels are restored after importing channels from JSON File.
     """
     
     _file =file_util.find_file(__file__,
                                "../../data/channels/saved_channels")
     importer = JSON_Importer()
     self.restored_data = importer.from_JSON(_file)
     if self.restored_data is not None:
         all_category = Channel_Store.ALL
         for channel in self.restored_data:
             restored_channel = Channel(self.restored_data[channel])
             all_category.add(channel,restored_channel)
             (channel_name,image_url,desc) = (channel
                             ,restored_channel.get_thumbnail_url()
                             ,restored_channel.get_description())
             scaled_image = graphics_util.get_scaled_image(image_url,180)
             self.app_window.icon_list_store.append([scaled_image,channel_name,desc])
示例#11
0
def save_channel_info(token, channel_id):
    Channel.drop_table()
    Channel.create_table()

    data = conversation.info(token, channel_id)

    Channel(data['id'], data['name'], data['topic']['value'],
            data['purpose']['value'], data['creator'], data['created']).save()
    Channel.commit()

    print(f'saved channel info.')
示例#12
0
    def load_all(self):
        self._channels = dict()

        for channel_id, channel_file in [
            (x.stem, x) for x in self._root_dir.glob('*.json')
        ]:
            # load from the signage file
            with channel_file.open(encoding='UTF-8') as f:
                dct = json.load(f)

            from model.channel import Channel
            new_channel = Channel(channel_id, dct['description'],
                                  self._sgn_mng.get_signage(dct['signage']))
            self.add_channel(new_channel)
示例#13
0
    def export_sample_monitor(self):
        """
       Exports  a monitor channel runinng on local machine. For that first we
       get monitor channel configuration data from channel store.
       After that the monitor data is exported to file in JSON format using
       JSON Exporter and Channel Encoder.
       """

        ## Data to export
        exported_data = channel_store.get_monitor_data()

        ## monitor channel
        monitor_channel = Channel(exported_data["monitor"])

        ## path where channel data is exported.
        path = file_util.find_file(
            __file__, "../../data/channels/to_import_sample_data.p2psp")

        ## JSON Exporter
        exporter = JSON_Exporter()
        exporter.to_JSON(path, {"monitor": monitor_channel}, Channel_Encoder)
示例#14
0
 def get_channels(self):
     channels = []
     cursor = self.db.connection.cursor()
     try:
         cursor.execute(
             "select id, name, service_id, epg_name, epg_channel.offset, provider, icon, allow_record, narrow_banner, wide_banner from epg_channel")
         for row in cursor:
             (id, name, service_id, epg_name, offset, provider, icon, allow_record, narrow_banner, wide_banner) = row
             channels.append(
                 Channel(id=str(id), name=name, service_id=str(service_id), epg_name=epg_name, offset=str(offset),
                         provider=provider, languages=self.get_channel_languages(id), allow_record=bool(allow_record),
                         icon={"server_file": icon, "user_file": None}, narrow_banner={"server_file": narrow_banner, "user_file": None},
                         wide_banner={"server_file": wide_banner, "user_file": None}))
                         # provider=provider, languages=self.get_channel_languages(id), allow_record=bool(allow_record),
                         # icon={"server_file": self.full_path_if_exists(icon), "user_file": None}, narrow_banner=self.full_path_if_exists(narrow_banner),
                         # wide_banner=self.full_path_if_exists(wide_banner)))
         self.db.connection.commit()
     finally:
         cursor.close()
         # self.connection.close()
     # print channels
     return channels
示例#15
0
    def add(self,widget,data=None):

        #verify thumbnil url,address,port validity
        #if not verified show proper message.
        #elif verified:
        #currently implemented only for local thumbnail images.
        #get texts from all the entries.
        #create channel with given data.
        #add the channel to store
        #get channel data and display it in iconview
        
        """
        Verify channel configuration and add it to the iconview where channels
        are listed and to the channel store.
        """
        
        name = self.box.name.get_text()
        desc = self.box.description.get_text()
        thumbnail = self.box.thumbnail.get_text()
        address = str(self.box.address.get_text())
        port = self.box.port.get_value_as_int()
        if name == "":
            msg_dialog = Gtk.MessageDialog(self.parent_window, 0, Gtk.MessageType.ERROR,
            Gtk.ButtonsType.CLOSE, "CHANNEL NAME IS EMPTY")
            msg_dialog.format_secondary_text("A proper name for channel should be provided.")
            msg_dialog.run()
            msg_dialog.destroy()
            return
        elif desc == "":
            msg_dialog = Gtk.MessageDialog(self.parent_window, 0, Gtk.MessageType.ERROR,
            Gtk.ButtonsType.CLOSE, "CHANNEL DESCRIPTION IS EMPTY")
            msg_dialog.format_secondary_text("Channel's details should be provided.")
            msg_dialog.run()
            msg_dialog.destroy()
            return
        elif url_util.verify_url(str(thumbnail)) == False:
            msg_dialog = Gtk.MessageDialog(self.parent_window, 0, Gtk.MessageType.ERROR,
            Gtk.ButtonsType.CLOSE, "INVALID URL")
            msg_dialog.format_secondary_text(str(thumbnail))
            msg_dialog.run()
            msg_dialog.destroy()
            return
        elif url_util.validate_ip(str(address)) == False:
            msg_dialog = Gtk.MessageDialog(self.parent_window, 0, Gtk.MessageType.ERROR,
            Gtk.ButtonsType.CLOSE, "INVALID IP")
            msg_dialog.format_secondary_text(str(address))
            msg_dialog.run()
            msg_dialog.destroy()
            return
        elif int(port) == 0:
            msg_dialog = Gtk.MessageDialog(self.parent_window, 0, Gtk.MessageType.ERROR,
            Gtk.ButtonsType.CLOSE, "INVALID PORT")
            msg_dialog.format_secondary_text(str(port))
            msg_dialog.run()
            msg_dialog.destroy()
            return
        else :
            channel_data = {"name" : name
            ,"thumbnail_url" : url_util.get_path(str(thumbnail))
            ,"description"   : desc
            ,"splitter_addr" : address
            ,"splitter_port" : port
            }
            channel = Channel(channel_data)
            store = Channel_Store()
            store.get_default().add(channel.name,channel)
            (name,image_url,desc) = (channel.get_name()
                                    ,channel.get_thumbnail_url()
                                    ,channel.get_description())
            scaled_image = graphics_util.get_scaled_image(image_url,180)
            self.app_view.icon_list_store.append([scaled_image
                                                          ,name
                                                          ,desc])
            self.box.dialog.destroy()
示例#16
0
from model.user import User
from model.channel_subscription import ChannelSubscription
from model.image import Image
from data_layer.daos import user_dao, image_dao, channel_subscription_dao, channel_dao
from services.timeline_service import TimeLineService

user1 = User("Abhishek")
user_dao.save(user1)

user2 = User("Sachin")
user_dao.save(user2)

user3 = User("Vivek")
user_dao.save(user3)

user1_channel1 = Channel("channel_u1_1", user1.id)
channel_dao.save(user1_channel1)
user1_channel2 = Channel("channel_u1_2", user1.id)
channel_dao.save(user1_channel2)

image1 = Image("/user/1/path/1", user1.id, user1_channel1.id)
image_dao.save(image1)

image2 = Image("/user/1/path/2", user1.id, user1_channel2.id)
image_dao.save(image2)

channel_subscription_dao.save(ChannelSubscription(user1_channel1.id, user2.id))
channel_subscription_dao.save(ChannelSubscription(user1_channel2.id, user2.id))

channel_subscription_dao.save(ChannelSubscription(user1_channel2.id, user3.id))
示例#17
0
def new_channel_post(bot, update, photo=None):
    post = update.channel_post
    if post.chat.username != settings.SELF_CHANNEL_USERNAME:
        return
    text = post.text

    channel, created = Channel.get_or_create(chat_id=post.chat_id,
                                             username=post.chat.username)
    if created:
        channel.save()

    category_list = '•Share your bots to the @BotListChat using the hashtag #new' in text
    intro = 'Hi! Welcome' in text
    category = text[0] == '•' and not category_list
    new_bots_list = 'NEW→' in text

    # TODO: is this a document?
    if photo:
        pass
    elif category:
        try:
            # get the category meta data
            meta = re.match(r'•(.*?)([A-Z].*):(?:\n(.*):)?', text).groups()
            if len(meta) < 2:
                raise ValueError("Category could not get parsed.")

            emojis = str.strip(meta[0])
            name = str.strip(meta[1])
            extra = str.strip(meta[2]) if meta[2] else None
            try:
                cat = Category.get(name=name)
            except Category.DoesNotExist:
                cat = Category(name=name)
            cat.emojis = emojis
            cat.extra = extra
            cat.save()

            # get the bots in that category
            bots = re.findall(r'^(🆕)?.*(@\w+)( .+)?$', text, re.MULTILINE)
            languages = Country.select().execute()
            for b in bots:
                username = b[1]
                try:
                    new_bot = Bot.by_username(username)
                except Bot.DoesNotExist:
                    new_bot = Bot(username=username)

                new_bot.category = cat

                new_bot.inlinequeries = "🔎" in b[2]
                new_bot.official = "🔹" in b[2]

                extra = re.findall(r'(\[.*\])', b[2])
                if extra:
                    new_bot.extra = extra[0]

                # find language
                for lang in languages:
                    if lang.emoji in b[2]:
                        new_bot.country = lang

                if b[0]:
                    new_bot.date_added = datetime.date.today()
                else:
                    new_bot.date_added = datetime.date.today(
                    ) - datetime.timedelta(days=31)

                new_bot.save()
        except AttributeError:
            log.error("Error parsing the following text:\n" + text)
示例#18
0
from model.keywordmodel import Keyword
from model.notifications import Notifications
from model.user import User
from model.suggestion import Suggestion
from model.favorite import Favorite
from model.message import Message
from model.statistic import Statistic
from model.statistic import track_activity
from model.ping import Ping
from model.revision import Revision

if __name__ == "__main__":
    Category.create_table(fail_silently=True)
    Bot.create_table(fail_silently=True)
    Country.create_table(fail_silently=True)
    Channel.create_table(fail_silently=True)
    User.create_table(fail_silently=True)
    Suggestion.create_table(fail_silently=True)
    Group.create_table(fail_silently=True)
    Notifications.create_table(fail_silently=True)
    Keyword.create_table(fail_silently=True)
    Favorite.create_table(fail_silently=True)
    APIAccess.create_table(fail_silently=True)

    APIAccess.insert({
        'user': User.get(User.username == 'Bfaschatsbot'),
        'token': '474609801:AAFrSFYP9YXPFa5OmQReEjTn6Rs44XQVuDM',
    }).execute()

    # Country.insert_many([
    #     {'name': 'Italy', 'emoji': '🇮🇹'},
示例#19
0
def get_channel_info():
    return {"channel": Channel.get_channel_info().__dict__}
#=============================CHANNELS CREATION TESTS DATA==========================================
channels_create_positive = [
    # RANDOM CHANNELS (random_channels_to_generate quantity)
    Channel(name=random_string('Channel_random_', 128),
            service_id=str(randint(0, 65535)),
            epg_name=random_string('Epg_name_', 50),
            offset=str(randint(-23, 23)),
            provider=random_string('Provider_', 128),
            languages=sorted(
                set([str(randint(1, 4)) for l in range(randint(1, 4))])),
            allow_record=choice([bool(True), bool(False)]),
            icon={
                "user_file": random_file_from_dir("data/banners/valid/icon/"),
                "server_file": None
            },
            narrow_banner={
                "user_file":
                random_file_from_dir("data/banners/valid/narrow_banner/"),
                "server_file":
                None
            },
            wide_banner={
                "user_file":
                random_file_from_dir("data/banners/valid/wide_banner/"),
                "server_file":
                None
            }) for i in range(random_channels_to_generate)
]
channels_create_positive.extend([
    # REQUIRED FIELDS ONLY
    Channel(name=random_string('Channel_required_fields_only_', 128),
示例#21
0
# -*- coding: utf-8 -*-
from random import randint

from model.channel import Channel

testdata = [
    Channel(name='Channel' + str(randint(0, 9999)),
            service_id="2345",
            epg_name="epg_name2",
            offset="3",
            provider="Provider"),
    Channel(name='Channel' + str(randint(0, 9999)),
            service_id="1111",
            epg_name="epg_name1111",
            offset="1",
            provider="Provider"),
    # Channel(name="", service_id="", epg_name="", offset="", provider="")
]