Пример #1
0
 def _notify_emails(self, emails, always_show = None, allow_click = True):
     if self.enabled:
         fire('email.new', emails = emails,
                           onclick = self.OnClickEmail if allow_click else None,
                           always_show = always_show,
                           buttons = self.popup_buttons,
                           icon = self.icon)
Пример #2
0
    def on_error(self):
        # This is now really a cleanup routine, but without checking for every callsite,
        # it doesn't seem like a good idea to rename it
        do_fire = True
        if self.state not in self.states.ErrorStates:
            log.info('%r: %r is not an error. Not firing popup.', self,
                     self.state)
            do_fire = False
        else:
            log.info('%r: %r is a file transfer error. Firing popup...', self,
                     self.state)

        if self._done:
            return

        if do_fire:
            sending = self.direction == "outgoing"

            errmsg = _(
                'Failed to send {filename} to {name}') if sending else _(
                    'Failed to receive {filename} from {name}')

            fire('filetransfer.error',
                 sticky=False,
                 errmsg=errmsg.format(filename=self.name,
                                      name=self.buddy.name))

        if getattr(self, 'openfile', None) is not None:
            of, self.openfile = self.openfile, None
            of.close()

        self._done = True
Пример #3
0
    def on_error(self):
        # This is now really a cleanup routine, but without checking for every callsite,
        # it doesn't seem like a good idea to rename it
        do_fire = True
        if self.state not in self.states.ErrorStates:
            log.info('%r: %r is not an error. Not firing popup.', self, self.state)
            do_fire = False
        else:
            log.info('%r: %r is a file transfer error. Firing popup...', self, self.state)

        if self._done:
            return

        if do_fire:
            sending = self.direction == "outgoing"

            errmsg = _('Failed to send {filename} to {name}') if sending else _('Failed to receive {filename} from {name}')

            fire('filetransfer.error', sticky=False,
                 errmsg = errmsg.format(filename = self.name, name = self.buddy.name))


        if getattr(self, 'openfile', None) is not None:
            of, self.openfile = self.openfile, None
            of.close()

        self._done = True
Пример #4
0
def mailclient_launch_error(msg=None):
    if msg is None:
        msg = _('Could not start system mail client.')

    fire('error', title   = _('Error launching system mail client'),
                  msg     = msg,
                  details = '')
Пример #5
0
 def SendMessage(self, user_id, display_name, *a):
     event = dict(sender_uid = int(user_id))
     fire('tagged.toast',
          title = _('New Message to: %s') % display_name,
          msg = '',
          sticky = True,
          input = lambda text, opts, *a: self.connection.send_message(text, opts, event),
          popupid = ('tagged_toast!%r!%r' % (int(user_id), id(self.connection))))
Пример #6
0
def mailclient_launch_error(msg=None):
    if msg is None:
        msg = _('Could not start system mail client.')

    fire('error',
         title=_('Error launching system mail client'),
         msg=msg,
         details='')
Пример #7
0
 def _notify_emails(self, emails, always_show=None, allow_click=True):
     if self.enabled:
         fire('email.new',
              emails=emails,
              onclick=self.OnClickEmail if allow_click else None,
              always_show=always_show,
              buttons=self.popup_buttons,
              icon=self.icon)
Пример #8
0
 def SendMessage(self, user_id, display_name, *a):
     event = dict(sender_uid=int(user_id))
     fire('tagged.toast',
          title=_('New Message to: %s') % display_name,
          msg='',
          sticky=True,
          input=lambda text, opts, *a: self.connection.send_message(
              text, opts, event),
          popupid=('tagged_toast!%r!%r' %
                   (int(user_id), id(self.connection))))
Пример #9
0
    def notify(self, buddy, update):
        bkey = key(buddy)

        # stupid hack for common.buddy AND 'StatusMessage' as buddy objects
        try:
            # $$plugin status change
            if not plugin_act('digsby.im.status.change.pre', buddy):
                return
            plugin_act('digsby.im.status.change.async', buddy)
        except:
            info('invalid buddy')

        quiet = getattr(buddy.protocol, '_notifyquiet', False)
        selfbuddy = buddy is buddy.protocol.self_buddy

        #self.active[bkey] = update
        nots = self.determine_notifies(buddy, update)

        debug('Got the following notifies for update %r: %r', update, nots)

        def pop():
            debug('Removing %r from active dictionary', bkey)
            self.active.pop(bkey, None)

        try:
            watcher = self.watchers[bkey]
        except KeyError:
            pass
        else:
            watcher(update)

        fired = set()

        pop = CallCounter(
            len(nots), pop
        )  # Help! this isn't right. it should be the number of reactions that happened.

        for notify in nots:
            if notify['topic'] not in fired:
                fired.add(notify['topic'])
                notify['on_done'] = pop

                if not (quiet or selfbuddy):
                    fire(**notify)
                else:
                    if quiet:
                        reason = 'quiet'
                    elif selfbuddy:
                        reason = 'selfbuddy'
                    info('Not firing notifications for %r because of %r',
                         buddy, reason)
                    pop()
            else:
                pop()
