Sort posts before selecting one by number
[jan-pona-mute.git] / jan-pona-mute.py
index 9932951e0a1c7ec27524c283a6a9941eafbf0a13..7b7e1151e4b88f3304cd3f0bd02dfb570f04a57e 100755 (executable)
@@ -22,17 +22,6 @@ import cmd
 import sys
 import os
 
-# Command abbreviations
-_ABBREVS = {
-    "q":    "quit",
-    "p":    "preview",
-    "c":    "comments",
-    "r":    "reload",
-    "n":    "notifications",
-    "e":    "edit",
-    "d":    "delete",
-}
-
 _RC_PATHS = (
     "~/.config/jan-pona-mute/login",
     "~/.jan-pona-mute.d/login"
@@ -57,6 +46,17 @@ _EDITORS = (
     "ed"
 )
 
+shortcuts = {
+    "q":    "quit",
+    "p":    "preview",
+    "c":    "comments",
+    "r":    "reload",
+    "n":    "notifications",
+    "e":    "edit",
+    "d":    "delete",
+    "g":    "notifications reload",
+}
+
 def get_rcfile():
     """Init file finder"""
     for path in _RC_PATHS:
@@ -109,7 +109,7 @@ class DiasporaClient(cmd.Cmd):
 
     connection = None
     notifications = []
-    home = []
+    home = None
     numbers_refer_to = None
     post = None
     post_cache = {} # key is self.post.uid, and notification.id
@@ -151,7 +151,7 @@ enter a number to select the corresponding item.
 
     def do_info(self, line):
         """Get some info about things. By default, it is info about yourself."""
-        print("Info about yourself:")
+        print(self.header("Info"))
         print("Username: %s" % self.username)
         print("Password: %s" % ("None" if self.password == None else "set"))
         print("Pod:      %s" % self.pod)
@@ -232,11 +232,12 @@ enter a number to select the corresponding item.
         elif self.password == None:
             print("Use the 'password' command.")
         else:
+            print("Setting up a connection...")
             self.connection = diaspy.connection.Connection(
                 pod = "https://%s" % self.pod, username = self.username, password = self.password)
             try:
+                print("Logging in...")
                 self.connection.login()
-                self.onecmd("notifications")
             except diaspy.errors.LoginError:
                 print("Login failed.")
 
@@ -258,7 +259,7 @@ enter a number to select the corresponding item.
         """List notifications. Use 'notifications reload' to reload them."""
         if line == "" and self.notifications:
             print("Redisplaying the notifications in the cache.")
-            print("Use the 'reload' argument to reload them.")
+            print("Use 'notifications reload' to reload them.")
         elif line == "reload" or not self.notifications:
             if self.connection == None:
                 print("Use the 'login' command, first.")
@@ -269,7 +270,10 @@ enter a number to select the corresponding item.
             return
         if self.notifications:
             for n, notification in enumerate(self.notifications):
-                print(self.header("%2d. %s %s") % (n+1, notification.when(), notification))
+                if notification.unread:
+                    print(self.header("%2d. %s %s") % (n+1, notification.when(), notification))
+                else:
+                    print("%2d. %s %s" % (n+1, notification.when(), notification))
             print("Enter a number to select the notification.")
             self.numbers_refer_to = 'notifications'
         else:
@@ -287,8 +291,8 @@ enter a number to select the corresponding item.
 
         # Expand abbreviated commands
         first_word = line.split()[0].strip()
-        if first_word in _ABBREVS:
-            full_cmd = _ABBREVS[first_word]
+        if first_word in shortcuts:
+            full_cmd = shortcuts[first_word]
             expanded = line.replace(first_word, full_cmd, 1)
             return self.onecmd(expanded)
 
@@ -298,30 +302,33 @@ enter a number to select the corresponding item.
     def do_show(self, line):
         """Show the post given by the index number.
 The index number must refer to the current list of notifications
-or the home stream."""
+or the home stream. If no index number is given, show the current
+post again."""
         if not self.notifications and not self.home:
             print("Use the 'login' command to load notifications.")
             return
-        if line == "":
+        if line == "" and self.post == None:
             print("Please specify a number.")
             return
-        try:
-            n = int(line.strip())
-            if self.numbers_refer_to == 'notifications':
-                notification = self.notifications[n-1]
-                self.show(notification)
-                self.load(notification.about())
-            elif self.numbers_refer_to == 'home':
-                self.post = self.home[n-1]
-            else:
-                print("Internal error: not sure what numbers '%s' refer to." % self.numbers_refer_to)
+        if line != "":
+            try:
+                n = int(line.strip())
+                if self.numbers_refer_to == 'notifications':
+                    notification = self.notifications[n-1]
+                    self.show(notification)
+                    self.load(notification.about())
+                elif self.numbers_refer_to == 'home':
+                    posts = sorted(self.home, key=lambda x: x.data()["created_at"])
+                    self.post = posts[n-1]
+                else:
+                    print("Internal error: not sure what numbers '%s' refer to." % self.numbers_refer_to)
+                    return
+            except ValueError:
+                print("The 'show' command takes a notification number but '%s' is not a number" % line)
+                return
+            except IndexError:
+                print("Index too high!")
                 return
-        except ValueError:
-            print("The 'show' command takes a notification number but '%s' is not a number" % line)
-            return
-        except IndexError:
-            print("Index too high!")
-            return
 
         print()
         self.show(self.post)
@@ -430,6 +437,34 @@ Use the 'edit' command to edit notes."""
         self.undo.append("delete comment %s from %s" % (comment.id, self.post.id))
         print("Comment posted.")
 
+    def do_post(self, line):
+        """Write a post on the current stream.
+If you just use a number as your post, it will refer to a note.
+Use the 'edit' command to edit notes."""
+        if self.home == None:
+            self.home = diaspy.streams.Stream(self.connection)
+        try:
+            # if the post is just a number, use a note to post
+            n = int(line.strip())
+            notes = self.get_notes()
+            if notes:
+                try:
+                    line = self.read_note(notes[n-1])
+                    print("Using note #%d: %s" % (n, notes[n-1]))
+                except IndexError:
+                    print("Use the 'list notes' command to list valid numbers.")
+                    return
+            else:
+                print("There are no notes to use.")
+                return
+        except ValueError:
+            # in which case we'll simply post the line
+            pass
+        self.post = self.home.post(text = line)
+        self.post_cache[self.post.id] = self.post
+        self.undo.append("delete post %s" % self.post.id)
+        print("Posted. Use the 'show' command to show it.")
+
     def do_delete(self, line):
         """Delete a comment."""
         words = line.strip().split()
@@ -523,10 +558,12 @@ Use the 'edit' command to edit notes."""
         if notes:
             for n, note in enumerate(notes):
                 print(self.header("%2d. %s") % (n+1, note))
-            else:
-                print("Use 'edit' to create a note.")
+            print("Use the 'edit' command to edit a note.")
+            print("Use the 'preview' command to look at a note.")
+            print("Use the 'post' command to post a note.")
+            print("Use the 'comment' command to post a comment.")
         else:
-            print("Things to list: notes.")
+            print("Use 'edit' to create a note.")
 
     def get_notes(self):
         """Get the list of notes."""
@@ -595,7 +632,7 @@ the user enabled those."""
                 self.home.fill()
 
         n = 5
-        posts = self.home
+        posts = sorted(self.home, key=lambda x: x.data()["created_at"])
 
         if line == "all":
             n = None
@@ -626,6 +663,30 @@ the user enabled those."""
             print("The people you follow have nothing to say.")
             print("The tags you follow are empty. ðŸ˜¢")
 
+    def do_shortcuts(self, line):
+        """List all shortcuts."""
+        if line != "":
+            print("The 'shortcuts' command does not take an argument.")
+            return
+        print(self.header("Shortcuts"))
+        for shortcut in sorted(shortcuts):
+            print("%s\t%s" % (shortcut, shortcuts[shortcut]))
+        print("Use the 'shortcut' command to change or add shortcuts.")
+
+    def do_shortcut(self, line):
+        """Define a new shortcut."""
+        words = line.strip().split(maxsplit = 1)
+        if len(words) == 0:
+            return self.onecmd("shortcuts")
+        elif len(words) == 1:
+            shortcut = words[0]
+            if shortcut in shortcuts:
+                print("%s\t%s" % (shortcut, shortcuts[shortcut]))
+            else:
+                print("%s is not a shortcut" % shortcut)
+        else:
+            shortcuts[words[0]] = words[1]
+
 # Main function
 def main():