crawler.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. from flask import escape, json
  2. import requests
  3. import io
  4. from ispformat.validator import validate_isp
  5. from .models import ISP
  6. class Crawler(object):
  7. MAX_JSON_SIZE=1*1024*1024
  8. format_validation_errors=unicode
  9. escape=lambda x:x
  10. def m(self, msg, evt=None):
  11. return u'%sdata: %s\n\n'%(u'event: %s\n'%evt if evt else '', msg)
  12. def err(self, msg, *args):
  13. return self.m(u'! %s'%msg, *args)
  14. def warn(self, msg):
  15. return self.m(u'@ %s'%msg)
  16. def info(self, msg):
  17. return self.m(u'\u2013 %s'%msg)
  18. def abort(self, msg):
  19. return (self.m('<br />== <span style="color: crimson">%s</span>'%msg)+
  20. self.m(json.dumps({'closed': 1}), 'control'))
  21. def done_cb(self):
  22. pass
  23. def __call__(self, url):
  24. esc=self.escape
  25. yield self.m('Starting the validation process...')
  26. r=None
  27. try:
  28. yield self.m('* Attempting to retreive <strong>%s</strong>'%url)
  29. r=requests.get(url, verify='/etc/ssl/certs/ca-certificates.crt',
  30. headers={'User-Agent': 'FFDN DB validator'},
  31. stream=True, timeout=10)
  32. except requests.exceptions.SSLError as e:
  33. yield self.err('Unable to connect, SSL Error: <code style="color: #dd1144;">%s</code>'%esc(e))
  34. except requests.exceptions.ConnectionError as e:
  35. yield self.err('Unable to connect: <code style="color: #dd1144;">%s</code>'%e)
  36. except requests.exceptions.Timeout as e:
  37. yield self.err('Connection timeout')
  38. except requests.exceptions.TooManyRedirects as e:
  39. yield self.err('Too many redirects')
  40. except requests.exceptions.RequestException as e:
  41. yield self.err('Internal request exception')
  42. except Exception as e:
  43. yield self.err('Unexpected request exception')
  44. if r is None:
  45. yield self.abort('Connection could not be established, aborting')
  46. return
  47. yield self.info('Connection established')
  48. yield self.info('Response code: <strong>%s %s</strong>'%(esc(r.status_code), esc(r.reason)))
  49. try:
  50. r.raise_for_status()
  51. except requests.exceptions.HTTPError as e:
  52. yield cls.err('Response code indicates an error')
  53. yield cls.abort('Invalid response code')
  54. return
  55. yield self.info('Content type: <strong>%s</strong>'%(esc(r.headers.get('content-type', 'not defined'))))
  56. if not r.headers.get('content-type'):
  57. yield self.error('Content-type <strong>MUST</strong> be defined')
  58. yield self.abort('The file must have a proper content-type to continue')
  59. elif r.headers.get('content-type').lower() != 'application/json':
  60. yield self.warn('Content-type <em>SHOULD</em> be application/json')
  61. if not r.encoding:
  62. yield self.warn('Encoding not set. Assuming it\'s unicode, as per RFC4627 section 3')
  63. yield self.info('Content length: <strong>%s</strong>'%(esc(r.headers.get('content-length', 'not set'))))
  64. cl=r.headers.get('content-length')
  65. if not cl:
  66. yield self.warn('No content-length. Note that we will not process a file whose size exceed 1MiB')
  67. elif int(cl) > self.MAX_JSON_SIZE:
  68. yield self.abort('File too big ! File size must be less then 1MiB')
  69. yield self.info('Reading response into memory...')
  70. b=io.BytesIO()
  71. for d in r.iter_content(requests.models.CONTENT_CHUNK_SIZE):
  72. b.write(d)
  73. if b.tell() > self.MAX_JSON_SIZE:
  74. yield self.abort('File too big ! File size must be less then 1MiB')
  75. return
  76. r._content=b.getvalue()
  77. del b
  78. yield self.info('Successfully read %d bytes'%len(r.content))
  79. yield self.m('<br>* Parsing the JSON file')
  80. if not r.encoding:
  81. charset=requests.utils.guess_json_utf(r.content)
  82. if not charset:
  83. yield self.err('Unable to guess unicode charset')
  84. yield self.abort('The file MUST be unicode-encoded when no explicit charset is in the content-type')
  85. return
  86. yield self.info('Guessed charset: <strong>%s</strong>'%charset)
  87. try:
  88. txt=r.content.decode(r.encoding or charset)
  89. yield self.info('Successfully decoded file as %s'%esc(r.encoding or charset))
  90. except LookupError as e:
  91. yield self.err('Invalid/unknown charset: %s'%esc(e))
  92. yield self.abort('Charset error, Cannot continue')
  93. return
  94. except UnicodeDecodeError as e:
  95. yield self.err('Unicode decode error: %s'%e)
  96. yield self.abort('Charset error, cannot continue')
  97. return
  98. except Exception:
  99. yield self.abort('Unexpected charset error')
  100. return
  101. jdict=None
  102. try:
  103. jdict=json.loads(txt)
  104. except ValueError as e:
  105. yield self.err('Error while parsing JSON: %s'%esc(e))
  106. except Exception as e:
  107. yield self.err('Unexpected error while parsing JSON: %s'%esc(e))
  108. if not jdict:
  109. yield self.abort('Could not parse JSON')
  110. return
  111. yield self.info('JSON parsed successfully')
  112. yield self.m('<br />* Validating the JSON against the schema')
  113. v=list(validate_isp(jdict))
  114. if v:
  115. yield self.err('Validation errors:<br />%s'%esc(self.format_validation_errors(v)))
  116. yield self.abort('Your JSON file does not follow the schema, please fix it')
  117. return
  118. else:
  119. yield self.info('Done. No errors encountered \o')
  120. # check name uniqueness
  121. where = (ISP.name == jdict['name'])
  122. if 'shortname' in jdict and jdict['shortname']:
  123. where |= (ISP.shortname == jdict.get('shortname'))
  124. if ISP.query.filter(where).count() > 0:
  125. yield self.err('An ISP named "%s" already exist'%esc(
  126. jdict['name']+(' ('+jdict['shortname']+')' if jdict.get('shortname') else '')
  127. ))
  128. yield self.abort('The name of your ISP must be unique')
  129. return
  130. yield (self.m('<br />== <span style="color: forestgreen">All good ! You can click on Confirm now</span>')+
  131. self.m(json.dumps({'passed': 1}), 'control'))
  132. self.jdict=jdict
  133. self.done_cb()
  134. class PrettyValidator(Crawler):
  135. def __init__(self, session=None, *args, **kwargs):
  136. super(PrettyValidator, self).__init__(*args, **kwargs)
  137. self.session=session
  138. self.escape=escape
  139. def err(self, msg, *args):
  140. return self.m(u'<strong style="color: crimson">!</strong> %s'%msg, *args)
  141. def warn(self, msg):
  142. return self.m(u'<strong style="color: dodgerblue">@</strong> %s'%msg)
  143. def info(self, msg):
  144. return self.m(u'&ndash; %s'%msg)
  145. def abort(self, msg):
  146. return (self.m(u'<br />== <span style="color: crimson">%s</span>'%msg)+
  147. self.m(json.dumps({'closed': 1}), 'control'))
  148. def format_validation_errors(self, errs):
  149. r=[]
  150. for e in errs:
  151. r.append(u' %s: %s'%('.'.join(list(e.schema_path)[1:]), str(e)))
  152. return '\n'.join(r)
  153. def done_cb(self):
  154. self.session['form_json']['validated']=True
  155. self.session['form_json']['jdict']=self.jdict
  156. self.session.save()