Esempio n. 1
0
def view_books_by_id(request, scheme):
    """
    Find books with IDs of the requested schema, and return mapping of
    IDs to urls that match those books.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request.
    @type scheme: C{string}
    """
    logWarning("looking for books with %r identifier" % scheme)
    from booki.bookizip import DC
    from booki.editor.views import getVersion
    from urllib import urlencode
    namefilter = '{%s}identifier{%s}' % (DC, scheme)
    data = {}

    #from django.db import connection, transaction
    #cursor = connection.cursor()
    books = models.Book.objects.raw('SELECT editor_book.*, editor_info.value_string AS remote_id'
                                    ' FROM editor_book LEFT OUTER JOIN editor_info ON'
                                    ' (editor_book.id=editor_info.book_id) WHERE'
                                    ' editor_info.name=%s',  (namefilter,))

    for book in books:
        if book.hidden:
            continue
        values = data.setdefault(book.remote_id, [])
        values.append(book)
        logWarning(values)
    #data keys are identifiers in the set scheme, and the values are
    # a list of books with that identifier.
    #
    # depending on the mode, some books will be dropped.
    logWarning(data)
    selected_books = []
    for ID, books in data.iteritems():
        for book in books:
            if _is_book_modified(book):
                selected_books.append((ID, book.url_title, True))
                break
        else:
            selected_books.append((ID, books[0].url_title, False))

    msg = {}
    for ID, booki_id, modified in selected_books:
        msg[ID] = {'edit': '%s/%s/edit/' % (BOOKI_URL, booki_id), #edit link
                   'epub': (None if not modified                  #epub link
                            else  OBJAVI_URL + '?' + urlencode(
                                {'server': THIS_BOOKI_SERVER,
                                 'book': booki_id,
                                 'mode': 'epub',
                                 'destination': 'download',
                                 })
                            )
                   }

    s = json.dumps(msg)

    response = HttpResponse(s, mimetype="application/json")
    return response
Esempio n. 2
0
def view_books_autocomplete(request, *args, **kwargs):
    """
    Returns data for jQuery UI autocomplete.
    
    @param request: Django Request.
    
    """

    term = request.GET.get("term", "").lower()
    book = request.GET.get("book", "").lower()

    if not book:
        books = models.Book.objects.filter(hidden=False).order_by("title")
        data = [dict(label_no_use=book.title, value=book.url_title) 
                for book in books
                if not term or (term in book.title.lower() or
                                term in book.url_title)]
    else:
        chapters = models.Chapter.objects.filter(book__url_title=book)
        data = [dict(label_no_use=chapter.title, value=chapter.url_title)
                for chapter in chapters
                if not term or (term in chapter.title.lower() or 
                                term in chapter.url_title)]

    return HttpResponse(json.dumps(data), "text/plain")
Esempio n. 3
0
def view_books_by_id(request, scheme):
    """
    Find books with IDs of the requested schema, and return mapping of
    IDs to urls that match those books.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request.
    @type scheme: C{string}
    """
    logWarning("looking for books with %r identifier" % scheme)
    from booki.bookizip import DC
    from booki.editor.views import getVersion
    from urllib import urlencode
    namefilter = '{%s}identifier{%s}' % (DC, scheme)
    data = {}

    #from django.db import connection, transaction
    #cursor = connection.cursor()
    books = models.Book.objects.raw('SELECT editor_book.*, editor_info.value_string AS remote_id'
                                    ' FROM editor_book LEFT OUTER JOIN editor_info ON'
                                    ' (editor_book.id=editor_info.book_id) WHERE'
                                    ' editor_info.name=%s',  (namefilter,))

    for book in books:
        if book.hidden:
            continue
        values = data.setdefault(book.remote_id, [])
        values.append(book)
        logWarning(values)
    #data keys are identifiers in the set scheme, and the values are
    # a list of books with that identifier.
    #
    # depending on the mode, some books will be dropped.
    logWarning(data)
    selected_books = []
    for ID, books in data.iteritems():
        for book in books:
            if _is_book_modified(book):
                selected_books.append((ID, book.url_title, True))
                break
        else:
            selected_books.append((ID, books[0].url_title, False))

    msg = {}
    for ID, booki_id, modified in selected_books:
        msg[ID] = {'edit': '%s/%s/edit/' % (BOOKI_URL, booki_id), #edit link
                   'epub': (None if not modified                  #epub link
                            else  OBJAVI_URL + '?' + urlencode(
                                {'server': THIS_BOOKI_SERVER,
                                 'book': booki_id,
                                 'mode': 'epub',
                                 'destination': 'download',
                                 })
                            )
                   }

    s = json.dumps(msg)

    response = HttpResponse(s, mimetype="application/json")
    return response
