<commit_before>from bottle import request, response, HTTPError

from webrecorder.basecontroller import BaseController
from webrecorder.webreccork import ValidationException
import json


# ============================================================================
class CollsController(BaseController):
    def __init__(self, app, jinja_env, manager, config):
        super(CollsController, self).__init__(app, jinja_env, manager, config)
        self.default_coll_desc = config['coll_desc']

    def init_routes(self):
        @self.app.post('/api/v1/collections')
        def create_collection():
            user = self.get_user(api=True)

            title = request.forms.get('title')
            coll = self.sanitize_title(title)

            collection = self.manager.create_collection(user, coll, title)

            return {'collection': collection}

        @self.app.get('/api/v1/collections')
        def get_collections():
            user = self.get_user(api=True)

            coll_list = self.manager.get_collections(user)

            return {'collections': coll_list}

        @self.app.get('/api/v1/collections/<coll>')
        def get_collection(coll):
            user = self.get_user(api=True)

            return self.get_collection_info(user, coll)

        @self.app.delete('/api/v1/collections/<coll>')
        def delete_collection(coll):
            user = self.get_user(api=True)

            self._ensure_coll_exists(user, coll)

            self.manager.delete_collection(user, coll)

            return {'deleted_id': coll}

        @self.app.post('/api/v1/collections/<coll>/rename/<new_coll_title>')
        def rename_collection(coll, new_coll_title):
            user = self.get_user(api=True)

            self._ensure_coll_exists(user, coll)

            new_coll = self.sanitize_title(new_coll_title)
            print(new_coll)

            self.manager.rename(user=user,
                                coll=coll,
                                new_coll=new_coll,
                                title=new_coll_title)

            return {'id': new_coll, 'title': new_coll_title}

        @self.app.post('/api/v1/collections/<coll>/public')
        def set_public(coll):
            user = self.get_user(api=True)
            self._ensure_coll_exists(user, coll)

            public = self.post_get('public') == 'true'
            self.manager.set_public(user, coll, public)

        @self.app.post('/api/v1/collections/<coll>/desc')
        def update_desc(coll):
            user = self.get_user(api=True)
            self._ensure_coll_exists(user, coll)

            desc = request.body.read().decode('utf-8')

            self.manager.set_coll_desc(user, coll, desc)
            return {}

        @self.app.get('/api/v1/collections/<coll>/num_pages')
        def get_num_pages(coll):
            user = self.get_user(api=True)

            return {'count': self.manager.count_pages(user, coll, rec='*') }

        # Create Collection
        @self.app.get('/_create')
        @self.jinja2_view('create_collection.html')
        def create_coll_view():
            self.manager.assert_logged_in()
            return {}

        @self.app.post('/_create')
        def create_coll_post():
            title = self.post_get('title')
            if not title:
                self.flash_message('Title is required')
                self.redirect('/_create')

            is_public = self.post_get('public') == 'on'

            coll = self.sanitize_title(title)

            user = self.manager.get_curr_user()

            try:
                #self.manager.add_collection(user, coll_name, title, access)
                collection = self.manager.create_collection(user, coll, title,
                                                            desc='', public=is_public)
                self.flash_message('Created collection <b>{0}</b>!'.format(collection['title']), 'success')
                redir_to = self.get_redir_back('/_create')
            except ValidationException as ve:
                self.flash_message(str(ve))
                redir_to = '/_create'

            self.redirect(redir_to)

        @self.app.post(['/_delete_coll'])
        def delete_collection_post():
            user, coll = self.get_user_coll(api=False)

            success = False
            try:
                success = self.manager.delete_collection(user, coll)
            except Exception as e:
                print(e)

            if success:
                self.flash_message('Collection {0} has been deleted!'.format(coll), 'success')

                if self.manager.is_anon(user):
                    self.get_session().delete()

                self.redirect(self.get_path(user))
            else:
                self.flash_message('There was an error deleting {0}'.format(coll))
                self.redirect(self.get_path(user, coll))

        # Collection view (all recordings)
        @self.app.get(['/<user>/<coll>', '/<user>/<coll>/'])
        @self.jinja2_view('collection_info.html')
        def coll_info(user, coll):
            return self.get_collection_info_for_view(user, coll)

        @self.app.get(['/<user>/<coll>/<rec_list>', '/<user>/<coll>/<rec_list>/'])
        @self.jinja2_view('collection_info.html')
        def coll_info(user, coll, rec_list):
            rec_list = [self.sanitize_title(title) for title in rec_list.split(',')]
            return self.get_collection_info_for_view(user, coll, rec_list)

    def get_collection_info_for_view(self, user, coll, rec_list=None):
        result = self.get_collection_info(user, coll)
        if result.get('error_message'):
            self._raise_error(404, 'Collection not found')

        result['size_remaining'] = self.manager.get_size_remaining(user)
        result['user'] = self.get_view_user(user)
        result['coll'] = coll
        result['bookmarks'] = []

        result['rec_title'] = ''
        result['coll_title'] = result['collection']['title']

        for rec in result['collection']['recordings']:
           rec['pages'] = self.manager.list_pages(user, coll, rec['id'])
           result['bookmarks'].append(rec['pages'])

        if not result['collection'].get('desc'):
            result['collection']['desc'] = self.default_coll_desc.format(result['coll_title'])

        rec_list = rec_list or []
        result['rec_list'] = json.dumps(rec_list)

        return result

    def get_collection_info(self, user, coll):
        collection = self.manager.get_collection(user, coll)

        if not collection:
            response.status = 404
            return {'error_message': 'Collection not found', 'id': coll}

        return {'collection': collection}

    def _ensure_coll_exists(self, user, coll):
        if not self.manager.has_collection(user, coll):
            self._raise_error(404, 'Collection not found', api=True, id=coll)