Пример #10
0
    def Finalize(self):
        """
            Decompress the CWLs to make RWSs
        """
        def quote_encode(s):
            return '"%s"' % s.encode('filesys')

        aspell_opts = [
            "--lang=%s" % self.id,
            "--local-data-dir=%s" %
            quote_encode(LocalAspellDataDir().strip('\\')), "create", "master"
        ]
        decomp_opts = ['d']

        decomp_exe = ASPELLBINDIR / 'word-list-compress.exe'
        aspell_exe = ASPELLBINDIR / 'aspell.exe'

        startupinfo = subprocess.STARTUPINFO()  #@UndefinedVariable
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW  #@UndefinedVariable
        startupinfo.wShowWindow = subprocess.SW_HIDE  #@UndefinedVariable

        log.info('Decompressing wordlists')
        for cwl in self.cwl_files:
            rws = path(LocalAspellDataDir()) / cwl.namebase + '.rws'
            command = ['cmd', '/c', quote_encode(decomp_exe)] + decomp_opts + \
                       ['<', quote_encode(cwl), '|', quote_encode(aspell_exe)] + aspell_opts + [quote_encode(rws)]

            command = ' '.join(command)
            # this will raise an exception if the command fails, and callsback will call our error callback
            log.info('Decompressing %s', cwl)
            log.info("Executing: %r", command)
            subprocess.check_call(command, shell=True, startupinfo=startupinfo)
            os.remove(cwl)

        os.remove(self.bz2path)

        #Make the digsby dict
        local_dir = LocalAspellDataDir()
        digsby_dict_location = local_dir / ('digsby-%s.rws' % id)
        if not digsby_dict_location.isfile():
            try:
                MakeDigsbyDict(self.id, local_dir)
            except Exception:
                log.error(
                    "failed to create Digsby Dictionary in '%s', probable cause: dict not yet downloaded",
                    id)
                return None

        #dictionary installed notification
        fire('dictionary.install',
             title=_('Dictionary Installed'),
             msg=_('Setting spellcheck language...'),
             popupid='dict_install_%s' % self.id)
        return True
Пример #11
0
 def on_error(response, *a, **k):
     # if we don't have stream publish permissions, show a popup allowing
     # the user to grant it.
     if isinstance(response, fberrors.FacebookError) and int(response.tag.error_code) == 200:
         fire(
             'error', title=_('Facebook Error'),
             major = _('Error posting {thing}').format(thing=thing),
             minor = _('Digsby does not have permission to publish to your stream.'),
             buttons = [(_('Grant Permissions'), self.do_grant),
                        (_('Close'), lambda: None)]
         )
Пример #12
0
 def on_error(response, *a, **k):
     # if we don't have stream publish permissions, show a popup allowing
     # the user to grant it.
     if isinstance(response, fberrors.FacebookError) and int(response.tag.error_code) == 200:
         fire(
             "error",
             title=_("Facebook Error"),
             major=_("Error posting {thing}").format(thing=thing),
             minor=_("Digsby does not have permission to publish to your stream."),
             buttons=[(_("Grant Permissions"), self.do_grant), (_("Close"), lambda: None)],
         )
Пример #13
0
 def fail(self, check, answer=None, *a, **k):
     if isinstance(answer, dict) and answer.get('read_stream', None) == 0:
         try:
             fire(
                 'error',
                 title="Facebook Error",
                 major="Permission Missing - News Feed",
                 minor=('Digsby requires permission to access your News Feed to function properly.'
                        '  This permission was not allowed.')
             )
         except Exception:
             traceback.print_exc()
     self.set_offline(self.Reasons.BAD_PASSWORD)