Esempio n. 4
0
def view_books_autocomplete(request, *args, **kwargs):
    """
    Returns data for jQuery UI autocomplete.
    
    @param request: Django Request.
    
    """

    term = request.GET.get("term", "").lower()
    book = request.GET.get("book", "").lower()

    if not book:
        books = models.Book.objects.filter(hidden=False).order_by("title")
        data = [dict(label_no_use=book.title, value=book.url_title) 
                for book in books
                if not term or (term in book.title.lower() or
                                term in book.url_title)]
    else:
        chapters = models.Chapter.objects.filter(book__url_title=book)
        data = [dict(label_no_use=chapter.title, value=chapter.url_title)
                for chapter in chapters
                if not term or (term in chapter.title.lower() or 
                                term in chapter.url_title)]

    return HttpResponse(json.dumps(data), "text/plain")
Esempio n. 5
0
 def finish(self):
     """Finalise the metadata and write to disk"""
     self.info['manifest'] = self.manifest
     infojson = json.dumps(self.info, indent=2)
     self.add_to_package('info.json', 'info.json', infojson,
                         'application/json')
     self._close()
Esempio n. 6
0
    def handle(self, *args, **options):
        if not hasattr(settings, 'BOOKTYPE_CONFIG'):
            raise CommandError('Does not have BOOKTYPE_CONFIG in settings.py file.')

        if len(args) != 1:
            raise CommandError("You must specify variable name")

        if not settings.BOOKTYPE_CONFIG.has_key(args[0]):
            raise CommandError("There is no such variable.")

        value = settings.BOOKTYPE_CONFIG[args[0]]

        if options['as_json']:
            value = json.dumps(value)

        self.stdout.write(str(value)+"\n")
Esempio n. 7
0
    def handle(self, *args, **options):
        if not hasattr(settings, 'BOOKTYPE_CONFIG'):
            raise CommandError(
                'Does not have BOOKTYPE_CONFIG in settings.py file.')

        if len(args) != 1:
            raise CommandError("You must specify variable name")

        if not settings.BOOKTYPE_CONFIG.has_key(args[0]):
            raise CommandError("There is no such variable.")

        value = settings.BOOKTYPE_CONFIG[args[0]]

        if options['as_json']:
            value = json.dumps(value)

        self.stdout.write(str(value) + "\n")
