Ejemplo n.º 1
0
    def render_page(self, screen, user):
        channels = Channel.get_visible_channels_of(user)
        plugin_channels = [c for c in channels if type(c) == PluginChannel]
        bundle_channels = [c for c in channels if type(c) == ChannelBundle]
        """Let admins select channels with the same orientation as the screen orientation """
        plugin_channels = [c for c in plugin_channels if (c.plugin.name == "editor" and c.get_config_param(
            'vertical') and "Portrait" == screen.orientation) or (c.plugin.name == "editor" and not c.get_config_param(
            'vertical') and "Landscape" == screen.orientation) or (c.plugin.name != "editor")]

        subscriptions=user.get_subscriptions_of_owned_screens()
        last_by =   {sub.channel.id:
                    {
                        'user': sub.created_by.readable_name,
                        'channel_name': sub.channel.name,
                        'plugin_channel': hasattr(sub.channel, 'plugin')
                    }
                    for sub in subscriptions if sub.screen.id == screen.id
                }

        return self.renderer.screen_subscriptions(
            screen=screen,
            user=user,
            users=User.select(),
            screen_channels=Channel.get_screens_channels_from(user=user),
            plugin_channels=plugin_channels,
            bundle_channels=bundle_channels,
            subscriptions=subscriptions,
            last_by = last_by,
            plugin_channels_names = {c.id: c.name for c in plugin_channels},
            bundle_channels_names = {c.id: c.name for c in bundle_channels}
        )
def verify_diff(diff, screen):
    """ Verifies that all the channels in the diff have been correctly added to/removed from the bundle"""
    for (channel_id, subscribed) in diff.items():
        if subscribed:
            assert Channel.get(channel_id) in screen.subscribed_channels
        else:
            assert Channel.get(channel_id) not in screen.subscribed_channels
Ejemplo n.º 3
0
 def assert_public_channels():
     channel.subscription_right = 'restricted'
     assert Channel.get_visible_channels_of(u) == {
         plugin_channel, bundle_channel
     }
     channel.subscription_right = 'private'
     assert Channel.get_visible_channels_of(u) == {
         plugin_channel, bundle_channel
     }
     channel.subscription_right = 'public'
Ejemplo n.º 4
0
 def post(self, channel_id):
     channel = Channel.get(int(channel_id))
     form = self.form
     try:
         if form.action == 'add-channel-to-bundles':
             bundles_diff = json.loads(form.pop('diff', '{}'))
             for bundle_id, part_of in bundles_diff.items():
                 bundle = ChannelBundle.get(int(bundle_id))
                 if part_of:
                     try:
                         bundle.add_channel(channel)
                     except ValueError:
                         raise ImmediateFeedback(form.action,
                                                 'bundle_cycle',
                                                 bundle.name)
                 else:
                     bundle.remove_channel(channel)
             add_feedback(form.action, 'ok')
     except ImmediateFeedback:
         pass
     form.was_bundle = type(
         channel
     ) == ChannelBundle  # Hack to display the bundles tab instead
     form.data_edit = json.dumps([b.id for b in channel.bundles])
     form.channel_id = channel_id
     form.name = channel.name
     store_form(form)
     resp.seeother('/channels')
Ejemplo n.º 5
0
    def runTest(self):
        """ Tests the Role SQLObject """
        Channel.deleteMany(None)
        fake_plugin = Plugin(name='fake_plugin', activated='notfound')
        plugin_channel = PluginChannel(name='Plugin Channel',
                                       plugin=fake_plugin,
                                       subscription_right='public')
        user = User(fullname='User', email='test@localhost')

        role = Role(user=user,
                    channel=plugin_channel,
                    permission_level=UserPermissions.channel_administrator)
        assert role._SO_get_permission_level() == 'channel_administrator'
        assert role.permission_level == UserPermissions.channel_administrator
        role.permission_level = UserPermissions.channel_contributor
        assert role._SO_get_permission_level() == 'channel_contributor'
        assert role.permission_level == UserPermissions.channel_contributor
Ejemplo n.º 6
0
 def runTest(self):
     """ Tests the ChannelRenderer page. """
     Channel.deleteMany(None)
     fake_plugin = Plugin.byName('fake_plugin')
     plugin_channel = PluginChannel(plugin=fake_plugin,
                                    name='This is a cool channel',
                                    subscription_right='public')
     body = self.testApp.get(plugin_channel.get_preview_link(),
                             status=200).body
     assert b'This is a cool channel' in body
     assert b"Reveal.toggleAutoSlide(true);" in body
     assert self.testApp.get(plugin_channel.get_preview_link() +
                             'incorrect_secret',
                             status=403)
     assert self.testApp.get('/preview/channels/%d/incorrect_secret' %
                             (plugin_channel.id + 42),
                             status=404)
Ejemplo n.º 7
0
def create_database():
    Building.createTable()
    Channel.createTable()
    Plugin.createTable()
    User.createTable()
    PluginChannel.createTable()
    ChannelBundle.createTable()
    Role.createTable()
    Screen.createTable()
    ScreenMac.createTable()
    Subscription.createTable()
    Template.createTable()
    Asset.createTable()
    PluginParamAccessRights.createTable()
    LogStat.createTable()
    DBVersion.createTable()
    DBVersion(version=database_version)
    User(username="******", fullname="ICTV Admin", email="admin@ictv", super_admin=True, disabled=False)