Пример #14
0
    def newsfeed_popups(self, filter_old=True):
        log.info("doing newsfeed popups")
        s = self.connection.last_stream
        old_ids = self.old_stream_ids if filter_old else ()
        feed = s["posts"]
        new_posts = []
        for post in feed:
            if post["post_id"] in old_ids:
                log.info("post %r is old", post["post_id"])
                break
            source = post.get("source_id")
            actor = post.get("actor_id")
            viewer = post.get("viewer_id")
            try:
                do_add = source and viewer and int(source) != int(viewer) and int(actor) != int(viewer)
            except ValueError:
                do_add = True
            if do_add:
                new_posts.append(post)
            else:
                log.info("filtered message %s because it came from this account", post["post_id"])

        options = dict(buttons=self.get_popup_buttons)

        if new_posts:
            from gui import skin

            if common.pref("facebook.popups.user_icons", default=True):
                from gui.browser.webkit.imageloader import LazyWebKitImage

                default_icon = skin.get("serviceicons.facebook", None)
                for post in new_posts:
                    try:
                        url = s.profiles[int(post["actor_id"])].pic_square
                    except Exception:
                        traceback.print_exc()
                    else:
                        post.icon = LazyWebKitImage(url, default_icon)

            fire(
                "facebook.newsfeed",
                profiles=s["profiles"],
                posts=new_posts,
                popupid="%d.facebook" % id(self),
                update="paged",
                badge=skin.get("serviceicons.facebook", None),
                scrape_clean=string_helpers.scrape_clean,
                onclick=self.on_popup_click_post,
                **options
            )
        self.old_stream_ids = set(self.connection.last_stream["post_ids"])
Пример #15
0
    def notify(self, buddy, update):
        bkey = key(buddy)

        # stupid hack for common.buddy AND 'StatusMessage' as buddy objects
        try:
            # $$plugin status change
            if not plugin_act('digsby.im.status.change.pre', buddy):
                return
            plugin_act('digsby.im.status.change.async', buddy)
        except:
            info('invalid buddy')

        quiet  = getattr(buddy.protocol, '_notifyquiet', False)
        selfbuddy = buddy is buddy.protocol.self_buddy

        #self.active[bkey] = update
        nots = self.determine_notifies(buddy, update)

        debug('Got the following notifies for update %r: %r', update, nots)

        def pop():
            debug('Removing %r from active dictionary', bkey)
            self.active.pop(bkey, None)

        try:
            watcher = self.watchers[bkey]
        except KeyError:
            pass
        else:
            watcher(update)

        fired = set()

        pop = CallCounter(len(nots), pop) # Help! this isn't right. it should be the number of reactions that happened.

        for notify in nots:
            if notify['topic'] not in fired:
                fired.add(notify['topic'])
                notify['on_done'] = pop

                if not (quiet or selfbuddy):
                    fire(**notify)
                else:
                    if quiet:
                        reason = 'quiet'
                    elif selfbuddy:
                        reason = 'selfbuddy'
                    info('Not firing notifications for %r because of %r', buddy, reason)
                    pop()
            else:
                pop()
Пример #16
0
    def Install(self, callback=None):
        log.info('Installing Dictionary...')

        #fire a notification
        fire('dictionary.install',
             title=_('Installing Dictionary'),
             msg=_('Dictionary will be activated after install completes.'),
             popupid='dict_install_%s' % self.id)

        #go Extract, then Finalize on success
        self.Extract(error=callback.error,
                     success=lambda: self.Finalize(callback=callback))

        log.info('Finished Installing Dictionary')
Пример #17
0
 def fail(self, check, answer=None, *a, **k):
     if isinstance(answer, dict) and answer.get("read_stream", None) == 0:
         try:
             fire(
                 "error",
                 title="Facebook Error",
                 major="Permission Missing - News Feed",
                 minor=(
                     "Digsby requires permission to access your News Feed to function properly."
                     "  This permission was not allowed."
                 ),
             )
         except Exception:
             traceback.print_exc()
     self.set_offline(self.Reasons.BAD_PASSWORD)
Пример #18
0
    def Install(self, callback=None):
        log.info("Installing Dictionary...")

        # fire a notification
        fire(
            "dictionary.install",
            title=_("Installing Dictionary"),
            msg=_("Dictionary will be activated after install completes."),
            popupid="dict_install_%s" % self.id,
        )

        # go Extract, then Finalize on success
        self.Extract(error=callback.error, success=lambda: self.Finalize(callback=callback))

        log.info("Finished Installing Dictionary")