Esempio n. 8
0
def import_book(request, username):
    """
    Django View. Book Import dialog.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    @type username: C{string}
    @param username: Username.
    """

    from django.contrib.auth.models import User
    from booki.utils.misc import isBookLimitReached

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            resp = pages.ErrorPage(request, "errors/user_does_not_exist.html",
                                   {"username": username})
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    if isBookLimitReached() or not request.user.is_authenticated():
        try:
            resp = pages.ErrorPage(request, "errors/no_permissions.html")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    from booki.utils.book import checkGroupAvailability, createBookiGroup
    from booki.editor import models

    if request.GET.get("q", "") == "check":
        from booki.utils.json_wrapper import json

        data = {
            "available":
            checkGroupAvailability(request.GET.get('groupname', '').strip())
        }

        try:
            resp = HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    book_visible = config.getConfiguration('CREATE_BOOK_VISIBLE')
    admin_import = config.getConfiguration('ADMIN_IMPORT_BOOKS')

    if request.user.is_superuser:
        admin_import = False

    if request.GET.get("q", "") == "import" and admin_import == False:
        from booki.utils.json_wrapper import json

        data = {}

        try:
            bookid = request.GET.get('source', '')
            importType = request.GET.get('importtype', '')
            renameTitle = request.GET.get('title', '')

            extraOptions = {}

            if renameTitle:
                extraOptions['book_title'] = renameTitle

            if request.GET.get('hidden', '') != '':
                extraOptions['hidden'] = True

            ESPRI_URL = config.getConfiguration('ESPRI_URL')

            importSources = {
                "archive": (ESPRI_URL, "archive.org"),
                "wikibooks": (ESPRI_URL, "wikibooks"),
                "epub": (ESPRI_URL, "url"),
            }

            if importType == "booki":
                bookid = bookid.rstrip('/')
                booki_url, book_url_title = bookid.rsplit("/", 1)
                base_url = "%s/export/%s/export" % (booki_url, book_url_title)
                source = "booki"
            else:
                base_url, source = importSources[importType]

            book = common.importBookFromUrl2(user,
                                             base_url,
                                             args=dict(source=source,
                                                       book=bookid),
                                             **extraOptions)
        except Exception:
            data['imported'] = False
            transaction.rollback()
        else:
            transaction.commit()
            data['imported'] = True

            from django.core.urlresolvers import reverse
            data['info_url'] = reverse('book_info', args=[book.url_title])

        try:
            resp = HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    try:
        resp = render_to_response(
            'account/import_book.html', {
                "request": request,
                "book_visible": book_visible,
                "admin_import": admin_import,
                "user": user
            })
    except:
        transaction.rollback()
        raise
    else:
        transaction.commit()

    return resp
Esempio n. 9
0
def create_group(request, username):
    """
    Django View. Show content for Create Group dialog and creates group.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    @type username: C{string}
    @param username: Username.
    """

    from django.contrib.auth.models import User

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            resp = pages.ErrorPage(request, "errors/user_does_not_exist.html",
                                   {"username": username})
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    if not request.user.is_authenticated():
        try:
            resp = pages.ErrorPage(request, "errors/no_permissions.html")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    from booki.utils.book import checkGroupAvailability, createBookiGroup
    from booki.editor import models

    if request.GET.get("q", "") == "check":
        from booki.utils.json_wrapper import json

        data = {
            "available":
            checkGroupAvailability(request.GET.get('groupname', '').strip())
        }

        try:
            resp = HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    if request.GET.get("q", "") == "create":
        from booki.utils.json_wrapper import json

        groupName = request.GET.get('name', '').strip()
        groupDescription = request.GET.get('description', '').strip()

        groupCreated = False

        if checkGroupAvailability(groupName):
            try:
                group = createBookiGroup(groupName, groupDescription,
                                         request.user)
                group.members.add(request.user)
                groupCreated = True
            except BookiGroupExist:
                groupCreated = False
                transaction.rollback()
            else:
                transaction.commit()

        data = {'created': groupCreated}

        try:
            resp = HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    try:
        resp = render_to_response('account/create_group.html', {
            "request": request,
            "user": user
        })
    except:
        transaction.rollback()
        raise
    else:
        transaction.commit()

    return resp
