/blogmaker/blog/trackback_update.py

http://blogmaker.googlecode.com/ · Python · 116 lines · 76 code · 20 blank · 20 comment · 17 complexity · 30954b3536128e85bb3bfb26b7d88508 MD5 · raw file

  1. ''' Utility to attempt current trackbacks logging the results.
  2. Copyright (c) 2006-2007, PreFab Software Inc.
  3. '''
  4. from __future__ import with_statement
  5. import datetime, logging, sys
  6. from cStringIO import StringIO
  7. from itertools import chain, imap, islice
  8. from django.conf import settings
  9. import blogcosm.django_setup
  10. from django.core.mail import send_mail
  11. from blogmaker.blog.models import Entry
  12. from blogmaker.util import logToData
  13. from blogmaker.util.trap_errors import error_trapping
  14. def main():
  15. ''' Attempt all current trackbacks.
  16. Email the results to settings.MANAGERS.
  17. '''
  18. logToData('trackback.log')
  19. # Set up to capture logging info for email
  20. log = getLogger()
  21. buf = StringIO()
  22. handler = logging.StreamHandler(buf)
  23. formatter = logging.Formatter('%(message)s')
  24. handler.setFormatter(formatter)
  25. log.addHandler(handler)
  26. # The actual attempt
  27. log.info('--------------------- Start Trackback Attempt for %s ------------------' % settings.DATABASE_NAME)
  28. attempts = attempt_all_current()
  29. # Email the results if any
  30. log.removeHandler(handler)
  31. if attempts:
  32. results = buf.getvalue()
  33. toaddrs = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
  34. with error_trapping('sending email'):
  35. send_mail('Trackback Results %s' % datetime.date.today(), results,
  36. settings.DEFAULT_FROM_EMAIL, toaddrs, fail_silently=False)
  37. def attempt_all_current():
  38. ''' Find all current entries.
  39. Update their trackback list to reflect their current links.
  40. Attempt all eligible trackbacks for the entries.
  41. Returns a count of the number of trackbacks attempted. '''
  42. log = getLogger()
  43. now = datetime.datetime.now()
  44. startDate = now - datetime.timedelta(days=7)
  45. attempts = 0
  46. for entry in Entry.objects.exclude(pub_date__gt=now).exclude(pub_date__lt=startDate):
  47. entry.update_trackbacks()
  48. for tb in entry.trackbacks.all():
  49. if tb.eligible:
  50. with error_trapping():
  51. attempts += 1
  52. log.info('Attempting trackback for "%s" (%s)' % (tb.entry.headline, tb.link))
  53. tb.attempt()
  54. if tb.message:
  55. log.info('Result: %s: %s', tb.get_status_display(), tb.message)
  56. else:
  57. log.info('Result: %s', tb.get_status_display())
  58. if tb.status=='NoLink' and hasattr(tb, 'page_data'):
  59. count = logPossibles(log, tb.page_data)
  60. if count:
  61. tb.appendMessage("%s candidate(s) found; see email for details" % count)
  62. else:
  63. tb.appendMessage("No candidates found")
  64. tb.save()
  65. log.info('')
  66. return attempts
  67. def logPossibles(log, data):
  68. ''' Log possible trackbacks and return a count of how many were found. '''
  69. log.info('Possible trackbacks:')
  70. found = False
  71. count = 0
  72. for prev, curr, next in triples(data.splitlines()):
  73. if 'trackback' in curr.lower():
  74. log.info(' ' + prev)
  75. log.info(' ' + curr)
  76. log.info(' ' + next)
  77. found = True
  78. count += 1
  79. if not found:
  80. log.info(' None')
  81. return count
  82. def triples(seq, fill=''):
  83. ''' Yield walking triples of items in seq.
  84. Each item in seq appears once as the middle item.
  85. End triples are filled with fill.
  86. '''
  87. iters = [ chain([fill], iter(seq)),
  88. iter(seq),
  89. chain(islice(seq, 1, sys.maxint), [fill]) ]
  90. return imap(None, *iters)
  91. def getLogger():
  92. return logging.getLogger('blogmaker.blog.trackback_update')
  93. if __name__ == '__main__':
  94. main()