def _handle_import(contents, use_tags, owner): """ Handles the import of a bookmarks file Loops through all links in the file and adds them as bookmarks. It then tags them if the file contains tags and "use_tags" is true. """ lines = contents.decode("utf-8").split("\n") title = re.compile(r"<a.*?>(.+?)</a>", re.I) url = re.compile(r"""<a.*href=['"](.+?)['"]""", re.I) tags = re.compile(r"""<a.*?tags=["'](.+?)["']""", re.I) addTime = re.compile(r"""<a.*?add_date=["'](\d+?)["']""", re.I) for l in lines: if "<a" in l.lower() and "</a>" in l.lower(): bookmark = {} bookmark["title"] = title.search(l) if not bookmark["title"]: continue bookmark["title"] = _unescape(bookmark["title"].group(1)) bookmark["url"] = url.search(l) if not bookmark["url"]: continue bookmark["url"] = _unescape(bookmark["url"].group(1)) bookmark["tags"] = []; if use_tags: result = tags.search(l) if result: bookmark["tags"] = map(_unescape, result.group(1).split(",")) bookmark["added"] = addTime.search(l) if bookmark["added"]: bookmark["added"] = bookmark["added"].group(1) if not Bookmark.objects.filter(owner=owner, url=bookmark["url"]).exists(): bm = Bookmark(owner=owner, url=bookmark["url"], title=bookmark["title"]) bm.save() if bookmark["added"]: bm.added = datetime.datetime.fromtimestamp(int(bookmark["added"])) for t in bookmark["tags"]: bm.tag(t) bm.save() bm.autotag_rules()
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")