Esempio n. 10
0
def create_book(request, username):
    """
    Django View. Show content for Create Book dialog and creates book.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    @type username: C{string}
    @param username: Username.
    """

    from django.contrib.auth.models import User
    from booki.utils.misc import isBookLimitReached

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            resp = pages.ErrorPage(request, "errors/user_does_not_exist.html",
                                   {"username": username})
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    if isBookLimitReached() or not request.user.is_authenticated():
        try:
            resp = pages.ErrorPage(request, "errors/no_permissions.html")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    from booki.utils.book import checkBookAvailability, createBook
    from booki.editor import models

    book_visible = config.getConfiguration('CREATE_BOOK_VISIBLE')
    book_license = config.getConfiguration('CREATE_BOOK_LICENSE')
    admin_create = config.getConfiguration('ADMIN_CREATE_BOOKS')

    if request.user.is_superuser:
        admin_create = False

    if request.GET.get("q", "") == "check":
        from booki.utils.json_wrapper import json

        data = {
            "available":
            checkBookAvailability(request.GET.get('bookname', '').strip())
        }

        try:
            resp = HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    if request.method == 'POST' and admin_create == False:
        book = None
        try:
            # hidden on
            # description
            # license
            # title
            # cover

            book = createBook(request.user, request.POST.get('title'))

            lic = models.License.objects.get(
                abbrevation=request.POST.get('license'))
            book.license = lic
            book.description = request.POST.get('description', '')

            if request.POST.get("hidden", "") == "on":
                is_hidden = True
            else:
                is_hidden = False
            book.hidden = is_hidden

            from django.core.files import File

            if request.FILES.has_key('cover'):
                # TODO: Show some kind of error message to the user
                from booki.utils import misc
                import os

                try:
                    fh, fname = misc.saveUploadedAsFile(request.FILES['cover'])
                    book.setCover(fname)
                    os.unlink(fname)
                except:
                    pass

            book.save()

        except:
            transaction.rollback()
        else:
            transaction.commit()

        try:
            resp = render_to_response('account/create_book_redirect.html', {
                "request": request,
                "user": user,
                "book": book
            })
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    from booki.editor.models import License

    licenses = License.objects.all().order_by('name')

    try:
        resp = render_to_response(
            'account/create_book.html', {
                "request": request,
                "book_visible": book_visible,
                "book_license": book_license,
                "admin_create": admin_create,
                "licenses": licenses,
                "user": user
            })
    except:
        transaction.rollback()
        raise
    else:
        transaction.commit()

    return resp
Esempio n. 11
0
def import_book(request, username):
    """
    Django View. Book Import dialog.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    @type username: C{string}
    @param username: Username.
    """

    from django.contrib.auth.models import User

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            return pages.ErrorPage(request, "errors/user_does_not_exist.html", {"username": username})
        except:
            transaction.rollback()
        finally:
            transaction.commit()    

    if not request.user.is_authenticated():
        try:
            return pages.ErrorPage(request, "errors/no_permissions.html")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    
            
    from booki.utils.book import checkGroupAvailability, createBookiGroup
    from booki.editor import models

    if request.GET.get("q", "") == "check":
        from booki.utils.json_wrapper import json

        data = {"available": checkGroupAvailability(request.GET.get('groupname', '').strip())}

        try:
            return HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    

    if request.GET.get("q", "") == "import":
        from booki.utils.json_wrapper import json

        data = {}

        try:
            bookid = request.GET.get('source', '')
            importType = request.GET.get('importtype', '')
            renameTitle = request.GET.get('title', '')

            extraOptions = {}

            if renameTitle:
                extraOptions['book_title'] = renameTitle

            if request.GET.get('hidden', '') != '':
                extraOptions['hidden'] = True

            importSources = {  
                'flossmanuals': (TWIKI_GATEWAY_URL, "en.flossmanuals.net"),
                "archive":      (ESPRI_URL, "archive.org"),
                "wikibooks":    (ESPRI_URL, "wikibooks"),
                "epub":         (ESPRI_URL, "url"),
                }
            
            if importType == "booki":
                bookid = bookid.rstrip('/')
                booki_url, book_url_title = bookid.rsplit("/", 1)
                base_url = "%s/export/%s/export" % (booki_url, book_url_title)
                source = "booki"
            else:
                base_url, source = importSources[importType]

            book = common.importBookFromUrl2(user, base_url,
                                             args=dict(source=source,
                                                       book=bookid),
                                             **extraOptions
                                             )
        except Exception:
            data['imported'] = False
            transaction.rollback()
        else:
            transaction.commit()
            data['imported'] = True

            from django.core.urlresolvers import reverse
            data['info_url'] = reverse('book_info', args=[book.url_title])

        try:
            return HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    


    try:
        return render_to_response('account/import_book.html', {"request": request,
                                                               "user": user})
    except:
        transaction.rollback()
    finally:
        transaction.commit()    
