コード例 #1
0
 def handleGetExistingPurchasesResponse(self, event):
     print(event, event.type, event.code)
     if (event.type == SUCCESS_RESPONSE):
         purchases = self.getPurchases(event)
         tart.send('existingPurchasesResponse', purchases=purchases)
     elif (event.type == FAILURE_RESPONSE): 
         self.handleErrorResponse(event)
コード例 #2
0
 def onSendComment(self, source, text):
     res = self.sess.postComment(source, text)
     text = text.replace('*', '')
     if (res == True):
         tart.send('commentPosted', result="true", comment=text)
         return
     tart.send('commentPosted', result="false", comment="")
コード例 #3
0
 def send_flags_message(self):
     allowed = bbmsp_is_access_allowed()
     access = self.get_access_code()
     profile = bbmsp_can_show_profile_box()
     invite = bbmsp_can_send_bbm_invite()
     tart.send('bbmFlags', allowed=allowed, access=access,
         profile=profile, invite=invite)
コード例 #4
0
 def onGetGlobalStream(self):
     from adn.adn import Adn
     app = Adn()
     self.stream = app.globalStream()
     validStream = True
     for item in self.stream['data']:
         if 'html' in item:
             item['html'] = item['html'].replace("<br>", "<br/>")
             validStream = True
         else:
             validStream = False
     if validStream:
         tart.send('receivedGlobalStream', stream=self.stream)
         import tempfile
         temp_dir = tempfile.gettempdir()
         import os
         for the_file in os.listdir(temp_dir):
             filepath = os.path.join(temp_dir, the_file)
             try: 
                 if os.path.isfile(filepath):
                     os.unlink(filepath)
             except Exception as e:
                 print(e)
         self.getAvatarImages()
     else:
         self.onGetGlobalStream()