Ejemplo n.º 8
0
 def setUp(self):
     super(ChannelsPageTestCase, self).setUp()
     Channel.deleteMany(None)
     self.fake_plugin = Plugin.byName('fake_plugin')
     self.pc1 = PluginChannel(plugin=self.fake_plugin,
                              name='PC 1',
                              subscription_right='public')
     self.pc2 = PluginChannel(plugin=self.fake_plugin,
                              name='PC 2',
                              subscription_right='public')
     self.pc3 = PluginChannel(plugin=self.fake_plugin,
                              name='PC 3',
                              subscription_right='public')
     self.bundle = ChannelBundle(name='Bundle', subscription_right='public')
     self.building = Building(name='Building')
     self.screen = Screen(name='Screen', building=self.building)
     self.user_nothing = User(email='nothing@localhost', disabled=False)
     self.user_contrib = User(email='contrib@localhost', disabled=False)
     self.pc1.give_permission_to_user(self.user_contrib,
                                      UserPermissions.channel_contributor)
     self.user_chan_admin = User(email='chan_admin@localhost',
                                 disabled=False)
     self.user_chan_admin2 = User(email='chan_admin2@localhost',
                                  disabled=False)
     self.pc1.give_permission_to_user(self.user_chan_admin,
                                      UserPermissions.channel_administrator)
     self.pc2.give_permission_to_user(self.user_chan_admin2,
                                      UserPermissions.channel_administrator)
     self.user_screen_admin = User(email='screen_admin@locahost',
                                   disabled=False)
     self.screen.safe_add_user(self.user_screen_admin)
     self.user_admin = User(email='admin@localhost',
                            disabled=False,
                            admin=True)
     self.user_super_admin = User(email='super_admin@localhost',
                                  disabled=False,
                                  admin=True,
                                  super_admin=True)
     self.users = [
         self.user_nothing, self.user_contrib, self.user_chan_admin,
         self.user_chan_admin2, self.user_screen_admin, self.user_admin,
         self.user_super_admin
     ]
Ejemplo n.º 9
0
 def render_page(self, bundle, user):
     channels = Channel.select()
     plugin_channels = [c for c in channels if type(c) == PluginChannel]
     bundle_channels = [c for c in channels if type(c) == ChannelBundle]
     return self.renderer.manage_bundle(
         bundle=bundle,
         user=user,
         subscribed_channels=bundle.bundled_channels,
         plugin_channels=plugin_channels,
         bundle_channels=bundle_channels,
     )
Ejemplo n.º 10
0
 def render_page(self):
     u = User.get(self.session['user']['id'])
     screen_status_validity = datetime.now() - timedelta(hours=1)
     return self.renderer.screens(
         screens=Screen.get_visible_screens_of(u),
         buildings=Building.select(),
         user=u,
         users=User.select(),
         channels=Channel.get_screens_channels_from(user=u),
         subscriptions=u.get_subscriptions_of_owned_screens(),
         screen_status_validity=screen_status_validity,
         max_inactivity_period=timedelta(weeks=4))
Ejemplo n.º 11
0
    def get(self, id, user_id):
        channel_id = int(id)
        chan = Channel.get(channel_id)
        user_id = int(user_id)
        user = User.get(user_id)

        st = "You just receive a request of subscription for channel " + chan.name + ". Could you please subscribe " + str(
            user.fullname) + " (" + user.email + ") to this channel."
        for admin in chan.get_admins():
            web.sendmail(web.config.smtp_sendername,
                         admin.email,
                         'Request for subscription to a channel',
                         st,
                         headers={'Content-Type': 'text/html;charset=utf-8'})
        resp.seeother('/channels')
Ejemplo n.º 12
0
 def GET(self, channel_id, secret):
     """ Render the capsules of this channel. """
     try:
         channel = Channel.get(channel_id)
         if channel.secret != secret:
             raise web.forbidden()
     except SQLObjectNotFound:
         raise web.notfound()
     channel_capsules = []
     already_added_channels = set()
     for plugin_channel in channel.flatten(keep_disabled_channels=True):
         if plugin_channel.id not in already_added_channels:
             if plugin_channel.plugin.activated == 'yes':
                 for capsule in self.plugin_manager.get_plugin_content(
                         plugin_channel):
                     if len(capsule.get_slides()) > 0:
                         channel_capsules.append(capsule)
             already_added_channels.add(plugin_channel.id)
     return self.ictv_renderer.preview_capsules(channel_capsules,
                                                context='channel',
                                                auto_slide=True)
Ejemplo n.º 13
0
 def get(self, channel_id):
     channel = Channel.get(channel_id)
     current_user = User.get(self.session['user']['id'])
     screens_of_current_user = Screen.get_visible_screens_of(current_user)
     subscriptions = current_user.get_subscriptions_of_owned_screens()
     last_by = {
         sub.screen.id: {
             'user': sub.created_by.readable_name,
             'channel_name': sub.channel.name,
             'plugin_channel': hasattr(sub.channel, 'plugin')
         }
         for sub in subscriptions if sub.channel.id == channel.id
     }
     screen_names = {s.id: s.name for s in screens_of_current_user}
     return self.renderer.channel_subscriptions(
         channel=channel,
         possible_screens=screens_of_current_user,
         user=current_user,
         subscriptions=subscriptions,
         last_by=last_by,
         screen_names=screen_names)
Ejemplo n.º 14
0
    def render_page(self):
        u = User.get(self.session['user']['id'])
        screen_status_validity = datetime.now() - timedelta(hours=1)

        def get_data_edit_object(screen):
            object = screen.to_dictionary(['name', 'comment', 'location'])
            object['screenid'] = screen.id
            object['mac'] = screen.get_macs_string(
            ) if screen.macs is not None else ''
            object['building-name'] = screen.building.name
            return json.dumps(object)

        return self.renderer.screens(
            screens=Screen.get_visible_screens_of(u),
            buildings=Building.select(),
            user=u,
            highest_permission_level=u.highest_permission_level,
            users=User.select(),
            channels=Channel.get_screens_channels_from(user=u),
            subscriptions=u.get_subscriptions_of_owned_screens(),
            screen_status_validity=screen_status_validity,
            max_inactivity_period=timedelta(weeks=4),
            get_data_edit_object=get_data_edit_object)