Esempio n. 12
0
def create_group(request, username):
    """
    Django View. Show content for Create Group dialog and creates group.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    @type username: C{string}
    @param username: Username.
    """

    from django.contrib.auth.models import User

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            return pages.ErrorPage(request, "errors/user_does_not_exist.html", {"username": username})
        except:
            transaction.rollback()
        finally:
            transaction.commit()    

    if not request.user.is_authenticated():
        try:
            return pages.ErrorPage(request, "errors/no_permissions.html")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    

            
    from booki.utils.book import checkGroupAvailability, createBookiGroup
    from booki.editor import models

    if request.GET.get("q", "") == "check":
        from booki.utils.json_wrapper import json

        data = {"available": checkGroupAvailability(request.GET.get('groupname', '').strip())}

        try:
            return HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    


    if request.GET.get("q", "") == "create":
        from booki.utils.json_wrapper import json

        groupName = request.GET.get('name', '').strip()
        groupDescription = request.GET.get('description', '').strip()

        groupCreated = False

        if checkGroupAvailability(groupName):
            try:
                group = createBookiGroup(groupName, groupDescription, request.user)
                group.members.add(request.user)
                groupCreated = True
            except BookiGroupExist:
                groupCreated = False
                transaction.rollback()
            else:
                transaction.commit()

        data = {'created': groupCreated}

        try:
            return HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    


    try:
        return render_to_response('account/create_group.html', {"request": request,
                                                               "user": user})
    except:
        transaction.rollback()
    finally:
        transaction.commit()    
Esempio n. 13
0
def create_book(request, username):
    """
    Django View. Show content for Create Book dialog and creates book.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    @type username: C{string}
    @param username: Username.
    """

    from django.contrib.auth.models import User

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            return pages.ErrorPage(request, "errors/user_does_not_exist.html", {"username": username})
        except:
            transaction.rollback()
        finally:
            transaction.commit()    

    if not request.user.is_authenticated():
        try:
            return pages.ErrorPage(request, "errors/no_permissions.html")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    


    from booki.utils.book import checkBookAvailability, createBook
    from booki.editor import models

    if request.GET.get("q", "") == "check":
        from booki.utils.json_wrapper import json

        data = {"available": checkBookAvailability(request.GET.get('bookname', '').strip())}

        try:
            return HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    

    if request.method == 'POST':
        book = None
        try:
            # hidden on
            # description
            # license
            # title
            # cover

            book = createBook(request.user, request.POST.get('title'))

            lic = models.License.objects.get(abbrevation=request.POST.get('license'))
            book.license = lic
            book.description = request.POST.get('description', '')

            if request.POST.get("hidden", "") == "on":
                is_hidden = True
            else:
                is_hidden = False
            book.hidden = is_hidden
            
            from django.core.files import File

            if request.FILES.has_key('cover'):
                import tempfile
                import os

                fh, fname = tempfile.mkstemp(suffix='', prefix='cover')
                
                f = open(fname, 'wb')
                for chunk in request.FILES['cover'].chunks():
                    f.write(chunk)
                f.close()


                try:
                    import Image
                    
                    im = Image.open(fname)
                    im.thumbnail((240, 240), Image.ANTIALIAS)
                    imageName = '%s.jpg' % fname
                    im.save(imageName)
                    
                    book.cover.save('%s.jpg' % book.url_title, File(file(imageName)))
                except:
                    pass

                os.unlink(fname)

            book.save()
                
        except:
            transaction.rollback()
        else:
            transaction.commit()
        try:
            return render_to_response('account/create_book_redirect.html', {"request": request,
                                                                            "user": user,
                                                                            "book": book})
        except:
            transaction.rollback()
        finally:
            transaction.commit()    
        
    from booki.editor.models import License
    
    licenses = License.objects.all().order_by('name')

    try:
        return render_to_response('account/create_book.html', {"request": request,
                                                               "licenses": licenses,
                                                               "user": user})
    except:
        transaction.rollback()
    finally:
        transaction.commit()    