Пример #19
0
    def newsfeed_popups(self, filter_old=True):
        log.info('doing newsfeed popups')
        s = self.connection.last_stream
        old_ids = self.old_stream_ids if filter_old else ()
        feed = s['posts']
        new_posts = []
        for post in feed:
            if post['post_id'] in old_ids:
                log.info('post %r is old', post['post_id'])
                break
            source = post.get('source_id')
            actor  = post.get('actor_id')
            viewer = post.get('viewer_id')
            try:
                do_add = source and viewer and int(source) != int(viewer) and int(actor) != int(viewer)
            except ValueError:
                do_add = True
            if do_add:
                new_posts.append(post)
            else:
                log.info('filtered message %s because it came from this account', post['post_id'])

        options = dict(buttons=self.get_popup_buttons)

        if new_posts:
            from gui import skin
            if common.pref('facebook.popups.user_icons', default=True):
                from gui.browser.webkit.imageloader import LazyWebKitImage
                default_icon = skin.get('serviceicons.facebook', None)
                for post in new_posts:
                    try:
                        url = s.profiles[int(post['actor_id'])].pic_square
                    except Exception:
                        traceback.print_exc()
                    else:
                        post.icon = LazyWebKitImage(url, default_icon)

            fire(
                'facebook.newsfeed',
                profiles = s['profiles'],
                posts=new_posts,
                popupid='%d.facebook' % id(self),
                update='paged',
                badge=skin.get('serviceicons.facebook', None),
                scrape_clean=string_helpers.scrape_clean,
                onclick = self.on_popup_click_post, **options
            )
        self.old_stream_ids = set(self.connection.last_stream['post_ids'])
Пример #20
0
    def notification_popups(self, filter_old=True, filter_read=True):
        log.info("doing notification popups")
        s = self.connection.last_stream
        old_ids = self.old_notification_ids if filter_old else ()
        new_notifications = []
        notifications = s["notifications"]
        for notification in notifications:
            if filter_read and int(notification["is_unread"]) != 1:
                continue
            if notification["notification_id"] in old_ids:
                log.info("notification %r is old", notification["notification_id"])
                break
            if not notification["title_text"]:
                continue
            new_notifications.append(notification)

        if new_notifications:
            from gui import skin

            options = {}
            if common.pref("facebook.popups.user_icons", default=True):
                from gui.browser.webkit.imageloader import LazyWebKitImage

                default_icon = skin.get("serviceicons.facebook", None)
                for notification in new_notifications:
                    try:
                        url = s.profiles[int(notification["sender_id"])].pic_square
                    except Exception:
                        traceback.print_exc()
                    else:
                        notification.icon = LazyWebKitImage(url, default_icon)
            fire(
                "facebook.notifications",
                profiles=s["profiles"],
                notifications=new_notifications,
                popupid="%d.facebook" % id(self),
                update="paged",
                sticky=common.pref("facebook.notifications.sticky_popup", type=bool, default=False),
                badge=skin.get("serviceicons.facebook", None),
                onclick=self.on_popup_click_notification,
                **options
            )

        self.old_notification_ids = set(n["notification_id"] for n in notifications)
Пример #21
0
    def _ondone(self):
        oldstate = self.state
        if self.state in self.states.TransferringStates:
            self.state = self.states.FINISHED

        if self.state in self.states.CompleteStates:
            fire('filetransfer.ends',
                 filetransfer = self,
                 buddy = self.buddy,
                 target = self,
                 onclick = lambda *a: self.filepath.openfolder()) # clicking the popup opens the folder
        elif self.state in self.states.FailStates:
            #see comment in on_error
            self.on_error()

        self._done = True

        if oldstate != self.state:
            self.notify('state', oldstate, self.state)
Пример #22
0
    def _ondone(self):
        oldstate = self.state
        if self.state in self.states.TransferringStates:
            self.state = self.states.FINISHED

        if self.state in self.states.CompleteStates:
            fire('filetransfer.ends',
                 filetransfer=self,
                 buddy=self.buddy,
                 target=self,
                 onclick=lambda *a: self.filepath.openfolder()
                 )  # clicking the popup opens the folder
        elif self.state in self.states.FailStates:
            #see comment in on_error
            self.on_error()

        self._done = True

        if oldstate != self.state:
            self.notify('state', oldstate, self.state)