<commit_msg>delete coll: if deleting the temp collection, redirect to home page after<commit_after>from bottle import request, response, HTTPError

from webrecorder.basecontroller import BaseController
from webrecorder.webreccork import ValidationException
import json


# ============================================================================
class CollsController(BaseController):
    def __init__(self, app, jinja_env, manager, config):
        super(CollsController, self).__init__(app, jinja_env, manager, config)
        self.default_coll_desc = config['coll_desc']

    def init_routes(self):
        @self.app.post('/api/v1/collections')
        def create_collection():
            user = self.get_user(api=True)

            title = request.forms.get('title')
            coll = self.sanitize_title(title)

            collection = self.manager.create_collection(user, coll, title)

            return {'collection': collection}

        @self.app.get('/api/v1/collections')
        def get_collections():
            user = self.get_user(api=True)

            coll_list = self.manager.get_collections(user)

            return {'collections': coll_list}

        @self.app.get('/api/v1/collections/<coll>')
        def get_collection(coll):
            user = self.get_user(api=True)

            return self.get_collection_info(user, coll)

        @self.app.delete('/api/v1/collections/<coll>')
        def delete_collection(coll):
            user = self.get_user(api=True)

            self._ensure_coll_exists(user, coll)

            self.manager.delete_collection(user, coll)

            return {'deleted_id': coll}

        @self.app.post('/api/v1/collections/<coll>/rename/<new_coll_title>')
        def rename_collection(coll, new_coll_title):
            user = self.get_user(api=True)

            self._ensure_coll_exists(user, coll)

            new_coll = self.sanitize_title(new_coll_title)
            print(new_coll)

            self.manager.rename(user=user,
                                coll=coll,
                                new_coll=new_coll,
                                title=new_coll_title)

            return {'id': new_coll, 'title': new_coll_title}

        @self.app.post('/api/v1/collections/<coll>/public')
        def set_public(coll):
            user = self.get_user(api=True)
            self._ensure_coll_exists(user, coll)

            public = self.post_get('public') == 'true'
            self.manager.set_public(user, coll, public)

        @self.app.post('/api/v1/collections/<coll>/desc')
        def update_desc(coll):
            user = self.get_user(api=True)
            self._ensure_coll_exists(user, coll)

            desc = request.body.read().decode('utf-8')

            self.manager.set_coll_desc(user, coll, desc)
            return {}

        @self.app.get('/api/v1/collections/<coll>/num_pages')
        def get_num_pages(coll):
            user = self.get_user(api=True)

            return {'count': self.manager.count_pages(user, coll, rec='*') }

        # Create Collection
        @self.app.get('/_create')
        @self.jinja2_view('create_collection.html')
        def create_coll_view():
            self.manager.assert_logged_in()
            return {}

        @self.app.post('/_create')
        def create_coll_post():
            title = self.post_get('title')
            if not title:
                self.flash_message('Title is required')
                self.redirect('/_create')

            is_public = self.post_get('public') == 'on'

            coll = self.sanitize_title(title)

            user = self.manager.get_curr_user()

            try:
                #self.manager.add_collection(user, coll_name, title, access)
                collection = self.manager.create_collection(user, coll, title,
                                                            desc='', public=is_public)
                self.flash_message('Created collection <b>{0}</b>!'.format(collection['title']), 'success')
                redir_to = self.get_redir_back('/_create')
            except ValidationException as ve:
                self.flash_message(str(ve))
                redir_to = '/_create'

            self.redirect(redir_to)

        @self.app.post(['/_delete_coll'])
        def delete_collection_post():
            user, coll = self.get_user_coll(api=False)

            success = False
            try:
                success = self.manager.delete_collection(user, coll)
            except Exception as e:
                print(e)

            if success:
                self.flash_message('Collection {0} has been deleted!'.format(coll), 'success')

                # if anon user/temp collection, delete user and redirect to homepage
                if self.manager.is_anon(user):
                    self.get_session().delete()
                    self.redirect('/')
                else:
                    self.redirect(self.get_path(user))

            else:
                self.flash_message('There was an error deleting {0}'.format(coll))
                self.redirect(self.get_path(user, coll))

        # Collection view (all recordings)
        @self.app.get(['/<user>/<coll>', '/<user>/<coll>/'])
        @self.jinja2_view('collection_info.html')
        def coll_info(user, coll):
            return self.get_collection_info_for_view(user, coll)

        @self.app.get(['/<user>/<coll>/<rec_list>', '/<user>/<coll>/<rec_list>/'])
        @self.jinja2_view('collection_info.html')
        def coll_info(user, coll, rec_list):
            rec_list = [self.sanitize_title(title) for title in rec_list.split(',')]
            return self.get_collection_info_for_view(user, coll, rec_list)

    def get_collection_info_for_view(self, user, coll, rec_list=None):
        result = self.get_collection_info(user, coll)
        if result.get('error_message'):
            self._raise_error(404, 'Collection not found')

        result['size_remaining'] = self.manager.get_size_remaining(user)
        result['user'] = self.get_view_user(user)
        result['coll'] = coll
        result['bookmarks'] = []

        result['rec_title'] = ''
        result['coll_title'] = result['collection']['title']

        for rec in result['collection']['recordings']:
           rec['pages'] = self.manager.list_pages(user, coll, rec['id'])
           result['bookmarks'].append(rec['pages'])

        if not result['collection'].get('desc'):
            result['collection']['desc'] = self.default_coll_desc.format(result['coll_title'])

        rec_list = rec_list or []
        result['rec_list'] = json.dumps(rec_list)

        return result

    def get_collection_info(self, user, coll):
        collection = self.manager.get_collection(user, coll)

        if not collection:
            response.status = 404
            return {'error_message': 'Collection not found', 'id': coll}

        return {'collection': collection}

    def _ensure_coll_exists(self, user, coll):
        if not self.manager.has_collection(user, coll):
            self._raise_error(404, 'Collection not found', api=True, id=coll)


{'fraction_non_alphanumeric': 0.13486513486513488, 'fraction_numerical': 0.0034251462822891396, 'mean_word_length': 2.208562271062271, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2968134', 'n_tokens_mistral': 4095, 'n_tokens_neox': 3924, 'n_words': 695}