Ejemplo n.º 15
0
    def render_page(self, bundle, user):
        channels = Channel.select()
        plugin_channels = [c for c in channels if type(c) == PluginChannel]
        bundle_channels = [c for c in channels if type(c) == ChannelBundle]

        subscribed =   {channel.id:
                            {
                                'channel_name': channel.name,
                                'plugin_channel': hasattr(channel, 'plugin')
                            }
                            for channel in bundle.bundled_channels
                        }

        return self.renderer.manage_bundle(
            bundle=bundle,
            user=user,
            subscribed_channels=bundle.bundled_channels,
            plugin_channels=plugin_channels,
            bundle_channels=bundle_channels,
            subscribed=subscribed,
            plugin_channels_names={c.id: c.name for c in plugin_channels},
            bundle_channels_names = {c.id: c.name for c in bundle_channels}
        )
Ejemplo n.º 16
0
    def render_page(self, current_user=None, users=None):
        if current_user is None:
            current_user = User.get(self.session['user']['id'])
        if UserPermissions.channel_administrator in current_user.highest_permission_level:
            users = User.select()

        channels = list(Channel.get_visible_channels_of(current_user))

        plugin_channels = []
        bundles = []

        for channel in channels:
            if type(channel) is PluginChannel:
                plugin_channels.append(channel)
            elif type(channel) is ChannelBundle:
                bundles.append(channel)

        return self.renderer.channels(
            plugin_channels=plugin_channels,
            bundles=bundles,
            current_user=current_user,
            users=users,
            activated_plugins=Plugin.selectBy(activated='yes'),
            found_plugins=Plugin.select(NOT(Plugin.q.activated == 'notfound')))
Ejemplo n.º 17
0
    def post(self):
        """ Handles screen creation, editing, deletion, channel subscriptions. """
        form = self.form
        u = User.get(self.session['user']['id'])
        try:
            if form.action == 'delete':
                if not u.super_admin:
                    resp.forbidden()
                try:
                    screenid = int(form.screenid)
                except ValueError:
                    raise ImmediateFeedback(form.action, 'invalid_id')
                try:
                    Screen.delete(screenid)
                    raise ImmediateFeedback(form.action, 'ok')
                except SQLObjectNotFound as e:
                    raise ImmediateFeedback(form.action, 'no_id_matching')
            elif form.action == 'subscribe':
                if form.diff == 'diff':
                    raise ImmediateFeedback(form.action, 'nothing_changed')
                try:
                    diff = json.loads(form.diff)
                except (json.JSONDecodeError, ValueError):
                    raise ImmediateFeedback(form.action, 'inconsistent_diff')
                try:
                    screenid = int(form.screenid)
                except ValueError:
                    raise ImmediateFeedback(form.action,
                                            'invalid_channel/screen_id')
                for k, v in diff.items():
                    try:
                        sub = bool(v)
                    except ValueError:
                        raise ImmediateFeedback(form.action,
                                                'invalid_channel/screen_id')
                    try:
                        channelid = int(k)
                    except ValueError:
                        raise ImmediateFeedback(form.action,
                                                'invalid_channel/screen_id')
                    try:
                        channel = Channel.get(channelid)
                        screen = Screen.get(screenid)
                        if UserPermissions.administrator not in u.highest_permission_level and not (
                                channel.can_subscribe(u)
                                and u in screen.owners):
                            resp.forbidden()
                        if sub:
                            if hasattr(channel, "plugin"
                                       ) and channel.plugin.activated != 'yes':
                                resp.forbidden()
                            screen.subscribe_to(user=u, channel=channel)
                        else:
                            screen.unsubscribe_from(user=u, channel=channel)
                    except SQLObjectNotFound:
                        raise ImmediateFeedback(form.action,
                                                'invalid_channel/screen_id')
                    except DuplicateEntryError:
                        # if the user has checked + unchecked the same checkbox, it will appear on the diff,
                        # we just need to do nothing.
                        pass
                    except SQLObjectIntegrityError:
                        # when there id more than one subscription matching the pair channel/screen
                        # TODO: log something
                        pass
            elif form.action == 'chown':
                if form.diff == 'diff':
                    raise ImmediateFeedback(form.action, 'nothing_changed')
                try:
                    diff = json.loads(form.diff)
                except (json.JSONDecodeError, ValueError):
                    raise ImmediateFeedback(form.action, 'inconsistent_diff')
                try:
                    screenid = int(form.screenid)
                except ValueError:
                    raise ImmediateFeedback(form.action, 'screenid')
                for k, v in diff.items():
                    try:
                        own = bool(v)
                    except ValueError:
                        raise ImmediateFeedback(form.action,
                                                'invalid_screen/user_id')
                    try:
                        userid = int(k)
                    except ValueError:
                        raise ImmediateFeedback(form.action,
                                                'invalid_screen/user_id')
                    try:
                        screen = Screen.get(screenid)
                        if UserPermissions.administrator not in u.highest_permission_level and u not in screen.owners:
                            resp.forbidden()
                        user = User.get(userid)
                        if own:
                            screen.safe_add_user(user)
                        else:
                            screen.removeUser(user)
                    except SQLObjectNotFound:
                        raise ImmediateFeedback(form.action,
                                                'invalid_screen/user_id')
                    except DuplicateEntryError:
                        # if the user has checked + unchecked the same checkbox, it will appear on the diff,
                        # we just need to do nothing.
                        pass
                    except SQLObjectIntegrityError:
                        # when there is more than one subscription mathing the pair channel/screen
                        # TODO: log something
                        pass
            elif form.action == 'configure':
                screen = Screen.get(int(form.id))
                screen.shuffle = form.get('shuffle') == 'on'
                screen.show_postit = form.get('postit') == 'on'
                screen.show_slide_number = form.get(
                    'show_slide_number') == 'on'
            else:
                building = Building.get(form.building.strip())
                name = form.name.strip()
                form.building_name = None
                if not building:
                    raise ImmediateFeedback(form.action, 'empty_building')
                form.building_name = building.name
                if not name:
                    raise ImmediateFeedback(form.action, 'empty_name')
                if len(name) > Screen.sqlmeta.columns['name'].length:
                    raise ImmediateFeedback(form.action, 'too_long_name')

                try:
                    macs = {
                        self.check_mac_address(mac)
                        for mac in form.mac.strip().lower().split(';') if mac
                    }
                except ValueError:
                    raise ImmediateFeedback(form.action, 'invalid_mac_address')

                if form.action == 'create':
                    if UserPermissions.administrator not in u.highest_permission_level:
                        resp.forbidden()
                    try:
                        screen = Screen(name=form.name.strip(),
                                        building=form.building,
                                        location=form.location.strip(),
                                        comment=form.comment.strip(),
                                        orientation=form.orientation)
                    except DuplicateEntryError:
                        raise ImmediateFeedback(form.action,
                                                'name_already_exists')

                elif form.action == 'edit':
                    if UserPermissions.administrator not in u.highest_permission_level:
                        resp.forbidden()
                    try:
                        screenid = int(form.screenid)
                    except ValueError:
                        raise ImmediateFeedback(form.action, 'invalid_id')

                    screen = Screen.get(screenid)
                    if screen is None:
                        raise ImmediateFeedback(form.action, 'no_id_matching')

                    try:
                        screen.name = form.name.strip()
                        screen.building = form.building
                        screen.orientation = form.orientation
                    except DuplicateEntryError:
                        raise ImmediateFeedback(form.action,
                                                'name_already_exists')
                    screen.location = form.location.strip()
                    screen.comment = form.comment.strip()
                else:
                    raise NotImplementedError

                try:
                    screen_macs = [
                        screen_mac.mac for screen_mac in screen.macs
                    ]
                    for mac in screen_macs:
                        if mac not in macs:
                            ScreenMac.selectBy(mac=mac).getOne().destroySelf()
                    for mac in macs:
                        if mac not in screen_macs:
                            ScreenMac(screen=screen, mac=mac)
                except DuplicateEntryError:
                    raise ImmediateFeedback(form.action, 'mac_already_exists')

            add_feedback(form.action, 'ok')
        except ImmediateFeedback:
            pass
        store_form(form)

        return self.render_page()