Esempio n. 14
0
def create_book(request, username):
    """
    Django View. Show content for Create Book dialog and creates book.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    @type username: C{string}
    @param username: Username.
    """

    from django.contrib.auth.models import User

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            return pages.ErrorPage(request, "errors/user_does_not_exist.html", {"username": username})
        except:
            transaction.rollback()
        finally:
            transaction.commit()    

    if not request.user.is_authenticated():
        try:
            return pages.ErrorPage(request, "errors/no_permissions.html")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    


    from booki.utils.book import checkBookAvailability, createBook
    from booki.editor import models

    book_visible = config.getConfiguration('CREATE_BOOK_VISIBLE')
    book_license = config.getConfiguration('CREATE_BOOK_LICENSE')
    admin_create = config.getConfiguration('ADMIN_CREATE_BOOKS')

    if request.user.is_superuser:
        admin_create = False


    if request.GET.get("q", "") == "check":
        from booki.utils.json_wrapper import json

        data = {"available": checkBookAvailability(request.GET.get('bookname', '').strip())}

        try:
            return HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
        finally:
            transaction.commit()    

    if request.method == 'POST' and admin_create == False:
        book = None
        try:
            # hidden on
            # description
            # license
            # title
            # cover

            book = createBook(request.user, request.POST.get('title'))

            lic = models.License.objects.get(abbrevation=request.POST.get('license'))
            book.license = lic
            book.description = request.POST.get('description', '')

            if request.POST.get("hidden", "") == "on":
                is_hidden = True
            else:
                is_hidden = False
            book.hidden = is_hidden
            
            from django.core.files import File

            if request.FILES.has_key('cover'):
                # TODO: Show some kind of error message to the user
                from booki.utils import misc
                import os

                try:
                    fh, fname = misc.saveUploadedAsFile(request.FILES['cover'])
                    book.setCover(fname)
                    os.unlink(fname)
                except:
                    pass

            book.save()
                
        except:
            transaction.rollback()
        else:
            transaction.commit()
        try:
            return render_to_response('account/create_book_redirect.html', {"request": request,
                                                                            "user": user,
                                                                            "book": book})
        except:
            transaction.rollback()
        finally:
            transaction.commit()    
        
    from booki.editor.models import License
    
    licenses = License.objects.all().order_by('name')


    try:
        return render_to_response('account/create_book.html', {"request": request,
                                                               "book_visible": book_visible,
                                                               "book_license": book_license,
                                                               "admin_create": admin_create,
                                                               "licenses": licenses,
                                                               "user": user})
    except:
        transaction.rollback()
    finally:
        transaction.commit()    
