text
stringlengths
81
112k
Return a decorator that interacts with a handler's cache. This decorator must be applied to a DefaultHandler class method or instance method as it assumes `cache`, `ca_lock` and `timeouts` are available. def with_cache(function): """Return a decorator that interacts with a handler's ca...
Remove items from cache matching URLs. Return the number of items removed. def evict(cls, urls): """Remove items from cache matching URLs. Return the number of items removed. """ if isinstance(urls, text_type): urls = [urls] urls = set(normalize_url(url) f...
Send the request through the server and return the HTTP response. def _relay(self, **kwargs): """Send the request through the server and return the HTTP response.""" retval = None delay_time = 2 # For connection retries read_attempts = 0 # For reading from socket while retval ...
Attempt to load settings from various praw.ini files. def _load_configuration(): """Attempt to load settings from various praw.ini files.""" config = configparser.RawConfigParser() module_dir = os.path.dirname(sys.modules[__name__].__file__) if 'APPDATA' in os.environ: # Windows os_config_path...
Bind the theme's colors to curses's internal color pair map. This method must be called once (after curses has been initialized) before any element attributes can be accessed. Color codes and other special attributes will be mixed bitwise into a single value that can be passed into curs...
Returns the curses attribute code for the given element. def get(self, element, selected=False): """ Returns the curses attribute code for the given element. """ if self._attribute_map is None: raise RuntimeError('Attempted to access theme attribute before ' ...
Compile all of the themes configuration files in the search path. def list_themes(cls, path=THEMES): """ Compile all of the themes configuration files in the search path. """ themes, errors = [], OrderedDict() def load_themes(path, source): """ Load all ...
Prints a human-readable summary of the installed themes to stdout. This is intended to be used as a command-line utility, outside of the main curses display loop. def print_themes(cls, path=THEMES): """ Prints a human-readable summary of the installed themes to stdout. This is...
Search for the given theme on the filesystem and attempt to load it. Directories will be checked in a pre-determined order. If the name is provided as an absolute file path, it will be loaded directly. def from_name(cls, name, path=THEMES): """ Search for the given theme on the filesys...
Load a theme from the specified configuration file. Parameters: filename: The name of the filename to load. source: A description of where the theme was loaded from. def from_file(cls, filename, source): """ Load a theme from the specified configuration file. P...
Parse a single line from a theme file. Format: <element>: <foreground> <background> <attributes> def _parse_line(cls, element, line, filename=None): """ Parse a single line from a theme file. Format: <element>: <foreground> <background> <attributes> """...
Helper function used to set the fallback attributes of an element when they are defined by the configuration as "None" or "-". def _set_fallback(elements, src_field, fallback, dest_field=None): """ Helper function used to set the fallback attributes of an element when they are defined b...
Converts hex RGB to the 6x6x6 xterm color space Args: color (str): RGB color string in the format "#RRGGBB" Returns: str: ansi color string in the format "ansi_n", where n is between 16 and 230 Reference: https://github.com/chadj2/bash-ui/bl...
Traverse the list in the given direction and return the next theme def _step(self, theme, direction): """ Traverse the list in the given direction and return the next theme """ if not self.themes: self.reload() # Try to find the starting index key = (theme.s...
The entry point from the praw-multiprocess utility. def run(): """The entry point from the praw-multiprocess utility.""" parser = OptionParser(version='%prog {0}'.format(__version__)) parser.add_option('-a', '--addr', default='localhost', help=('The address or host to listen on. Speci...
Mute tracebacks of common errors. def handle_error(_, client_addr): """Mute tracebacks of common errors.""" exc_type, exc_value, _ = sys.exc_info() if exc_type is socket.error and exc_value[0] == 32: pass elif exc_type is cPickle.UnpicklingError: sys.stderr.write...
Dispatch the actual request and return the result. def do_request(self, request, proxies, timeout, **_): """Dispatch the actual request and return the result.""" print('{0} {1}'.format(request.method, request.url)) response = self.http.send(request, proxies=proxies, timeout=timeout, ...
Parse the RPC, make the call, and pickle up the return value. def handle(self): """Parse the RPC, make the call, and pickle up the return value.""" data = cPickle.load(self.rfile) # pylint: disable=E1101 method = data.pop('method') try: retval = getattr(self, 'do_{0}'.forma...
Copy a file from the repo to the user's home directory. def _copy_settings_file(source, destination, name): """ Copy a file from the repo to the user's home directory. """ if os.path.exists(destination): try: ch = six.moves.input( 'File %s already exists, overwrite?...
Load settings from the command line. def get_args(): """ Load settings from the command line. """ parser = build_parser() args = vars(parser.parse_args()) # Overwrite the deprecated "-l" option into the link variable if args['link_deprecated'] and args['link'] ...
Load settings from an rtv configuration file. def get_file(cls, filename=None): """ Load settings from an rtv configuration file. """ if filename is None: filename = CONFIG config = configparser.ConfigParser() if os.path.exists(filename): with c...
Ensure that the directory exists before trying to write to the file. def _ensure_filepath(filename): """ Ensure that the directory exists before trying to write to the file. """ filepath = os.path.dirname(filename) if not os.path.exists(filepath): os.makedirs(filepa...
Open the subscription and submission pages subwindows, but close the current page if any other type of page is selected. def handle_selected_page(self): """ Open the subscription and submission pages subwindows, but close the current page if any other type of page is selected. "...
Mark the selected message or comment as seen. def mark_seen(self): """ Mark the selected message or comment as seen. """ data = self.get_selected_item() if data['is_new']: with self.term.loader('Marking as read'): data['object'].mark_as_read() ...
View the context surrounding the selected comment. def view_context(self): """ View the context surrounding the selected comment. """ url = self.get_selected_item().get('context') if url: self.selected_page = self.open_submission_page(url)
Open the full submission and comment tree for the selected comment. def open_submission(self): """ Open the full submission and comment tree for the selected comment. """ url = self.get_selected_item().get('submission_permalink') if url: self.selected_page = self.ope...
Decorator for Page methods that require the user to be authenticated. def logged_in(f): """ Decorator for Page methods that require the user to be authenticated. """ @wraps(f) def wrapped_method(self, *args, **kwargs): if not self.reddit.is_oauth_session(): self.term.show_notif...
Main control loop runs the following steps: 1. Re-draw the screen 2. Wait for user to press a key (includes terminal resizing) 3. Trigger the method registered to the input key 4. Check if there are any nested pages that need to be looped over The loop will run u...
Cycle to preview the previous theme from the internal list of themes. def previous_theme(self): """ Cycle to preview the previous theme from the internal list of themes. """ theme = self.term.theme_list.previous(self.term.theme) while not self.term.check_theme(theme): ...
Cycle to preview the next theme from the internal list of themes. def next_theme(self): """ Cycle to preview the next theme from the internal list of themes. """ theme = self.term.theme_list.next(self.term.theme) while not self.term.check_theme(theme): theme = self.t...
Move the cursor to the first item on the page. def move_page_top(self): """ Move the cursor to the first item on the page. """ self.nav.page_index = self.content.range[0] self.nav.cursor_index = 0 self.nav.inverted = False
Move the cursor to the last item on the page. def move_page_bottom(self): """ Move the cursor to the last item on the page. """ self.nav.page_index = self.content.range[1] self.nav.cursor_index = 0 self.nav.inverted = True
Upvote the currently selected item. def upvote(self): """ Upvote the currently selected item. """ data = self.get_selected_item() if 'likes' not in data: self.term.flash() elif getattr(data['object'], 'archived'): self.term.show_notification("Voti...
Downvote the currently selected item. def downvote(self): """ Downvote the currently selected item. """ data = self.get_selected_item() if 'likes' not in data: self.term.flash() elif getattr(data['object'], 'archived'): self.term.show_notification...
Mark the currently selected item as saved through the reddit API. def save(self): """ Mark the currently selected item as saved through the reddit API. """ data = self.get_selected_item() if 'saved' not in data: self.term.flash() elif not data['saved']: ...
Prompt to log into the user's account, or log out of the current account. def login(self): """ Prompt to log into the user's account, or log out of the current account. """ if self.reddit.is_oauth_session(): ch = self.term.show_notification('Log out? (y/n)') ...
Reply to the selected item. This is a utility method and should not be bound to a key directly. Item type: Submission - add a top level comment Comment - add a comment reply Message - reply to a private message def reply(self): """ Reply to the selec...
Delete a submission or comment. def delete_item(self): """ Delete a submission or comment. """ data = self.get_selected_item() if data.get('author') != self.reddit.user.name: self.term.flash() return prompt = 'Are you sure you want to delete this...
Edit a submission or comment. def edit(self): """ Edit a submission or comment. """ data = self.get_selected_item() if data.get('author') != self.reddit.user.name: self.term.flash() return if data['type'] == 'Submission': content = da...
Send a new private message to another user. def send_private_message(self): """ Send a new private message to another user. """ message_info = docs.MESSAGE_FILE with self.term.open_editor(message_info) as text: if not text: self.term.show_notification...
Prompt the user to select a link from a list to open. Return the link that was selected, or ``None`` if no link was selected. def prompt_and_select_link(self): """ Prompt the user to select a link from a list to open. Return the link that was selected, or ``None`` if no link was selec...
Attempt to copy the selected URL to the user's clipboard def copy_to_clipboard(self, url): """ Attempt to copy the selected URL to the user's clipboard """ if url is None: self.term.flash() return try: clipboard_copy(url) except (Prog...
Open a prompt to navigate to a different subreddit or comment" def prompt(self): """ Open a prompt to navigate to a different subreddit or comment" """ name = self.term.prompt_input('Enter page: /') if name: # Check if opening a submission url or a subreddit url ...
Open an instance of the inbox page for the logged in user. def open_inbox_page(self, content_type): """ Open an instance of the inbox page for the logged in user. """ from .inbox_page import InboxPage with self.term.loader('Loading inbox'): page = InboxPage(self.red...
Open an instance of the subscriptions page with the selected content. def open_subscription_page(self, content_type): """ Open an instance of the subscriptions page with the selected content. """ from .subscription_page import SubscriptionPage with self.term.loader('Loading {0}...
Open an instance of the submission page for the given submission URL. def open_submission_page(self, url=None, submission=None): """ Open an instance of the submission page for the given submission URL. """ from .submission_page import SubmissionPage with self.term.loader('Load...
Open an instance of the subreddit page for the given subreddit name. def open_subreddit_page(self, name): """ Open an instance of the subreddit page for the given subreddit name. """ from .subreddit_page import SubredditPage with self.term.loader('Loading subreddit'): ...
Clear the terminal screen and redraw all of the sub-windows def draw(self): """ Clear the terminal screen and redraw all of the sub-windows """ n_rows, n_cols = self.term.stdscr.getmaxyx() if n_rows < self.term.MIN_HEIGHT or n_cols < self.term.MIN_WIDTH: # TODO: Will...
Draw the title bar at the top of the screen def _draw_header(self): """ Draw the title bar at the top of the screen """ n_rows, n_cols = self.term.stdscr.getmaxyx() # Note: 2 argument form of derwin breaks PDcurses on Windows 7! window = self.term.stdscr.derwin(1, n_col...
Draw the banner with sorting options at the top of the page def _draw_banner(self): """ Draw the banner with sorting options at the top of the page """ n_rows, n_cols = self.term.stdscr.getmaxyx() window = self.term.stdscr.derwin(1, n_cols, self._row, 0) window.erase() ...
Loop through submissions and fill up the content page. def _draw_content(self): """ Loop through submissions and fill up the content page. """ n_rows, n_cols = self.term.stdscr.getmaxyx() window = self.term.stdscr.derwin(n_rows - self._row - 1, n_cols, self._row, 0) wind...
Draw the key binds help bar at the bottom of the screen def _draw_footer(self): """ Draw the key binds help bar at the bottom of the screen """ n_rows, n_cols = self.term.stdscr.getmaxyx() window = self.term.stdscr.derwin(1, n_cols, self._row, 0) window.erase() w...
Accepts GET requests to http://localhost:6500/, and stores the query params in the global dict. If shutdown_on_request is true, stop the server after the first successful request. The http request may contain the following query params: - state : unique identifier, should match what...
Params: template_file (text): Path to an index.html template Returns: body (bytes): THe utf-8 encoded document body def build_body(self, template_file=INDEX): """ Params: template_file (text): Path to an index.html template Returns: body...
Main entry point def main(): """Main entry point""" # Squelch SSL warnings logging.captureWarnings(True) if six.PY3: # These ones get triggered even when capturing warnings is turned on warnings.simplefilter('ignore', ResourceWarning) # pylint:disable=E0602 # Set the terminal tit...
Use a number of methods to guess if the default webbrowser will open in the background as opposed to opening directly in the terminal. def display(self): """ Use a number of methods to guess if the default webbrowser will open in the background as opposed to opening directly in the term...
Curses addch() method that fixes a major bug in python 3.4. See http://bugs.python.org/issue21088 def addch(window, y, x, ch, attr): """ Curses addch() method that fixes a major bug in python 3.4. See http://bugs.python.org/issue21088 """ if sys.version_info[:3] == (3...
Curses does define constants for symbols (e.g. curses.ACS_BULLET). However, they rely on using the curses.addch() function, which has been found to be buggy and a general PITA to work with. By defining them as unicode points they can be added via the more reliable curses.addstr(). http:/...
Required reading! http://nedbatchelder.com/text/unipain.html Python 2 input string will be a unicode type (unicode code points). Curses will accept unicode if all of the points are in the ascii range. However, if any of the code points are not valid ascii curses will throw a...
Unicode aware version of curses's built-in addnstr method. Safely draws a line of text on the window starting at position (row, col). Checks the boundaries of the window and cuts off the text if it exceeds the length of the window. def add_line(self, window, text, row=None, col=None, attr=None...
Shortcut for adding a single space to a window at the current position def add_space(window): """ Shortcut for adding a single space to a window at the current position """ row, col = window.getyx() _, max_cols = window.getmaxyx() n_cols = max_cols - col - 1 if ...
Overlay a message box on the center of the screen and wait for input. Params: message (list or string): List of strings, one per line. timeout (float): Optional, maximum length of time that the message will be shown before disappearing. style (str): The theme...
Prompt the user to select a link from a list to open. Return the link that was selected, or ``None`` if no link was selected. def prompt_user_to_select_link(self, links): """ Prompt the user to select a link from a list to open. Return the link that was selected, or ``None`` if no lin...
Given a list of links, separate them into pages that can be displayed to the user and navigated using the 1-9 and 0 number keys. def get_link_pages(links): """ Given a list of links, separate them into pages that can be displayed to the user and navigated using the 1-9 and 0 number keys...
Construct the dialog box to display a list of links to the user. def get_link_page_text(link_page): """ Construct the dialog box to display a list of links to the user. """ text = '' for i, link in enumerate(link_page): capped_link_text = (link['text'] if len(link['t...
Open a media link using the definitions from the user's mailcap file. Most urls are parsed using their file extension, but special cases exist for websites that are prevalent on reddit such as Imgur and Gfycat. If there are no valid mailcap definitions, RTV will fall back to using the d...
Search through the mime handlers list and attempt to find the appropriate command to open the provided url with. Will raise a MailcapEntryNotFound exception if no valid command exists. Params: url (text): URL that will be checked Returns: command (text): The st...
Open the given url using the default webbrowser. The preferred browser can specified with the $BROWSER environment variable. If not specified, python webbrowser will try to determine the default to use based on your system. For browsers requiring an X display, we open a new subprocess a...
View a long block of text using an external pager / viewer. The setting of the RTV_PAGER variable will be used if set, otherwise the system's default pager is chosen, finally defaulting to 'less' if both RTV_PAGER and PAGER is unset in the calling environment. The data string will be p...
Open a file for editing using the system's default editor. After the file has been altered, the text will be read back and the HTML comment tag <!--INSRUCTIONS --> will be stripped. If an error occurs inside of the context manager, the file will be preserved so users can recover their d...
Pipe a block of text to urlview, which displays a list of urls contained in the text and allows the user to open them with their web browser. def open_urlview(self, data): """ Pipe a block of text to urlview, which displays a list of urls contained in the text and allows the use...
Transform a window into a text box that will accept user input and loop until an escape sequence is entered. If the escape key (27) is pressed, cancel the textbox and return None. Otherwise, the textbox will wait until it is full (^j, or a new line is entered on the bottom line) or the ...
Display a text prompt at the bottom of the screen. Params: prompt (string): Text prompt that will be displayed key (bool): If true, grab a single keystroke instead of a full string. This can be faster than pressing enter for single key pro...
Wrapper around prompt_input for simple yes/no queries. def prompt_y_or_n(self, prompt): """ Wrapper around prompt_input for simple yes/no queries. """ ch = self.prompt_input(prompt, key=True) if ch in (ord('Y'), ord('y')): return True elif ch in (ord('N'), o...
Attempt to intelligently strip excess whitespace from the output of a curses textpad. def strip_textpad(text): """ Attempt to intelligently strip excess whitespace from the output of a curses textpad. """ if text is None: return text # Trivial case ...
Remove instructional HTML comment tags inserted by RTV. We used to use # to annotate comments, but it conflicted with the header tag for markdown, which some people use to format their posts. def strip_instructions(text): """ Remove instructional HTML comment tags inserted by RTV. ...
In the beginning this always called touchwin(). However, a bug was discovered in tmux when TERM was set to `xterm-256color`, where only part of the screen got redrawn when scrolling. tmux automatically sets TERM to `screen-256color`, but many people choose to override this in their tmux....
Check if the given theme is compatible with the terminal def check_theme(theme): """ Check if the given theme is compatible with the terminal """ terminal_colors = curses.COLORS if curses.has_colors() else 0 if theme.required_colors > terminal_colors: return False ...
Check that the terminal supports the provided theme, and applies the theme to the terminal if possible. If the terminal doesn't support the theme, this falls back to the default theme. The default theme only requires 8 colors so it should be compatible with any terminal that supports ba...
Return the object's fullname. A fullname is an object's kind mapping like `t3` followed by an underscore and the object's base36 id, e.g., `t1_c5s96e0`. def fullname(self): """Return the object's fullname. A fullname is an object's kind mapping like `t3` followed by an undersc...
Approve object. This reverts a removal, resets the report counter, marks it with a green check mark (only visible to other moderators) on the website view and sets the approved_by attribute to the logged in user. :returns: The json response from the server. def approve(self): ...
Distinguish object as made by mod, admin or special. Distinguished objects have a different author color. With Reddit Enhancement Suite it is the background color that changes. `sticky` argument only used for top-level Comments. :returns: The json response from the server. def distin...
Ignore future reports on this object. This prevents future reports from causing notifications or appearing in the various moderation listing. The report count will still increment. def ignore_reports(self): """Ignore future reports on this object. This prevents future reports ...
Remove object. This is the moderator version of delete. The object is removed from the subreddit listings and placed into the spam listing. If spam is set to True, then the automatic spam filter will try to remove objects with similar attributes in the future. :returns: The json respon...
Remove ignoring of future reports on this object. Undoes 'ignore_reports'. Future reports will now cause notifications and appear in the various moderation listings. def unignore_reports(self): """Remove ignoring of future reports on this object. Undoes 'ignore_reports'. Future report...
Delete this object. :returns: The json response from the server. def delete(self): """Delete this object. :returns: The json response from the server. """ url = self.reddit_session.config['del'] data = {'id': self.fullname} response = self.reddit_session.reque...
Replace the body of the object with `text`. :returns: The updated object. def edit(self, text): """Replace the body of the object with `text`. :returns: The updated object. """ url = self.reddit_session.config['edit'] data = {'thing_id': self.fullname, ...
Gild the Redditor or author of the content. :param months: Specifies the number of months to gild. This parameter is Only valid when the instance called upon is of type Redditor. When not provided, the value defaults to 1. :returns: True on success, otherwise raises an exception...
Hide object in the context of the logged in user. :param _unhide: If True, unhide the item instead. Use :meth:`~praw.objects.Hideable.unhide` instead of setting this manually. :returns: The json response from the server. def hide(self, _unhide=False): """Hide object i...
Reply to object with the specified text. :returns: A Comment object for the newly created comment (reply). def reply(self, text): """Reply to object with the specified text. :returns: A Comment object for the newly created comment (reply). """ # pylint: disable=W0212 ...
Re-query to update object with latest values. Return the object. Any listing, such as the submissions on a subreddits top page, will automatically be refreshed serverside. Refreshing a submission will also refresh all its comments. In the rare case of a comment being deleted or removed...
Report this object to the moderators. :param reason: The user-supplied reason for reporting a comment or submission. Default: None (blank reason) :returns: The json response from the server. def report(self, reason=None): """Report this object to the moderators. :param rea...
Save the object. :returns: The json response from the server. def save(self, unsave=False): """Save the object. :returns: The json response from the server. """ url = self.reddit_session.config['unsave' if unsave else 'save'] data = {'id': self.fullname, ...
Vote for the given item in the direction specified. Note: votes must be cast by humans. That is, API clients proxying a human's action one-for-one are OK, but bots deciding how to vote on content or amplifying a human's vote are not. See the reddit rules for more details on what constit...
Return the short permalink to the comment. def _fast_permalink(self): """Return the short permalink to the comment.""" if hasattr(self, 'link_id'): # from /r or /u comments page sid = self.link_id.split('_')[1] else: # from user's /message page sid = self.context.split...
Submission isn't set on __init__ thus we need to update it. def _update_submission(self, submission): """Submission isn't set on __init__ thus we need to update it.""" submission._comments_by_id[self.name] = self # pylint: disable=W0212 self._submission = submission if self._replies: ...
Return True when the comment is a top level comment. def is_root(self): """Return True when the comment is a top level comment.""" sub_prefix = self.reddit_session.config.by_object[Submission] return self.parent_id.startswith(sub_prefix)
Return a list of the comment replies to this comment. If the comment is not from a submission, :meth:`replies` will always be an empty list unless you call :meth:`refresh() before calling :meth:`replies` due to a limitation in reddit's API. def replies(self): """Return a list o...
Return the Submission object this comment belongs to. def submission(self): """Return the Submission object this comment belongs to.""" if not self._submission: # Comment not from submission self._submission = self.reddit_session.get_submission( url=self._fast_permalink) ...
Request the url for a Message and return a Message object. :param reddit_session: The session to make the request with. :param message_id: The ID of the message to request. The additional parameters are passed directly into :meth:`.request_json`. def from_id(reddit_session, message_id...