コード例 #5
0
ファイル: app.py プロジェクト: joelghill/snappy
    def onParseFeed(self, snaps):
        print("Parsing snaps...")
        for snap in snaps:
            if 'media' not in snap:
                snap['media'] = ''
            if snap['countdown'] != '':
                snap['countdown'] = int(snap['countdown'])
            print("MEDIA TYPE NUMBER", snap['media_type'])
            snap['time'] = self.prettyDate(snap['sent'] // 1000)
            if snap['media_type'] == 0:
                snap['media'] = 'picture'
            elif snap['media_type'] in [1, 2]:
                snap['media'] = 'video'
            if snap['recipient'] == '': # Snap recieved
                snap['type'] = 'Recieved' # recieved == 1
            else:
                snap['user'] = snap['recipient']
                print(snap['opened'])
                if snap['opened'] == 1:
                    snap['type'] = 'Opened' # sent == 2
                    snap['media'] = 'sent'
                else:
                    snap['type'] = 'Sent' # sent == 2
                    snap['media'] = 'sent'
            if snap['media_type'] != '':
                if int(snap['media_type']) >= 3: # Notifications
                    snap['type'] = 'Notification' # notif == 3

        for result in sorted(snaps, key=itemgetter('type')):
            tart.send('snapsReceived', snap=result)
コード例 #6
0
ファイル: app.py プロジェクト: HorizonXP/blackberry-py
    def onUiReady(self):
        # need to defer sending this, for now, until the event loop has started
        tart.send('restoreSettings', **self.settings)

        # install BPS event handler for vkb events, which for now reports
        # "keyboardState" events with boolean property "visible"
        vkb_handler.VkbHandler(self.bps_dispatcher)
コード例 #7
0
ファイル: app.py プロジェクト: rmquapp/Reader-YC
 def onCopyComment(self, comment, poster):
     soup = BeautifulSoup(comment)
     from tart import clipboard
     c = clipboard.Clipboard()
     mimeType = 'text/plain'
     c.insert(mimeType, str(soup.text))
     tart.send('commentCopied', poster=poster)
コード例 #8
0
    def onParseFeed(self, updates):
        snaps = []
        for item in updates['snaps']:
            snap = {
            'url': item['id'],
            'media_id': self.testEmpty(item, 'c_id'),
            'media_type': self.testEmpty(item, 'm'), # >3 Friend Request
            'time': self.testEmpty(item,'t'),
            'sender': self.testEmpty(item, 'sn'),
            'recipient': self.testEmpty(item, 'rp'),
            'status': item['st'], # Sent, Delivered, Opened, Screenshotted
            'sent': item['sts'],
            'opened': item['ts']
            }
            if snap['media_type'] == 0:
                snap['media'] = 'image'
            elif snap['media_type'] in [1, 2]:
                snap['media'] = 'video'
            if snap['recipient'] == '': # Snap recieved
                snap['type'] = '1' # recieved == 1
            else:
                snap['type'] = '2' # sent == 2

            if snap['media_type'] >= 3: # Notifications
                snap['type'] = '3' # notif == 3

            snaps.append(snap)
        for result in sorted(snaps, key=itemgetter('type')):
            tart.send('snapsRecieved', snap=result)
コード例 #9
0
ファイル: app.py プロジェクト: krruzic/GitDating
    def onCopy(self, data):
        from tart import clipboard

        c = clipboard.Clipboard()
        mimeType = "text/plain"
        c.insert(mimeType, articleLink)
        tart.send("copyResult", text=data + " copied to clipboard!")
コード例 #10
0
ファイル: app.py プロジェクト: HorizonXP/blackberry-py
    def run(self):
        while True:
            # wait for some time or for someone to signal us
            try:
                msg = self.queue.get(timeout=self.CHECK_PERIOD)
            except queue.Empty:
                pass
            else:
                print('got', msg)
                if msg is None:
                    break
                # process msg, if any

            changed = []
            for target in os.listdir(self.folder):
                if not target.endswith('.qml'):
                    # print('ignoring', target)
                    continue
                if re.match(self.CLONE_PAT, target):
                    # print('ignoring', target)
                    continue

                tpath = os.path.join(self.folder, target)
                stat = os.stat(tpath)
                signature = (stat.st_mtime, stat.st_size)
                if signature != self._prev_sigs.get(target):
                    print('sig', target, signature)
                    self._prev_sigs[target] = signature
                    changed.append(target)

            if changed:
                print('files changed: {}'.format(', '.join(sorted(changed))))
                path = self.clone_target()
                tart.send('fileChanged', path=path)
コード例 #11
0
ファイル: app.py プロジェクト: rmquapp/Reader-YC
 def onSendComment(self, source, text):
     res = self.sess.postComment(source, text)
     text = text.replace('*', '')
     if (res == True):
         tart.send('commentPosted', result="true", comment=text)
         return
     tart.send('commentPosted', result="false", comment="")
コード例 #12
0
    def handle_event(self, bps_event):
        '''Handle BPS events for bbmsp domain'''

        # print('domain', domain, 'bbm_domain', bbmsp_get_domain())
        event = self.make_event(bps_event)
        if event.is_reg_state_event():
            # TODO: build the code into the event somehow (can you
            # retrieve it from the event?)
            self.prev_access = code = self.get_access_code()
            tart.send('bbmAccess', state=code,
                text=self.REG_STATE_NAMES.get(code, '?unrecognized?'))
            # tart.send('bbmAccessTest', state=code,
            #     text=self.REG_STATE_NAMES.get(code, '?unrecognized?'))

        else:
            code = self.get_access_code()
            if code != self.prev_access:
                self.prev_access = code

                tart.send('bbmAccess', state=code,
                    text=self.REG_STATE_NAMES.get(code, '?unrecognized?'))
                # tart.send('bbmAccessTest', state=code,
                #     text=self.REG_STATE_NAMES.get(code, '?unrecognized?'))

                fake_event = BbmEvent(0,
                    BBMSP_REGISTRATION,
                    BBMSP_SP_EVENT_ACCESS_CHANGED,
                    None,
                    fake=True)
                self.fsm.execute(fake_event)

        if event.is_user_profile_event():
            self.check_user_profile_event(event)

        self.fsm.execute(event)
コード例 #13
0
ファイル: app.py プロジェクト: MobileAppQueen/GitDating
 def onFillList(self):
     print("Getting list of users....")
     gd = gitDate()
     results = gd.calculateCompatibility(self.personalData)
     print("List Received!!")
     for result in results:
         tart.send('datesReceived', result=result)
コード例 #14
0
ファイル: app.py プロジェクト: HorizonXP/blackberry-py
    def parseFeed(self, feed):
        print('parsing', feed.feed.title, feed.updated)
        self.state['last_published'] = time.mktime(feed.updated_parsed)
        self.state['last_checked'] = time.time()
        url = self.state['site_url'] = feed.feed.link
        tart.send('siteUrl', url=url)

        print('found entries:', len(feed.entries))
        count = 0
        for item in feed.entries:
            # ignore ones we've already seen
            if item.link in self.entries:
                print('ignoring, known', item.link)
                continue

            count += 1
            imagepath = self.addImage(item)
            tags = {x.term for x in item.tags} - {'Uncategorized'}
            entry = {
                'url': item.link,
                'title': item.title,
                'pubtime': time.mktime(item.published_parsed),
                'image': imagepath,
                'summary': item.summary.split('Filed under')[0].strip(),
                'tags': ', '.join(sorted(tags)),
                }

            self.addEntry(entry)
            self.entries[entry['url']] = entry

        return count
コード例 #15
0
ファイル: app.py プロジェクト: AlphaX2/FreiertagBlackBerry10
    def parse_loop_feiertage(self, termine):
        results = []
        for start_ende in termine.readlines():
            
            if start_ende.startswith('SUMMARY:'):
                summary = start_ende[8:-1]

                if summary != 'Volkstrauertag':
                        summary = summary.replace('ue', 'ü')
                        summary = summary.replace('ae', 'ä')
                        summary = summary.replace('oe', 'ö')

                results.append(summary)

            #date of the holiday
            if start_ende.startswith('DTSTART;VALUE=DATE:'):
                datum_start = start_ende[19:27]
                ds = datum_start[6:8] 
                ms = datum_start[4:6] 
                ys = datum_start[0:4]
                #set day of the week with datetime.weekday()
                tag = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"][date(int(ys), int(ms), int(ds)).weekday()]

                datum = '{0}, {1}.{2}.{3}'.format(tag, ds, ms, ys)
                results.append(datum)
			
		#Send the final list to QMLs "onGetPythonList" function via BB-Tart
        tart.send("getPythonList", liste=results)
コード例 #16
0
ファイル: app.py プロジェクト: AlphaX2/FreiertagBlackBerry10
    def parse_ferien(self, jahr, bundesland):
        results = []
        with open('app/native/assets/data/{0}/ferien/Ferien_{1}_{2}.ics'.format(jahr, bundesland, jahr)) as termine:
            for start_ende in termine.readlines():
                #holiday names are found at SUMMARY and is parsed here
                if start_ende.startswith('SUMMARY:'):
                    summary = start_ende[8:-1]
                    summary = summary.replace('ue', 'ü')
                    summary = summary[:len(summary)-len(bundesland)]

                    results.append(summary)

                #start and end of the holidays parsed
                if start_ende.startswith('DTSTART;VALUE=DATE:'):
                    datum_start = start_ende[19:27]
                    ds = datum_start[6:8] 
                    ms = datum_start[4:6] 
                    ys = datum_start[0:4]

                if start_ende.startswith('DTEND;VALUE=DATE:'):
                    datum_ende = start_ende[17:25]
                    de = datum_ende[6:8] 
                    me = datum_ende[4:6] 
                    ye = datum_ende[0:4]

                    datum = '{0}.{1}.{2} - {3}.{4}.{5}'.format(ds, ms, ys, de, me, ye)
                    results.append(datum)

			#Send the final list to QMLs "onGetPythonList" function via BB-Tart
            tart.send('getPythonList', liste=results)
コード例 #17
0
 def handlePurchaseResponse(self, event):
     print(event, event.type, event.code)
     if (event.type == SUCCESS_RESPONSE):
         purchases = self.getPurchases(event)
         if len(purchases):
             tart.send('purchaseResponse', purchases=purchases)
     elif (event.type == FAILURE_RESPONSE): 
         self.handleErrorResponse(event)
コード例 #18
0
ファイル: app.py プロジェクト: rmquapp/Reader-YC
    def onLogout(self):
        self.sess.logout()
        try:
            os.remove(self.COOKIE)
        except OSError:
            tart.send('logoutResult', text="logged out successfully!")

        tart.send('logoutResult', text="logged out successfully!")
コード例 #19
0
ファイル: app.py プロジェクト: CamHardy/Reader-YC
    def onDeleteArticle(self, hnid):
        conn = sqlite3.connect("data/favourites.db")

        hnid = str(hnid)
        cursor = conn.cursor()
        cursor.execute("DELETE FROM articles WHERE hnid=?", (hnid,) )
        conn.commit()
        tart.send('deleteResult', text="Article removed from favourites", itemToRemove=selected)
コード例 #20
0
ファイル: app.py プロジェクト: CamHardy/Reader-YC
 def onGetProfile(self, username):
     info = self.sess.getProfile(username)
     print(info)
     if (info == False):
         os.remove(self.COOKIE)
         tart.send('logoutResult', text="Unable to get profile, forcing logout...")
         return
     tart.send('profileRetrieved', email=info[2], about=info[1])
コード例 #21
0
    def onLogout(self):
        self.sess.logout()
        try:
            os.remove(self.COOKIE)
        except OSError:
            tart.send('logoutResult', text="logged out successfully!")

        tart.send('logoutResult', text="logged out successfully!")
コード例 #22
0
ファイル: app.py プロジェクト: krruzic/GitDating
 def onFillList(self):
     gd = gitDate()
     print(self.personalData)
     results = gd.calculateCompatibility(self.personalData)
     print("List Received!!")
     print(results)
     for result in results:
         tart.send("datesReceived", result=result)
コード例 #23
0
ファイル: app.py プロジェクト: krruzic/Reader-YC
 def onCopyHTML(self, content, meta):
     print(content)
     print(meta)
     soup = BeautifulSoup(content)
     from tart import clipboard
     c = clipboard.Clipboard()
     mimeType = 'text/plain'
     c.insert(mimeType, str(soup.text))
     tart.send('contentCopied', meta=meta)
コード例 #24
0
 def onGetProfile(self, username):
     info = self.sess.getProfile(username)
     print(info)
     if (info == False):
         os.remove(self.COOKIE)
         tart.send('logoutResult',
                   text="Unable to get profile, forcing logout...")
         return
     tart.send('profileRetrieved', email=info[3], about=info[2])
コード例 #25
0
 def onCopyHTML(self, content, meta):
     print(content)
     print(meta)
     soup = BeautifulSoup(content)
     from tart import clipboard
     c = clipboard.Clipboard()
     mimeType = 'text/plain'
     c.insert(mimeType, str(soup.text))
     tart.send('contentCopied', meta=meta)
コード例 #26
0
ファイル: app.py プロジェクト: krruzic/snappy
 def onRequestImage(self, source):
     data = self.session.getMedia(source)
     imageURI = os.getcwd() + '/data/' + source + '.jpeg'
     if data != None:
         f = open('data/' + source + '.jpeg', 'wb')
         f.write(data)
         print("image written")
         f.close()
         tart.send('snapData', imageSource=imageURI)
コード例 #27
0
ファイル: app.py プロジェクト: HorizonXP/blackberry-py
    def onUiReady(self):
        # These need to be absolute paths for the C++ approach (app.composeEmail)
        # but for some reason not when we're directly invoking via Python.
        self.paths = [
            # os.path.abspath('shared/misc/testfile.txt'),
            # os.path.abspath('/accounts/1000/shared/camera/IMG_00000043.png'),
            os.path.abspath('sharewith/pim/testfile.txt'),
            ]

        tart.send('filePathUpdated', paths=self.paths)
コード例 #28
0
    def __init__(self, dispatcher):
        # must call this only once, apparently (see native sample)
        rc = paymentservice_request_events(0)
        if rc == FAILURE_RESPONSE:
            tart.send('paymentsDisabled')
            raise BbmError('cannot use payment service, try restart')
        print('paymentservice_request_events(0), rc', rc)

        dispatcher.add_handler(paymentservice_get_domain(), self.handle_event)
        self.prev_access = -1
コード例 #29
0
ファイル: app.py プロジェクト: HorizonXP/blackberry-py
    def onRefreshFeed(self, url=URLFEED):
        try:
            feed = feedparser.parse(url)
            if feed.status == 200:
                count = self.parseFeed(feed)
                if not count:
                    tart.send('noEntriesFound')

        except Exception as ex:
            tart.send('pyError', traceback=traceback.format_exc())
コード例 #30
0
ファイル: app.py プロジェクト: HorizonXP/blackberry-py
 def onFakeNew(self):
     entry = {
         'url': '',
         'title': 'A faked entry',
         'pubtime': time.time(),
         'image': '',
         'summary': 'This entry was faked',
         'tags': 'Faked,Totally',
         }
     tart.send('entryAdded', entry=entry)
コード例 #31
0
 def send_flags_message(self):
     allowed = bbmsp_is_access_allowed()
     access = self.get_access_code()
     profile = bbmsp_can_show_profile_box()
     invite = bbmsp_can_send_bbm_invite()
     tart.send('bbmFlags',
               allowed=allowed,
               access=access,
               profile=profile,
               invite=invite)
コード例 #32
0
    def onDeleteArticle(self, hnid, selected):
        conn = sqlite3.connect("data/favourites.db")

        hnid = str(hnid)
        cursor = conn.cursor()
        cursor.execute("DELETE FROM articles WHERE hnid=?", (hnid, ))
        conn.commit()
        tart.send('deleteResult',
                  text="Article removed from favourites",
                  itemToRemove=selected)
コード例 #33
0
ファイル: app.py プロジェクト: joelghill/snappy
    def onLogin(self, username=None, password=None):

        self.settings['username'] = username
        self.settings['password'] = password
        self.session = Snappy(username, password)

        self.settings['login'] = self.session.authenticated
        if self.settings['login']:
            self.settings['authToken'] = self.session.authToken
        tart.send('loginResult', value=self.settings['login'])
        self.onSaveSettings(self.settings)
コード例 #34
0
ファイル: app.py プロジェクト: HorizonXP/blackberry-py
    def onRequestPage(self, source='news'):
        resp = urlopen(URL.format(source))
        body = resp.read().decode('utf-8')
        soup = BeautifulSoup(body)

        stories = []
        for item in soup.find_all('td', class_='title'):
            if item.a is not None:
                stories.append((item.a.string, item.a['href']))

        tart.send('addStories', stories=stories)
コード例 #35
0
ファイル: app.py プロジェクト: rmquapp/Reader-YC
 def onDeleteCache(self):
     print("PYTHON DELETING CACHE")
     workingDir = os.getcwd() + '/data/cache/'
     cursor = self.conn.cursor()
     print("Dropping favourites table")
     cursor.execute("""DROP TABLE IF EXISTS articles""")
     cursor.execute("""CREATE TABLE IF NOT EXISTS articles
             (title text, articleURL text, saveTime text,
             poster text, numComments text, isAsk text,
             domain text, points text, hnid text PRIMARY KEY)
         """)
     tart.send('cacheDeleted', text="Cache cleared!")
コード例 #36
0
ファイル: app.py プロジェクト: krruzic/snappy
 def onLogin(self, username=None, password=None):
     if username == None:
         self.session = Snappy(self.settings['username'], self.settings['password'], self.settings['authToken'])
     else:
         self.session = Snappy(username, password)
     if self.session.authenticated:
         self.onRequestFeed() # now we request the feed
         self.settings['username'] = username
         self.settings['password'] = password
         self.settings['authToken'] = self.session.authToken
         self.settings['login'] = '******'
     tart.send('loginResult', value=self.session.authenticated)
コード例 #37
0
 def onDeleteCache(self):
     print("PYTHON DELETING CACHE")
     workingDir = os.getcwd() + '/data/cache/'
     cursor = self.conn.cursor()
     print("Dropping favourites table")
     cursor.execute("""DROP TABLE IF EXISTS articles""")
     cursor.execute("""CREATE TABLE IF NOT EXISTS articles
             (title text, articleURL text, saveTime text,
             poster text, numComments text, isAsk text,
             domain text, points text, hnid text PRIMARY KEY)
         """)
     tart.send('cacheDeleted', text="Cache cleared!")
コード例 #38
0
    def onLoadFavourites(self):
        conn = sqlite3.connect("data/favourites.db")

        cursor = conn.cursor()
        cursor.execute("""CREATE TABLE IF NOT EXISTS articles
                  (title text, articleURL text, saveTime text,
                   poster text, numComments text, isAsk text,
                   domain text, points text, hnid text PRIMARY KEY)
                """)
        cursor.execute('SELECT * FROM articles')
        results = readerutils.get_rowdicts(cursor)
        tart.send('fillList', results=results)
コード例 #39
0
 def searchRoutine(self, startIndex, source):
     print("Searching for: " + str(source))
     try:
         result = self.sess.getSearchStories(startIndex, source)
         if result == []:
             tart.send(
                 'searchError',
                 text=
                 "<b><span style='color:#f99925'>No results found!</span></b>"
             )
             return
         for res in result:
             tart.send('addSearchStories', story=res)
     except requests.exceptions.ConnectionError:
         tart.send(
             'searchError',
             text=
             "<b><span style='color:#f99925'>Error getting stories</span></b>\nCheck your connection and try again!"
         )
     except SocketError:
         tart.send(
             'searchError',
             text=
             "<b><span style='color:#f99925'>Error getting stories</span></b>\nCheck your connection and try again!"
         )
コード例 #40
0
 def storyRoutine(self, source, sentBy):
     # try:
     stories, moreLink = self.sess.getStories(source)
     # except requests.exceptions.ConnectionError:
     # tart.send('{0}ListError'.format(sentBy),
     #               text="<b><span style='color:#f99925'>Error getting stories</span></b>\nCheck your connection and try again!")
     # return
     # except IndexError:
     #     print("Expired link?")
     #     tart.send('{0}ListError'.format(sentBy),
     #               text="<b><span style='color:#f99925'>Link expired</span></b>\nPlease refresh the page")
     #     return
     print(stories)
     for story in stories:
         tart.send('add{0}Stories'.format(sentBy),
                   story=story,
                   moreLink=moreLink,
                   sentTo=sentBy)
     if (source == 'news'):
         tart.send('addCoverStories', stories=stories)
コード例 #41
0
    def onLogin(self, username=None, password=None):

        if self.settings['login'] == 'true':
            session = Snappy(self.settings['username'], self.settings['password'])
        else:
            self.settings['username'] = username
            self.settings['password'] = password
            self.onSaveSettings(self.settings)
            session = Snappy(username, password)

        self.settings['login'] = session.authenticated

        if session.authenticated == True:
            self.settings['login'] = '******'
            tart.send('loginResult', value='true')
        else:
            self.settings['login'] = '******'
            tart.send('loginResult', value='false')

        self.onSaveSettings(self.settings)
コード例 #42
0
    def onSaveArticle(self, article):
        conn = sqlite3.connect("data/favourites.db")
        print(article)
        article = tuple(article)
        cursor = conn.cursor()
        cursor.execute("""CREATE TABLE IF NOT EXISTS articles
                          (title text, articleURL text, saveTime text,
                           poster text, numComments text, isAsk text,
                           domain text, points text, hnid text PRIMARY KEY)
                       """)

        # insert to table
        try:
            cursor.execute("INSERT INTO articles VALUES (?,?,?,?,?,?,?,?,?)",
                           article)
            print("Article saved!")
            # save data to database
            conn.commit()
            tart.send('saveResult', text="Article successfully favourited")
        except sqlite3.IntegrityError:
            print("Article already saved!")
            tart.send('saveResult', text="Article already favourited")
コード例 #43
0
    def __init__(self, uuid, dispatcher):
        self.uuid = uuid
        self.fsm = StateMachine(stateOrigin=self,
                                onStateChanged=self.onStateChanged,
                                debug=True)

        # must call this only once, apparently (see native sample)
        rc = bbmsp_request_events(0)
        if rc == BBMSP_FAILURE:
            tart.send('bbmDisabled')
            raise BbmError('cannot use BBM, try restart')
        print('bbmsp_request_events(0), rc', rc)

        self.status = None
        self.status_message = None
        self.personal_message = None

        self.prev_access = -1

        dispatcher.add_handler(bbmsp_get_domain(), self.handle_event)

        self.send_flags_message()
コード例 #44
0
    def handle_event(self, bps_event):
        '''Handle BPS events for bbmsp domain'''

        # print('domain', domain, 'bbm_domain', bbmsp_get_domain())
        event = self.make_event(bps_event)
        if event.is_reg_state_event():
            # TODO: build the code into the event somehow (can you
            # retrieve it from the event?)
            self.prev_access = code = self.get_access_code()
            tart.send('bbmAccess',
                      state=code,
                      text=self.REG_STATE_NAMES.get(code, '?unrecognized?'))
            # tart.send('bbmAccessTest', state=code,
            #     text=self.REG_STATE_NAMES.get(code, '?unrecognized?'))

        else:
            code = self.get_access_code()
            if code != self.prev_access:
                self.prev_access = code

                tart.send('bbmAccess',
                          state=code,
                          text=self.REG_STATE_NAMES.get(
                              code, '?unrecognized?'))
                # tart.send('bbmAccessTest', state=code,
                #     text=self.REG_STATE_NAMES.get(code, '?unrecognized?'))

                fake_event = BbmEvent(0,
                                      BBMSP_REGISTRATION,
                                      BBMSP_SP_EVENT_ACCESS_CHANGED,
                                      None,
                                      fake=True)
                self.fsm.execute(fake_event)

        if event.is_user_profile_event():
            self.check_user_profile_event(event)

        self.fsm.execute(event)
コード例 #45
0
 def onSaveProfile(self, username, email, about):
     res = False
     try:
         res = self.sess.postProfile(username, email, about)
     except:
         tart.send(
             'profileSaved',
             text="Unable to update profile, check connection and try again"
         )
     if (res == True):
         tart.send('profileSaved', text="Profile updated!")
     else:
         tart.send(
             'profileSaved',
             text="Unable to update profile, check connection and try again"
         )
コード例 #46
0
ファイル: vkb_handler.py プロジェクト: YaDev/BB10-Py-App
 def handle_event(self, event):
     '''Handle BPS events for our domain'''
     code = bps.bps_event_get_code(event)
     if code in self.KB_STATE_CODES:
         tart.send('keyboardState',
                   visible=(code == bps.VIRTUALKEYBOARD_EVENT_VISIBLE))
コード例 #47
0
 def onManualExit(self):
     '''Sent when the app is exiting, so we can save state etc.
     Override in subclasses as required.'''
     tart.send('continueExit')
コード例 #48
0
ファイル: app.py プロジェクト: YaDev/BB10-Py-App
 def js(self, text):
     '''send to JavaScript for evaluation'''
     tart.send('evalJavascript', text=text)
コード例 #49
0
 def onRequestLogin(self, username, password):
     result = self.sess.login(username, password)
     tart.send('loginResult', result=result)
コード例 #50
0
    def commentsRoutine(self, source, askPost):
        print("source sent:" + source)

        try:
            text, comments = self.sess.getComments(
                source, askPost, self.settings['legacyFetch'])
            if (text != ""):
                text = readerutils.textReplace(text)

            tart.send('addText', text=text, hnid=source)
            if (comments == []):
                tart.send('commentError',
                          text="No comments, check back later!",
                          hnid=source)
            for comment in comments:
                comment['text'] = readerutils.textReplace(comment['text'])
                comment['barColour'] = "#" + \
                    readerutils.getColour(comment["indent"] // 40)
                tart.send('addComments', comment=comment, hnid=source)

        except requests.exceptions.ConnectionError:
            print("ERROR GETTING COMMENTS")
            tart.send('addText', text='', hnid=source)
            tart.send(
                'commentError',
                text=
                "<b><span style='color:#f99925'>Error getting comments</span></b>\nCheck your connection and try again!",
                hnid=source)
        except SocketError:
            print("ERROR GETTING COMMENTS")
            tart.send('addText', text='', hnid=source)
            tart.send(
                'commentError',
                text=
                "<b><span style='color:#f99925'>Error getting comments</span></b>\nCheck your connection and try again!",
                hnid=source)
コード例 #51
0
 def onCopy(self, articleLink):
     from tart import clipboard
     c = clipboard.Clipboard()
     mimeType = 'text/plain'
     c.insert(mimeType, articleLink)
     tart.send('copyResult', text=articleLink + " copied to clipboard!")
コード例 #52
0
 def onUiReady(self):
     print("UI READY!!")
     tart.send('restoreSettings', **self.settings)
     self.onRequestPage("news", "news")
コード例 #53
0
 def onPostStory(self, title, url, text):
     res = self.sess.postStory(title, url, text)
     if (res == True):
         tart.send('storyPosted', result='true')
     else:
         tart.send('storyPosted', result='false')