jurl.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env python3
  2. #
  3. # jurl.py by Bill Weinman <http://bw.org/contact/>
  4. # Jump to URL (a private short URL service)
  5. # Copyright (c) 2010-2017 The BearHeart Group, LLC
  6. # created 2017-03-10
  7. # updated 2017-09-29
  8. #
  9. from bwCGI import bwCGI
  10. from bwDB import bwDB
  11. from bwConfig import configFile
  12. import random
  13. import os, sys
  14. g = dict(
  15. config_file = 'db.conf',
  16. table_name = 'jurl'
  17. )
  18. default_url = 'https://bw.org/error'
  19. def main():
  20. init()
  21. db = g['db']
  22. v = g['vars']
  23. if 'u' in v:
  24. key = v.getfirst('u')
  25. elif 'PATH_INFO' in os.environ:
  26. key = os.environ['PATH_INFO']
  27. elif len(sys.argv) > 1:
  28. key = sys.argv[1]
  29. else:
  30. redirect(default_url)
  31. return 0
  32. if key.startswith('/'): key = key[1:]
  33. try:
  34. target = db.sql_query_value("SELECT targetURL FROM jurl WHERE shortURL = ?", [ key ]);
  35. except TypeError as e:
  36. redirect(default_url)
  37. else:
  38. redirect(target)
  39. def redirect(u):
  40. # print("content-type: text/plain", end = '\r\n\r\n') # uncomment for debugging
  41. print("Status: 302 Found", end = '\r\n')
  42. print("Location: {}".format(u), end = '\r\n\r\n')
  43. def init():
  44. g['cgi'] = bwCGI()
  45. g['vars'] = g['cgi'].vars()
  46. g['config'] = configFile(g['config_file']).recs()
  47. g['db'] = bwDB(filename = g['config']['db'], table = g['table_name'])
  48. def error(e):
  49. print(e)
  50. exit(0)
  51. if __name__ == "__main__": main()