Пример #23
0
    def alerts_update(self, event, *a):
        def onclick(link):
            if link != '':
                TU.launchbrowser(link)

        # event : {'alerts_updated', 'alert_type'}
        if event['alerts_updated']:
            self.getAlerts(success = lambda *a: self.acct.set_dirty(),
                           error = lambda *a: self.set_offline(self.acct.Reasons.CONN_LOST)) # To re-render the Alerts in the infobox

            type = event['alert_type']
            strings = alerts.popup_strings

            if self.acct.whitelist[type]:
                # TODO strings[type]['link'] sometimes look like something.html?a=A&b=B. the ? part seems to get lost after the weblink
                fire('tagged.alert',
                     title = 'Tagged Alert',
                     msg = strings[type]['string'],
                     popupid = 'tagged.alert!%r' % id(self),
                     onclick = lambda *a: onclick(strings[type]['link']))
Пример #24
0
    def notification_popups(self, filter_old=True, filter_read=True):
        log.info('doing notification popups')
        s = self.connection.last_stream
        old_ids = self.old_notification_ids if filter_old else ()
        new_notifications = []
        notifications = s['notifications']
        for notification in notifications:
            if filter_read and int(notification['is_unread']) != 1:
                continue
            if notification['notification_id'] in old_ids:
                log.info('notification %r is old', notification['notification_id'])
                break
            if not notification['title_text']:
                continue
            new_notifications.append(notification)

        if new_notifications:
            from gui import skin
            options = {}
            if common.pref('facebook.popups.user_icons', default=True):
                from gui.browser.webkit.imageloader import LazyWebKitImage
                default_icon = skin.get('serviceicons.facebook', None)
                for notification in new_notifications:
                    try:
                        url = s.profiles[int(notification['sender_id'])].pic_square
                    except Exception:
                        traceback.print_exc()
                    else:
                        notification.icon = LazyWebKitImage(url, default_icon)
            fire(
                'facebook.notifications',
                profiles = s['profiles'],
                notifications=new_notifications,
                popupid='%d.facebook' % id(self),
                update='paged',
                sticky = common.pref('facebook.notifications.sticky_popup', type = bool, default = False),
                badge=skin.get('serviceicons.facebook', None),
                onclick = self.on_popup_click_notification, **options
            )

        self.old_notification_ids = set(n['notification_id'] for n in notifications)
Пример #25
0
    def toast_update(self, event, *a):
        def meetme(*a):
            '''meetme : {'age', 'gender', 'location', 'sender_display_name', 'sender_url',
                         'sender_thumbnail', 'sender_uid', 'meetme_url', 'isMatch'}'''
            fire_opts.update(title = _('Meet Me') + _('Match from: %s') if event['isMatch'] else _('Interest from: %s') % event['sender_display_name'],
                             msg = '')
            if event['isMatch']:
                fire_opts.update(input = lambda text, opts, *a: self.send_message(text, opts, event))

        def message(*a):
            '''message : {'sender_display_name', 'sender_url', 'sender_uid',
                          'subject', 'message', 'message_id', 'sender_thumbnail'}'''
            fire_opts.update(title = _('New Message from: %s') % event['sender_display_name'],
                             msg = strings.strip_html(event['message']).strip(),
                             sticky = True,
                             input = lambda text, opts, *a: self.send_message(text, opts, event))

        def friend_request(*a):
            '''friend_request : {'isNewFriend', 'age', 'gender', 'location', 'sender_display_name',
                                 'sender_url', 'sender_uid', 'sender_thumbnail'}'''
            fire_opts.update(title = _('%s is now your friend') if event['isNewFriend'] else _('Friend Request from: %s') % event['sender_display_name'],
                             msg = '')
            if event['isNewFriend']:
                fire_opts.update(input = lambda text, opts, *a: self.send_message(text, opts, event))

        def topics(*a):
            '''topics : {'topics_type', 'conv_id', 'post_id', 'init_text', 'text', 'sender_displayName',
                         'sender_url', 'sender_thumbnail', 'sender_uid'}'''
            pass # TODO implement topics

        fire_opts = dict(onclick = lambda *a: TU.launchbrowser(event['sender_url']),
                         popupid = 'tagged_toast!%r!%r' % (event['sender_uid'], id(self)))

        {'meetme'         : meetme,
         'message'        : message,
         'friend_request' : friend_request,
         'topics'         : topics
         }[event['sub_type']]()

        if event['sub_type'] != 'topics': # TODO implement topics
            fire('tagged.toast', **fire_opts)