Esempio n. 15
0
def create_book(request, username):
    """
    Django View. Show content for Create Book dialog and creates book.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    @type username: C{string}
    @param username: Username.
    """

    import os
    from glob import glob
    import datetime
    from xml.dom import minidom
    from django.contrib.auth.models import User
    from booki.utils.misc import isBookLimitReached

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        try:
            resp = pages.ErrorPage(request, "errors/user_does_not_exist.html", {"username": username})
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()    

        return resp

    if isBookLimitReached() or not request.user.is_authenticated():
        try:
            resp = pages.ErrorPage(request, "errors/no_permissions.html")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()    

        return resp

    from booki.utils.book import checkBookAvailability, createBook
    from booki.editor import models

    book_visible = config.getConfiguration('CREATE_BOOK_VISIBLE')
    book_license = config.getConfiguration('CREATE_BOOK_LICENSE')
    admin_create = config.getConfiguration('ADMIN_CREATE_BOOKS')
    templates_source = config.getConfiguration('BOOK_TYPES_DIR')

    if request.user.is_superuser:
        admin_create = False


    if request.GET.get("q", "") == "check":
        from booki.utils.json_wrapper import json

        data = {"available": checkBookAvailability(request.GET.get('bookname', '').strip())}

        try:
            resp = HttpResponse(json.dumps(data), "text/plain")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()    

        return resp

    if request.method == 'POST' and admin_create == False:
        book = None
        try:
            # hidden on
            # description
            # license
            # title
            # cover
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[-1].strip()
            else:
                ip = request.META.get('REMOTE_ADDR')
            book = createBook(request.user, request.POST.get('title'), ip)

            lic = models.License.objects.get(abbrevation=request.POST.get('license'))
            book.license = lic
            book.description = request.POST.get('description', '')

            if request.POST.get("hidden", "") == "on":
                is_hidden = True
            else:
                is_hidden = False
            book.hidden = is_hidden
            
            from django.core.files import File

            if request.FILES.has_key('cover'):
                # TODO: Show some kind of error message to the user
                from booki.utils import misc
                import os

                try:
                    fh, fname = misc.saveUploadedAsFile(request.FILES['cover'])
                    book.setCover(fname)
                    os.unlink(fname)
                except:
                    pass

            book.save()
            book_version = book.getVersion()
            tf = request.POST.get('template', '')
            try:
                xmldoc = minidom.parse(tf)
                chapters = xmldoc.getElementsByTagName('chapter')
            except:
                chapters = []
            for chapter in chapters:
                chapter_title = chapter.attributes['title'].value
                chapter_content = u'<h1>{}</h1>'.format(chapter.attributes['content'].value)
                url_title = bookiSlugify(chapter_title)
                status = models.BookStatus.objects.filter(book=book).order_by("-weight")[0]
                chapter_o = models.Chapter(book=book,
                                 version = book_version,
                                 url_title = url_title,
                                 title = chapter_title,
                                 status = status,
                                 content = chapter_content,
                                 created = datetime.datetime.now(),
                                 modified = datetime.datetime.now())
                chapter_o.save()

                toc_items = len(book_version.getTOC()) + 1
                for itm in models.BookToc.objects.filter(version=book_version, book=book).order_by("-weight"):
                    itm.weight = toc_items
                    itm.save()
                toc_items -= 1
                tc = models.BookToc(version=book_version,
                                book = book,
                                name = chapter_title,
                                chapter = chapter_o,
                                weight = 1,
                                typeof = 1)
                tc.save()

        except:
            lines = traceback.format_exc().split('\n')
            for line in lines:
                print line
            transaction.rollback()
        else:
            transaction.commit()


        try:
            resp = render_to_response('account/create_book_redirect.html', {"request": request,
                                                                            "user": user,
                                                                            "book": book})
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()    

        return resp
        
    from booki.editor.models import License
    
    licenses = License.objects.all().order_by('name')

    try:
        template_files = glob(os.path.join(templates_source, '*.xml'))
    except:
        template_files = []
    templates = [{'name': 'Vac\xc3\xado', 'file': '/'}]
    for tf in template_files:
        print 'parse ' + tf
        xmldoc = minidom.parse(tf)
        print 'ok'
        tpltag = xmldoc.getElementsByTagName('template')[0]
        template = {}
        template['name'] = tpltag.attributes['title'].value
        template['file'] = tf
        templates.append(template)

    try:
        resp = render_to_response('account/create_book.html', {"request": request,
                                                               "book_visible": book_visible,
                                                               "book_license": book_license,
                                                               "admin_create": admin_create,
                                                               "licenses": licenses,
                                                               'templates': templates,
                                                               "user": user})
    except:
        transaction.rollback()
        raise
    else:
        transaction.commit()    

    return resp
Esempio n. 16
0
 def finish(self):
     """Finalise the metadata and write to disk"""
     self.info['manifest'] = self.manifest
     infojson = json.dumps(self.info, indent=2)
     self.add_to_package('info.json', 'info.json', infojson, 'application/json')
     self._close()