Ejemplo n.º 18
0
    def post(self, channel_id):
        form = self.form
        u = User.get(self.session['user']['id'])
        subscribed = []
        unsubscribed = []
        if form.diff == 'diff':
            raise ImmediateFeedback(form.action, 'nothing_changed')
        try:
            diff = json.loads(form.diff)
        except (json.JSONDecodeError, ValueError):
            raise ImmediateFeedback(form.action, 'inconsistent_diff')
        try:
            channelid = int(channel_id)
        except ValueError:
            raise ImmediateFeedback(form.action, 'invalid_channel/screen_id')
        for k, v in diff.items():
            try:
                sub = bool(v)
            except ValueError:
                raise ImmediateFeedback(form.action,
                                        'invalid_channel/screen_id')
            try:
                screenid = int(k)
            except ValueError:
                raise ImmediateFeedback(form.action,
                                        'invalid_channel/screen_id')
            try:
                channel = Channel.get(channelid)
                if not channel.can_subscribe(u):
                    raise self.forbidden(message="You're not allow to do that")
                screen = Screen.get(screenid)
                if not u in screen.owners:
                    raise self.forbidden(message="You're not allow to do that")
                #sub true -> New subscription
                #sub false -> Remove subscription
                if sub:
                    screen.subscribe_to(u, channel)
                    subscribed.append(str(channel.id))
                else:
                    screen.unsubscribe_from(u, channel)
                    unsubscribed.append(str(channel.id))
                if subscribed and unsubscribed:
                    message = "user %s has subscribed screen %d to channel(s) %s and unsubscribed from channel(s) %s" % \
                              (u.log_name, screen.id, ', '.join(subscribed), ', '.join(unsubscribed))
                else:
                    message = "user %s has %s screen %d to channel(s) %s" % \
                              (u.log_name, "subscribed" if subscribed else "unsubscribed", screen.id,
                               ', '.join(subscribed if subscribed else unsubscribed))
                logger.info(message)
                add_feedback("subscription", 'ok')

            except SQLObjectNotFound:
                raise ImmediateFeedback(form.action,
                                        'invalid_channel/screen_id')
            except DuplicateEntryError:
                # if the user has checked + unchecked the same checkbox, it will appear on the diff,
                # we just need to do nothing.
                pass
            except SQLObjectIntegrityError:
                # when there id more than one subscription matching the pair channel/screen
                pass
        resp.seeother("/channels/config/%s/subscriptions" % channel_id)
Ejemplo n.º 19
0
 def assert_channels(*channels):
     assert set(
         Channel.get_screens_channels_from(u)) == set(channels)
Ejemplo n.º 20
0
 def assert_all_channels():
     assert set(Channel.get_screens_channels_from(u)) == {
         channel, plugin_channel, bundle_channel
     }
