Ejemplo n.º 1
0
def add(request):
    """ Adds a new bookmark
    
    Expects the url to be provided by the url POST value.
    
    The URL is automatically validated, if it isn't a valid URL, then http:// is prepended to it. If that fails, then
    the bookmark isn't added and an error is sent.
    
    The title for the bookmark is automatically downloaded based on the URL.
    
    If it succeeds, it returns the JSON representation of thebookmark it has added.
    
    If it fails it returns a JSON object with only an "error" property.
    """
    if "url" not in request.POST:
        raise SuspiciousOperation
    
    url = request.POST["url"]
    val = URLValidator()
    
    if request.user.settings.url_settings == Settings.URL_SETTINGS_VALIDATE:
        try:
            val(url)
        except ValidationError:
            try:
                val("http://"+url)
                url = "http://"+url
            except ValidationError:
                return HttpResponse('{"error":"Invalid URL"}', content_type="application/json", status=422)
    
    bm = Bookmark(owner=request.user, url=url)
    
    bm.title = url
    bm.save()
    if bm.valid_url:
        bm.download_title()
        bm.save()
    
    if "tag" in request.POST:
        bm.tag(request.POST["tag"])
    
    bm.autotag_rules()
    
    return HttpResponse(bm.to_json(), content_type="application/json")