Пример #1
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.parent = parent
        self.ui = Ui_feedIO()
        self.ui.setupUi(self)
        self.raise_()

        self.newFont = QFont()
        self.newFont.setWeight(75)

        self.unreadFont = QFont()
        self.unreadFont.setWeight(75)

        self.readFont = QFont()
        self.readFont.setWeight(50)

        self.readColor = QColor("#666666")
        self.unreadColor = QColor("#444444")
        self.newColor = QColor("#070788")

        self.feedList = []
        self.itemList = []
        self.topicList = []
        self.readList = []
        self.currentItem = None
        self.currentTopic = classifier.getTopic("General")

        self.updated = True
        self.displayTopics()
        self.displayFeeds()
        self.displayItems()

        self.ui.listOld.setFocus()
        self.ui.comboFeed.setCurrentIndex(len(self.feedList))


        # Twitter authentication details.
#        self.twitterAuthenticated = False
#        self.twitterAuthKey = ''
#        self.twitterAuthSecret = ''

        self.connect(self.ui.comboFeed, SIGNAL("currentIndexChanged(int)"), self.displayItems)
        self.connect(self.ui.comboTopic, SIGNAL("currentIndexChanged(int)"), self.displayItems)
        self.connect(self.ui.listUnread, SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"), self.setCurrentFromUnread)

        self.connect(self.ui.listUnread, SIGNAL("itemDoubleClicked(QTreeWidgetItem *,int)"), self.on_actionReadItLater_activated)
        self.connect(self.ui.listOld, SIGNAL("itemDoubleClicked(QTreeWidgetItem *,int)"), self.on_actionReadItLater_activated)

        self.connect(self.ui.listOld, SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"), self.setCurrentFromOld)
        self.connect(self.ui.actionVisitPage, SIGNAL("activated()"), self.visitPage)
        self.connect(self.ui.actionFetchAllFeeds, SIGNAL("activated()"), parent.fetchAllFeeds)
        self.connect(self.ui.actionReCalculateScores, SIGNAL("activated()"), self.reCalculateAllScores)
        self.connect(self.ui.actionFetchFeed, SIGNAL("activated()"), self.fetchFeed)
        self.connect(self.ui.actionUpVote, SIGNAL("activated()"), self.upVoteArticle)
        self.connect(self.ui.actionDownVote, SIGNAL("activated()"), self.downVoteArticle)
        self.connect(self.ui.actionUnread, SIGNAL("activated()"), self.markAsUnread)
#        self.connect(self, SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.ui.btnUp, SIGNAL('clicked()'), self.upVoteArticle)
        self.connect(self.ui.btnDown, SIGNAL('clicked()'), self.downVoteArticle)
Пример #2
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.parent = parent
        self.ui = Ui_feedIO()
        self.ui.setupUi(self)
        self.raise_()

        self.newFont = QFont()
        self.newFont.setWeight(75)

        self.unreadFont = QFont()
        self.unreadFont.setWeight(75)

        self.readFont = QFont()
        self.readFont.setWeight(50)

        self.readColor = QColor("#666666")
        self.unreadColor = QColor("#444444")
        self.newColor = QColor("#070788")

        self.feedList = []
        self.itemList = []
        self.topicList = []
        self.readList = []
        self.currentItem = None
        self.currentTopic = classifier.getTopic("General")

        self.updated = True
        self.displayTopics()
        self.displayFeeds()
        self.displayItems()

        self.ui.listOld.setFocus()
        self.ui.comboFeed.setCurrentIndex(len(self.feedList))


        # Twitter authentication details.
#        self.twitterAuthenticated = False
#        self.twitterAuthKey = ''
#        self.twitterAuthSecret = ''

        self.connect(self.ui.comboFeed, SIGNAL("currentIndexChanged(int)"), self.displayItems)
        self.connect(self.ui.comboTopic, SIGNAL("currentIndexChanged(int)"), self.displayItems)
        self.connect(self.ui.listUnread, SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"), self.setCurrentFromUnread)

        self.connect(self.ui.listUnread, SIGNAL("itemDoubleClicked(QTreeWidgetItem *,int)"), self.on_actionReadItLater_activated)
        self.connect(self.ui.listOld, SIGNAL("itemDoubleClicked(QTreeWidgetItem *,int)"), self.on_actionReadItLater_activated)

        self.connect(self.ui.listOld, SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"), self.setCurrentFromOld)
        self.connect(self.ui.actionVisitPage, SIGNAL("activated()"), self.visitPage)
        self.connect(self.ui.actionFetchAllFeeds, SIGNAL("activated()"), parent.fetchAllFeeds)
        self.connect(self.ui.actionReCalculateScores, SIGNAL("activated()"), self.reCalculateAllScores)
        self.connect(self.ui.actionFetchFeed, SIGNAL("activated()"), self.fetchFeed)
        self.connect(self.ui.actionUpVote, SIGNAL("activated()"), self.upVoteArticle)
        self.connect(self.ui.actionDownVote, SIGNAL("activated()"), self.downVoteArticle)
        self.connect(self.ui.actionUnread, SIGNAL("activated()"), self.markAsUnread)
#        self.connect(self, SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.ui.btnUp, SIGNAL('clicked()'), self.upVoteArticle)
        self.connect(self.ui.btnDown, SIGNAL('clicked()'), self.downVoteArticle)
Пример #3
0
class mainUI(QMainWindow):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.parent = parent
        self.ui = Ui_feedIO()
        self.ui.setupUi(self)
        self.raise_()

        self.newFont = QFont()
        self.newFont.setWeight(75)

        self.unreadFont = QFont()
        self.unreadFont.setWeight(75)

        self.readFont = QFont()
        self.readFont.setWeight(50)

        self.readColor = QColor("#666666")
        self.unreadColor = QColor("#444444")
        self.newColor = QColor("#070788")

        self.feedList = []
        self.itemList = []
        self.topicList = []
        self.readList = []
        self.currentItem = None
        self.currentTopic = classifier.getTopic("General")

        self.updated = True
        self.displayTopics()
        self.displayFeeds()
        self.displayItems()

        self.ui.listOld.setFocus()
        self.ui.comboFeed.setCurrentIndex(len(self.feedList))


        # Twitter authentication details.
#        self.twitterAuthenticated = False
#        self.twitterAuthKey = ''
#        self.twitterAuthSecret = ''

        self.connect(self.ui.comboFeed, SIGNAL("currentIndexChanged(int)"), self.displayItems)
        self.connect(self.ui.comboTopic, SIGNAL("currentIndexChanged(int)"), self.displayItems)
        self.connect(self.ui.listUnread, SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"), self.setCurrentFromUnread)

        self.connect(self.ui.listUnread, SIGNAL("itemDoubleClicked(QTreeWidgetItem *,int)"), self.on_actionReadItLater_activated)
        self.connect(self.ui.listOld, SIGNAL("itemDoubleClicked(QTreeWidgetItem *,int)"), self.on_actionReadItLater_activated)

        self.connect(self.ui.listOld, SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"), self.setCurrentFromOld)
        self.connect(self.ui.actionVisitPage, SIGNAL("activated()"), self.visitPage)
        self.connect(self.ui.actionFetchAllFeeds, SIGNAL("activated()"), parent.fetchAllFeeds)
        self.connect(self.ui.actionReCalculateScores, SIGNAL("activated()"), self.reCalculateAllScores)
        self.connect(self.ui.actionFetchFeed, SIGNAL("activated()"), self.fetchFeed)
        self.connect(self.ui.actionUpVote, SIGNAL("activated()"), self.upVoteArticle)
        self.connect(self.ui.actionDownVote, SIGNAL("activated()"), self.downVoteArticle)
        self.connect(self.ui.actionUnread, SIGNAL("activated()"), self.markAsUnread)
#        self.connect(self, SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.ui.btnUp, SIGNAL('clicked()'), self.upVoteArticle)
        self.connect(self.ui.btnDown, SIGNAL('clicked()'), self.downVoteArticle)


    def closeEvent(self, event):
        """
        Modification to the closeEvent so that pressing the close button in main window will only exit the
        """
        self.hide()
        event.ignore()


    def displayTopics(self):
        self.topicList = classifier.listTopics()
        topicTitles = [topic.title for topic in self.topicList]
        self.ui.comboTopic.clear()
        self.ui.comboTopic.addItems(topicTitles)


    def displayFeeds(self):
        self.feedList = fm.listFeeds()
        feedTitles = [feed.title for feed in self.feedList]
        feedTitles.append("All Feeds")
        self.ui.comboFeed.clear()
        self.ui.comboFeed.addItems(feedTitles)
        self.ui.comboFeed.setCurrentIndex(len(self.feedList))


    def displayItems(self):
        """
        Function to display unread and read article lists in the Two QTreeWidget
        boxes using two seperate threads to keep the UI responsiveness.
        """
        self.displayUnread()
        self.displayRead()


    def displayUnread(self):
        """
        function to update the Unread Articles list according to the selected feeds list.
        """

        selectedFeedIndex = self.ui.comboFeed.currentIndex()

        selectedTopicIndex = self.ui.comboTopic.currentIndex()
        self.currentTopic = self.topicList[selectedTopicIndex]
        print self.currentTopic

        if len(self.feedList) == 0:
            self.scoreItemList = []
        else:

            if selectedFeedIndex == len(self.feedList):
                pri = prioritizer.Prioritizer(self.currentTopic)
                self.scoreItemList = pri.listScoreItems()
                # Now filter out the Old items using a generator
                #this is being done in the prioritizer now
#                self.scoreItemList = [scoreItem for scoreItem in self.scoreItemList if scoreItem.item.isUnread is True]

                # prioritize the list according to the scores
                self.scoreItemList = pri.prioritize(self.scoreItemList)

                windowTitle = "All Feeds - feedIO"
                self.setWindowTitle(windowTitle)
            else:
                selectedFeed = self.feedList[selectedFeedIndex]

                pri = prioritizer.Prioritizer(self.currentTopic)
                self.scoreItemList = pri.listScoreItems(selectedFeed)
                # Now filter out the items for the current Feed using a generator
                #this is being done in the prioritizer now
#                self.scoreItemList = [scoreItem for scoreItem in self.scoreItemList if (scoreItem.item.feed is selectedFeed and scoreItem.item.isUnread is True)]

                self.scoreItemList = pri.prioritize(self.scoreItemList)

                #Code to change the window title to the currently viewing feed's title
                windowTitle = selectedFeed.title + " - feedIO"
                self.setWindowTitle(windowTitle)

        self.ui.listUnread.clear()

        itemIcon = QIcon()
        itemIcon.addPixmap(QPixmap(":/images/article.png"), QIcon.Normal, QIcon.Off)

        # Sort self.scoreItemList according to "isNew" property as primary
        # Secondary sort it by isUnread
        # Then sort it according to Score
        # then sort it according to the Article date.

        for scoreItem in self.scoreItemList:
#            treeItem=QTreeWidgetItem([ str(scoreItem.score), scoreItem.item.title])
            treeItem=QTreeWidgetItem([scoreItem.item.title,])
            treeItem.article = scoreItem.item

            treeItem.setIcon(0, itemIcon)

#            # Set a part of the article text as the tooltip of Items
#            itemTip = purify.cleanText(str(scoreItem.score))
            itemTip = "Score: <b>" + str(scoreItem.score) + "</b> &nbsp; &nbsp;&nbsp;" + "<br>Topic: " + "<i>" + scoreItem.topic.title + "</i>" + "<br>Via: " + "<i>" + scoreItem.item.feed.title + "</i>"
#            tip = purify.shorten(itemTip, 200)
            treeItem.setToolTip(0, itemTip)

            if scoreItem.item.age is 0:
                treeItem.setFont(0, self.newFont)
                treeItem.setTextColor(0, self.newColor)

            elif scoreItem.item.age is 1:
                treeItem.setFont(0, self.unreadFont)
                treeItem.setTextColor(0, self.unreadColor)

            else:
                treeItem.setFont(0, self.readFont)
                treeItem.setTextColor(0, self.readColor)

            self.ui.listUnread.addTopLevelItem(treeItem)

        self.ui.listOld.setFocus()


    def displayRead(self):
        """
        function to update the read Articles list according to the selected feeds list.
        """
        pass

        selectedFeedIndex = self.ui.comboFeed.currentIndex()

        if len(self.feedList) == 0:
            self.readList = []
        else:

            if selectedFeedIndex == len(self.feedList):
                self.readList = fm.listRead()

            else:
                selectedFeed = self.feedList[selectedFeedIndex]

                self.readList = fm.listRead(selectedFeed)

        self.ui.listOld.clear()

        itemIcon = QIcon()
        itemIcon.addPixmap(QPixmap(":/images/article.png"), QIcon.Normal, QIcon.Off)

        for article in self.readList:
            treeItem=QTreeWidgetItem([article.title,])
            treeItem.article = article

            treeItem.setIcon(0, itemIcon)

            treeItem.setFont(0, self.readFont)
            treeItem.setTextColor(0, self.readColor)

            self.ui.listOld.addTopLevelItem(treeItem)

    def setCurrentFromUnread(self):
        """
        Function to set the currently selected Item in the Unread list as the self.currentItem
        """
        self.currentItem = self.ui.listUnread.currentItem()
        self.displayArticle()


    def setCurrentFromOld(self):
        """
        Function to set the currently selected Item in the Old list as the self.currentItem
        """
        self.currentItem = self.ui.listOld.currentItem()
        self.displayArticle()


    def displayArticle(self):
        """
        displays the selected article on the viewer.
        """
        try:
            selected = self.currentItem
            selectedItem = selected.article

            text = "<style>.bg_color {background-color: #f8f8ff ;}.blue {color: #6f6fff;}.big { font-size: 8em; }.bold { font-weight: bold; }.date{ font-weight: bold; color: #066bb6;  }.info     { font-size: .95em; margin: 2px 0 6px !important; color: #148d04; }.headline_font_size {font-size: .80em;}</style>" + \
                "<div class=\" bg_color \">" + \
                "<div class=\" blue \">" + \
                "<H3>" + selectedItem.title + \
                "</div>" + \
                "<div class=\" bold headline_font_size\">" + \
                "</H3>(" + selectedItem.feed.title + ")<br>" + \
                "</div>" + \
                "<div class=\"date info\">" + \
                time.ctime(selectedItem.updated) + "<br>" + \
                "</div>" + \
                "<div class = \"bg_color\">" + \
                selectedItem.description + \
                "</div>"
        except:
            text = "Add some interesting feeds!"
        else:
            self.ui.viewArticle.setHtml(text)
            windowTitle = selectedItem.title + " - " + selectedItem.feed.title + " - feedIO"
            self.setWindowTitle(windowTitle)

            if selectedItem.age == 0 or selectedItem.age == 1:
                selected.setFont(0, self.readFont)
                selected.setTextColor(0, self.readColor)
                fm.setItemFlag(selectedItem, 2)


    def markAsRead(self):
        # create font with normal weight to show the read articles
        selected = self.currentItem
        selected.setFont(0, self.readFont)
        selected.setTextColor(0,self.readColor)
        fm.setItemFlag(selected.article, 2)


    def markAsUnread(self):
        # create font with heavy weight to show the unread articles
        selected = self.currentItem
        selected.setFont(0, self.unreadFont)
        selected.setTextColor(0, self.unreadColor)
        fm.setItemFlag(selected.article, 1)


    def fetchAllFeeds(self):
        """
        Fetch all action implementataion. Creates a new thread and fetches the updates for them in that thread.
        """

        thread = threading.Thread(target=self.fetchAll, args=())
        thread.start()
#        thread.join()
#        self.displayItems()

    def fetchAll(self):
        print "fetching Updates..."
        fm.updateAll()

        print "Calculating priority Scores"
        self.parent.setNewItemScores()


    def fetchFeed(self):
        """
        Fetch the selected feed.
        """
        selected = self.currentItem
        thread = threading.Thread(target=fm.updateFeed, args=(selected.article.feed,))
        thread.start()


    def  visitPage(self):
        """
        function to visit the original web page of selected article from the built in web browser.
        """
        try:
            selected = self.currentItem
        except:
            text = "Not implemented yet."
        else:
            self.ui.viewArticle.load(QUrl(selected.article.url))

            self.parent.status = "Visiting %s in browser mode..." % selected.article.feed.title
            self.parent.sendNotification()



    def upVoteArticle(self):
        """
        Function to upvote the current article
        """
        selected = self.currentItem

        if selected == None:
            print "Nothing to vote!"
        else:
            selectedTopicIndex = self.ui.comboTopic.currentIndex()
            selectedTopic = self.topicList[selectedTopicIndex]

            #call the classifier module
            classifier.voteArticle("up",selected.article, selectedTopic)

#            #upVote the feed
#            classifier.voteFeed("up", selected.article.feed)
#            print "Up Voted %s" % selected.article.title

            self.parent.status = "Up Voted %s under %s" % (selected.article.title, selectedTopic.title)
            self.parent.sendNotification()


    def downVoteArticle(self):
        """
        Function to Down Vote the current article
        """
        selected = self.currentItem

        if selected == None:
            print "Nothing to vote!"
        else:
            selectedTopicIndex = self.ui.comboTopic.currentIndex()
            selectedTopic = self.topicList[selectedTopicIndex]

            #call the classifier module
            classifier.voteArticle("down", selected.article, selectedTopic)

#            #downVote the feed
#            classifier.voteFeed("down", selected.article.feed)
#            print "Down Voted %s" % selected.article.title

            self.parent.status = "Down Voted %s under %s" % (selected.article.title, selectedTopic.title)
            self.parent.sendNotification()

    def reCalculateAllScores(self):
        """
        calls the parent.reCalculateAllScores inside a thread.
        """
        print "reCalculateAllScores called"
        thread = threading.Thread(target=self.parent.reCalculateAllScores, args=())
#        thread.setDaemon(True)
        thread.start()



    def on_actionManageFeeds_activated(self, i = None):
        """
        Manage feeds action implementataion. displays the manageFeeds dialog box.
        """
        if i is None: return
        ManageFeedsDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayFeeds()
            self.parent.refreshDisplay = False


    def on_actionAddFeed_activated(self, i = None):
        if i is None: return

        AddFeedDialog(self).exec_()
        #self.displayFeeds()


    def on_actionRemoveFeed_activated(self, i = None):
        if i is None: return

        RemoveFeedDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayFeeds()
            self.parent.refreshDisplay = False

    def on_actionManageTopics_activated(self, i = None):
        """
        Manage feeds action implementataion. displays the manageFeeds dialog box.
        """
        if i is None: return

        ManageTopicsDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayTopics()
            self.parent.refreshDisplay = False


    def on_actionAddTopic_activated(self, i = None):
        if i is None: return

        AddTopicDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayTopics()
            self.parent.refreshDisplay = False


    def on_actionRemoveTopic_activated(self, i = None):
        if i is None: return

        RemoveTopicDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayTopics()
            self.parent.refreshDisplay = False


    def on_actionExit_activated(self, i = None):
        """
        Exit action implementataion. Exits the application.
        """
        if i is None: return
        self.parent.close()


    def on_actionMinimizeToTray_activated(self, i = None):
        """
        Exit action implementataion. Exits the application.
        """
        if i is None: return
        self.close()


    def on_actionAbout_activated(self, i = None):
        """
        About action implementataion.
        """
        if i is None: return
        AboutDialog(self).exec_()

    def on_actionRead_activated(self, i = None):
        """
        Read article implementataion.Can play or stop the selected article.
        """
        if i is None: return
        selected = self.currentItem
        if self.parent.playerState =='standby':
            self.parent.playerState = 'playing'
            self.parent.sp.say(purify.cleanText(str(selected.article.title + "....." + selected.article.description)))
            #self.sp.say(selected.article.description)
        	
        else:
            self.parent.sp.stop()
            self.parent.playerState='standby'

    def on_actionPreferences_activated(self, i = None):
        """
        Settings  action implementataion.
        """
        if i is None: return
        SettingsDialog(self).exec_()


    def on_actionSignInToTwitter_activated(self, i = None):
        """
        Sign into twitter.
        """
        if i is None: return

        # create a QSettings object to get twitter auth data.
        s = QSettings()
        twitterPlugin.ACCESS_KEY  = str(s.value("TWITTER_ACCESS_KEY").toString())
        twitterPlugin.ACCESS_SECRET = str(s.value("TWITTER_ACCESS_SECRET").toString())


        if twitterPlugin.ACCESS_KEY is '':
            try:
                print "signing into twitter using the browser..."
                tp = twitterPlugin.TwitterPlugin()

                auth_url = tp.authenticate()

                webbrowser.open_new(auth_url)

                TwitterPinDialog(self).exec_()
                # return is the VERIFIER code is not set.
                if twitterPlugin.VERIFIER is '': return

                (twitterPlugin.ACCESS_KEY, twitterPlugin.ACCESS_SECRET) = tp.verify()
                #Store the values using in a QSettings object.
                s = QSettings()

                s.setValue("TWITTER_ACCESS_KEY", twitterPlugin.ACCESS_KEY)
                s.setValue("TWITTER_ACCESS_SECRET", twitterPlugin.ACCESS_SECRET)


            except tweepy.TweepError:
                print "Not authenticated properly. check the PIN number"
                self.parent.status = "Error Logging to twitter.com!"
                self.parent.sendNotification()
            else:
                self.parent.status = "You have Signed in to twitter.com"
                self.parent.sendNotification()


    def on_actionSignOffFromTwitter_activated(self, i = None):
        """
        Sign off from the twitter session.
        """
        if i is None: return

        twitterPlugin.ACCESS_KEY = ''
        twitterPlugin.ACCESS_SECRET = ''
        twitterPlugin.VERIFIER = ''

        #Store the values using in a QSettings object.
        s = QSettings()

        s.setValue("TWITTER_ACCESS_KEY", twitterPlugin.ACCESS_KEY)
        s.setValue("TWITTER_ACCESS_SECRET", twitterPlugin.ACCESS_SECRET)

        self.parent.status = "You have Signed Off from twitter."
        self.parent.sendNotification()

        print "Signed off from twitter."


    def on_actionPostToTwitter_activated(self, i = None):
        """
        post to twitter action implementataion.
        """
        if i is None: return

        selected = self.currentItem
        shortUrl = purify.shortenUrl(selected.article.url)
        if shortUrl is False: return

#        # Dirty hack to make the tweet limit to 140 chars.
#        urlWidth = len(selected.article.url)
#        articleTitle = purify.shorten(selected.article.title, (135-urlWidth))

        message = selected.article.title +" "+ shortUrl

#        message = selected.article.url + selected.article.title

        # create a QSettings object to get twitter auth data.
        s = QSettings()
        twitterPlugin.ACCESS_KEY  = str(s.value("TWITTER_ACCESS_KEY").toString())
        twitterPlugin.ACCESS_SECRET = str(s.value("TWITTER_ACCESS_SECRET").toString())

        if twitterPlugin.ACCESS_KEY is '':
            try:
                print "signing into twitter using the browser..."
                tp = twitterPlugin.TwitterPlugin()

                auth_url = tp.authenticate()

                webbrowser.open_new(auth_url)

                TwitterPinDialog(self).exec_()
                # return is the VERIFIER code is not set.
                if twitterPlugin.VERIFIER is '': return

                (twitterPlugin.ACCESS_KEY, twitterPlugin.ACCESS_SECRET) = tp.verify()
                #Store the values using in a QSettings object.
                s = QSettings()
                s.setValue("TWITTER_ACCESS_KEY", twitterPlugin.ACCESS_KEY)
                s.setValue("TWITTER_ACCESS_SECRET", twitterPlugin.ACCESS_SECRET)

            except tweepy.TweepError:
                print "Not authenticated properly. check the PIN number"
                self.parent.status = "Error Logging to twitter.com!"
                self.parent.sendNotification()

            else:
                tp.tweet(message)
                self.parent.status = message + " posted to twitter."
                self.parent.sendNotification()

        else:
            try:
                tp = twitterPlugin.TwitterPlugin()
                tp.tweet(message)
            except:
                print "Error in tweeting"
            else:
                self.parent.status = message + " posted to twitter."
                self.parent.sendNotification()


    def on_actionSignInToRIL_activated(self, i = None):
        """
        Sign in to Read It Later, action implementataion.
        """
        if i is None: return
        rilPlugin.SESSION = None

        print "Asking to Sign into RIL..."
        RilLoginDialog(self).exec_()

        if rilPlugin.SESSION is None: return

        # TODO: do something like bookmarking the selected article.
        self.parent.status = "Signed in to Read It Later..."
        self.parent.sendNotification()


    def on_actionSignOffFromRIL_activated(self, i = None):
        """
        Sign off from Read It Later, action implementataion.
        """
        if i is None: return

        rilPlugin.SESSION = None
        # create a QSettings object to get RIL auth data.
        s = QSettings()
        s.setValue("RIL_USER", '')
        s.setValue("RIL_PW", '')

        self.parent.status = "You have Signed Off from Read It Later."
        self.parent.sendNotification()

        print "Signed off from RIL."


    def on_actionReadItLater_activated(self, i = None):
        """
        Read It Later, action implementataion.
        """
        if i is None: return

        selected = self.currentItem


        if rilPlugin.SESSION is None:
            s = QSettings()
            username = str(s.value("RIL_USER").toString())
            pw = str(s.value("RIL_PW").toString())

            if username is not '' and pw is not '':
                # Not logged in but the username and pw is there.
                try:
                    rilPlugin.SESSION = rilPlugin.RilSession(username, pw)
                    rilPlugin.SESSION.submitItem(selected.article)
                except rilPlugin.LogInError:
                    print "LoginError! invalid username/pw."
                    ## invalid credentials. prompt to re-enter username/pw.
                    #self.on_actionSignOffFromRIL_activated()
                else:
                    # TODO: do something like bookmarking the selected article.
                    self.parent.status = selected.article.title + "Added to Read It Later List."
                    self.parent.sendNotification()

            else:
                # Not logged in and the username and pw is not stored.
                print "Asking to Sign into RIL..."
                RilLoginDialog(self).exec_()

                if rilPlugin.SESSION is not None:
                    try:
                        rilPlugin.SESSION.submitItem(selected.article)
                    except:
                        print "Error in Submitting to RIL"
                    else:
                        # TODO: do something like bookmarking the selected article.
                        self.parent.status = selected.article.title + "Added to Read It Later List."
                        self.parent.sendNotification()

        else:
            try:
                rilPlugin.SESSION.submitItem(selected.article)
            except:
                print "Error in Submitting to RIL"
            else:
                # TODO: do something like bookmarking the selected article.
                self.parent.status = selected.article.title + "Added to Read It Later List."
                self.parent.sendNotification()
Пример #4
0
class mainUI(QMainWindow):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.parent = parent
        self.ui = Ui_feedIO()
        self.ui.setupUi(self)
        self.raise_()

        self.newFont = QFont()
        self.newFont.setWeight(75)

        self.unreadFont = QFont()
        self.unreadFont.setWeight(75)

        self.readFont = QFont()
        self.readFont.setWeight(50)

        self.readColor = QColor("#666666")
        self.unreadColor = QColor("#444444")
        self.newColor = QColor("#070788")

        self.feedList = []
        self.itemList = []
        self.topicList = []
        self.readList = []
        self.currentItem = None
        self.currentTopic = classifier.getTopic("General")

        self.updated = True
        self.displayTopics()
        self.displayFeeds()
        self.displayItems()

        self.ui.listOld.setFocus()
        self.ui.comboFeed.setCurrentIndex(len(self.feedList))

        # Twitter authentication details.
        #        self.twitterAuthenticated = False
        #        self.twitterAuthKey = ''
        #        self.twitterAuthSecret = ''

        self.connect(self.ui.comboFeed, SIGNAL("currentIndexChanged(int)"),
                     self.displayItems)
        self.connect(self.ui.comboTopic, SIGNAL("currentIndexChanged(int)"),
                     self.displayItems)
        self.connect(
            self.ui.listUnread,
            SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"),
            self.setCurrentFromUnread)

        self.connect(self.ui.listUnread,
                     SIGNAL("itemDoubleClicked(QTreeWidgetItem *,int)"),
                     self.on_actionReadItLater_activated)
        self.connect(self.ui.listOld,
                     SIGNAL("itemDoubleClicked(QTreeWidgetItem *,int)"),
                     self.on_actionReadItLater_activated)

        self.connect(
            self.ui.listOld,
            SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"),
            self.setCurrentFromOld)
        self.connect(self.ui.actionVisitPage, SIGNAL("activated()"),
                     self.visitPage)
        self.connect(self.ui.actionFetchAllFeeds, SIGNAL("activated()"),
                     parent.fetchAllFeeds)
        self.connect(self.ui.actionReCalculateScores, SIGNAL("activated()"),
                     self.reCalculateAllScores)
        self.connect(self.ui.actionFetchFeed, SIGNAL("activated()"),
                     self.fetchFeed)
        self.connect(self.ui.actionUpVote, SIGNAL("activated()"),
                     self.upVoteArticle)
        self.connect(self.ui.actionDownVote, SIGNAL("activated()"),
                     self.downVoteArticle)
        self.connect(self.ui.actionUnread, SIGNAL("activated()"),
                     self.markAsUnread)
        #        self.connect(self, SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.ui.btnUp, SIGNAL('clicked()'), self.upVoteArticle)
        self.connect(self.ui.btnDown, SIGNAL('clicked()'),
                     self.downVoteArticle)

    def closeEvent(self, event):
        """
        Modification to the closeEvent so that pressing the close button in main window will only exit the
        """
        self.hide()
        event.ignore()

    def displayTopics(self):
        self.topicList = classifier.listTopics()
        topicTitles = [topic.title for topic in self.topicList]
        self.ui.comboTopic.clear()
        self.ui.comboTopic.addItems(topicTitles)

    def displayFeeds(self):
        self.feedList = fm.listFeeds()
        feedTitles = [feed.title for feed in self.feedList]
        feedTitles.append("All Feeds")
        self.ui.comboFeed.clear()
        self.ui.comboFeed.addItems(feedTitles)
        self.ui.comboFeed.setCurrentIndex(len(self.feedList))

    def displayItems(self):
        """
        Function to display unread and read article lists in the Two QTreeWidget
        boxes using two seperate threads to keep the UI responsiveness.
        """
        self.displayUnread()
        self.displayRead()

    def displayUnread(self):
        """
        function to update the Unread Articles list according to the selected feeds list.
        """

        selectedFeedIndex = self.ui.comboFeed.currentIndex()

        selectedTopicIndex = self.ui.comboTopic.currentIndex()
        self.currentTopic = self.topicList[selectedTopicIndex]
        print self.currentTopic

        if len(self.feedList) == 0:
            self.scoreItemList = []
        else:

            if selectedFeedIndex == len(self.feedList):
                pri = prioritizer.Prioritizer(self.currentTopic)
                self.scoreItemList = pri.listScoreItems()
                # Now filter out the Old items using a generator
                #this is being done in the prioritizer now
                #                self.scoreItemList = [scoreItem for scoreItem in self.scoreItemList if scoreItem.item.isUnread is True]

                # prioritize the list according to the scores
                self.scoreItemList = pri.prioritize(self.scoreItemList)

                windowTitle = "All Feeds - feedIO"
                self.setWindowTitle(windowTitle)
            else:
                selectedFeed = self.feedList[selectedFeedIndex]

                pri = prioritizer.Prioritizer(self.currentTopic)
                self.scoreItemList = pri.listScoreItems(selectedFeed)
                # Now filter out the items for the current Feed using a generator
                #this is being done in the prioritizer now
                #                self.scoreItemList = [scoreItem for scoreItem in self.scoreItemList if (scoreItem.item.feed is selectedFeed and scoreItem.item.isUnread is True)]

                self.scoreItemList = pri.prioritize(self.scoreItemList)

                #Code to change the window title to the currently viewing feed's title
                windowTitle = selectedFeed.title + " - feedIO"
                self.setWindowTitle(windowTitle)

        self.ui.listUnread.clear()

        itemIcon = QIcon()
        itemIcon.addPixmap(QPixmap(":/images/article.png"), QIcon.Normal,
                           QIcon.Off)

        # Sort self.scoreItemList according to "isNew" property as primary
        # Secondary sort it by isUnread
        # Then sort it according to Score
        # then sort it according to the Article date.

        for scoreItem in self.scoreItemList:
            #            treeItem=QTreeWidgetItem([ str(scoreItem.score), scoreItem.item.title])
            treeItem = QTreeWidgetItem([
                scoreItem.item.title,
            ])
            treeItem.article = scoreItem.item

            treeItem.setIcon(0, itemIcon)

            #            # Set a part of the article text as the tooltip of Items
            #            itemTip = purify.cleanText(str(scoreItem.score))
            itemTip = "Score: <b>" + str(
                scoreItem.score
            ) + "</b> &nbsp; &nbsp;&nbsp;" + "<br>Topic: " + "<i>" + scoreItem.topic.title + "</i>" + "<br>Via: " + "<i>" + scoreItem.item.feed.title + "</i>"
            #            tip = purify.shorten(itemTip, 200)
            treeItem.setToolTip(0, itemTip)

            if scoreItem.item.age is 0:
                treeItem.setFont(0, self.newFont)
                treeItem.setTextColor(0, self.newColor)

            elif scoreItem.item.age is 1:
                treeItem.setFont(0, self.unreadFont)
                treeItem.setTextColor(0, self.unreadColor)

            else:
                treeItem.setFont(0, self.readFont)
                treeItem.setTextColor(0, self.readColor)

            self.ui.listUnread.addTopLevelItem(treeItem)

        self.ui.listOld.setFocus()

    def displayRead(self):
        """
        function to update the read Articles list according to the selected feeds list.
        """
        pass

        selectedFeedIndex = self.ui.comboFeed.currentIndex()

        if len(self.feedList) == 0:
            self.readList = []
        else:

            if selectedFeedIndex == len(self.feedList):
                self.readList = fm.listRead()

            else:
                selectedFeed = self.feedList[selectedFeedIndex]

                self.readList = fm.listRead(selectedFeed)

        self.ui.listOld.clear()

        itemIcon = QIcon()
        itemIcon.addPixmap(QPixmap(":/images/article.png"), QIcon.Normal,
                           QIcon.Off)

        for article in self.readList:
            treeItem = QTreeWidgetItem([
                article.title,
            ])
            treeItem.article = article

            treeItem.setIcon(0, itemIcon)

            treeItem.setFont(0, self.readFont)
            treeItem.setTextColor(0, self.readColor)

            self.ui.listOld.addTopLevelItem(treeItem)

    def setCurrentFromUnread(self):
        """
        Function to set the currently selected Item in the Unread list as the self.currentItem
        """
        self.currentItem = self.ui.listUnread.currentItem()
        self.displayArticle()

    def setCurrentFromOld(self):
        """
        Function to set the currently selected Item in the Old list as the self.currentItem
        """
        self.currentItem = self.ui.listOld.currentItem()
        self.displayArticle()

    def displayArticle(self):
        """
        displays the selected article on the viewer.
        """
        try:
            selected = self.currentItem
            selectedItem = selected.article

            text = "<style>.bg_color {background-color: #f8f8ff ;}.blue {color: #6f6fff;}.big { font-size: 8em; }.bold { font-weight: bold; }.date{ font-weight: bold; color: #066bb6;  }.info     { font-size: .95em; margin: 2px 0 6px !important; color: #148d04; }.headline_font_size {font-size: .80em;}</style>" + \
                "<div class=\" bg_color \">" + \
                "<div class=\" blue \">" + \
                "<H3>" + selectedItem.title + \
                "</div>" + \
                "<div class=\" bold headline_font_size\">" + \
                "</H3>(" + selectedItem.feed.title + ")<br>" + \
                "</div>" + \
                "<div class=\"date info\">" + \
                time.ctime(selectedItem.updated) + "<br>" + \
                "</div>" + \
                "<div class = \"bg_color\">" + \
                selectedItem.description + \
                "</div>"
        except:
            text = "Add some interesting feeds!"
        else:
            self.ui.viewArticle.setHtml(text)
            windowTitle = selectedItem.title + " - " + selectedItem.feed.title + " - feedIO"
            self.setWindowTitle(windowTitle)

            if selectedItem.age == 0 or selectedItem.age == 1:
                selected.setFont(0, self.readFont)
                selected.setTextColor(0, self.readColor)
                fm.setItemFlag(selectedItem, 2)

    def markAsRead(self):
        # create font with normal weight to show the read articles
        selected = self.currentItem
        selected.setFont(0, self.readFont)
        selected.setTextColor(0, self.readColor)
        fm.setItemFlag(selected.article, 2)

    def markAsUnread(self):
        # create font with heavy weight to show the unread articles
        selected = self.currentItem
        selected.setFont(0, self.unreadFont)
        selected.setTextColor(0, self.unreadColor)
        fm.setItemFlag(selected.article, 1)

    def fetchAllFeeds(self):
        """
        Fetch all action implementataion. Creates a new thread and fetches the updates for them in that thread.
        """

        thread = threading.Thread(target=self.fetchAll, args=())
        thread.start()


#        thread.join()
#        self.displayItems()

    def fetchAll(self):
        print "fetching Updates..."
        fm.updateAll()

        print "Calculating priority Scores"
        self.parent.setNewItemScores()

    def fetchFeed(self):
        """
        Fetch the selected feed.
        """
        selected = self.currentItem
        thread = threading.Thread(target=fm.updateFeed,
                                  args=(selected.article.feed, ))
        thread.start()

    def visitPage(self):
        """
        function to visit the original web page of selected article from the built in web browser.
        """
        try:
            selected = self.currentItem
        except:
            text = "Not implemented yet."
        else:
            self.ui.viewArticle.load(QUrl(selected.article.url))

            self.parent.status = "Visiting %s in browser mode..." % selected.article.feed.title
            self.parent.sendNotification()

    def upVoteArticle(self):
        """
        Function to upvote the current article
        """
        selected = self.currentItem

        if selected == None:
            print "Nothing to vote!"
        else:
            selectedTopicIndex = self.ui.comboTopic.currentIndex()
            selectedTopic = self.topicList[selectedTopicIndex]

            #call the classifier module
            classifier.voteArticle("up", selected.article, selectedTopic)

            #            #upVote the feed
            #            classifier.voteFeed("up", selected.article.feed)
            #            print "Up Voted %s" % selected.article.title

            self.parent.status = "Up Voted %s under %s" % (
                selected.article.title, selectedTopic.title)
            self.parent.sendNotification()

    def downVoteArticle(self):
        """
        Function to Down Vote the current article
        """
        selected = self.currentItem

        if selected == None:
            print "Nothing to vote!"
        else:
            selectedTopicIndex = self.ui.comboTopic.currentIndex()
            selectedTopic = self.topicList[selectedTopicIndex]

            #call the classifier module
            classifier.voteArticle("down", selected.article, selectedTopic)

            #            #downVote the feed
            #            classifier.voteFeed("down", selected.article.feed)
            #            print "Down Voted %s" % selected.article.title

            self.parent.status = "Down Voted %s under %s" % (
                selected.article.title, selectedTopic.title)
            self.parent.sendNotification()

    def reCalculateAllScores(self):
        """
        calls the parent.reCalculateAllScores inside a thread.
        """
        print "reCalculateAllScores called"
        thread = threading.Thread(target=self.parent.reCalculateAllScores,
                                  args=())
        #        thread.setDaemon(True)
        thread.start()

    def on_actionManageFeeds_activated(self, i=None):
        """
        Manage feeds action implementataion. displays the manageFeeds dialog box.
        """
        if i is None: return
        ManageFeedsDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayFeeds()
            self.parent.refreshDisplay = False

    def on_actionAddFeed_activated(self, i=None):
        if i is None: return

        AddFeedDialog(self).exec_()
        #self.displayFeeds()

    def on_actionRemoveFeed_activated(self, i=None):
        if i is None: return

        RemoveFeedDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayFeeds()
            self.parent.refreshDisplay = False

    def on_actionManageTopics_activated(self, i=None):
        """
        Manage feeds action implementataion. displays the manageFeeds dialog box.
        """
        if i is None: return

        ManageTopicsDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayTopics()
            self.parent.refreshDisplay = False

    def on_actionAddTopic_activated(self, i=None):
        if i is None: return

        AddTopicDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayTopics()
            self.parent.refreshDisplay = False

    def on_actionRemoveTopic_activated(self, i=None):
        if i is None: return

        RemoveTopicDialog(self).exec_()

        if self.parent.refreshDisplay is True:
            self.displayTopics()
            self.parent.refreshDisplay = False

    def on_actionExit_activated(self, i=None):
        """
        Exit action implementataion. Exits the application.
        """
        if i is None: return
        self.parent.close()

    def on_actionMinimizeToTray_activated(self, i=None):
        """
        Exit action implementataion. Exits the application.
        """
        if i is None: return
        self.close()

    def on_actionAbout_activated(self, i=None):
        """
        About action implementataion.
        """
        if i is None: return
        AboutDialog(self).exec_()

    def on_actionRead_activated(self, i=None):
        """
        Read article implementataion.Can play or stop the selected article.
        """
        if i is None: return
        selected = self.currentItem
        if self.parent.playerState == 'standby':
            self.parent.playerState = 'playing'
            self.parent.sp.say(
                purify.cleanText(
                    str(selected.article.title + "....." +
                        selected.article.description)))
            #self.sp.say(selected.article.description)

        else:
            self.parent.sp.stop()
            self.parent.playerState = 'standby'

    def on_actionPreferences_activated(self, i=None):
        """
        Settings  action implementataion.
        """
        if i is None: return
        SettingsDialog(self).exec_()

    def on_actionSignInToTwitter_activated(self, i=None):
        """
        Sign into twitter.
        """
        if i is None: return

        # create a QSettings object to get twitter auth data.
        s = QSettings()
        twitterPlugin.ACCESS_KEY = str(
            s.value("TWITTER_ACCESS_KEY").toString())
        twitterPlugin.ACCESS_SECRET = str(
            s.value("TWITTER_ACCESS_SECRET").toString())

        if twitterPlugin.ACCESS_KEY is '':
            try:
                print "signing into twitter using the browser..."
                tp = twitterPlugin.TwitterPlugin()

                auth_url = tp.authenticate()

                webbrowser.open_new(auth_url)

                TwitterPinDialog(self).exec_()
                # return is the VERIFIER code is not set.
                if twitterPlugin.VERIFIER is '': return

                (twitterPlugin.ACCESS_KEY,
                 twitterPlugin.ACCESS_SECRET) = tp.verify()
                #Store the values using in a QSettings object.
                s = QSettings()

                s.setValue("TWITTER_ACCESS_KEY", twitterPlugin.ACCESS_KEY)
                s.setValue("TWITTER_ACCESS_SECRET",
                           twitterPlugin.ACCESS_SECRET)

            except tweepy.TweepError:
                print "Not authenticated properly. check the PIN number"
                self.parent.status = "Error Logging to twitter.com!"
                self.parent.sendNotification()
            else:
                self.parent.status = "You have Signed in to twitter.com"
                self.parent.sendNotification()

    def on_actionSignOffFromTwitter_activated(self, i=None):
        """
        Sign off from the twitter session.
        """
        if i is None: return

        twitterPlugin.ACCESS_KEY = ''
        twitterPlugin.ACCESS_SECRET = ''
        twitterPlugin.VERIFIER = ''

        #Store the values using in a QSettings object.
        s = QSettings()

        s.setValue("TWITTER_ACCESS_KEY", twitterPlugin.ACCESS_KEY)
        s.setValue("TWITTER_ACCESS_SECRET", twitterPlugin.ACCESS_SECRET)

        self.parent.status = "You have Signed Off from twitter."
        self.parent.sendNotification()

        print "Signed off from twitter."

    def on_actionPostToTwitter_activated(self, i=None):
        """
        post to twitter action implementataion.
        """
        if i is None: return

        selected = self.currentItem
        shortUrl = purify.shortenUrl(selected.article.url)
        if shortUrl is False: return

        #        # Dirty hack to make the tweet limit to 140 chars.
        #        urlWidth = len(selected.article.url)
        #        articleTitle = purify.shorten(selected.article.title, (135-urlWidth))

        message = selected.article.title + " " + shortUrl

        #        message = selected.article.url + selected.article.title

        # create a QSettings object to get twitter auth data.
        s = QSettings()
        twitterPlugin.ACCESS_KEY = str(
            s.value("TWITTER_ACCESS_KEY").toString())
        twitterPlugin.ACCESS_SECRET = str(
            s.value("TWITTER_ACCESS_SECRET").toString())

        if twitterPlugin.ACCESS_KEY is '':
            try:
                print "signing into twitter using the browser..."
                tp = twitterPlugin.TwitterPlugin()

                auth_url = tp.authenticate()

                webbrowser.open_new(auth_url)

                TwitterPinDialog(self).exec_()
                # return is the VERIFIER code is not set.
                if twitterPlugin.VERIFIER is '': return

                (twitterPlugin.ACCESS_KEY,
                 twitterPlugin.ACCESS_SECRET) = tp.verify()
                #Store the values using in a QSettings object.
                s = QSettings()
                s.setValue("TWITTER_ACCESS_KEY", twitterPlugin.ACCESS_KEY)
                s.setValue("TWITTER_ACCESS_SECRET",
                           twitterPlugin.ACCESS_SECRET)

            except tweepy.TweepError:
                print "Not authenticated properly. check the PIN number"
                self.parent.status = "Error Logging to twitter.com!"
                self.parent.sendNotification()

            else:
                tp.tweet(message)
                self.parent.status = message + " posted to twitter."
                self.parent.sendNotification()

        else:
            try:
                tp = twitterPlugin.TwitterPlugin()
                tp.tweet(message)
            except:
                print "Error in tweeting"
            else:
                self.parent.status = message + " posted to twitter."
                self.parent.sendNotification()

    def on_actionSignInToRIL_activated(self, i=None):
        """
        Sign in to Read It Later, action implementataion.
        """
        if i is None: return
        rilPlugin.SESSION = None

        print "Asking to Sign into RIL..."
        RilLoginDialog(self).exec_()

        if rilPlugin.SESSION is None: return

        # TODO: do something like bookmarking the selected article.
        self.parent.status = "Signed in to Read It Later..."
        self.parent.sendNotification()

    def on_actionSignOffFromRIL_activated(self, i=None):
        """
        Sign off from Read It Later, action implementataion.
        """
        if i is None: return

        rilPlugin.SESSION = None
        # create a QSettings object to get RIL auth data.
        s = QSettings()
        s.setValue("RIL_USER", '')
        s.setValue("RIL_PW", '')

        self.parent.status = "You have Signed Off from Read It Later."
        self.parent.sendNotification()

        print "Signed off from RIL."

    def on_actionReadItLater_activated(self, i=None):
        """
        Read It Later, action implementataion.
        """
        if i is None: return

        selected = self.currentItem

        if rilPlugin.SESSION is None:
            s = QSettings()
            username = str(s.value("RIL_USER").toString())
            pw = str(s.value("RIL_PW").toString())

            if username is not '' and pw is not '':
                # Not logged in but the username and pw is there.
                try:
                    rilPlugin.SESSION = rilPlugin.RilSession(username, pw)
                    rilPlugin.SESSION.submitItem(selected.article)
                except rilPlugin.LogInError:
                    print "LoginError! invalid username/pw."
                    ## invalid credentials. prompt to re-enter username/pw.
                    #self.on_actionSignOffFromRIL_activated()
                else:
                    # TODO: do something like bookmarking the selected article.
                    self.parent.status = selected.article.title + "Added to Read It Later List."
                    self.parent.sendNotification()

            else:
                # Not logged in and the username and pw is not stored.
                print "Asking to Sign into RIL..."
                RilLoginDialog(self).exec_()

                if rilPlugin.SESSION is not None:
                    try:
                        rilPlugin.SESSION.submitItem(selected.article)
                    except:
                        print "Error in Submitting to RIL"
                    else:
                        # TODO: do something like bookmarking the selected article.
                        self.parent.status = selected.article.title + "Added to Read It Later List."
                        self.parent.sendNotification()

        else:
            try:
                rilPlugin.SESSION.submitItem(selected.article)
            except:
                print "Error in Submitting to RIL"
            else:
                # TODO: do something like bookmarking the selected article.
                self.parent.status = selected.article.title + "Added to Read It Later List."
                self.parent.sendNotification()
Пример #5
0
Файл: ui.py Проект: Lanka/feedIO
class mainUI(QMainWindow):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.parent = parent
        self.ui = Ui_feedIO()
        self.ui.setupUi(self)
        self.raise_()

        self.newFont = QFont()
        self.newFont.setWeight(75)

        self.unreadFont = QFont()
        self.unreadFont.setWeight(75)

        self.readFont = QFont()
        self.readFont.setWeight(50)

        self.readColor = QColor("#666666")
        self.unreadColor = QColor("#444444")
        self.newColor = QColor("#070788")

        self.feedList = []
        self.itemList = []
        self.topicList = []
        self.readList = []
        self.currentItem = None
        self.currentTopic = classifier.getTopic("General")

        self.updated = True
        self.displayTopics()
        self.displayFeeds()
        self.displayItems()

        self.ui.listOld.setFocus()
        self.ui.comboFeed.setCurrentIndex(len(self.feedList))

        self.connect(self.ui.comboFeed, SIGNAL("currentIndexChanged(int)"), self.displayItems)
        self.connect(self.ui.comboTopic, SIGNAL("currentIndexChanged(int)"), self.displayItems)
        self.connect(self.ui.listUnread, SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"), self.setCurrentFromUnread)
        self.connect(self.ui.listOld, SIGNAL("currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)"), self.setCurrentFromOld)
        self.connect(self.ui.actionVisitPage, SIGNAL("activated()"), self.visitPage)
        self.connect(self.ui.actionFetchAllFeeds, SIGNAL("activated()"), parent.fetchAllFeeds)
        self.connect(self.ui.actionFetchFeed, SIGNAL("activated()"), self.fetchFeed)
        self.connect(self.ui.actionUpVote, SIGNAL("activated()"), self.upVoteArticle)
        self.connect(self.ui.actionDownVote, SIGNAL("activated()"), self.downVoteArticle)
        self.connect(self.ui.actionUnread, SIGNAL("activated()"), self.markAsUnread)
#        self.connect(self, SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.ui.btnUp, SIGNAL('clicked()'), self.upVoteArticle)
        self.connect(self.ui.btnDown, SIGNAL('clicked()'), self.downVoteArticle)


    def closeEvent(self, event):
        """
        Modification to the closeEvent so that pressing the close button in main window will only exit the
        """
        self.hide()
        event.ignore()


    def displayTopics(self):
        self.topicList = classifier.listTopics()
        topicTitles = [topic.title for topic in self.topicList]
        self.ui.comboTopic.clear()
        self.ui.comboTopic.addItems(topicTitles)


    def displayFeeds(self):
        self.feedList = fm.listFeeds()
        feedTitles = [feed.title for feed in self.feedList]
        feedTitles.append("All Feeds")
        self.ui.comboFeed.clear()
        self.ui.comboFeed.addItems(feedTitles)
        self.ui.comboFeed.setCurrentIndex(len(self.feedList))


    def displayItems(self):
        """
        Function to display unread and read article lists in the Two QTreeWidget
        boxes using two seperate threads to keep the UI responsiveness.
        """
        self.displayUnread()
        self.displayRead()


    def displayUnread(self):
        """
        function to update the Unread Articles list according to the selected feeds list.
        """

        selectedFeedIndex = self.ui.comboFeed.currentIndex()

        selectedTopicIndex = self.ui.comboTopic.currentIndex()
        self.currentTopic = self.topicList[selectedTopicIndex]
        print self.currentTopic

        if len(self.feedList) == 0:
            self.scoreItemList = []
        else:

            if selectedFeedIndex == len(self.feedList):
                pri = prioritizer.Prioritizer(self.currentTopic)
                self.scoreItemList = pri.listScoreItems()
                # Now filter out the Old items using a generator

                self.scoreItemList = [scoreItem for scoreItem in self.scoreItemList if scoreItem.item.isUnread is True]
                # prioritize the list according to the scores
                self.scoreItemList = pri.prioritize(self.scoreItemList)

                windowTitle = "All Feeds - feedIO"
                self.setWindowTitle(windowTitle)
            else:
                selectedFeed = self.feedList[selectedFeedIndex]

                pri = prioritizer.Prioritizer(self.currentTopic)
                self.scoreItemList = pri.listScoreItems()
                # Now filter out the items for the current Feed using a generator
                self.scoreItemList = [scoreItem for scoreItem in self.scoreItemList if (scoreItem.item.feed is selectedFeed and scoreItem.item.isUnread is True)]

                self.scoreItemList = pri.prioritize(self.scoreItemList)

                #Code to change the window title to the currently viewing feed's title
                windowTitle = selectedFeed.title + " - feedIO"
                self.setWindowTitle(windowTitle)

        self.ui.listUnread.clear()

        itemIcon = QIcon()
        itemIcon.addPixmap(QPixmap(":/images/article.png"), QIcon.Normal, QIcon.Off)

        # Sort self.scoreItemList according to "isNew" property as primary
        # Secondary sort it by isUnread
        # Then sort it according to Score
        # then sort it according to the Article date.

        for scoreItem in self.scoreItemList:
#           treeItem=QTreeWidgetItem([scoreItem.item.title, str(time.ctime(scoreItem.item.updated))])
            treeItem=QTreeWidgetItem([scoreItem.item.title,])
            treeItem.article = scoreItem.item

            treeItem.setIcon(0, itemIcon)

#            # Set a part of the article text as the tooltip of Items
#            tipLong = purify.cleanText(item.article.description)
#            tip = purify.shorten(tipLong, 200)
#            treeItem.setToolTip(0, tip)

            if scoreItem.item.age is 0:
                treeItem.setFont(0, self.newFont)
                treeItem.setTextColor(0, self.newColor)

            elif scoreItem.item.age is 1:
                treeItem.setFont(0, self.unreadFont)
                treeItem.setTextColor(0, self.unreadColor)

            else:
                treeItem.setFont(0, self.readFont)
                treeItem.setTextColor(0, self.readColor)

            self.ui.listUnread.addTopLevelItem(treeItem)

        self.ui.listOld.setFocus()


    def displayRead(self):
        """
        function to update the read Articles list according to the selected feeds list.
        """
        pass

        selectedFeedIndex = self.ui.comboFeed.currentIndex()

        if len(self.feedList) == 0:
            self.readList = []
        else:

            if selectedFeedIndex == len(self.feedList):
                self.readList = fm.listRead()

            else:
                selectedFeed = self.feedList[selectedFeedIndex]

                self.readList = fm.listRead(selectedFeed)

        self.ui.listOld.clear()

        itemIcon = QIcon()
        itemIcon.addPixmap(QPixmap(":/images/article.png"), QIcon.Normal, QIcon.Off)

        for article in self.readList:
            treeItem=QTreeWidgetItem([article.title,])
            treeItem.article = article

            treeItem.setIcon(0, itemIcon)

            treeItem.setFont(0, self.readFont)
            treeItem.setTextColor(0, self.readColor)

            self.ui.listOld.addTopLevelItem(treeItem)

    def setCurrentFromUnread(self):
        """
        Function to set the currently selected Item in the Unread list as the self.currentItem
        """
        self.currentItem = self.ui.listUnread.currentItem()
        self.displayArticle()


    def setCurrentFromOld(self):
        """
        Function to set the currently selected Item in the Old list as the self.currentItem
        """
        self.currentItem = self.ui.listOld.currentItem()
        self.displayArticle()


    def displayArticle(self):
        """
        displays the selected article on the viewer.
        """
        try:
            selected = self.currentItem
            selectedItem = selected.article

            text = "<font face=Georgia color =#444444 >" + "<H3>" + selectedItem.title + \
                "</H3>(" + selectedItem.feed.title + ")<br>" + \
                time.ctime(selectedItem.updated) + "<br>" + \
                selectedItem.description + "</font>"
        except:
            text = "Add some interesting feeds!"
        else:
            self.ui.viewArticle.setHtml(text)
            windowTitle = selectedItem.title + " - " + selectedItem.feed.title + " - feedIO"
            self.setWindowTitle(windowTitle)

            if selectedItem.age == 0 or selectedItem.age == 1:
                selected.setFont(0, self.readFont)
                selected.setTextColor(0, self.readColor)
                fm.setItemFlag(selectedItem, 2)


    def markAsRead(self):
        # create font with normal weight to show the read articles
        selected = self.currentItem
        selected.setFont(0, self.readFont)
        selected.setTextColor(0,self.readColor)
        fm.setItemFlag(selected.article, 2)


    def markAsUnread(self):
        # create font with heavy weight to show the unread articles
        selected = self.currentItem
        selected.setFont(0, self.unreadFont)
        selected.setTextColor(0, self.unreadColor)
        fm.setItemFlag(selected.article, 1)


    def fetchAllFeeds(self):
        """
        Fetch all action implementataion. Creates a new thread and fetches the updates for them in that thread.
        """

        thread = threading.Thread(target=self.fetchAll, args=())
        thread.start()
#        thread.join()
#        self.displayItems()

    def fetchAll(self):
        print "fetching Updates..."
        fm.updateAll()

        print "Calculating priority Scores"
        self.parent.setNewItemScores()


    def fetchFeed(self):
        """
        Fetch the selected feed.
        """
        selected = self.currentItem
        thread = threading.Thread(target=fm.updateFeed, args=(selected.article.feed,))
        thread.start()


    def  visitPage(self):
        """
        function to visit the original web page of selected article from the built in web browser.
        """
        try:
            selected = self.currentItem
        except:
            text = "Not implemented yet."
        else:
            self.ui.viewArticle.load(QUrl(selected.article.url))

            self.parent.status = "Visiting %s in browser mode..." % selected.article.feed.title
            self.parent.sendNotification()



    def upVoteArticle(self):
        """
        Function to upvote the current article
        """
        selected = self.currentItem

        if selected == None:
            print "Nothing to vote!"
        else:
            selectedTopicIndex = self.ui.comboTopic.currentIndex()
            selectedTopic = self.topicList[selectedTopicIndex]

            #call the classifier module
            classifier.voteArticle("up",selected.article, selectedTopic.title)

            #upVote the feed
            classifier.voteFeed("up", selected.article.feed)
            print "Up Voted %s" % selected.article.title

            self.parent.status = "Up Voted %s under %s" % (selected.article.title, selectedTopic.title)
            self.parent.sendNotification()


    def downVoteArticle(self):
        """
        Function to Down Vote the current article
        """
        selected = self.currentItem

        if selected == None:
            print "Nothing to vote!"
        else:
            selectedTopicIndex = self.ui.comboTopic.currentIndex()
            selectedTopic = self.topicList[selectedTopicIndex]

            #call the classifier module
            classifier.voteArticle("down", selected.article, selectedTopic.title)

            #downVote the feed
            classifier.voteFeed("down", selected.article.feed)
            print "Down Voted %s" % selected.article.title

            self.parent.status = "Down Voted %s under %s" % (selected.article.title, selectedTopic.title)
            self.parent.sendNotification()


    def on_actionManageFeeds_activated(self, i = None):
        """
        Manage feeds action implementataion. displays the manageFeeds dialog box.
        """
        if i is None: return
        ManageFeedsDialog(self).exec_()
        self.displayFeeds()


    def on_actionAddFeed_activated(self, i = None):
        if i is None: return

        AddFeedDialog(self).exec_()
        self.displayFeeds()


    def on_actionRemoveFeed_activated(self, i = None):
        if i is None: return

        RemoveFeedDialog(self).exec_()
        self.displayFeeds()


    def on_actionManageTopics_activated(self, i = None):
        """
        Manage feeds action implementataion. displays the manageFeeds dialog box.
        """
        if i is None: return

        ManageTopicsDialog(self).exec_()
        self.displayTopics()


    def on_actionAddTopic_activated(self, i = None):
        if i is None: return

        AddTopicDialog(self).exec_()
        self.displayTopics()


    def on_actionRemoveTopic_activated(self, i = None):
        if i is None: return

        RemoveTopicDialog(self).exec_()
        self.displayTopics()


    def on_actionExit_activated(self, i = None):
        """
        Exit action implementataion. Exits the application.
        """
        if i is None: return
        self.parent.close()


    def on_actionMinimizeToTray_activated(self, i = None):
        """
        Exit action implementataion. Exits the application.
        """
        if i is None: return
        self.close()


    def on_actionAbout_activated(self, i = None):
        """
        About action implementataion.
        """
        if i is None: return
        AboutDialog(self).exec_()