Ejemplo n.º 21
0
    def post(self, bundle_id):
        def wrong_channel(channel, bundle, add):
            """ returns True if the channel to add is the bundle itself
                or if the channel is a PluginChannel with disabled plugin """
            return bundle.id == channel.id or add and type(channel) is PluginChannel and channel.plugin.activated != "yes"
        form = self.form
        try:
            bundle = ChannelBundle.get(bundle_id)
            u = User.get(self.session['user']['id'])
            diff = json.loads(form.diff)
            if diff == {}:
                logger.info('user %s submitted empty diff for bundle management %s', u.log_name, bundle.name)
                raise ImmediateFeedback("manage_channels", 'nothing_changed')
            # Do the subscription/unsubscription for every channel in the diff
            contained = []
            not_contained = []
            try:
                changes = [(Channel.get(channel_id), add) for channel_id, add in diff.items()]
            except SQLObjectNotFound:
                logger.warning('user %s tried to add a channel which does not exist to bundle %d',
                               u.log_name, bundle.id)
                resp.forbidden()
            # if somebody tries to add a channel with a disabled plugin or to add a bundle to itself
            wrong_channels = [(channel, add) for channel, add in changes if wrong_channel(channel, bundle, add)]
            if wrong_channels:
                channel, add = wrong_channels[0]
                if channel.id == bundle.id:
                    logger.warning('user %s tried to %s bundle %d to itself',
                                   u.log_name, 'add' if add else "remove", bundle.id)
                    raise ImmediateFeedback("manage_channels", "added_to_itself")
                else:
                    logger.warning('user %s tried to %s channel %d with disabled plugin to bundle %d',
                                   u.log_name, 'add' if add else "remove", channel.id, bundle.id)
                    raise ImmediateFeedback("manage_channels", "disabled_plugin")
            for channel, add in changes:
                if add:
                    try:
                        bundle.add_channel(channel)
                    except ValueError:
                        logger.warning("user %s has made changes in channels management of bundle %d that created a "
                                       "cycle of bundles by adding channel %d (%s)", u.log_name, bundle.id, channel.id,
                                       channel.name)
                        form.channel_name = channel.name
                        raise ImmediateFeedback("manage_channels", "bundle_cycle")

                    contained.append(str(channel.id))
                else:
                    bundle.remove_channel(channel)
                    not_contained.append(str(channel.id))
            if contained and not_contained:
                message = "user %s has added to channel(s) %s and removed channel(s) %s to bundle %d" % \
                          (u.log_name, ', '.join(contained), ', '.join(not_contained), bundle.id)
            else:
                message = "user %s has %s channel(s) %s to bundle %d" % \
                          (u.log_name, "added" if contained else "removed",
                           ', '.join(contained if contained else not_contained), bundle.id)
            logger.info(message)
            add_feedback("manage_channels", 'ok')
        except SQLObjectNotFound:
            resp.notfound()
        except ImmediateFeedback:
            pass
        store_form(form)
        resp.seeother("/channels/config/%s/manage_bundle" % bundle.id)
Ejemplo n.º 22
0
    def runTest(self):
        """ Tests the PluginChannel SQLObject """
        Channel.deleteMany(None)
        fake_plugin = Plugin.selectBy(name='fake_plugin').getOne()
        plugin_channel = PluginChannel(name='MyPluginChannel',
                                       plugin=fake_plugin,
                                       subscription_right='public')
        user = User(fullname='User', email='test@localhost')
        user2 = User(fullname='User2', email='test2@localhost')

        assert plugin_channel.get_type_name() == 'Plugin fake_plugin'

        # Test user permissions
        def assert_no_permission(c, u):
            assert c.get_channel_permissions_of(
                u) == UserPermissions.no_permission
            assert u not in c.get_admins() and u not in c.get_contribs()

        def has_contrib(u, check_inlist=True):
            return plugin_channel.has_contrib(u) and (
                not check_inlist or u in plugin_channel.get_contribs())

        def has_admin(u):
            return plugin_channel.has_admin(
                u) and u in plugin_channel.get_admins()

        assert_no_permission(plugin_channel, user)
        assert_no_permission(plugin_channel, user2)

        plugin_channel.give_permission_to_user(
            user, UserPermissions.channel_contributor)
        role = Role.selectBy(user=user, channel=plugin_channel).getOne()

        assert has_contrib(user)
        assert not has_admin(user)
        assert not has_contrib(user2)
        assert not has_admin(user2)
        assert role.permission_level == UserPermissions.channel_contributor == plugin_channel.get_channel_permissions_of(
            user)

        assert json.loads(plugin_channel.get_users_as_json()) == {
            str(user.id): UserPermissions.channel_contributor.value
        }

        plugin_channel.give_permission_to_user(
            user, UserPermissions.channel_administrator)
        assert has_contrib(user, check_inlist=False)
        assert has_admin(user)
        assert not has_contrib(user2)
        assert not has_admin(user2)
        assert role.permission_level == UserPermissions.channel_administrator == plugin_channel.get_channel_permissions_of(
            user)

        assert json.loads(plugin_channel.get_users_as_json()) == {
            str(user.id): UserPermissions.channel_administrator.value
        }
        assert json.loads(PluginChannel.get_channels_users_as_json([plugin_channel])) == \
            {str(plugin_channel.id): {str(user.id): UserPermissions.channel_administrator.value}}

        plugin_channel.remove_permission_to_user(user)
        plugin_channel.give_permission_to_user(
            user2, UserPermissions.channel_administrator)
        assert not has_contrib(user)
        assert not has_admin(user)
        assert has_contrib(user2, check_inlist=False)
        assert has_admin(user2)
        plugin_channel.remove_permission_to_user(user2)
        assert not has_contrib(user2)
        assert not has_admin(user2)

        # Test plugin config parameters
        assert plugin_channel.get_config_param(
            'string_param') == 'default string'
        assert plugin_channel.get_config_param('int_param') == 1
        assert plugin_channel.get_config_param('float_param') == float('-inf')
        assert plugin_channel.get_config_param('boolean_param') is True
        assert plugin_channel.get_config_param('template_param') is None
        with pytest.raises(KeyError):
            assert plugin_channel.get_config_param(
                'this_param_does_not_exists')

        def assert_value_is_set(param, value):
            plugin_channel.plugin_config[param] = value
            plugin_channel.plugin_config = plugin_channel.plugin_config  # Force SQLObject update
            assert plugin_channel.get_config_param(param) == value

        assert_value_is_set('string_param', 'Hello, world!')
        assert_value_is_set('int_param', 42)
        assert_value_is_set('float_param', 42.0)
        assert_value_is_set('boolean_param', False)
        assert_value_is_set('template_param', 'fake-template')

        # Test parameters access rights
        ppar = PluginParamAccessRights.selectBy(plugin=fake_plugin,
                                                name='int_param').getOne()
        ppar.channel_contributor_read = False
        ppar.channel_contributor_write = False
        ppar.channel_administrator_read = True
        ppar.channel_administrator_write = False
        ppar.administrator_read = True
        ppar.administrator_write = True

        user.super_admin = True
        assert plugin_channel.has_visible_params_for(user)
        for param in [
                'string_param', 'int_param', 'float_param', 'boolean_param',
                'template_param'
        ]:
            assert plugin_channel.get_access_rights_for(param,
                                                        user) == (True, True)
        user.super_admin = False

        assert not plugin_channel.has_visible_params_for(user)
        plugin_channel.give_permission_to_user(
            user, UserPermissions.channel_contributor)
        assert not plugin_channel.has_visible_params_for(user)
        assert plugin_channel.get_access_rights_for('int_param',
                                                    user) == (False, False)
        plugin_channel.give_permission_to_user(
            user, UserPermissions.channel_administrator)
        assert plugin_channel.has_visible_params_for(user)
        assert plugin_channel.get_access_rights_for('int_param',
                                                    user) == (True, False)
        user.admin = True
        assert plugin_channel.has_visible_params_for(user)
        assert plugin_channel.get_access_rights_for('int_param',
                                                    user) == (True, True)
        plugin_channel.remove_permission_to_user(user)
        user.admin = False
        assert not plugin_channel.has_visible_params_for(user)
        assert plugin_channel.get_access_rights_for('int_param',
                                                    user) == (False, False)

        # Test miscellaneous parameters
        assert plugin_channel.cache_activated is True
        plugin_channel.plugin.cache_activated_default = False
        assert plugin_channel.cache_activated is False
        plugin_channel.cache_activated = True
        assert plugin_channel.cache_activated is True

        assert plugin_channel.cache_validity is 60
        plugin_channel.plugin.cache_validity_default = 120
        assert plugin_channel.cache_validity is 120
        plugin_channel.cache_validity = 42
        assert plugin_channel.cache_validity is 42

        assert plugin_channel.keep_noncomplying_capsules is False
        plugin_channel.plugin.keep_noncomplying_capsules_default = True
        assert plugin_channel.keep_noncomplying_capsules is True
        plugin_channel.keep_noncomplying_capsules = False
        assert plugin_channel.keep_noncomplying_capsules is False

        # Test flatten()
        plugin_channel.enabled = False
        assert plugin_channel.flatten() == []
        assert plugin_channel.flatten(keep_disabled_channels=True) == [
            plugin_channel
        ]
        plugin_channel.enabled = True
        assert plugin_channel.flatten() == [plugin_channel]
