# Path: yithlibraryserver/backups/utils.py
# def get_backup_filename(date):
#     return 'yith-library-backup-%d-%02d-%02d.yith' % (
#         date.year, date.month, date.day)
# 
# Path: yithlibraryserver/backups/utils.py
# def get_user_passwords(db, user):
#     passwords_manager = PasswordsManager(db)
#     return [remove_attrs(password, 'owner', '_id')
#             for password in passwords_manager.retrieve(user)]
# 
# Path: yithlibraryserver/backups/utils.py
# def compress(passwords):
#     buf = BytesIO()
#     gzip_data = gzip.GzipFile(fileobj=buf, mode='wb')
#     data = json.dumps(passwords)
#     gzip_data.write(data.encode('utf-8'))
#     gzip_data.close()
#     return buf.getvalue()
# 
# def uncompress(compressed_data):
#     buf = BytesIO(compressed_data)
#     gzip_data = gzip.GzipFile(fileobj=buf, mode='rb')
#     raw_data = gzip_data.read()
#     return json.loads(raw_data.decode('utf-8'))
# 
# Path: yithlibraryserver/i18n.py
# def deform_translator(term):
# def locale_negotiator(request):
# 
# Path: yithlibraryserver/i18n.py
# def deform_translator(term):
# def locale_negotiator(request):
# 
# Path: yithlibraryserver/password/models.py
# class PasswordsManager(object):
# 
#     def __init__(self, db):
#         self.db = db
# 
#     def create(self, user, password):
#         """Creates and returns a new password or a set of passwords.
# 
#         Stores the password in the database for this specific user
#         and returns a new dict with the 'owner' and '_id' fields
#         filled.
# 
#         If password is a list, do the same with each password in
#         this list.
#         """
#         if isinstance(password, dict):
#             if password:
#                 new_password = dict(password)  # copy since we are changing this object
#                 new_password['owner'] = user['_id']
#                 _id = self.db.passwords.insert(new_password, safe=True)
#                 new_password['_id'] = _id
#                 return new_password
#         else:
#             new_passwords = []  # copy since we are changing this object
#             for p in password:
#                 if p:
#                     p = dict(p)
#                     p['owner'] = user['_id']
#                     new_passwords.append(p)
# 
#             if new_passwords:
# 
#                 _ids = self.db.passwords.insert(new_passwords, safe=True)
# 
#                 for i in range(len(new_passwords)):
#                     new_passwords[i]['_id'] = _ids[i]
# 
#                 return new_passwords
# 
#     def retrieve(self, user, _id=None):
#         """Return the user's passwords or just one.
# 
#         If _id is None return the whole set of passwords for this
#         user. Otherwise, it returns the password with that _id.
#         """
#         if _id is None:
#             return self.db.passwords.find({'owner': user['_id']})
#         else:
#             return self.db.passwords.find_one({
#                     '_id': _id,
#                     'owner': user['_id'],
#                     })
# 
#     def update(self, user, _id, password):
#         """Update a password in the database.
# 
#         Return the updated password on success or None if the original
#         password does not exist.
#         """
#         new_password = dict(password)  # copy since we are changing this object
#         new_password['owner'] = user['_id']
#         result = self.db.passwords.update({
#                 '_id': _id,
#                 'owner': user['_id'],
#                 }, new_password, safe=True)
#         new_password['_id'] = _id
# 
#         # result['n'] is the number of documents updated
#         # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue
#         if result['n'] == 1:
#             return new_password
#         else:
#             return None
# 
#     def delete(self, user, _id=None):
#         """Deletes a password from the database or the whole set for this user.
# 
#         Returns True if the delete is succesfull or False otherwise.
#         """
#         query = {'owner': user['_id']}
#         if _id is not None:
#             query['_id'] = _id
# 
#         result = self.db.passwords.remove(query, safe=True)
#         return result['n'] > 0


from pyramid.i18n import get_localizer
from pyramid.httpexceptions import HTTPFound
from pyramid.response import Response
from pyramid.view import view_config
from yithlibraryserver.backups.utils import get_backup_filename
from yithlibraryserver.backups.utils import get_user_passwords
from yithlibraryserver.backups.utils import compress, uncompress
from yithlibraryserver.i18n import translation_domain
from yithlibraryserver.i18n import TranslationString as _
from yithlibraryserver.password.models import PasswordsManager
    today = request.date_service.today()
    filename = get_backup_filename(today)
    response.content_disposition = 'attachment; filename=%s' % filename
    return response


@view_config(route_name='backups_import',
             renderer='string',
             permission='backups')