Пример #26
0
    def elections_project_contribution(self, event, *a):
        '''project : {'hash', 'total_contributions', 'contributors', 'max_contribution',
                      'starter_id', 'contributions', 'id', 'starter', 'num_contributors',
                      'finish_time', 'state', 'catalog_id', 'time_remaining'}'''

        project = event['project']
        state = project['state']

        if state == -1:  # FAILED
            msg = _('not able to get fully funded')

        elif state == 0: # ACTIVE
            msg = _('contributed')

        elif state == 1: # COMPLETED
            msg = _('completed')

        fire('tagged.elections',
             title = _('Elections'),
             msg = _('A project was %s') % msg, # TODO we need the projects catalog to be more specific
             onclick = lambda *a: TU.launchbrowser('apps/elections.html'))
Пример #27
0
        def on_install_success():
            log.info('%r has been installed.', need)

            #Swap out the language if the new language is still selected
            if self.expectedNext == need:
                #Attempt the swap and fire a notification on success
                if self.SwapEngine(shouldDownloadOnFail=False):
                    fire(
                        'dictionary.install',
                        title=_('Dictionary Set'),
                        msg=_('Spellcheck language has been set to {langname}.'
                              ).format(langname=langName),
                        popupid='dict_install_%s' % self.lang)
                #If successfull download and install, but fails to load, fire a error notification
                else:
                    fire(
                        'dictionary.install',
                        title=_('Spellcheck error'),
                        msg=
                        _('Failed setting up dictionary. Try reselecting desired language in the preferences.'
                          ),
                        popupid='dict_install_%s' % self.lang)

            #if no longer the set language announce the install was complete
            else:
                fire(
                    'dictionary.install',
                    title=_('Dictionary Installed'),
                    msg=
                    _('You can set this language in the conversation preferences.'
                      ),
                    popupid='dict_install_%s' % self.lang)

            #Remove the language from current downloads
            self.currentDownloads.discard(need)
Пример #28
0
        def on_install_success():
            log.info("%r has been installed.", need)

            # Swap out the language if the new language is still selected
            if self.expectedNext == need:
                # Attempt the swap and fire a notification on success
                if self.SwapEngine(shouldDownloadOnFail=False):
                    fire(
                        "dictionary.install",
                        title=_("Dictionary Set"),
                        msg=_("Spellcheck language has been set to {langname}.").format(langname=langName),
                        popupid="dict_install_%s" % self.lang,
                    )
                # If successfull download and install, but fails to load, fire a error notification
                else:
                    fire(
                        "dictionary.install",
                        title=_("Spellcheck error"),
                        msg=_("Failed setting up dictionary. Try reselecting desired language in the preferences."),
                        popupid="dict_install_%s" % self.lang,
                    )

            # if no longer the set language announce the install was complete
            else:
                fire(
                    "dictionary.install",
                    title=_("Dictionary Installed"),
                    msg=_("You can set this language in the conversation preferences."),
                    popupid="dict_install_%s" % self.lang,
                )

            # Remove the language from current downloads
            self.currentDownloads.discard(need)
Пример #29
0
    def fire_notifications(self, old_alerts, new_alerts):
        '''
        fires notifications for new information from facebook.
        '''
        log.debug('doing alert notifications')

        alerts = new_alerts - old_alerts
        if alerts and self.enabled:

            # newer, and still exists
            TITLE     = _("Facebook Alerts")

            fire_alerts = list()
            def firealert(msg, onclick):
                fire_alerts.append((msg, onclick))

            if alerts.msgs_time > 0 and new_alerts['num_msgs']:
                firealert(_('You have new messages.'), 'msgs')

            if alerts.pokes_time > 0 and new_alerts['num_pokes']:
                firealert(_('You have new pokes.'),    'pokes')

            if alerts.shares_time > 0 and new_alerts['num_shares']:
                firealert(_('You have new shares.'), 'shares')

            if alerts['num_friend_requests']:
                firealert(_('You have new friend requests.'), 'friend_requests')

            if alerts['num_group_invites']:
                firealert(_('You have new group invites.'), 'group_invites')

            if alerts['num_event_invites']:
                firealert(_('You have new event invites.'), 'event_invites')

            #this one isn't really useful by itself
            #we should check if the popups for notifications are on
            if alerts['num_notifications'] and fire_alerts:
                firealert(_('You have new notifications.'), 'notifications')

            if fire_alerts:
                if len(fire_alerts) > 1:
                    # With more than one type of new alert, just go to the main facebook page.
                    onclick = self.facebook_url
                else:
                    # Otherwise, get a more specific URL from Alerts.urls
                    msg, url_type = fire_alerts[0]
                    onclick = alerts.urls[url_type]

                message = u'\n'.join(k for k,_v in fire_alerts)

                fire(
                    'facebook.alert',
                    title   = TITLE,
                    msg     = message,
                    buttons = lambda item: [], # this is necessary until popups recognize "None" as clearing buttons.
                    update='paged',
                    popupid = '%d.facebook' % id(self),
                    onclick = onclick
                )

        if self.enabled:
            self.notify('count')