Ejemplo n.º 23
0
 def assert_channel(c):
     assert set(Channel.get_screens_channels_from(u)) == {c}
Ejemplo n.º 24
0
 def get(self, channel_id):
     channel = Channel.get(int(channel_id))
     current_user = User.get(self.session['user']['id'])
     if channel in Channel.get_visible_channels_of(current_user):
         return self.render_page(channel)
     raise self.forbidden()
Ejemplo n.º 25
0
 def assert_all_channels():
     assert Channel.get_visible_channels_of(u) == {
         channel, plugin_channel, bundle_channel
     }
Ejemplo n.º 26
0
 def assert_channel(c):
     assert Channel.get_visible_channels_of(u) == {c}
Ejemplo n.º 27
0
    def runTest(self):
        """ Tests the Screen SQLObject """
        Channel.deleteMany(None)
        Screen.deleteMany(None)
        channel = Channel(name='Channel',
                          subscription_right='public',
                          secret='abcdef')
        plugin_channel = PluginChannel(name='Channel2',
                                       plugin=Plugin.byName('fake_plugin'),
                                       subscription_right='public')
        plugin_channel2 = PluginChannel(name='Channel3',
                                        plugin=Plugin.byName('fake_plugin'),
                                        subscription_right='public')
        bundle_channel = ChannelBundle(name='Channel4',
                                       subscription_right='public')
        bundle_channel.add_channel(plugin_channel2)
        building = Building(name='building')
        screen = Screen(name='Screen', building=building, secret='abcdef')
        screen2 = Screen(name='Screen2', building=building)
        user = User(fullname='User', email='test@localhost')
        user2 = User(fullname='User2', email='test2@localhost')

        # Miscellaneous test
        assert screen.get_view_link() == '/screens/%d/view/abcdef' % screen.id
        assert screen.get_client_link(
        ) == '/screens/%d/client/abcdef' % screen.id
        assert screen.get_macs_string() == ''
        assert screen not in user.screens
        screen.safe_add_user(user)
        assert screen in user.screens
        assert screen not in user2.screens
        screen.removeUser(user)
        assert screen not in user2.screens

        # Test subscription
        assert not screen.is_subscribed_to(channel)
        screen.subscribe_to(user, channel)
        assert screen.is_subscribed_to(channel)
        sub = screen.subscriptions[0]
        screen.subscribe_to(user2, channel, weight=42)
        assert sub.created_by == user2
        assert sub.weight == 42
        assert screen.is_subscribed_to(channel)
        assert list(screen.subscribed_channels) == [channel]
        screen.unsubscribe_from(user2, channel)
        assert not screen.is_subscribed_to(channel)

        # Test macs
        ScreenMac(screen=screen, mac='00b16b00b500')
        ScreenMac(screen=screen, mac='00b16b00b501')
        assert screen.get_macs_string(
        ) == '00:b1:6b:00:b5:00;00:b1:6b:00:b5:01'

        # Test get_visible_screens_of()
        assert list(Screen.get_visible_screens_of(user)) == list(
            Screen.get_visible_screens_of(user2)) == []
        user.admin = True
        assert list(Screen.get_visible_screens_of(user)) == [screen, screen2]
        assert list(Screen.get_visible_screens_of(user2)) == []
        user.admin = False
        user2.super_admin = True
        assert list(Screen.get_visible_screens_of(user2)) == [screen, screen2]
        assert list(Screen.get_visible_screens_of(user)) == []
        user2.super_admin = False
        screen.safe_add_user(user)
        screen2.safe_add_user(user2)
        assert list(Screen.get_visible_screens_of(user)) == [screen]
        assert list(Screen.get_visible_screens_of(user2)) == [screen2]

        # Test channel content
        screen.subscribe_to(user, plugin_channel)
        screen.subscribe_to(user, bundle_channel)
        screen_content = screen.get_channels_content(self.ictv_app)
        assert len(screen_content) == 2
        assert len(screen_content[0].get_slides()) == 1
        assert screen_content[0].get_slides()[0].get_content() == {
            'background-1': {
                'size': 'contain',
                'src': ''
            },
            'title-1': {
                'text': 'Channel2'
            },
            'text-1': {
                'text': ''
            }
        }
        assert len(screen_content[1].get_slides()) == 1
        assert screen_content[1].get_slides()[0].get_content() == {
            'background-1': {
                'size': 'contain',
                'src': ''
            },
            'title-1': {
                'text': 'Channel3'
            },
            'text-1': {
                'text': ''
            }
        }
        screen.shuffle = True
        assert len(screen.get_channels_content(self.ictv_app)) == 2
