コード例 #1
0
ファイル: views.py プロジェクト: dnet/omnom
def load(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/accounts/login")
    if request.method == 'POST':
        form = ImportDeliciousForm(request.POST,request.FILES)
        if form.is_valid():
            db = get_database()[Bookmark.collection_name]
            html=request.FILES['exported'].read().decode('utf8')
            soup=BeautifulSoup(html)
            for item in soup.findAll('dt'):
                desc=''
                next=item.findNextSiblings()
                if next:
                    next=next[0]
                    if 'name' in dir(next) and next.name=='dd':
                        desc=unescape(u''.join(imap(unicode, next.contents)))
                db.Bookmark({'url': urlSanitize(item.a['href']),
                             'seq': getNextVal('seq'),
                             'tags': item.a['tags'].split(','),
                             'user': unicode(request.user),
                             'created': datetime.fromtimestamp(float(item.a['add_date'])),
                             'private': item.a['private']=='1',
                             'title': unescape(unicode(item.a.string)),
                             'notes': unicode(desc)}).save()
            return HttpResponseRedirect('/u/%s/' % request.user)
    else:
        form = ImportDeliciousForm()
    return render_to_response('import.html', { 'form': form, }, context_instance=RequestContext(request) )
コード例 #2
0
ファイル: views.py プロジェクト: dnet/omnom
def purloin(request,id):
    try: id = int(id)
    except: return HttpResponse("error: not an integer: %s" % id)
    db = get_database()[Bookmark.collection_name]
    fromobj=db.find_one({'seq': id})
    if not fromobj:
        return HttpResponse("error: no such object")

    obj=db.Bookmark({'url': fromobj['url'],
                     'seq': getNextVal('seq'),
                     'user': unicode(request.user),
                     'created': datetime.today(),
                     'private': False,
                     'title': fromobj['title'],
                     'notes': unicode(""),
                     'tags': fromobj['tags'],
                     'snapshot': fromobj.get('snapshot', []),
                     })
    obj.save()
    return HttpResponseRedirect("/v/%s" % base62.from_decimal(obj['seq']))
コード例 #3
0
def load(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/accounts/login")
    if request.method == 'POST':
        form = ImportDeliciousForm(request.POST, request.FILES)
        if form.is_valid():
            db = get_database()[Bookmark.collection_name]
            html = request.FILES['exported'].read().decode('utf8')
            soup = BeautifulSoup(html)
            for item in soup.findAll('dt'):
                desc = ''
                next = item.findNextSiblings()
                if next:
                    next = next[0]
                    if 'name' in dir(next) and next.name == 'dd':
                        desc = unescape(u''.join(imap(unicode, next.contents)))
                db.Bookmark({
                    'url':
                    urlSanitize(item.a['href']),
                    'seq':
                    getNextVal('seq'),
                    'tags':
                    item.a['tags'].split(','),
                    'user':
                    unicode(request.user),
                    'created':
                    datetime.fromtimestamp(float(item.a['add_date'])),
                    'private':
                    item.a['private'] == '1',
                    'title':
                    unescape(unicode(item.a.string)),
                    'notes':
                    unicode(desc)
                }).save()
            return HttpResponseRedirect('/u/%s/' % request.user)
    else:
        form = ImportDeliciousForm()
    return render_to_response('import.html', {
        'form': form,
    },
                              context_instance=RequestContext(request))
コード例 #4
0
def purloin(request, id):
    try:
        id = int(id)
    except:
        return HttpResponse("error: not an integer: %s" % id)
    db = get_database()[Bookmark.collection_name]
    fromobj = db.find_one({'seq': id})
    if not fromobj:
        return HttpResponse("error: no such object")

    obj = db.Bookmark({
        'url': fromobj['url'],
        'seq': getNextVal('seq'),
        'user': unicode(request.user),
        'created': datetime.today(),
        'private': False,
        'title': fromobj['title'],
        'notes': unicode(""),
        'tags': fromobj['tags'],
        'snapshot': fromobj.get('snapshot', []),
    })
    obj.save()
    return HttpResponseRedirect("/v/%s" % base62.from_decimal(obj['seq']))
コード例 #5
0
ファイル: views.py プロジェクト: dnet/omnom
def add(request,url=None):
    done=False
    if request.method == 'GET':
        form = AddBookmarkForm(request.GET)
    elif request.method == 'POST':
        form = AddBookmarkForm(request.POST)
        if request.GET.get('close'):
            done=True
    else:
        return HttpResponse("wrong method")
    try: user=User.objects.get(username=request.user)
    except ObjectDoesNotExist:
        return HttpResponseRedirect("/accounts/login")
    suggestedTags=set()
    db = get_database()[Bookmark.collection_name]
    if request.REQUEST.get("dontsave", 0) or not form.is_valid() or form.cleaned_data['popup']:
        if url: # try to edit an existing bookmark?
            url=fixApacheMadness(url)
            url=urlSanitize(url)
            try:
                obj=db.find_one({'url':url, 'user': unicode(user)})
            except ObjectDoesNotExist: obj=None
            if obj: # yes, edit an existing bookmark
                data={ 'url' : url,
                       'title' : obj['title'],
                       'tags' : ' '.join([unicode(x) for x in obj['tags']]),
                       'notes' : obj['notes'],
                       'private' : obj['private'],
                       'popup' : form.cleaned_data['popup'] }
                try:
                    suggestedTags=set(suggestTags(data['url']).keys())
                except: suggestedTags=set()
                try:
                    suggestedTags.update(getCalaisTags(data['notes']))
                except: pass
                form = AddBookmarkForm(data)
        try:
            suggestedTags=set(suggestTags(form.cleaned_data['url']).keys())
        except: pass
        try:
            suggestedTags.update(getCalaisTags(form.cleaned_data['notes']))
        except: pass
        if hasattr(form, "cleaned_data"):
            tpl='add.html' if form.cleaned_data.get('popup','') == 1 else 'addWidget.html'
        else:
            tpl='addWidget.html'
        return render_to_response(tpl,
                                  { 'form': form,
                                    'suggestedTags': sorted(suggestedTags) },
                                  context_instance=RequestContext(request))

    # ok we have some valid form. let's save it.
    url=urlSanitize(form.cleaned_data['url'])
    try:
        obj=db.one({'url': url, 'user': unicode(user)})
    except ObjectDoesNotExist:
        obj=None

    snapshot=form.cleaned_data['page'].encode('utf8')
    if snapshot:
        hash=hashlib.sha512(snapshot).hexdigest()
        fname="%s/snapshots/%s" % (settings.BASE_PATH, hash)
        dump=gzip.open(fname,'wb')
        dump.write(snapshot)
        dump.close()
        snapshot=hash
    if obj: # edit
        obj=db.Bookmark(obj)
        if form.cleaned_data['private']: obj['private']=form.cleaned_data['private']
        if form.cleaned_data['title']: obj['title']=sanitizeHtml(form.cleaned_data['title'])
        if form.cleaned_data['notes']: obj['notes']=sanitizeHtml(form.cleaned_data['notes'])
        if form.cleaned_data['tags']: obj['tags']=map(sanitizeHtml, form.cleaned_data['tags'].split(" "))
        if 'updated' in obj: del(obj['updated'])
        if not snapshot in obj: obj['snapshot']=[]
        if snapshot and snapshot not in obj['snapshot']: obj['snapshot'].append(unicode(snapshot))
    else: # create
        obj=db.Bookmark({'url': url,
                         'seq': getNextVal('seq'),
                         'user': unicode(request.user),
                         'created': datetime.today(),
                         'private': form.cleaned_data['private'],
                         'title': sanitizeHtml(form.cleaned_data['title']),
                         'notes': sanitizeHtml(form.cleaned_data['notes']),
                         'tags': map(sanitizeHtml, form.cleaned_data['tags'].split(' ')),
                         'snapshot': [unicode(snapshot)],
                        })
    obj.save()
    return HttpResponseRedirect("/v/%s?raw=1" % base62.from_decimal(obj['seq']))
コード例 #6
0
def add(request, url=None):
    done = False
    if request.method == 'GET':
        form = AddBookmarkForm(request.GET)
    elif request.method == 'POST':
        form = AddBookmarkForm(request.POST)
        if request.GET.get('close'):
            done = True
    else:
        return HttpResponse("wrong method")
    try:
        user = User.objects.get(username=request.user)
    except ObjectDoesNotExist:
        return HttpResponseRedirect("/accounts/login")
    suggestedTags = set()
    db = get_database()[Bookmark.collection_name]
    if request.REQUEST.get(
            "dontsave",
            0) or not form.is_valid() or form.cleaned_data['popup']:
        if url:  # try to edit an existing bookmark?
            url = fixApacheMadness(url)
            url = urlSanitize(url)
            try:
                obj = db.find_one({'url': url, 'user': unicode(user)})
            except ObjectDoesNotExist:
                obj = None
            if obj:  # yes, edit an existing bookmark
                data = {
                    'url': url,
                    'title': obj['title'],
                    'tags': ' '.join([unicode(x) for x in obj['tags']]),
                    'notes': obj['notes'],
                    'private': obj['private'],
                }
                if form.is_valid():
                    data['popup'] = form.cleaned_data.get('popup')
                try:
                    suggestedTags = set(suggestTags(data['url']).keys())
                except:
                    suggestedTags = set()
                try:
                    suggestedTags.update(getCalaisTags(data['notes']))
                except:
                    pass
                form = AddBookmarkForm(data)
        try:
            suggestedTags = set(suggestTags(form.cleaned_data['url']).keys())
        except:
            pass
        try:
            suggestedTags.update(getCalaisTags(form.cleaned_data['notes']))
        except:
            pass
        if hasattr(form, "cleaned_data"):
            tpl = 'add.html' if form.cleaned_data.get(
                'popup', '') == 1 else 'addWidget.html'
        else:
            tpl = 'add.html'
        return render_to_response(tpl, {
            'form': form,
            'suggestedTags': sorted(suggestedTags)
        },
                                  context_instance=RequestContext(request))

    # ok we have some valid form. let's save it.
    url = urlSanitize(form.cleaned_data['url'])
    try:
        obj = db.one({'url': url, 'user': unicode(user)})
    except ObjectDoesNotExist:
        obj = None

    snapshot = form.cleaned_data['page'].encode('utf8')
    if snapshot:
        hash = hashlib.sha512(snapshot).hexdigest()
        fname = "%s/snapshots/%s" % (settings.BASE_PATH, hash)
        dump = gzip.open(fname, 'wb')
        dump.write(snapshot)
        dump.close()
        snapshot = hash
    if obj:  # edit
        obj = db.Bookmark(obj)
        if form.cleaned_data['private']:
            obj['private'] = form.cleaned_data['private']
        if form.cleaned_data['title']:
            obj['title'] = sanitizeHtml(form.cleaned_data['title'])
        if form.cleaned_data['notes']:
            obj['notes'] = sanitizeHtml(form.cleaned_data['notes'])
        if form.cleaned_data['tags']:
            obj['tags'] = map(sanitizeHtml,
                              form.cleaned_data['tags'].split(" "))
        if 'updated' in obj: del (obj['updated'])
        if not snapshot in obj: obj['snapshot'] = []
        if snapshot and snapshot not in obj['snapshot']:
            obj['snapshot'].append(unicode(snapshot))
    else:  # create
        obj = db.Bookmark({
            'url':
            url,
            'seq':
            getNextVal('seq'),
            'user':
            unicode(request.user),
            'created':
            datetime.today(),
            'private':
            form.cleaned_data['private'],
            'title':
            sanitizeHtml(form.cleaned_data['title']),
            'notes':
            sanitizeHtml(form.cleaned_data['notes']),
            'tags':
            map(sanitizeHtml, form.cleaned_data['tags'].split(' ')),
            'snapshot': [unicode(snapshot)],
        })
    obj.save()
    return HttpResponseRedirect("/v/%s?raw=1" %
                                base62.from_decimal(obj['seq']))