Пример #30
0
def fire(topic, *args, **kwargs):
    from common.notifications import fire
    fire(topic, *args, **kwargs)
Пример #31
0
def mailclient_error():
    # Show an error popup if there is no mail client at all.
    fire('error',
         title=_('No System Email Client'),
         msg=_('No system email client is configured.'),
         details='')
Пример #32
0
def mailclient_error():
    # Show an error popup if there is no mail client at all.
    fire('error', title   = _('No System Email Client'),
                  msg     = _('No system email client is configured.'),
                  details = '')
Пример #33
0
def fire(topic, *args, **kwargs):
    from common.notifications import fire
    fire(topic, *args, **kwargs)
Пример #34
0
def fire(*a, **k):
    from common.notifications import fire
    return fire(*a, **k)
Пример #35
0
def fire(*a, **k):
    from common.notifications import fire
    return fire(*a, **k)
Пример #36
0
def fire_notifications(msg, win, isnew, mode, hidden=False):
    '''
    Relays message information to the notifications system, for things like
    popups and sound effects.

    msg     a message object storage
    win     the ImWin about to show this message
    isnew   a bool indicating if the ImWin is "new"
    '''

    if msg is None or msg.buddy is None: return []

    convo = msg.conversation
    bud = msg.buddy

    def stop_notify(win=win):
        if win:
            try:
                win.Unnotify()
            except wx.PyDeadObjectError:
                pass
            else:
                if not win.Top.AnyNotified and pref('conversation_window.notify_flash'):
                    win.Top.StopFlashing()
        if hidden and pref('messaging.popups.close_dismisses_hidden', False):
            _remove_hidden_message(bud, msg)

    if msg.get('content_type', 'text/html') in ('text/html', 'text/xhtml'):
        try:
            popup_message = strip_html2(msg.message).decode('xml')
        except Exception:
            print_exc()
            popup_message = msg.message
    else:
        popup_message = msg.message

    # decide on options to pass to the popup
    fire_opts = dict(buddy = bud,
                     onuserclose = stop_notify)

    ischat = convo is not None and convo.ischat
    if ischat:
        from gui import skin
        fire_opts.update(header = _('Group Chat ({chat.chat_member_count:d})').format(chat=convo),
                         msg = _('{alias:s}: {message:s}').format(alias=bud.alias, message=popup_message),
                         icon = skin.get('ActionsBar.Icons.RoomList', None),
                         popupid = 'chat!!!%r!!!%r' % (convo.protocol.name, convo.chat_room_name))
    else:
        fire_opts.update(msg = popup_message,
                         icon = bud.buddy_icon if bud is not None else convo.icon,
                         popupid = msg.buddy.idstr())


    # Clicking on the popup should open that buddy's message window.
    #  - if there is text entered in the popup and not the IM window,
    #    copy it there
    if bud is not None:
        def click_popup(text):
            if pop_any_hidden(bud):
                return

            if convo.ischat:
                on_message(convo = convo, raisenow = True)
            else:
                begin_conversation(bud)

            if win:
                try:
                    val = win.input_area.Value
                except wx.PyDeadObjectError:
                    pass
                else:
                    if not val:
                        win.input_area.Value = text
                        wx.CallAfter(win.TextCtrl.SetInsertionPointEnd)

        fire_opts.update(onclick = click_popup)

    notification = _get_notification_types(bud, convo, win, hidden, isnew)

    def send_from_popup(text, options, convo = convo, win = win, opts = fire_opts.copy()):
        if not text: return

        CallLater(200, stop_notify)

        # if the window's still around, use its formatting
        convo.send_message(fmtstr.singleformat(text, format=_get_format(win)))

        if not wx.GetKeyState(wx.WXK_CONTROL):
            # returning a string appends it to the popup's content.
            return '> ' + text

        # returning None results in the popup closing

    fire_opts['input'] = send_from_popup

    return fire(notification, **fire_opts)