Ejemplo n.º 28
0
 def assert_no_channels():
     assert set(Channel.get_screens_channels_from(u)) == set()
Ejemplo n.º 29
0
 def post(self, screen_id):
     def wrong_channel(channel, subscribe, user):
         """ returns True if the the user wants to subscribe to the channel while its plugin is not activated or if
             the user tries to subscribe to the channel without being in its authorized subscribers"""
         return subscribe and (type(channel) is PluginChannel and channel.plugin.activated != "yes" or (subscribe and not channel.can_subscribe(user)))
     form = self.form
     try:
         screen = Screen.get(screen_id)
         u = User.get(self.session['user']['id'])
         # Forbid if not admin or does not own this screen
         if not (UserPermissions.administrator in u.highest_permission_level or screen in u.screens):
             logger.warning('user %s tried change subscriptions of screen %d without having the rights to do this',
                            u.log_name, screen.id)
             resp.forbidden()
         diff = json.loads(form.diff)
         if diff == {}:
             logger.info('user %s submitted empty diff for subscriptions of screen %s', u.log_name, screen.name)
             raise ImmediateFeedback("subscription", 'nothing_changed')
         # Do the subscription/unsubscription for every channel in the diff
         subscribed = []
         unsubscribed = []
         try:
             changes = [(Channel.get(channel_id), subscribe) for channel_id, subscribe in diff.items()]
         except SQLObjectNotFound:
             logger.warning('user %s tried to subscribe/unsubscribe screen %d to a channel which does not exist',
                            u.log_name, screen.id)
             resp.forbidden()
         # if somebody tries to subscribe to a channel with a disabled plugin
         wrong_channels = [(channel, subscribe) for channel, subscribe in changes if wrong_channel(channel, subscribe, u)]
         if wrong_channels:
             channel, subscribe = wrong_channels[0]
             if channel.plugin.activated != "yes":
                 logger.warning('user %s tried to %s screen %d to channel %d with disabled plugin',
                                u.log_name, 'subscribe' if subscribe else "unsubscribe", screen.id, channel.id)
                 raise ImmediateFeedback("subscription", "disabled_plugin")
             else:
                 logger.warning('user %s tried to subscribe screen %d to channel %d without having the right to do this',
                                u.log_name, screen.id, channel.id)
                 resp.forbidden()
         for channel, subscribe in changes:
             if subscribe:
                 screen.subscribe_to(u, channel)
                 subscribed.append(str(channel.id))
             else:
                 screen.unsubscribe_from(u, channel)
                 unsubscribed.append(str(channel.id))
         if subscribed and unsubscribed:
             message = "user %s has subscribed screen %d to channel(s) %s and unsubscribed from channel(s) %s" % \
                       (u.log_name, screen.id, ', '.join(subscribed), ', '.join(unsubscribed))
         else:
             message = "user %s has %s screen %d to channel(s) %s" % \
                       (u.log_name, "subscribed" if subscribed else "unsubscribed", screen.id,
                        ', '.join(subscribed if subscribed else unsubscribed))
         logger.info(message)
         add_feedback("subscription", 'ok')
     except SQLObjectNotFound:
         resp.notfound()
     except ImmediateFeedback:
         pass
     store_form(form)
     resp.seeother("/screens/%s/subscriptions" % screen.id)
