Beispiel #1
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
Beispiel #2
0
def my_books (request, username):
    """
    Django View. Show user books.

    @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.editor import models

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        return pages.ErrorPage(request, "errors/user_does_not_exist.html", {"username": username})
        
    books = models.Book.objects.filter(owner=user)

    if request.POST.get("action") == "hide":
        book = models.Book.objects.get(url_title=request.POST.get("book"))
        book.hidden = True
        book.save()
        transaction.commit()
    elif request.POST.get("action") == "unhide":
        book = models.Book.objects.get(url_title=request.POST.get("book"))
        book.hidden = False
        book.save()
        transaction.commit()

    if request.method == 'POST' and not request.POST.get("action"):
        project_form = BookForm(request.POST)
        import_form = ImportForm(request.POST)

        if import_form.is_valid() and import_form.cleaned_data["id"]:
            project_form = BookForm() # reset the other form

            try:
                ID = import_form.cleaned_data["id"]
                import_type = import_form.cleaned_data["type"]
                rename_title = import_form.cleaned_data["rename_title"]

                extraOptions = {}
                if rename_title:
                    extraOptions['book_title'] = rename_title

                if import_form.cleaned_data["hidden"]:
                    extraOptions['hidden'] = True

                import_sources = {   # base_url    source=
                    'flossmanuals': (TWIKI_GATEWAY_URL, "en.flossmanuals.net"),
                    "archive":      (ESPRI_URL, "archive.org"),
                    "wikibooks":    (ESPRI_URL, "wikibooks"),
                    "epub":         (ESPRI_URL, "url"),
                    }

                if import_type == "booki":
                    ID = ID.rstrip("/")
                    booki_url, book_url_title = ID.rsplit("/", 1)
                    base_url = "%s/export/%s/export" % (booki_url, book_url_title)
                    source = "booki"
                else:
                    base_url, source = import_sources[import_type]

                common.importBookFromUrl2(user, base_url,
                                          args=dict(source=source,
                                                    book=ID),
                                          **extraOptions
                                          )
            except Exception:
                transaction.rollback()
                logError(traceback.format_exc())
                return render_to_response('account/error_import.html',
                                          {"request": request, "user": user})
            else:
                transaction.commit()

        #XXX should this be elif? even if the POST is valid as both forms, the
        # transaction will end up being commited twice.
        if project_form.is_valid() and project_form.cleaned_data["title"]:
            import_form = ImportForm() # reset the other form
            
            from booki.utils.book import createBook
            title = project_form.cleaned_data["title"]

            try:
                book = createBook(user, title)

                license   = project_form.cleaned_data["license"]
                lic = models.License.objects.get(abbrevation=license)
                book.license = lic
                book.hidden = project_form.cleaned_data["hidden"]
                book.save()
            except:
                transaction.rollback()
            else:
                transaction.commit()

            return HttpResponseRedirect(reverse("my_books", args=[username]))
    else:
        project_form = BookForm()
        import_form = ImportForm()


    try:
        return render_to_response('account/my_books.html', {"request": request,
                                                            "user": user,
                                                            
                                                            "project_form": project_form,
                                                            "import_form": import_form,
                                                            
                                                            "books": books,})
    except:
        transaction.rollback()
    finally:
        transaction.commit()
Beispiel #3
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()    
Beispiel #4
0
def my_books (request, username):
    """
    Django View. Show user books.

    @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.editor import models
    from django.template.defaultfilters import slugify

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        return pages.ErrorPage(request, "errors/user_does_not_exist.html", {"username": username})
        
    books = models.Book.objects.filter(owner=user)

    if request.method == 'POST':
        project_form = BookForm(request.POST)
        import_form = ImportForm(request.POST)

        if import_form.is_valid() and import_form.cleaned_data["id"]:
            try:
                ID = import_form.cleaned_data["id"]
                import_type = import_form.cleaned_data["type"]

                import_sources = {   # base_url    source=
                    'flossmanuals': (TWIKI_GATEWAY_URL, "en.flossmanuals.net"),
                    "archive":      (ESPRI_URL, "archive.org"),
                    "wikibooks":    (ESPRI_URL, "wikibooks"),
                    "epub":         (ESPRI_URL, "url"),
                    }
                base_url, source = import_sources[import_type]
                common.importBookFromUrl2(user, base_url,
                                          source=source,
                                          book=ID
                                          )
            except Exception:
                transaction.rollback()
                logError(traceback.format_exc())
                return render_to_response('account/error_import.html',
                                          {"request": request, "user": user})
            else:
                transaction.commit()

        #XXX should this be elif? even if the POST is valid as both forms, the
        # transaction will end up being commited twice.
        if project_form.is_valid() and project_form.cleaned_data["title"] != "":
            from booki.utils.book import createBook
            title = project_form.cleaned_data["title"]

            try:
                book = createBook(user, title)

                license   = project_form.cleaned_data["license"]
                lic = models.License.objects.get(abbrevation=license)
                book.license = lic
                book.save()
            except:
                transaction.rollback()
            else:
                transaction.commit()

            return HttpResponseRedirect(reverse("my_books", args=[username]))
    else:
        project_form = BookForm()
        import_form = ImportForm()


    return render_to_response('account/my_books.html', {"request": request,
                                                            "user": user,

                                                            "project_form": project_form,
                                                            "import_form": import_form,

                                                            "books": books,})