def backups_import(request):
    response = HTTPFound(location=request.route_path('backups_index'))

    if 'passwords-file' in request.POST:
        passwords_field = request.POST['passwords-file']
        if passwords_field != '':
            try:
                json_data = uncompress(passwords_field.file.read())
                passwords_manager = PasswordsManager(request.db)
                passwords_manager.delete(request.user)
                passwords_manager.create(request.user, json_data)
            except (IOError, ValueError):
                request.session.flash(
                    _('There was a problem reading your passwords file'),
                    'error')
                return response

            n_passwords = len(json_data)
            localizer = get_localizer(request)
            msg = localizer.pluralize(
                _('Congratulations, ${n_passwords} password has been imported'),

# Path: yithlibraryserver/backups/utils.py
# def get_backup_filename(date):
#     return 'yith-library-backup-%d-%02d-%02d.yith' % (
#         date.year, date.month, date.day)
# 
# Path: yithlibraryserver/backups/utils.py
# def get_user_passwords(db, user):
#     passwords_manager = PasswordsManager(db)
#     return [remove_attrs(password, 'owner', '_id')
#             for password in passwords_manager.retrieve(user)]
# 
# Path: yithlibraryserver/backups/utils.py
# def compress(passwords):
#     buf = BytesIO()
#     gzip_data = gzip.GzipFile(fileobj=buf, mode='wb')
#     data = json.dumps(passwords)
#     gzip_data.write(data.encode('utf-8'))
#     gzip_data.close()
#     return buf.getvalue()
# 
# def uncompress(compressed_data):
#     buf = BytesIO(compressed_data)
#     gzip_data = gzip.GzipFile(fileobj=buf, mode='rb')
#     raw_data = gzip_data.read()
#     return json.loads(raw_data.decode('utf-8'))
# 
# Path: yithlibraryserver/i18n.py
# def deform_translator(term):
# def locale_negotiator(request):
# 
# Path: yithlibraryserver/i18n.py
# def deform_translator(term):
# def locale_negotiator(request):
# 
# Path: yithlibraryserver/password/models.py
# class PasswordsManager(object):
# 
#     def __init__(self, db):
#         self.db = db
# 
#     def create(self, user, password):
#         """Creates and returns a new password or a set of passwords.
# 
#         Stores the password in the database for this specific user
#         and returns a new dict with the 'owner' and '_id' fields
#         filled.
# 
#         If password is a list, do the same with each password in
#         this list.
#         """
#         if isinstance(password, dict):
#             if password:
#                 new_password = dict(password)  # copy since we are changing this object
#                 new_password['owner'] = user['_id']
#                 _id = self.db.passwords.insert(new_password, safe=True)
#                 new_password['_id'] = _id
#                 return new_password
#         else:
#             new_passwords = []  # copy since we are changing this object
#             for p in password:
#                 if p:
#                     p = dict(p)
#                     p['owner'] = user['_id']
#                     new_passwords.append(p)
# 
#             if new_passwords:
# 
#                 _ids = self.db.passwords.insert(new_passwords, safe=True)
# 
#                 for i in range(len(new_passwords)):
#                     new_passwords[i]['_id'] = _ids[i]
# 
#                 return new_passwords
# 
#     def retrieve(self, user, _id=None):
#         """Return the user's passwords or just one.
# 
#         If _id is None return the whole set of passwords for this
#         user. Otherwise, it returns the password with that _id.
#         """
#         if _id is None:
#             return self.db.passwords.find({'owner': user['_id']})
#         else:
#             return self.db.passwords.find_one({
#                     '_id': _id,
#                     'owner': user['_id'],
#                     })
# 
#     def update(self, user, _id, password):
#         """Update a password in the database.
# 
#         Return the updated password on success or None if the original
#         password does not exist.
#         """
#         new_password = dict(password)  # copy since we are changing this object
#         new_password['owner'] = user['_id']
#         result = self.db.passwords.update({
#                 '_id': _id,
#                 'owner': user['_id'],
#                 }, new_password, safe=True)
#         new_password['_id'] = _id
# 
#         # result['n'] is the number of documents updated
#         # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue
#         if result['n'] == 1:
#             return new_password
#         else:
#             return None
# 
#     def delete(self, user, _id=None):
#         """Deletes a password from the database or the whole set for this user.
# 
#         Returns True if the delete is succesfull or False otherwise.
#         """
#         query = {'owner': user['_id']}
#         if _id is not None:
#             query['_id'] = _id
# 
#         result = self.db.passwords.remove(query, safe=True)
#         return result['n'] > 0


# Path: yithlibraryserver/backups/views.py
from pyramid.i18n import get_localizer
from pyramid.httpexceptions import HTTPFound
from pyramid.response import Response
from pyramid.view import view_config
from yithlibraryserver.backups.utils import get_backup_filename
from yithlibraryserver.backups.utils import get_user_passwords
from yithlibraryserver.backups.utils import compress, uncompress
from yithlibraryserver.i18n import translation_domain
from yithlibraryserver.i18n import TranslationString as _
from yithlibraryserver.password.models import PasswordsManager

    today = request.date_service.today()
    filename = get_backup_filename(today)
    response.content_disposition = 'attachment; filename=%s' % filename
    return response


@view_config(route_name='backups_import',
             renderer='string',
             permission='backups')
def backups_import(request):
    response = HTTPFound(location=request.route_path('backups_index'))

    if 'passwords-file' in request.POST:
        passwords_field = request.POST['passwords-file']
        if passwords_field != '':
            try:
                json_data = uncompress(passwords_field.file.read())
                passwords_manager = PasswordsManager(request.db)
                passwords_manager.delete(request.user)
                passwords_manager.create(request.user, json_data)
            except (IOError, ValueError):
                request.session.flash(
                    _('There was a problem reading your passwords file'),
                    'error')
                return response

            n_passwords = len(json_data)
            localizer = get_localizer(request)
            msg = localizer.pluralize(
                _('Congratulations, ${n_passwords} password has been imported'),

                _('Congratulations, ${n_passwords} passwords have been imported'),