Ejemplo n.º 30
0
    def runTest(self):
        """ Tests the Channel SQLObject """
        Channel.deleteMany(None)
        fake_plugin = Plugin(name='fake_plugin', activated='notfound')
        channel = Channel(name='Channel',
                          subscription_right='public',
                          secret='abcdef')
        plugin_channel = PluginChannel(name='Channel2',
                                       plugin=fake_plugin,
                                       subscription_right='public')
        bundle_channel = ChannelBundle(name='Channel3',
                                       subscription_right='public')
        building = Building(name='building')
        screen = Screen(name='Screen', building=building)
        user = User(fullname='User', email='test@localhost')
        user2 = User(fullname='User2', email='test2@localhost')

        # Test can_subscribe()
        def test_channel_subscription(c, u):
            def assert_subscription_no_perm():
                assert c.can_subscribe(u)
                c.subscription_right = 'restricted'
                assert not c.can_subscribe(u)
                c.subscription_right = 'private'
                assert not c.can_subscribe(u)
                c.subscription_right = 'public'
                assert c.can_subscribe(u)

            def assert_subscription_admin():
                assert c.can_subscribe(u)
                c.subscription_right = 'restricted'
                assert c.can_subscribe(u)
                c.subscription_right = 'private'
                assert c.can_subscribe(u)
                c.subscription_right = 'public'
                assert c.can_subscribe(u)

            def assert_subscription_super_admin():
                assert c.can_subscribe(u)
                c.subscription_right = 'restricted'
                assert c.can_subscribe(u)
                c.subscription_right = 'private'
                assert c.can_subscribe(u)
                c.subscription_right = 'public'
                assert c.can_subscribe(u)

            assert_subscription_no_perm()
            user.admin = True
            assert_subscription_admin()
            user.admin = False
            user.super_admin = True
            assert_subscription_super_admin()
            user.super_admin = False

        test_channel_subscription(channel, user)
        test_channel_subscription(plugin_channel, user)
        test_channel_subscription(bundle_channel, user)

        # Test get_channels_authorized_subscribers_as_json()
        def test_channel_subscribers(c):
            def assert_no_users():
                assert Channel.get_channels_authorized_subscribers_as_json(
                    [c]) == '{"%d": []}' % c.id

            def assert_only_user(u):
                assert Channel.get_channels_authorized_subscribers_as_json(
                    [c]) == '{"%d": [%d]}' % (c.id, u.id)

            def assert_users(*users):
                for u in json.loads(
                        Channel.get_channels_authorized_subscribers_as_json(
                            [c]))[str(c.id)]:
                    assert u in [u.id for u in users]

            assert_no_users()
            c.safe_add_user(user)
            assert_only_user(user)
            # check that there is no duplicate
            c.safe_add_user(user)
            assert_only_user(user)
            c.removeUser(user)
            c.safe_add_user(user)
            assert_only_user(user)
            c.safe_add_user(user2)
            assert_users(user, user2)
            c.removeUser(user)
            assert_only_user(user2)
            c.removeUser(user2)
            assert_no_users()

        test_channel_subscribers(channel)
        test_channel_subscribers(plugin_channel)
        test_channel_subscribers(bundle_channel)

        # Test get_visible_channels_of()
        def test_visible_channels(u):
            def assert_no_channels():
                assert Channel.get_visible_channels_of(u) == set()

            def assert_channel(c):
                assert Channel.get_visible_channels_of(u) == {c}

            def assert_all_channels():
                assert Channel.get_visible_channels_of(u) == {
                    channel, plugin_channel, bundle_channel
                }

            def assert_public_channels():
                channel.subscription_right = 'restricted'
                assert Channel.get_visible_channels_of(u) == {
                    plugin_channel, bundle_channel
                }
                channel.subscription_right = 'private'
                assert Channel.get_visible_channels_of(u) == {
                    plugin_channel, bundle_channel
                }
                channel.subscription_right = 'public'

            assert_no_channels()
            u.admin = True
            assert_all_channels()
            u.admin = False
            assert_no_channels()
            u.super_admin = True
            assert_all_channels()
            u.super_admin = False
            assert_no_channels()

            screen.addUser(u)
            assert_public_channels()
            screen.removeUser(u)
            assert_no_channels()

            channel.subscription_right = 'restricted'
            assert_no_channels()
            channel.addUser(u)
            assert_channel(channel)
            screen.addUser(u)
            assert_all_channels()
            channel.removeUser(u)
            screen.removeUser(u)
            assert_no_channels()
            channel.subscription_right = 'public'

            plugin_channel.give_permission_to_user(
                u, UserPermissions.channel_contributor)
            assert_channel(plugin_channel)
            plugin_channel.give_permission_to_user(
                u, UserPermissions.channel_administrator)
            assert_channel(plugin_channel)
            plugin_channel.remove_permission_to_user(u)
            assert_no_channels()

        test_visible_channels(user)
        test_visible_channels(user2)

        # Test get_screens_channels_from()
        def test_screens_channels(u):
            def assert_no_channels():
                assert set(Channel.get_screens_channels_from(u)) == set()

            def assert_channel(c):
                assert set(Channel.get_screens_channels_from(u)) == {c}

            def assert_channels(*channels):
                assert set(
                    Channel.get_screens_channels_from(u)) == set(channels)

            def assert_all_channels():
                assert set(Channel.get_screens_channels_from(u)) == {
                    channel, plugin_channel, bundle_channel
                }

            assert_all_channels()
            channel.subscription_right = 'restricted'
            plugin_channel.subscription_right = 'restricted'
            bundle_channel.subscription_right = 'restricted'
            assert_no_channels()
            u.super_admin = True
            assert_all_channels()
            u.super_admin = False
            assert_no_channels()
            channel.addUser(u)
            assert_channel(channel)
            channel.removeUser(u)
            assert_no_channels()
            screen.addUser(user)
            screen.subscribe_to(user, channel)
            assert_channel(channel)
            screen.subscribe_to(user, bundle_channel)
            assert_channels(channel, bundle_channel)

            channel.subscription_right = 'public'
            plugin_channel.subscription_right = 'public'
            bundle_channel.subscription_right = 'public'

        test_screens_channels(user)

        # Test get_preview_link()
        assert channel.get_preview_link(
        ) == '/preview/channels/%d/abcdef' % channel.id