You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__main__.py 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import os
  2. import sys
  3. import argparse
  4. import locale
  5. import logging
  6. import requests
  7. import praw
  8. import praw.errors
  9. from six.moves import configparser
  10. from . import config
  11. from .exceptions import SubmissionError, SubredditError, ProgramError
  12. from .curses_helpers import curses_session
  13. from .submission import SubmissionPage
  14. from .subreddit import SubredditPage
  15. from .docs import *
  16. from .__version__ import __version__
  17. __all__ = []
  18. def load_config():
  19. """
  20. Search for a configuration file at the location ~/.rtv and attempt to load
  21. saved settings for things like the username and password.
  22. """
  23. config = configparser.ConfigParser()
  24. HOME = os.path.expanduser('~')
  25. XDG_CONFIG_HOME = os.getenv('XDG_CONFIG_HOME', os.path.join(HOME, '.config'))
  26. config_paths = [
  27. os.path.join(XDG_CONFIG_HOME, 'rtv', 'rtv.cfg'),
  28. os.path.join(HOME, '.rtv')
  29. ]
  30. # read only the first existing config file
  31. for config_path in config_paths:
  32. if os.path.exists(config_path):
  33. config.read(config_path)
  34. break
  35. defaults = {}
  36. if config.has_section('rtv'):
  37. defaults = dict(config.items('rtv'))
  38. if 'unicode' in defaults:
  39. defaults['unicode'] = config.getboolean('rtv', 'unicode')
  40. return defaults
  41. def command_line():
  42. parser = argparse.ArgumentParser(
  43. prog='rtv', description=SUMMARY,
  44. epilog=CONTROLS + HELP,
  45. formatter_class=argparse.RawDescriptionHelpFormatter)
  46. parser.add_argument('-s', dest='subreddit', help='subreddit name')
  47. parser.add_argument('-l', dest='link', help='full link to a submission')
  48. parser.add_argument('--unicode', action='store_true',
  49. help='enable unicode (experimental)')
  50. parser.add_argument('--log', metavar='FILE', action='store',
  51. help='Log HTTP requests')
  52. group = parser.add_argument_group('authentication (optional)', AUTH)
  53. group.add_argument('-u', dest='username', help='reddit username')
  54. group.add_argument('-p', dest='password', help='reddit password')
  55. args = parser.parse_args()
  56. return args
  57. def main():
  58. "Main entry point"
  59. # logging.basicConfig(level=logging.DEBUG, filename='rtv.log')
  60. locale.setlocale(locale.LC_ALL, '')
  61. args = command_line()
  62. local_config = load_config()
  63. # set the terminal title
  64. title = 'rtv {0}'.format(__version__)
  65. if os.name == 'nt':
  66. os.system('title {0}'.format(title))
  67. else:
  68. sys.stdout.write("\x1b]2;{0}\x07".format(title))
  69. # Fill in empty arguments with config file values. Paramaters explicitly
  70. # typed on the command line will take priority over config file params.
  71. for key, val in local_config.items():
  72. if getattr(args, key, None) is None:
  73. setattr(args, key, val)
  74. config.unicode = args.unicode
  75. if args.log:
  76. logging.basicConfig(level=logging.DEBUG, filename=args.log)
  77. try:
  78. print('Connecting...')
  79. reddit = praw.Reddit(user_agent=AGENT)
  80. reddit.config.decode_html_entities = True
  81. if args.username:
  82. # PRAW will prompt for password if it is None
  83. reddit.login(args.username, args.password)
  84. with curses_session() as stdscr:
  85. if args.link:
  86. page = SubmissionPage(stdscr, reddit, url=args.link)
  87. page.loop()
  88. subreddit = args.subreddit or 'front'
  89. page = SubredditPage(stdscr, reddit, subreddit)
  90. page.loop()
  91. except praw.errors.InvalidUserPass:
  92. print('Invalid password for username: {}'.format(args.username))
  93. except requests.ConnectionError:
  94. print('Connection timeout')
  95. except requests.HTTPError:
  96. print('HTTP Error: 404 Not Found')
  97. except SubmissionError as e:
  98. print('Could not reach submission URL: {}'.format(e.url))
  99. except SubredditError as e:
  100. print('Could not reach subreddit: {}'.format(e.name))
  101. except ProgramError as e:
  102. print('Error: could not open file with program "{}", '
  103. 'try setting RTV_EDITOR'.format(e.name))
  104. except KeyboardInterrupt:
  105. return
  106. sys.exit(main())