import datetime from django.core.exceptions import ObjectDoesNotExist from django.template.defaultfilters import striptags from django.core.mail import EmailMessage from django.conf import settings from links.models import Link # https://github.com/mgan59/python-pinboard/ import pinboard def safestr(s): """ Safely corerce *anything* to a string. If the object can't be str'd, an empty string will be returned. You can (and I do) use this for really crappy unicode handling, but it's a bit like killing a mosquito with a bazooka. """ if s is None: return "" if isinstance(s, unicode): return s.encode('ascii', 'xmlcharrefreplace') else: try: return str(s) except: return "" def sync_pinboard_links(): """ sync bookmarks from my pinboard account dependancies: python-pinboard https://github.com/mgan59/python-pinboard/ """ p = pinboard.open(settings.PIN_USER, settings.PIN_PASS) dupe = False links = p.posts(count=30) for link in links: try: #check to see if link exists row = Link.objects.get(link_id=safestr(link['hash'])) except ObjectDoesNotExist: l, created = Link.objects.get_or_create( title=link['description'], link_id=safestr(link['hash']), url=safestr(link['href']), description=safestr(link['extended']), rating="3", pub_date=datetime.datetime.strptime(link['time'], "%Y-%m-%dT%H:%M:%SZ"), status=0 ) print l.title if created: print l.title for t in link['tags']: l.tags.add(t) email_link(l) def email_link(link): """ Sends an imported link to Gmail (never hurts to have backups) """ subject = link.title body = "%s\n\n%s\n\n\nvisit site:%s\n" % (link.title, link.description, link.url) msg = EmailMessage(subject, striptags(body), 'sng@luxagraf.net', ['luxagraf+links@gmail.com']) msg.send() msg = EmailMessage(subject, striptags(body), 'sng@luxagraf.net', ['sng+links@luxagraf.net']) msg.send()