Пример #37
0
    def Finalize(self):
        """
            Decompress the CWLs to make RWSs
        """

        def quote_encode(s):
            return '"%s"' % s.encode("filesys")

        aspell_opts = [
            "--lang=%s" % self.id,
            "--local-data-dir=%s" % quote_encode(LocalAspellDataDir().strip("\\")),
            "create",
            "master",
        ]
        decomp_opts = ["d"]

        decomp_exe = ASPELLBINDIR / "word-list-compress.exe"
        aspell_exe = ASPELLBINDIR / "aspell.exe"

        startupinfo = subprocess.STARTUPINFO()  # @UndefinedVariable
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW  # @UndefinedVariable
        startupinfo.wShowWindow = subprocess.SW_HIDE  # @UndefinedVariable

        log.info("Decompressing wordlists")
        for cwl in self.cwl_files:
            rws = path(LocalAspellDataDir()) / cwl.namebase + ".rws"
            command = (
                ["cmd", "/c", quote_encode(decomp_exe)]
                + decomp_opts
                + ["<", quote_encode(cwl), "|", quote_encode(aspell_exe)]
                + aspell_opts
                + [quote_encode(rws)]
            )

            command = " ".join(command)
            # this will raise an exception if the command fails, and callsback will call our error callback
            log.info("Decompressing %s", cwl)
            log.info("Executing: %r", command)
            subprocess.check_call(command, shell=True, startupinfo=startupinfo)
            os.remove(cwl)

        os.remove(self.bz2path)

        # Make the digsby dict
        local_dir = LocalAspellDataDir()
        digsby_dict_location = local_dir / ("digsby-%s.rws" % id)
        if not digsby_dict_location.isfile():
            try:
                MakeDigsbyDict(self.id, local_dir)
            except Exception:
                log.error("failed to create Digsby Dictionary in '%s', probable cause: dict not yet downloaded", id)
                return None

        # dictionary installed notification
        fire(
            "dictionary.install",
            title=_("Dictionary Installed"),
            msg=_("Setting spellcheck language..."),
            popupid="dict_install_%s" % self.id,
        )
        return True
Пример #38
0
    def fire_notifications(self, old_alerts, new_alerts):
        """
        fires notifications for new information from facebook.
        """
        log.debug("doing alert notifications")

        alerts = new_alerts - old_alerts
        if alerts and self.enabled:

            # newer, and still exists
            TITLE = _("Facebook Alerts")

            fire_alerts = list()

            def firealert(msg, onclick):
                fire_alerts.append((msg, onclick))

            if alerts.msgs_time > 0 and new_alerts["num_msgs"]:
                firealert(_("You have new messages."), "msgs")

            if alerts.pokes_time > 0 and new_alerts["num_pokes"]:
                firealert(_("You have new pokes."), "pokes")

            if alerts.shares_time > 0 and new_alerts["num_shares"]:
                firealert(_("You have new shares."), "shares")

            if alerts["num_friend_requests"]:
                firealert(_("You have new friend requests."), "friend_requests")

            if alerts["num_group_invites"]:
                firealert(_("You have new group invites."), "group_invites")

            if alerts["num_event_invites"]:
                firealert(_("You have new event invites."), "event_invites")

            # this one isn't really useful by itself
            # we should check if the popups for notifications are on
            if alerts["num_notifications"] and fire_alerts:
                firealert(_("You have new notifications."), "notifications")

            if fire_alerts:
                if len(fire_alerts) > 1:
                    # With more than one type of new alert, just go to the main facebook page.
                    onclick = self.facebook_url
                else:
                    # Otherwise, get a more specific URL from Alerts.urls
                    msg, url_type = fire_alerts[0]
                    onclick = alerts.urls[url_type]

                message = u"\n".join(k for k, _v in fire_alerts)

                fire(
                    "facebook.alert",
                    title=TITLE,
                    msg=message,
                    buttons=lambda item: [],  # this is necessary until popups recognize "None" as clearing buttons.
                    update="paged",
                    popupid="%d.facebook" % id(self),
                    onclick=onclick,
                )

        if self.enabled:
            self.notify("count")