Example #1
0
    def POST_AUTH(self, capsule_id, channel):
        try:
            post_data = flask.request.get_json(force=True)
        except JSONDecodeError:
            resp.badrequest()

        try:
            c = EditorCapsule.selectBy(id=int(capsule_id),
                                       channel=channel).getOne()
        except SQLObjectNotFound:
            resp.notfound()

        if {'duration', 'template', 'content'} != set(post_data.keys()):
            resp.badrequest()
        try:
            s = EditorSlide(s_order=c.slides.count(), capsule=c, **post_data)
        except SQLObjectIntegrityError:
            resp.badrequest()

        EditorSlide.rectify_s_order(c.id)
        response = resp.created()
        response.header[
            'Location'] = '/channels/{}/api/capsules/{}/slides/{}'.format(
                channel.id, capsule_id, s.id)
        return response
Example #2
0
 def get(self, bundle_id):
     try:
         bundle = ChannelBundle.get(bundle_id)
         u = User.get(self.session['user']['id'])
     except SQLObjectNotFound:
         resp.notfound()
     return self.render_page(bundle, u)
Example #3
0
 def get(self, mac):
     """ Redirects a screen with its given mac to its secret link. """
     try:
         screen = ScreenMac.selectBy(mac=mac).getOne().screen
     except SQLObjectNotFound:
         resp.notfound()
     resp.seeother(screen.get_view_link())
Example #4
0
 def DELETE_AUTH(self, capsule_id, channel):
     try:
         c = EditorCapsule.selectBy(id=int(capsule_id),
                                    channel=channel).getOne()
         c.destroySelf()
     except SQLObjectNotFound:
         resp.notfound()
     resp.nocontent()
Example #5
0
 def get(self, screen_id):
     try:
         screen = Screen.get(screen_id)
         u = User.get(self.session['user']['id'])
         if not (UserPermissions.administrator in u.highest_permission_level or screen in u.screens):
             resp.forbidden()
     except SQLObjectNotFound:
         resp.notfound()
     return self.render_page(screen, u)
Example #6
0
 def GET_AUTH(self, capsule_id, slide_id, channel):
     try:
         EditorCapsule.selectBy(id=int(capsule_id),
                                channel=channel).getOne()
         return EditorSlide.selectBy(
             id=int(slide_id),
             capsule=int(capsule_id)).getOne().to_json_api()
     except SQLObjectNotFound:
         resp.notfound()
Example #7
0
 def post(self, channel):
     url = flask.request.get_data().decode()
     if FeedGetter._is_url(url):
         r = flask.Response(
             json.dumps(feedparser_parse(url).entries, cls=DateTimeEncoder))
         r.headers["Content-Type"] = "application/json"
         try:
             return r
         except TypeError:
             return "Feed could not be parsed"
     resp.notfound()
Example #8
0
 def get(self, asset_id):
     """ Waits for the given asset to be downloaded. Redirects the user to the asset when done. """
     try:
         asset_id = int(asset_id)
         if self.download_manager.has_pending_task_for_asset(asset_id):
             task = self.download_manager.get_pending_task_for_asset(asset_id)
             task.result()
         resp.seeother('/' + Asset.get(asset_id)._get_path(force=True))  # Task is complete but asset may be still marked as in flight
     except SQLObjectNotFound:
         resp.notfound()
     except KeyError:
         resp.seeother('/cache/' + str(asset_id))
Example #9
0
    def get(self, file):
        path = os.path.join(get_root_path(), 'client', 'ks', file)
        if os.path.exists(path):
            flags = 'r'
            if self._path_has_ext(path, 'zip'):
                flags += 'b'
                make_client_zip()
            with open(path, flags) as f:
                content = f.read()
            if self._path_has_ext(path, 'ks') or self._path_has_ext(path, 'cfg'):
                content = content.format(ictv_root_url=flask.g.homedomain, **self.config['client'])

            response = flask.Response(content)
            response.headers['Content-Type'] = 'application/zip'
            return response
        resp.notfound()
Example #10
0
    def PATCH_AUTH(self, capsule_id, channel):
        try:
            post_data = flask.request.get_json(force=True)
        except JSONDecodeError:
            resp.badrequest()

        try:
            c = EditorCapsule.selectBy(id=int(capsule_id),
                                       channel=channel).getOne()
        except SQLObjectNotFound:
            resp.notfound()

        if 'name' in post_data and len(post_data['name']) < 3:
            resp.badrequest()

        if 'validity' in post_data:
            validity_from, validity_to = post_data['validity']
            if not (type(validity_from) == type(validity_to) ==
                    int) or validity_to < validity_from:
                resp.badrequest()
            try:
                validity_from, validity_to = datetime.fromtimestamp(
                    validity_from), datetime.fromtimestamp(validity_to)
            except (TypeError, ValueError):
                resp.badrequest()
            post_data['validity_from'] = validity_from
            post_data['validity_to'] = validity_to
            del post_data['validity']

        update_dict = {
            k: v
            for k, v in filter(
                lambda x: x[0] in
                ['name', 'theme', 'validity_from', 'validity_to'],
                post_data.items())
        }
        try:
            c.set(**update_dict)
        except DuplicateEntryError:
            resp.badrequest()

        resp.nocontent()
Example #11
0
    def PATCH_AUTH(self, capsule_id, slide_id, channel):
        try:
            post_data = flask.request.get_json(force=True)
        except JSONDecodeError:
            resp.badrequest()

        try:
            c = EditorCapsule.selectBy(id=int(capsule_id),
                                       channel=channel).getOne()
            s = EditorSlide.selectBy(id=int(slide_id), capsule=c).getOne()
        except SQLObjectNotFound:
            resp.notfound()

        update_dict = {
            k: v
            for k, v in filter(
                lambda x: x[0] in ['duration', 'template', 'content'],
                post_data.items())
        }
        s.set(**update_dict)

        resp.nocontent()
Example #12
0
    def authenticate(self):
        """ Authenticates the request according to the API key and returns the channel. """
        if len(flask.g.homepath) > 0:  # We are in a sub-app
            channelid = re.findall(r'\d+', flask.g.homepath)[0]
        else:  # We are in the core app
            channelid = re.findall(r'\d+', flask.g.path)[0]
        try:
            channel = PluginChannel.get(channelid)
        except SQLObjectNotFound:
            resp.notfound()

        try:
            if not channel.get_config_param('enable_rest_api'):
                resp.forbidden()
            if not (channel.get_config_param('api_key') or '').strip():
                resp.forbidden()
            if (channel.get_config_param('api_key')
                    or '').strip() != flask.request.environ.get(
                        'HTTP_X_ICTV_EDITOR_API_KEY', '').strip():
                resp.forbidden()
        except KeyError:
            resp.forbidden()

        return channel
Example #13
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)
Example #14
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)