Пример #1
0
    def _getSettings(self):
        common.log('Reading settings')

        self.stg_pbAccessToken = __addon__.getSetting('pb_access_token')
        self.stg_notificationTime = int(
            __addon__.getSetting('notification_time'))
        self.stg_propotificationTime = __addon__.getSetting(
            'proportional_notification_time') == 'true'
        self.stg_autodismissPushes = __addon__.getSetting(
            'autodismiss_pushes') == 'true'
        self.stg_pbChannels = __addon__.getSetting('pb_channels') == 'true'

        self.stg_pbMirroring = __addon__.getSetting('pb_mirroring') == 'true'
        self.stg_pbFilterDeny = __addon__.getSetting('pb_filter_deny')
        self.stg_pbFilterAllow = __addon__.getSetting('pb_filter_allow')

        self.stg_pbMirroringOut = __addon__.getSetting(
            'pb_mirroring_out') == 'true'
        self.stg_pbMirroringOutMediaNfo = __addon__.getSetting(
            'pb_mirroring_out_media_nfo') == 'true'
        self.stg_cmdOnDismissPush = __addon__.getSetting('cmd_on_dismiss_push')
        self.stg_cmdOnPhoneCallPush = __addon__.getSetting(
            'cmd_on_phone_call_push')

        # read only settings
        self.stg_pbClientIden = __addon__.getSetting('pb_client_iden')
        self.stg_pbClientNickname = __addon__.getSetting('pb_client_nickname')
        self.stg_pbClientModel = __addon__.getSetting('pb_client_model')
    def onMessage(self, message):
        try:
            from json import dumps
            common.log('New push (%s) received: %s' % (message['type'], dumps(message)))

            if message['type'] == 'mirror':
                return self._onMirrorPush(message)

            # kodi action (pause, stop, skip) on push dismiss (from devices)
            elif message['type'] == 'dismissal':
                return self._onDismissPush(message, self.cmdOnDismissPush)

            elif message['type'] == 'link':
                return self._onMessageLink(message)

            elif message['type'] == 'file':
                return self._onMessageFile(message)

            elif message['type'] == 'note':
                return self._onMessageNote(message)

            elif message['type'] == 'address':
                return self._onMessageAddress(message)

            elif message['type'] == 'list':
                return self._onMessageList(message)


        except Exception as ex:
            common.traceError()
            common.log(' '.join(str(arg) for arg in ex.args), xbmc.LOGERROR)
    def _onMirrorPush(self, message):

        if 'icon' in message:
            # BUILD KODI NOTIFICATION
            applicationNameMirrored = message.get('application_name', '')
            titleMirrored = message.get('title', '')

            # Add Title...
            title = applicationNameMirrored if not titleMirrored else applicationNameMirrored + ': '
            title += titleMirrored

            # ...Body...
            body = message.get('body', '').rstrip('\n').replace('\n', ' / ')

            # ...and Icon
            iconPath = common.base64ToFile(message['icon'], self.imgFilePath, imgFormat='JPEG', imgSize=(96, 96))

            common.showNotification(title, body, self.notificationTime, iconPath)

            # Action on phone call
            # Works only with com.android.dialer (Android stock dialer)
            if self.cmdOnPhoneCallPush != 'none' and message.get('package_name', '') in ['com.android.dialer']:

                common.log('Execute action on phone call start (mirror): %s' % self.cmdOnPhoneCallPush)

                if self.cmdOnPhoneCallPush == 'pause':
                    common.executeJSONRPCMethod('Player.PlayPause', {'play': False})
                elif self.cmdOnPhoneCallPush == 'stop':
                    common.executeJSONRPCMethod('Player.Stop')
Пример #4
0
    def onMessage(self, message):
        try:
            from json import dumps
            common.log('New push (%s) received: %s' %
                       (message['type'], dumps(message)))

            if message['type'] == 'mirror':
                return self._onMirrorPush(message)

            # kodi action (pause, stop, skip) on push dismiss (from devices)
            elif message['type'] == 'dismissal':
                return self._onDismissPush(message, self.cmdOnDismissPush)

            elif message['type'] == 'link':
                return self._onMessageLink(message)

            elif message['type'] == 'file':
                return self._onMessageFile(message)

            elif message['type'] == 'note':
                return self._onMessageNote(message)

            elif message['type'] == 'address':
                return self._onMessageAddress(message)

            elif message['type'] == 'list':
                return self._onMessageList(message)

        except Exception as ex:
            common.traceError()
            common.log(' '.join(str(arg) for arg in ex.args), xbmc.LOGERROR)
Пример #5
0
    def _setupService(self):
        common.log('Setup Service and Pushbullet Client')

        # setup pushbullet
        self.pushbullet.setDeviceIden(self.stg_pbClientIden)
        self.pushbullet.setFilterDeny(
            {'application_name': self.stg_pbFilterDeny.split()})
        self.pushbullet.setFilterAllow(
            {'application_name': self.stg_pbFilterAllow.split()})
        self.pushbullet.setMirrorMode(self.stg_pbMirroring)
        self.pushbullet.setAutodismissPushes(self.stg_autodismissPushes)
        self.pushbullet.setViewChannels(self.stg_pbChannels)

        # setup service
        self.push2Notification.setNotificationTime(self.stg_notificationTime *
                                                   1000)
        common.showNotification.proportionalTextLengthTimeout = self.stg_propotificationTime
        self.push2Notification.setCmdOnDismissPush(
            self.stg_cmdOnDismissPush.lower())
        self.push2Notification.setCmdOnPhoneCallPush(
            self.stg_cmdOnPhoneCallPush.lower())

        # outbound mirroring
        if self.stg_pbMirroringOut:
            # trigger for Kodi Notification
            self.serviceMonitor.setOnNotificationAction(
                self._onKodiNotification)
        else:
            self.serviceMonitor.setOnNotificationAction(None)
Пример #6
0
 def __init__(self):
     self._parse_argv()
     # check how we were executed
     if self.MOVIEID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "movieid": %d }, "options":{ "resume": %s } }, "id": 1 }' % (int(self.MOVIEID), self.RESUME))
     elif self.EPISODEID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "episodeid": %d }, "options":{ "resume": %s }  }, "id": 1 }' % (int(self.EPISODEID), self.RESUME))
     elif self.MUSICVIDEOID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "musicvideoid": %d } }, "id": 1 }' % int(self.MUSICVIDEOID))
     elif self.ALBUMID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "albumid": %d } }, "id": 1 }' % int(self.ALBUMID))
     elif self.SONGID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "songid": %d } }, "id": 1 }' % int(self.SONGID))
     else:
         self._init_vars()
         self._init_property()
         # clear our property, if another instance is already running it should stop now
         WINDOW.clearProperty('SkinWidgets_Running')
         a_total = datetime.datetime.now()
         self._fetch_info_randomitems()
         self._fetch_info_recommended()
         self._fetch_info_recentitems()
         b_total = datetime.datetime.now()
         c_total = b_total - a_total
         log('Total time needed for all queries: %s' % c_total)
         # give a possible other instance some time to notice the empty property
         WINDOW.setProperty('SkinWidgets_Running', 'true')
         self._daemon()
    def _onDismissPush(self, message, cmd):

        # TODO: add package_name, source_device_iden for be sure is the right dismission
        """
        {"notification_id": 1812, "package_name": "com.podkicker", "notification_tag": null,
        "source_user_iden": "ujy9SIuzSFw", "source_device_iden": "ujy9SIuzSFwsjzWIEVDzOK", "type": "dismissal"}
        """
        if message['notification_id'] == self.pbPlaybackNotificationId:
            common.log('Execute action on dismiss push: %s' % cmd)

            if cmd == 'pause':
                common.executeJSONRPCMethod('Player.PlayPause')
            elif cmd == 'stop':
                common.executeJSONRPCMethod('Player.Stop')
            elif cmd == 'next':
                common.executeJSONRPCMethod('Player.GoTo', {'to': 'next'})

        # Action on phone call
        # Works only with com.android.dialer (Android stock dialer)
        if self.cmdOnPhoneCallPush != 'none' and message.get('package_name', '') in ['com.android.dialer']:

            common.log('Execute action on phone call end (dismiss): %s' % self.cmdOnPhoneCallPush)

            if self.cmdOnPhoneCallPush == 'pause':
                common.executeJSONRPCMethod('Player.PlayPause', {'play': True})
Пример #8
0
    def _onDismissPush(self, message, cmd):

        # TODO: add package_name, source_device_iden for be sure is the right dismission
        """
        {"notification_id": 1812, "package_name": "com.podkicker", "notification_tag": null,
        "source_user_iden": "ujy9SIuzSFw", "source_device_iden": "ujy9SIuzSFwsjzWIEVDzOK", "type": "dismissal"}
        """
        if message['notification_id'] == self.pbPlaybackNotificationId:
            common.log('Execute action on dismiss push: %s' % cmd)

            if cmd == 'pause':
                common.executeJSONRPCMethod('Player.PlayPause')
            elif cmd == 'stop':
                common.executeJSONRPCMethod('Player.Stop')
            elif cmd == 'next':
                common.executeJSONRPCMethod('Player.GoTo', {'to': 'next'})

        # Action on phone call
        # Works only with com.android.dialer (Android stock dialer)
        if self.cmdOnPhoneCallPush != 'none' and message.get(
                'package_name', '') in ['com.android.dialer']:

            common.log('Execute action on phone call end (dismiss): %s' %
                       self.cmdOnPhoneCallPush)

            if self.cmdOnPhoneCallPush == 'pause':
                common.executeJSONRPCMethod('Player.PlayPause', {'play': True})
Пример #9
0
def get_installedversion():
    # retrieve current installed version
    json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Application.GetProperties", "params": {"properties": ["version", "name"]}, "id": 1 }')
    json_query = unicode(json_query, 'utf-8', errors='ignore')
    json_query = jsoninterface.loads(json_query)
    version_installed = []
    if json_query.has_key('result') and json_query['result'].has_key('version'):
        version_installed  = json_query['result']['version']
        log("Version installed %s" %version_installed)
    return version_installed
Пример #10
0
 def _fetch_info_recommended(self):
     a = datetime.datetime.now()
     if __addon__.getSetting("recommended_enable") == 'true':
         self._fetch_movies('RecommendedMovie')
         self._fetch_tvshows_recommended('RecommendedEpisode')
         self._fetch_albums('RecommendedAlbum')
         self._fetch_musicvideos('RecommendedMusicVideo')
         b = datetime.datetime.now()
         c = b - a
         log('Total time needed to request recommended queries: %s' % c)
Пример #11
0
 def _fetch_info_recentitems(self):
     a = datetime.datetime.now()
     if __addon__.getSetting("recentitems_enable") == 'true':
         self.RECENTITEMS_UNPLAYED = __addon__.getSetting("recentitems_unplayed") == 'true'
         self._fetch_movies('RecentMovie')
         self._fetch_tvshows('RecentEpisode')
         self._fetch_musicvideos('RecentMusicVideo')
         self._fetch_albums('RecentAlbum')
         b = datetime.datetime.now()
         c = b - a
         log('Total time needed to request recent items queries: %s' % c)
Пример #12
0
def _checkcryptography():
    ver = None
    try:
        import cryptography
        ver = cryptography.__version__
    except:
        # If the module is not found - no problem
        return
        
    ver_parts = list(map(int, ver.split('.')))
    if len(ver_parts) < 2 or ver_parts[0] < 1 or (ver_parts[0] == 1 and ver_parts[1] < 7):
        log('Python cryptography module version %s is too old, at least version 1.7 needed' % ver)
        xbmcgui.Dialog().ok(ADDONNAME, localise(32040) % ver, localise(32041), localise(32042))
Пример #13
0
def get_installedversion():
    # retrieve current installed version
    json_query = xbmc.executeJSONRPC(
        '{ "jsonrpc": "2.0", "method": "Application.GetProperties", "params": {"properties": ["version", "name"]}, "id": 1 }'
    )
    json_query = unicode(json_query, 'utf-8', errors='ignore')
    json_query = jsoninterface.loads(json_query)
    version_installed = []
    if json_query.has_key('result') and json_query['result'].has_key(
            'version'):
        version_installed = json_query['result']['version']
        log("Version installed %s" % version_installed)
    return version_installed
Пример #14
0
 def _fetch_info_randomitems(self):
     a = datetime.datetime.now()
     if __addon__.getSetting("randomitems_enable") == 'true':
         self.RANDOMITEMS_UNPLAYED = __addon__.getSetting("randomitems_unplayed") == 'true'
         self._fetch_movies('RandomMovie')
         self._fetch_tvshows('RandomEpisode')
         self._fetch_musicvideos('RandomMusicVideo')
         self._fetch_albums('RandomAlbum')
         self._fetch_artists('RandomArtist')
         self._fetch_songs('RandomSong')
         self._fetch_addons('RandomAddon')
         b = datetime.datetime.now()
         c = b - a
         log('Total time needed to request random queries: %s' % c)
Пример #15
0
    def _getDevice(self):
        device = self.pushbullet.getDevice(self.stg_pbClientIden)

        if device:
            # set setting
            __addon__.setSetting(id='pb_client_nickname', value=device['nickname'])
            __addon__.setSetting(id='pb_client_model', value=device.get('model','')) # use .get() as model may not be set

            # update vars setting
            self.stg_pbClientNickname = __addon__.getSetting('pb_client_nickname')
            self.stg_pbClientModel  = __addon__.getSetting('pb_client_model')

            common.log('Device %s (%s) found e loaded' % (self.stg_pbClientNickname, self.stg_pbClientModel))
        else:
            raise Exception('No device found with iden: ' + self.stg_pbClientIden)
Пример #16
0
def _checkcryptography():
    ver = None
    try:
        import cryptography
        ver = cryptography.__version__
    except:
        # If the module is not found - no problem
        return

    ver_parts = list(map(int, ver.split('.')))
    if len(ver_parts) < 2 or ver_parts[0] < 1 or (ver_parts[0] == 1
                                                  and ver_parts[1] < 7):
        log('Python cryptography module version %s is too old, at least version 1.7 needed'
            % ver)
        xbmcgui.Dialog().ok(ADDONNAME,
                            localise(32040) % ver, localise(32041),
                            localise(32042))
Пример #17
0
    def executeKodiCmd(self, message):
        if self.kodiCmds and 'title' in message:
            match = self.re_kodiCmd.match(message['title'])

            if match:
                cmd = match.group('cmd')

                if cmd in self.kodiCmds:
                    try:
                        cmdObj = self.kodiCmds[cmd]
                        jsonrpc = cmdObj['JSONRPC']

                        if 'body' in message and len(message['body']) > 0:
                            params = message['body'].split('||')

                            # escape bracket '{}' => '{{}}'
                            jsonrpc = jsonrpc.replace('{',
                                                      '{{').replace('}', '}}')
                            # sobstitute custom placeholder '<$var>' => '{var}'
                            jsonrpc = self.re_kodiCmdPlaceholder.sub(
                                '{\\1}', jsonrpc)
                            # format with passed params
                            jsonrpc = jsonrpc.format(params=params)

                        common.log('Executing cmd "%s": %s' % (cmd, jsonrpc))

                        result = common.executeJSONRPC(jsonrpc)

                        common.log('Result for cmd "%s": %s' % (cmd, result))

                        title = common.localise(30104) % cmd
                        body = ''

                        if 'notification' in cmdObj:
                            # same transformation as jsonrpc var
                            body = cmdObj['notification'].replace(
                                '{', '{{').replace('}', '}}')
                            body = self.re_kodiCmdPlaceholder.sub(
                                '{\\1}', body)
                            body = body.format(result=result)

                    except Exception as ex:
                        title = 'ERROR: ' + common.localise(30104) % cmd
                        body = ' '.join(str(arg) for arg in ex.args)
                        common.log(body, xbmc.LOGERROR)
                        common.traceError()

                    common.showNotification(title, body, self.notificationTime,
                                            self.kodiCmdsNotificationIcon)
                    return True

                else:
                    common.log('No "%s" cmd founded!' % cmd, xbmc.LOGERROR)

        return False
Пример #18
0
def repayment_time_interface(name):
    """
    :param name:
    :return:
    """
    user_dic = db_handler.select(name)
    # 还款日期为20号

    now = int(time.strftime('%d'))
    if now < setting.REPAYMENT_TIME:
        d = 20 - int(now)  # user_dic['time'] = 21
        return '距离还款日期还剩:%s天' % d
    elif now > setting.REPAYMENT_TIME:
        d = 30 - abs((20 - int(now)))  #
        return '距离还款日期还剩:%s天' % d
    else:
        if user_dic['balance'] >= 0:
            return '当前余额充足...'
        else:
            print('请先对当前账户进行充值, 否则自动退出...')
            is_true = True
            while is_true:
                choice = input('是否进行充值(y/n):').strip()
                if choice == 'y':
                    while is_true:
                        money = input('充值金额:>>').strip()
                        if money == 'q':
                            break
                        if not money.isdigit():
                            print('充值的金额必须为数字类型...')
                            # print(user_info['name'])
                            continue
                        money = int(money)
                        flag, msg = account_recharge_interface(name, money)
                        if flag:
                            print(msg)
                            logger = common.log('recharge.log')
                            logger.info('%s 充值了 %s' % (name, money))
                            db_user_dic = db_handler.select(name)
                            if db_user_dic['balance'] >= 0:
                                is_true = False
                                break
                            else:
                                print('当前余额为:%s元,请继续进行充值或退出...' %
                                      db_user_dic['balance'])
                                continue
                        else:
                            print(msg)
                    pass
                elif choice == 'n':

                    db_user = db_handler.select(name)
                    if db_user['balance'] >= 0:
                        break
                    else:
                        sys.exit()
Пример #19
0
def crawlNews(oid, processNo, pushedNo, startTime):
    while True:
        try:
            _, _, newsRawDB = connectDB(host)
            metadataCollection = newsRawDB['metadata']
            try:
                startNo = metadataCollection.find_one({"oid": oid})['last']
            except:
                startNo = 1
            tmpDB = []
            cnt = 0
            pushedNo.value += startNo - 1
            log('Process oid=%03d started at aid=%d' % (oid, startNo),
                startTime, processNo, pushedNo.value)
            for i in range(startNo, 999999999):
                status, newsResponseText, summary = getRaw(oid, i)
                if not status:
                    continue
                tmpDB.append({
                    'body': newsResponseText,
                    'summary': summary,
                    'aid': i
                })
                cnt += 1
                if cnt >= chunk:
                    if len(tmpDB) > 0:
                        newsRawDB[str(oid)].insert_many(tmpDB)
                        pushedNo.value += len(tmpDB)
                    log(
                        'Pushed %03d objects to DB at oid=%03d for aid=%d' %
                        (len(tmpDB), oid, i), startTime, processNo,
                        pushedNo.value)
                    tmpDB = []
                    cnt = 0
                    try:
                        metadataCollection.delete_one({"oid": oid})
                        metadataCollection.insert_one({"oid": oid, "last": i})
                    except:
                        pass
        except:
            pass
Пример #20
0
    def _checkSettingChanged(self):
        """
        Run the correct "procedure" following which settings are changed
        """

        # if access_token is changed => (re)start service
        if self.stg_pbAccessToken != __addon__.getSetting('pb_access_token'):
            common.log('Access token is changed')

            self._getSettings()
            self.run()

        # if access token is set and...
        elif self.stg_pbAccessToken:

            # ...client_iden has been set => (re)start service
            if not self.stg_pbClientIden and __addon__.getSetting(
                    'pb_client_iden'):
                common.log('Device has been set')

                self._getSettings()
                self.run()

            # ...one of the listed settings are changed  => read setting setup service
            elif self._isSettingChanged():
                common.log('Setting is changed by user')

                self._getSettings()
                self._setupService()
Пример #21
0
    def _checkSettingChanged(self):
        """
        Run the correct "procedure" following which settings are changed
        """

        # if access_token is changed => (re)start service
        if self.stg_pbAccessToken != __addon__.getSetting('pb_access_token'):
            common.log('Access token is changed')

            self._getSettings()
            self.run()

        # if access token is set and...
        elif self.stg_pbAccessToken:

            # ...client_iden has been set => (re)start service
            if not self.stg_pbClientIden and __addon__.getSetting('pb_client_iden'):
                common.log('Device has been set')

                self._getSettings()
                self.run()

            # ...one of the listed settings are changed  => read setting setup service
            elif self._isSettingChanged():
                common.log('Setting is changed by user')

                self._getSettings()
                self._setupService()
    def executeKodiCmd(self, message):
        if self.kodiCmds and 'title' in message:
            match = self.re_kodiCmd.match(message['title'])

            if match:
                cmd = match.group('cmd')

                if cmd in self.kodiCmds:
                    try:
                        cmdObj = self.kodiCmds[cmd]
                        jsonrpc = cmdObj['JSONRPC']

                        if 'body' in message and len(message['body']) > 0:
                            params = message['body'].split('||')

                            # escape bracket '{}' => '{{}}'
                            jsonrpc = jsonrpc.replace('{', '{{').replace('}', '}}')
                            # sobstitute custom placeholder '<$var>' => '{var}'
                            jsonrpc = self.re_kodiCmdPlaceholder.sub('{\\1}', jsonrpc)
                            # format with passed params
                            jsonrpc = jsonrpc.format(params=params)

                        common.log('Executing cmd "%s": %s' % (cmd, jsonrpc))

                        result = common.executeJSONRPC(jsonrpc)

                        common.log('Result for cmd "%s": %s' % (cmd, result))

                        title = common.localise(30104) % cmd
                        body = ''

                        if 'notification' in cmdObj:
                            # same transformation as jsonrpc var
                            body = cmdObj['notification'].replace('{', '{{').replace('}', '}}')
                            body = self.re_kodiCmdPlaceholder.sub('{\\1}', body)
                            body = body.format(result=result)

                    except Exception as ex:
                        title = 'ERROR: ' + common.localise(30104) % cmd
                        body = ' '.join(str(arg) for arg in ex.args)
                        common.log(body, xbmc.LOGERROR)
                        common.traceError()

                    common.showNotification(title, body, self.notificationTime, self.kodiCmdsNotificationIcon)
                    return True

                else:
                    common.log('No "%s" cmd founded!' % cmd, xbmc.LOGERROR)

        return False
Пример #23
0
    def _getSettings(self):
        common.log('Reading settings')

        self.stg_pbAccessToken          = __addon__.getSetting('pb_access_token')
        self.stg_notificationTime       = int(__addon__.getSetting('notification_time'))
        self.stg_propotificationTime    = __addon__.getSetting('proportional_notification_time') == 'true'
        self.stg_autodismissPushes             = __addon__.getSetting('autodismiss_pushes') == 'true'
        self.stg_pbChannels             = __addon__.getSetting('pb_channels') == 'true'

        self.stg_pbMirroring            = __addon__.getSetting('pb_mirroring') == 'true'
        self.stg_pbFilterDeny           = __addon__.getSetting('pb_filter_deny')
        self.stg_pbFilterAllow          = __addon__.getSetting('pb_filter_allow')

        self.stg_pbMirroringOut         = __addon__.getSetting('pb_mirroring_out') == 'true'
        self.stg_pbMirroringOutMediaNfo = __addon__.getSetting('pb_mirroring_out_media_nfo') == 'true'
        self.stg_cmdOnDismissPush       = __addon__.getSetting('cmd_on_dismiss_push')
        self.stg_cmdOnPhoneCallPush       = __addon__.getSetting('cmd_on_phone_call_push')

        # read only settings
        self.stg_pbClientIden           = __addon__.getSetting('pb_client_iden')
        self.stg_pbClientNickname       = __addon__.getSetting('pb_client_nickname')
        self.stg_pbClientModel          = __addon__.getSetting('pb_client_model')
Пример #24
0
    def _getDevice(self):
        device = self.pushbullet.getDevice(self.stg_pbClientIden)

        if device:
            # set setting
            __addon__.setSetting(id='pb_client_nickname',
                                 value=device['nickname'])
            __addon__.setSetting(id='pb_client_model',
                                 value=device.get(
                                     'model',
                                     ''))  # use .get() as model may not be set

            # update vars setting
            self.stg_pbClientNickname = __addon__.getSetting(
                'pb_client_nickname')
            self.stg_pbClientModel = __addon__.getSetting('pb_client_model')

            common.log('Device %s (%s) found e loaded' %
                       (self.stg_pbClientNickname, self.stg_pbClientModel))
        else:
            raise Exception('No device found with iden: ' +
                            self.stg_pbClientIden)
Пример #25
0
    def _setupService(self):
        common.log('Setup Service and Pushbullet Client')

        # setup pushbullet
        self.pushbullet.setDeviceIden(self.stg_pbClientIden)
        self.pushbullet.setFilterDeny({'application_name': self.stg_pbFilterDeny.split()})
        self.pushbullet.setFilterAllow({'application_name': self.stg_pbFilterAllow.split()})
        self.pushbullet.setMirrorMode(self.stg_pbMirroring)
        self.pushbullet.setAutodismissPushes(self.stg_autodismissPushes)
        self.pushbullet.setViewChannels(self.stg_pbChannels)

        # setup service
        self.push2Notification.setNotificationTime(self.stg_notificationTime*1000)
        common.showNotification.proportionalTextLengthTimeout = self.stg_propotificationTime
        self.push2Notification.setCmdOnDismissPush(self.stg_cmdOnDismissPush.lower())
        self.push2Notification.setCmdOnPhoneCallPush(self.stg_cmdOnPhoneCallPush.lower())

        # outbound mirroring
        if self.stg_pbMirroringOut:
            # trigger for Kodi Notification
            self.serviceMonitor.setOnNotificationAction(self._onKodiNotification)
        else:
            self.serviceMonitor.setOnNotificationAction(None)
Пример #26
0
    def _onMirrorPush(self, message):

        if 'icon' in message:
            # BUILD KODI NOTIFICATION
            applicationNameMirrored = message.get('application_name', '')
            titleMirrored = message.get('title', '')

            # Add Title...
            title = applicationNameMirrored if not titleMirrored else applicationNameMirrored + ': '
            title += titleMirrored

            # ...Body...
            body = message.get('body', '').rstrip('\n').replace('\n', ' / ')

            # ...and Icon
            iconPath = common.base64ToFile(message['icon'],
                                           self.imgFilePath,
                                           imgFormat='JPEG',
                                           imgSize=(96, 96))

            common.showNotification(title, body, self.notificationTime,
                                    iconPath)

            # Action on phone call
            # Works only with com.android.dialer (Android stock dialer)
            if self.cmdOnPhoneCallPush != 'none' and message.get(
                    'package_name', '') in ['com.android.dialer']:

                common.log('Execute action on phone call start (mirror): %s' %
                           self.cmdOnPhoneCallPush)

                if self.cmdOnPhoneCallPush == 'pause':
                    common.executeJSONRPCMethod('Player.PlayPause',
                                                {'play': False})
                elif self.cmdOnPhoneCallPush == 'stop':
                    common.executeJSONRPCMethod('Player.Stop')
Пример #27
0
def _versionchecklinux(packages):
    if platform.dist()[0].lower() in ["ubuntu", "debian", "linuxmint"]:
        handler = False
        result = False
        try:
            # try aptdeamon first
            from lib.aptdeamonhandler import AptdeamonHandler

            handler = AptdeamonHandler()
        except:
            # fallback to shell
            # since we need the user password, ask to check for new version first
            from lib.shellhandlerapt import ShellHandlerApt

            sudo = True
            handler = ShellHandlerApt(sudo)
            if dialog_yesno(32015):
                pass
            elif dialog_yesno(32009, 32010):
                log("disabling addon by user request")
                __addon__.setSetting("versioncheck_enable", "false")
                return

        if handler:
            if handler.check_upgrade_available(packages[0]):
                if _upgrademessage(32012, True):
                    if __addon__.getSetting("upgrade_system") == "false":
                        result = handler.upgrade_package(packages[0])
                    else:
                        result = handler.upgrade_system()
                    if result:
                        from lib.common import message_upgrade_success, message_restart

                        message_upgrade_success()
                        message_restart()
                    else:
                        log("Error during upgrade")
        else:
            log("Error: no handler found")
    else:
        log("Unsupported platform %s" % platform.dist()[0])
        sys.exit(0)
Пример #28
0
    def __init__(self):
        common.log('Service version %s starting' % __addonversion__)

        self.pushbullet = None
        self.serviceMonitor = None
        self.push2Notification = None
        self.stg_pbAccessToken = None

        # notification time for service error
        self.serviceNotifcationTime = 6000

        # xbmc icon (used as ephemerals icon)
        import os
        xbmcImgPath = os.path.join(__addonpath__, 'resources', 'media',
                                   'xbmc.jpg')
        kodiCmdsNotificationIcon = os.path.join(__addonpath__, 'resources',
                                                'media', 'kcmd.png')

        import base64
        with open(xbmcImgPath, "rb") as imgFile:
            self.xbmcImgEncoded = base64.b64encode(imgFile.read())

        # catch add-on settings change
        self.serviceMonitor = common.serviceMonitor(
            onSettingsChangedAction=self._checkSettingChanged)

        # convert push to Kodi notification
        import random
        self.pbPlaybackNotificationId = random.randint(-300000000, 300000000)

        from lib.push2Notification import Push2Notification
        self.push2Notification = Push2Notification(
            notificationIcon=__addonicon__,
            tempPath=__addonprofile__,
            pbPlaybackNotificationId=self.pbPlaybackNotificationId,
            kodiCmds=common.getKodiCmdsFromFiles(),
            kodiCmdsNotificationIcon=kodiCmdsNotificationIcon)

        self._getSettings()
        self.run()

        while not xbmc.abortRequested:
            xbmc.sleep(200)

        common.log('Closing socket (waiting...)')

        if self.pushbullet: self.pushbullet.close()

        common.log('Service closed')
Пример #29
0
def _versionchecklinux(packages):
    if platform.dist()[0].lower() in ['ubuntu', 'debian', 'linuxmint']:
        handler = False
        result = False
        try:
            # try aptdaemon first
            from lib.aptdaemonhandler import AptdaemonHandler
            handler = AptdaemonHandler()
        except:
            # fallback to shell
            # since we need the user password, ask to check for new version first
            from lib.shellhandlerapt import ShellHandlerApt
            sudo = True
            handler = ShellHandlerApt(sudo)
            if dialog_yesno(32015):
                pass
            elif dialog_yesno(32009, 32010):
                log("disabling addon by user request")
                ADDON.setSetting("versioncheck_enable", 'false')
                return

        if handler:
            if handler.check_upgrade_available(packages[0]):
                if _upgrademessage(32012, oldversion, True):
                    if ADDON.getSetting("upgrade_system") == "false":
                        result = handler.upgrade_package(packages[0])
                    else:
                        result = handler.upgrade_system()
                    if result:
                        from lib.common import message_upgrade_success, message_restart
                        message_upgrade_success()
                        message_restart()
                    else:
                        log("Error during upgrade")
        else:
            log("Error: no handler found")
    else:
        log("Unsupported platform %s" % platform.dist()[0])
        sys.exit(0)
Пример #30
0
    def run(self):
        """
        Run or restart service.
        """

        if self.pushbullet:
            common.log('Restarting')
            self.pushbullet.close()

        try:
            if not self.stg_pbAccessToken or not self.stg_pbClientIden:
                raise Exception(common.localise(30100))

            from lib.pushbullet import Pushbullet

            # init pushbullet
            self.pushbullet = Pushbullet(
                access_token=self.stg_pbAccessToken,
                ping_timeout=6,
                last_modified=common.getSetting('last_modified', 0),
                last_modified_callback=self.setLastModified,
                log_callback=common.log)

            # get device info (also if edited by user on Pushbullet panel)
            self._getDevice()

            # setup service and pushbullet (iden, mirroring, filter)
            self._setupService()

            # start listening websocket
            self.pushbullet.realTimeEventStream(
                on_open=self.push2Notification.onOpen,
                on_message=self.push2Notification.onMessage,
                on_error=self.push2Notification.onError,
                on_close=self.push2Notification.onClose)

            common.log('Service started successfully')

        except Exception as ex:
            common.traceError()
            message = ' '.join(str(arg) for arg in ex.args)

            common.log(message, xbmc.LOGERROR)
            common.showNotification(common.localise(30101), message,
                                    self.serviceNotifcationTime)
Пример #31
0
    def __init__(self):
        common.log('Service version %s starting' % __addonversion__)

        self.pushbullet = None
        self.serviceMonitor = None
        self.push2Notification = None
        self.stg_pbAccessToken = None

        # notification time for service error
        self.serviceNotifcationTime = 6000

        # xbmc icon (used as ephemerals icon)
        import os
        xbmcImgPath = os.path.join(__addonpath__, 'resources', 'media', 'xbmc.jpg')
        kodiCmdsNotificationIcon = os.path.join(__addonpath__, 'resources', 'media', 'kcmd.png')

        import base64
        with open(xbmcImgPath, "rb") as imgFile:
            self.xbmcImgEncoded = base64.b64encode(imgFile.read())

        # catch add-on settings change
        self.serviceMonitor = common.serviceMonitor(onSettingsChangedAction=self._checkSettingChanged)

        # convert push to Kodi notification
        import random
        self.pbPlaybackNotificationId = random.randint(-300000000, 300000000)

        from lib.push2Notification import Push2Notification
        self.push2Notification = Push2Notification(notificationIcon=__addonicon__, tempPath=__addonprofile__,
                                                   pbPlaybackNotificationId=self.pbPlaybackNotificationId,
                                                   kodiCmds=common.getKodiCmdsFromFiles(),
                                                   kodiCmdsNotificationIcon=kodiCmdsNotificationIcon)

        self._getSettings()
        self.run()

        while not xbmc.abortRequested:
            xbmc.sleep(200)

        common.log('Closing socket (waiting...)')

        if self.pushbullet: self.pushbullet.close()

        common.log('Service closed')
Пример #32
0
    def run(self):
        """
        Run or restart service.
        """

        if self.pushbullet:
            common.log('Restarting')
            self.pushbullet.close()

        try:
            if not self.stg_pbAccessToken or not self.stg_pbClientIden:
                raise Exception(common.localise(30100))

            from lib.pushbullet import Pushbullet

            # init pushbullet
            self.pushbullet = Pushbullet(   access_token=self.stg_pbAccessToken,
                                            ping_timeout=6,
                                            last_modified=common.getSetting('last_modified',0),
                                            last_modified_callback=self.setLastModified,
                                            log_callback=common.log)

            # get device info (also if edited by user on Pushbullet panel)
            self._getDevice()

            # setup service and pushbullet (iden, mirroring, filter)
            self._setupService()

            # start listening websocket
            self.pushbullet.realTimeEventStream(on_open=self.push2Notification.onOpen,
                                                on_message=self.push2Notification.onMessage,
                                                on_error=self.push2Notification.onError,
                                                on_close=self.push2Notification.onClose)

            common.log('Service started successfully')

        except Exception as ex:
            common.traceError()
            message = ' '.join(str(arg) for arg in ex.args)

            common.log(message, xbmc.LOGERROR)
            common.showNotification(common.localise(30101), message, self.serviceNotifcationTime)
Пример #33
0
def parseNews(oid, processNo, parsedNo, startTime):
    while 1:
        try:
            log('Process oid=%03d started.' % oid, 0, 0, 0)
            newsDB, categoryDB, newsRawDB = connectDB(host)
            while 1:
                li = list(newsRawDB[str(oid)].find().limit(chunk))
                if len(li) == 0:
                    return
                log('Got %d Data from DB at oid=%03d' % (len(li), oid),
                    startTime, processNo, parsedNo.value)
                removeLi = []
                processedNews = []
                categoryDict = dict()
                for news in li:
                    try:
                        removeLi.append({'_id': news['_id']})
                        aid, body, summary = news['aid'], news['body'], news[
                            'summary']
                        summarySoup = BeautifulSoup(summary['summary'],
                                                    'html.parser')
                        summaryText = summarySoup.get_text()
                        newsText = ""
                        newsSoup = BeautifulSoup(body, 'html.parser')
                        bodyEl = newsSoup.find(id="articleBodyContents")
                        for i in bodyEl:
                            if type(i) is NavigableString:
                                newsText += i
                            elif type(i) is Comment:
                                pass
                            else:
                                if i.name == 'br':
                                    newsText += '\n'
                                if i.get('data-type') == 'ore':
                                    newsText += i.get_text()

                        newsText = newsText.replace('\n\n', '\n')
                        newsText = newsText.replace('\n', ' ')
                        newsText = newsText.replace('  ', ' ')
                        newsText = newsText.strip().decode(
                            'utf-8', 'ignore').encode("utf-8")

                        newsTitle = newsSoup.find(
                            id="articleTitle").get_text().strip()

                        category = []
                        for i in newsSoup.find_all(
                                "em", {"class": "guide_categorization_item"}):
                            category.append(sectionName[i.get_text()])
                            if sectionName[i.get_text()] not in categoryDict:
                                categoryDict[sectionName[i.get_text()]] = []
                            categoryDict[sectionName[i.get_text()]].append({
                                'oid':
                                oid,
                                'aid':
                                aid
                            })

                        publishTime = strToDate(
                            newsSoup.find_all("span",
                                              {"class": "t11"})[0].get_text())
                        if len(newsSoup.find_all("span",
                                                 {"class": "t11"})) == 2:
                            editedTime = strToDate(
                                newsSoup.find_all(
                                    "span", {"class": "t11"})[1].get_text())
                        else:
                            editedTime = strToDate(
                                newsSoup.find_all(
                                    "span", {"class": "t11"})[0].get_text())

                        processedNews.append({
                            'newsId': aid,
                            'title': newsTitle,
                            'body': newsText,
                            'summary': summaryText,
                            'category': category,
                            'publishTime': publishTime,
                            'editedTime': editedTime
                        })
                    except:
                        pass
                for section, data in categoryDict.items():
                    categoryDB[section].insert_many(data)
                if len(processedNews) > 0:
                    newsDB[str(oid)].insert_many(processedNews)
                    parsedNo.value += len(processedNews)
                log(
                    'Parsed %03d objects in DB at oid=%03d' %
                    (len(processedNews), oid), startTime, processNo,
                    parsedNo.value)
                for remove in removeLi:
                    newsRawDB[str(oid)].delete_one(remove)
                log('Dropped %03d objects in RAW at oid=%03d' % (chunk, oid),
                    startTime, processNo, parsedNo.value)
        except:
            pass
Пример #34
0
                pass
            elif dialog_yesno(32009, 32010):
                log("disabling addon by user request")
                ADDON.setSetting("versioncheck_enable", 'false')
                return

        if handler:
            if handler.check_upgrade_available(packages[0]):
                if _upgrademessage(32012, oldversion, True):
                    if ADDON.getSetting("upgrade_system") == "false":
                        result = handler.upgrade_package(packages[0])
                    else:
                        result = handler.upgrade_system()
                    if result:
                        from lib.common import message_upgrade_success, message_restart
                        message_upgrade_success()
                        message_restart()
                    else:
                        log("Error during upgrade")
        else:
            log("Error: no handler found")
    else:
        log("Unsupported platform %s" %platform.dist()[0])
        sys.exit(0)



if (__name__ == "__main__"):
    log('Version %s started' % ADDONVERSION)
    Main()
 def onOpen(self):
     common.log('Socket opened')
Пример #36
0
@author: ClementTurbelin
'''
from lib.common import geo_levels, read_file, create_insert_query, get_geo_field_name, get_upper_levels, log

import argparse

parser = argparse.ArgumentParser(description='Generate SQL to import zip codes (zip geographic level)')

parser.add_argument('file', nargs=1, help='file to import')

args = parser.parse_args()

fn = str(args.file[0])

log("Importing file " + fn)

data = read_file('data/zip/' + fn)

def create_levels(level, value):
    d = {}
    if level == 'nuts3':
        d['code_nuts3'] = value
        d['code_nuts2'] = value[0:4]
    if level == 'nuts2':
        d['code_nuts2'] = value
    n2 = d['code_nuts2']
    d['code_nuts1'] = n2[0:3]
    d['country'] = n2[0:2]
    return d
Пример #37
0
                log("disabling addon by user request")
                ADDON.setSetting("versioncheck_enable", 'false')
                return

        if handler:
            if handler.check_upgrade_available(packages[0]):
                if _upgrademessage(32012, oldversion, True):
                    if ADDON.getSetting("upgrade_system") == "false":
                        result = handler.upgrade_package(packages[0])
                    else:
                        result = handler.upgrade_system()
                    if result:
                        from lib.common import message_upgrade_success, message_restart
                        message_upgrade_success()
                        message_restart()
                    else:
                        log("Error during upgrade")
        else:
            log("Error: no handler found")
    else:
        log("Unsupported platform %s" % platform.dist()[0])
        sys.exit(0)


if (__name__ == "__main__"):
    if ADDON.getSetting("versioncheck_enable") == "false":
        log("Disabled")
    else:
        log('Version %s started' % ADDONVERSION)
        Main()
Пример #38
0
                    parsedNo.value += len(processedNews)
                log(
                    'Parsed %03d objects in DB at oid=%03d' %
                    (len(processedNews), oid), startTime, processNo,
                    parsedNo.value)
                for remove in removeLi:
                    newsRawDB[str(oid)].delete_one(remove)
                log('Dropped %03d objects in RAW at oid=%03d' % (chunk, oid),
                    startTime, processNo, parsedNo.value)
        except:
            pass


if __name__ == '__main__':
    multiprocessing.freeze_support()
    log('Parser main process started.', time.time(), 0, 0)
    thrs = []
    cnt = 0
    processNo = len(oidList)
    parsedNo = multiprocessing.Value('i', 0)
    startTime = time.time()
    for i in oidList:
        if cnt >= processNo:
            break
        thr = multiprocessing.Process(target=parseNews,
                                      args=(i, processNo, parsedNo, startTime))
        thrs.append(thr)
        thr.start()
        cnt += 1
    for i in thrs:
        i.join()
Пример #39
0
def compare_version(version_installed, versionlist):
    # Create seperate version lists
    versionlist_stable = versionlist['releases']['stable']
    versionlist_rc = versionlist['releases']['releasecandidate']
    versionlist_beta = versionlist['releases']['beta']
    versionlist_alpha = versionlist['releases']['alpha']
    versionlist_prealpha = versionlist['releases']['prealpha']
    log("Version installed %s" % version_installed)
    ### Check to upgrade to newest available stable version
    # check on smaller major version. Smaller version than available always notify
    oldversion = False
    msg = ''

    # check if current major version is smaller than available major stable
    # here we don't care if running non stable
    if version_installed['major'] < int(versionlist_stable[0]['major']):
        msg = 32003
        oldversion = "stable"
        log("Version available  %s" % versionlist_stable[0])
        log("You are running an older version")

    # check if current major version is equal than available major stable
    # however also check on minor version and still don't care about non stable
    elif version_installed['major'] == int(versionlist_stable[0]['major']):
        if version_installed['minor'] < int(versionlist_stable[0]['minor']):
            msg = 32003
            oldversion = "stable"
            log("Version available  %s" % versionlist_stable[0])
            log("You are running an older minor version")
        # check for <= minor !stable
        elif version_installed['tag'] != "stable" and version_installed[
                'minor'] <= int(versionlist_stable[0]['minor']):
            msg = 32003
            oldversion = True
            log("Version available  %s" % versionlist_stable[0])
            log("You are running an older non stable minor version")
        else:
            log("Version available  %s" % versionlist_stable[0])
            log("There is no newer stable available")

    ## Check to upgrade to newest available RC version if not installed stable
    ## Check also oldversion hasn't been set true by previous check because if so this need to be skipped
    elif version_installed['tag'] != "stable":
        # check if you are using a RC lower than current RC
        # then check if you are using a alpha/beta lower than current RC
        if version_installed['major'] <= int(versionlist_rc[0]['major']):
            if version_installed['tag'] in ["releasecandidate"]:
                if version_installed['revision'] < versionlist_rc[0][
                        'revision']:
                    msg = 32004
                    oldversion = True
                    log("Version available  %s" % versionlist_rc[0])
                    log("You are running an older RC version")
                elif version_installed['revision'] < versionlist_rc[0][
                        'revision']:
                    msg = 32004
                    oldversion = True
                    log("Version available  %s" % versionlist_rc[0])
                    log("You are running an older non RC version")
                else:
                    log("Version available  %s" % versionlist_rc[0])
                    log("You are running newest RC version")

        # exclude if you are running an RC
        # check if you are using a beta lower than current beta
        # then check if you are using a alpha/beta lower than current RC
        if not oldversion and version_installed['tag'] not in [
                "releasecandidate"
        ] and version_installed['major'] <= int(versionlist_beta[0]['major']):
            if version_installed['tag'] in ["beta"]:
                if version_installed['revision'] < versionlist_beta[0][
                        'revision']:
                    msg = 32005
                    oldversion = True
                    log("Version available  %s" % versionlist_beta[0])
                    log("You are running an older beta version")
                elif version_installed['revision'] < versionlist_beta[0][
                        'revision']:
                    msg = 32005
                    oldversion = True
                    log("Version available  %s" % versionlist_beta[0])
                    log("You are running an older non beta version")
                else:
                    log("Version available  %s" % versionlist_beta[0])
                    log("You are running newest beta version")

        # exclude if you are running an RC/beta
        # check if you are using a beta lower than current beta
        # then check if you are using a alpha/beta lower than current RC
        if not oldversion and version_installed['tag'] in [
                "prealpha"
        ] and version_installed['major'] <= int(
                versionlist_prealpha[0]['major']):
            if version_installed['revision'] < versionlist_prealpha[0][
                    'revision']:
                msg = 32006
                oldversion = True
                log("Version available  %s" % versionlist_prealpha[0])
                log("You are running an older alpha version")
            else:
                log("Version available  %s" % versionlist_prealpha[0])
                log("You are running newest alpha version")

    return oldversion, msg
Пример #40
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from lib.common import log
log("123", "sds")
Пример #41
0
    def _onKodiNotification(self, sender, method, data):

        import json
        data = json.loads(data)

        if sender == 'xbmc':
            if method == 'Player.OnPlay' and self.stg_pbMirroringOutMediaNfo:
                common.log('onKodiNotification: %s %s %s' % (sender, method, data))

                title = body = icon = None
                playerId = data['player']['playerid']
                if playerId < 0:
                    result = data
                else:
                    result = common.executeJSONRPC('{"jsonrpc": "2.0", "method": "Player.GetItem", "params": { "properties": ["title","year","tagline","album","artist","plot","episode","season","showtitle","channel","channeltype","channelnumber","thumbnail","file"], "playerid": ' + str(playerId) + ' }, "id": "1"}')

                if 'item' in result:
                    if data['item']['type'] == 'movie':
                        if 'title' in result['item'] and result['item']['title'] != '':
                            title = '%s (%s)' % (result['item']['title'], result['item'].get('year',''))
                            body = result['item'].get('tagline',xbmc.getInfoLabel('VideoPlayer.Tagline'))

                    elif data['item']['type'] == 'song' or data['item']['type'] == 'musicvideo':
                        if 'title' in result['item'] and result['item']['title'] != '':
                            title = result['item']['title']
                            body = '%s / %s' % (result['item']['album'], ', '.join(result['item']['artist']))

                    elif data['item']['type'] == 'picture':
                        title = 'Picture'
                        body = data['item']['file']

                    elif data['item']['type'] == 'episode':
                        title = result['item']['title']
                        body = '%s %sx%s' % (result['item']['showtitle'], result['item']['episode'], result['item']['season'])

                    elif data['item']['type'] == 'channel':
                        title = result['item']['title']
                        body = '%s - %s (%s)' % (result['item']['channelnumber'], result['item']['channel'], result['item']['channeltype'], )

                    else:
                        title = result['item']['label'] if 'label' in result['item'] else result['item']['file']
                        body = None

                    thumbnailFilePath = None
                    if 'thumbnail' in result['item']:
                        thumbnailFilePath = result['item']['thumbnail']
                    else:
                        thumbnailFilePath = xbmc.getInfoLabel('Player.Art(thumb)')

                    if thumbnailFilePath:
                        try:
                            icon = common.fileTobase64(thumbnailFilePath, imgFormat='JPEG', imgSize=(72, 72))
                            if not icon: raise Exception('No Icon')
                        except:
                            icon = self.xbmcImgEncoded

                else:
                    title = 'unknown'
                    body = None
                    icon = self.xbmcImgEncoded

                ephemeralMsg = {'title': title, 'body': body, 'notification_id': self.pbPlaybackNotificationId, 'icon': icon}

                if len(self.pushbullet.sendEphemeral(ephemeralMsg)) == 0:
                    common.log(u'Ephemeral push sended: {0} - {1}'.format(ephemeralMsg['title'], ephemeralMsg['body']))
                else:
                    common.log(u'Ephemeral push NOT send: {0} - {1}'.format(ephemeralMsg['title'], ephemeralMsg['body']), xbmc.LOGERROR)

            elif method == 'Player.OnStop' and self.stg_pbMirroringOutMediaNfo:
                common.log('onKodiNotification: %s %s %s' % (sender, method, data))

                ephemeralDimiss = {'notification_id': self.pbPlaybackNotificationId}

                if len(self.pushbullet.dismissEphemeral(ephemeralDimiss)) == 0:
                    common.log('Ephemeral dismiss send')
                else:
                    common.log('Ephemeral dismiss NOT send', xbmc.LOGERROR)
Пример #42
0
def compare_version(version_installed, versionlist):
    # Create seperate version lists
    versionlist_stable = versionlist['releases']['stable']
    versionlist_rc = versionlist['releases']['releasecandidate']
    versionlist_beta = versionlist['releases']['beta']
    versionlist_alpha = versionlist['releases']['alpha']
    versionlist_prealpha = versionlist['releases']['prealpha']
    ### Check to upgrade to newest available stable version
    # check on smaller major version. Smaller version than available always notify
    oldversion = False
    msg = ''
    if version_installed['major'] < int(versionlist_stable[0]['major']):
        msg = 32003
        oldversion = "stable"
        log("Version available  %s" % versionlist_stable[0])

    # check on same major version installed and available
    elif version_installed['major'] == int(versionlist_stable[0]['major']):
        # check on smaller minor version
        if version_installed['minor'] < int(versionlist_stable[0]['minor']):
            msg = 32003
            oldversion = "stable"
            log("Version available  %s" % versionlist_stable[0])
        # check if not installed a stable so always notify
        elif version_installed['minor'] == int(
                versionlist_stable[0]
            ['minor']) and version_installed['tag'] != "stable":
            msg = 32008
            oldversion = "stable"
            log("Version available  %s" % versionlist_stable[0])
        else:
            log("Last available stable installed")

    ### Check to upgrade to newest available RC version if not installed stable
    ## Check also oldversion hasn't been set true by previous check because if so this need to be skipped
    if not oldversion and version_installed['tag'] != "stable":
        if 'revision' in version_installed.keys():
            # only check on equal or lower major because newer installed beta/alpha/prealpha version will be higher
            if versionlist_rc and version_installed['major'] <= int(
                    versionlist_rc[0]['major']):
                if version_installed['revision'] <= versionlist_rc[0][
                        'revision']:
                    msg = 32004
                    oldversion = True
                    log("Version available  %s" % versionlist_rc[0])

            # exclude if installed RC on checking for newer beta
            if not oldversion and versionlist_beta and version_installed[
                    'tag'] not in ["releasecandidate"]:
                if version_installed['major'] <= int(
                        versionlist_beta[0]['major']):
                    if version_installed['revision'] < versionlist_beta[0][
                            'revision']:
                        msg = 32005
                        oldversion = True
                        log("Version available  %s" % versionlist_beta[0])

            # exclude if installed RC or beta on checking for newer alpha
            if not oldversion and versionlist_alpha and version_installed[
                    'tag'] not in ["releasecandidate", "beta"]:
                if version_installed['major'] <= int(
                        versionlist_alpha[0]['major']):
                    if version_installed['revision'] < versionlist_alpha[0][
                            'revision']:
                        msg = 32006
                        oldversion = True
                        log("Version available  %s" % versionlist_alpha[0])

            # exclude if installed RC, beta or alpha on checking for newer prealpha
            if not oldversion and versionlist_prealpha and version_installed[
                    'tag'] not in ["releasecandidate", "beta", "alpha"]:
                if version_installed['major'] <= int(
                        versionlist_prealpha[0]['major']):
                    if version_installed['revision'] < versionlist_prealpha[0][
                            'revision']:
                        msg = 32007
                        oldversion = True
                        log("Version available  %s" % versionlist_prealpha[0])

            # exclude if installed RC, beta or alpha on checking for newer prealpha
            # if no more monthlies are build enable this section
            if not oldversion and versionlist_prealpha and version_installed[
                    'tag'] not in ["releasecandidate", "beta", "alpha"]:
                if version_installed['major'] <= int(
                        versionlist_prealpha[0]['major']):
                    if version_installed['revision'] <= versionlist_prealpha[
                            0]['revision']:
                        msg = 32007
                        oldversion = "monthly"
                        log("Version available  %s" % versionlist_prealpha[0])

        log("Nothing to see here, move along. Running a latest non stable release"
            )
        # Nothing to see here, move along
    else:
        log("Nothing to see here, move along. Running a stable release")
        # Nothing to see here, move along
        pass
    return oldversion, msg
Пример #43
0
            if dialog_yesno(32015):
                pass
            elif dialog_yesno(32009, 32010):
                log("disabling addon by user request")
                __addon__.setSetting("versioncheck_enable", 'false')
                return

        if handler:
            if handler.check_upgrade_available(packages[0]):
                if _upgrademessage(32012, oldversion, True):
                    if __addon__.getSetting("upgrade_system") == "false":
                        result = handler.upgrade_package(packages[0])
                    else:
                        result = handler.upgrade_system()
                    if result:
                        from lib.common import message_upgrade_success, message_restart
                        message_upgrade_success()
                        message_restart()
                    else:
                        log("Error during upgrade")
        else:
            log("Error: no handler found")
    else:
        log("Unsupported platform %s" % platform.dist()[0])
        sys.exit(0)


if (__name__ == "__main__"):
    log('Version %s started' % __addonversion__)
    Main()
Пример #44
0
                pass
            elif dialog_yesno(32009, 32010):
                log("disabling addon by user request")
                __addon__.setSetting("versioncheck_enable", "false")
                return

        if handler:
            if handler.check_upgrade_available(packages[0]):
                if _upgrademessage(32012, True):
                    if __addon__.getSetting("upgrade_system") == "false":
                        result = handler.upgrade_package(packages[0])
                    else:
                        result = handler.upgrade_system()
                    if result:
                        from lib.common import message_upgrade_success, message_restart

                        message_upgrade_success()
                        message_restart()
                    else:
                        log("Error during upgrade")
        else:
            log("Error: no handler found")
    else:
        log("Unsupported platform %s" % platform.dist()[0])
        sys.exit(0)


if __name__ == "__main__":
    log("Version %s started" % __addonversion__)
    Main()
Пример #45
0
 def setLastModified(self,modified):
     common.setSetting('last_modified','{0:10f}'.format(modified))
     common.log('Updating last_modified: {0}'.format(modified))
Пример #46
0
 def onError(self, error):
     common.log(error, xbmc.LOGERROR)
     common.showNotification(common.localise(30101), error,
                             self.notificationTime, self.notificationIcon)
Пример #47
0
def compare_version(version_installed, versionlist):
    # Create seperate version lists
    versionlist_stable = versionlist['releases']['stable']
    versionlist_rc = versionlist['releases']['releasecandidate']
    versionlist_beta = versionlist['releases']['beta']
    versionlist_alpha = versionlist['releases']['alpha']
    versionlist_prealpha = versionlist['releases']['prealpha']
    log('Version installed %s' % version_installed)
    ### Check to upgrade to newest available stable version
    # check on smaller major version. Smaller version than available always notify
    oldversion = False
    version_available = ''
    # check if installed major version is smaller than available major stable
    # here we don't care if running non stable
    if version_installed['major'] < int(versionlist_stable[0]['major']):
        version_available = versionlist_stable[0]
        oldversion = 'stable'
        log('Version available  %s' % versionlist_stable[0])
        log('You are running an older version')

    # check if installed major version is equal than available major stable
    # however also check on minor version and still don't care about non stable
    elif version_installed['major'] == int(versionlist_stable[0]['major']):
        if version_installed['minor'] < int(versionlist_stable[0]['minor']):
            version_available = versionlist_stable[0]
            oldversion = 'stable'
            log('Version available  %s' % versionlist_stable[0])
            log('You are running an older minor version')
        # check for <= minor !stable
        elif version_installed['tag'] != 'stable' and version_installed[
                'minor'] <= int(versionlist_stable[0]['minor']):
            version_available = versionlist_stable[0]
            oldversion = True
            log('Version available  %s' % versionlist_stable[0])
            log('You are running an older non stable minor version')
        else:
            log('Version available  %s' % versionlist_stable[0])
            log('There is no newer stable available')

    # Already skipped a possible newer stable build. Let's continue with non stable builds.
    # Check also 'oldversion' hasn't been set to 'stable' or true by previous checks because if so,
    # those part need to be skipped

    #check for RC builds
    if not oldversion and version_installed['tag'] in ['releasecandidate']:
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0rc3 is newer than:  14.0rc1, 14.0b9, 14.0a15
        if version_installed['major'] <= int(versionlist_rc[0]['major']):
            if version_installed['minor'] <= int(versionlist_rc[0]['minor']):
                if version_installed.get('tagversion',
                                         '') < versionlist_rc[0]['tagversion']:
                    version_available = versionlist_rc[0]
                    oldversion = True
                    log('Version available  %s' % versionlist_rc[0])
                    log('You are running an older RC version')
    # now check if installed !=rc
    elif not oldversion and version_installed['tag'] in [
            'beta', 'alpha', 'prealpha'
    ]:
        if version_installed['major'] <= int(versionlist_rc[0]['major']):
            if version_installed['minor'] <= int(versionlist_beta[0]['minor']):
                version_available = versionlist_rc[0]
                oldversion = True
                log('Version available  %s' % versionlist_rc[0])
                log('You are running an older non RC version')

    #check for beta builds
    if not oldversion and version_installed['tag'] == 'beta':
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0b3 is newer than:  14.0b1, 14.0a15
        if version_installed['major'] <= int(versionlist_beta[0]['major']):
            if version_installed['minor'] <= int(versionlist_beta[0]['minor']):
                if version_installed.get(
                        'tagversion', '') < versionlist_beta[0]['tagversion']:
                    version_available = versionlist_beta[0]
                    oldversion = True
                    log('Version available  %s' % versionlist_beta[0])
                    log('You are running an older beta version')
    # now check if installed !=beta
    elif not oldversion and version_installed['tag'] in ['alpha', 'prealpha']:
        if version_installed['major'] <= int(versionlist_beta[0]['major']):
            if version_installed['minor'] <= int(versionlist_beta[0]['minor']):
                version_available = versionlist_beta[0]
                oldversion = True
                log('Version available  %s' % versionlist_beta[0])
                log('You are running an older non beta version')

    #check for alpha builds and older
    if not oldversion and version_installed['tag'] == 'alpha':
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0a3 is newer than: 14.0a1 or pre-alpha
        if version_installed['major'] <= int(versionlist_alpha[0]['major']):
            if version_installed['minor'] <= int(
                    versionlist_alpha[0]['minor']):
                if version_installed.get(
                        'tagversion', '') < versionlist_alpha[0]['tagversion']:
                    version_available = versionlist_alpha[0]
                    oldversion = True
                    log('Version available  %s' % versionlist_alpha[0])
                    log('You are running an older alpha version')
    # now check if installed !=alpha
    elif not oldversion and version_installed['tag'] in ['prealpha']:
        if version_installed['major'] <= int(versionlist_alpha[0]['major']):
            if version_installed['minor'] <= int(
                    versionlist_alpha[0]['minor']):
                version_available = versionlist_alpha[0]
                oldversion = True
                log('Version available  %s' % versionlist_alpha[0])
                log('You are running an older non alpha version')
    version_stable = versionlist_stable[0]
    return oldversion, version_installed, version_available, version_stable
Пример #48
0
 def onOpen(self):
     common.log('Socket opened')
Пример #49
0
                pass
            elif dialog_yesno(32009, 32010):
                log("disabling addon by user request")
                __addon__.setSetting("versioncheck_enable", 'false')
                return

        if handler:
            if handler.check_upgrade_available(packages[0]):
                if _upgrademessage(32012, oldversion, True):
                    if __addon__.getSetting("upgrade_system") == "false":
                        result = handler.upgrade_package(packages[0])
                    else:
                        result = handler.upgrade_system()
                    if result:
                        from lib.common import message_upgrade_success, message_restart
                        message_upgrade_success()
                        message_restart()
                    else:
                        log("Error during upgrade")
        else:
            log("Error: no handler found")
    else:
        log("Unsupported platform %s" %platform.dist()[0])
        sys.exit(0)



if (__name__ == "__main__"):
    log('Version %s started' % __addonversion__)
    Main()
Пример #50
0
def compare_version(version_installed, versionlist):
    # Create seperate version lists
    versionlist_stable = versionlist["releases"]["stable"]
    versionlist_rc = versionlist["releases"]["releasecandidate"]
    versionlist_beta = versionlist["releases"]["beta"]
    versionlist_alpha = versionlist["releases"]["alpha"]
    versionlist_prealpha = versionlist["releases"]["prealpha"]
    log("Version installed %s" % version_installed)
    ### Check to upgrade to newest available stable version
    # check on smaller major version. Smaller version than available always notify
    oldversion = False
    version_available = ""
    # check if installed major version is smaller than available major stable
    # here we don't care if running non stable
    if version_installed["major"] < int(versionlist_stable[0]["major"]):
        version_available = versionlist_stable[0]
        oldversion = "stable"
        log("Version available  %s" % versionlist_stable[0])
        log("You are running an older version")

    # check if installed major version is equal than available major stable
    # however also check on minor version and still don't care about non stable
    elif version_installed["major"] == int(versionlist_stable[0]["major"]):
        if version_installed["minor"] < int(versionlist_stable[0]["minor"]):
            version_available = versionlist_stable[0]
            oldversion = "stable"
            log("Version available  %s" % versionlist_stable[0])
            log("You are running an older minor version")
        # check for <= minor !stable
        elif version_installed["tag"] != "stable" and version_installed["minor"] <= int(versionlist_stable[0]["minor"]):
            version_available = versionlist_stable[0]
            oldversion = True
            log("Version available  %s" % versionlist_stable[0])
            log("You are running an older non stable minor version")
        else:
            log("Version available  %s" % versionlist_stable[0])
            log("There is no newer stable available")

    # Already skipped a possible newer stable build. Let's continue with non stable builds.
    # Check also 'oldversion' hasn't been set to 'stable' or true by previous checks because if so,
    # those part need to be skipped

    # check for RC builds
    if not oldversion and version_installed["tag"] in ["releasecandidate"]:
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0rc3 is newer than:  14.0rc1, 14.0b9, 14.0a15
        if version_installed["major"] <= int(versionlist_rc[0]["major"]):
            if version_installed["minor"] <= int(versionlist_rc[0]["minor"]):
                if version_installed.get("tagversion", "") < versionlist_rc[0]["tagversion"]:
                    version_available = versionlist_rc[0]
                    oldversion = True
                    log("Version available  %s" % versionlist_rc[0])
                    log("You are running an older RC version")
    # now check if installed !=rc
    elif not oldversion and version_installed["tag"] in ["beta", "alpha", "prealpha"]:
        if version_installed["major"] <= int(versionlist_rc[0]["major"]):
            if version_installed["minor"] <= int(versionlist_beta[0]["minor"]):
                version_available = versionlist_rc[0]
                oldversion = True
                log("Version available  %s" % versionlist_rc[0])
                log("You are running an older non RC version")

    # check for beta builds
    if not oldversion and version_installed["tag"] == "beta":
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0b3 is newer than:  14.0b1, 14.0a15
        if version_installed["major"] <= int(versionlist_beta[0]["major"]):
            if version_installed["minor"] <= int(versionlist_beta[0]["minor"]):
                if version_installed.get("tagversion", "") < versionlist_beta[0]["tagversion"]:
                    version_available = versionlist_beta[0]
                    oldversion = True
                    log("Version available  %s" % versionlist_beta[0])
                    log("You are running an older beta version")
    # now check if installed !=beta
    elif not oldversion and version_installed["tag"] in ["alpha", "prealpha"]:
        if version_installed["major"] <= int(versionlist_beta[0]["major"]):
            if version_installed["minor"] <= int(versionlist_beta[0]["minor"]):
                version_available = versionlist_beta[0]
                oldversion = True
                log("Version available  %s" % versionlist_beta[0])
                log("You are running an older non beta version")

    # check for alpha builds and older
    if not oldversion and version_installed["tag"] == "alpha":
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0a3 is newer than: 14.0a1 or pre-alpha
        if version_installed["major"] <= int(versionlist_alpha[0]["major"]):
            if version_installed["minor"] <= int(versionlist_alpha[0]["minor"]):
                if version_installed.get("tagversion", "") < versionlist_alpha[0]["tagversion"]:
                    version_available = versionlist_alpha[0]
                    oldversion = True
                    log("Version available  %s" % versionlist_alpha[0])
                    log("You are running an older alpha version")
    # now check if installed !=alpha
    elif not oldversion and version_installed["tag"] in ["prealpha"]:
        if version_installed["major"] <= int(versionlist_alpha[0]["major"]):
            if version_installed["minor"] <= int(versionlist_alpha[0]["minor"]):
                version_available = versionlist_alpha[0]
                oldversion = True
                log("Version available  %s" % versionlist_alpha[0])
                log("You are running an older non alpah version")
    version_stable = versionlist_stable[0]
    return oldversion, version_installed, version_available, version_stable
Пример #51
0
def compare_version(version_installed, versionlist):
    # Create seperate version lists
    versionlist_stable = versionlist['releases']['stable']
    versionlist_rc = versionlist['releases']['releasecandidate']
    versionlist_beta = versionlist['releases']['beta']
    versionlist_alpha = versionlist['releases']['alpha']
    versionlist_prealpha = versionlist['releases']['prealpha'] 
    log('Version installed %s' %version_installed)
    ### Check to upgrade to newest available stable version
    # check on smaller major version. Smaller version than available always notify
    oldversion = False
    version_available = ''
    # check if installed major version is smaller than available major stable
    # here we don't care if running non stable
    if version_installed['major'] < int(versionlist_stable[0]['major']):
        version_available = versionlist_stable[0]
        oldversion = 'stable'
        log('Version available  %s' %versionlist_stable[0])
        log('You are running an older version')


    # check if installed major version is equal than available major stable
    # however also check on minor version and still don't care about non stable
    elif version_installed['major'] == int(versionlist_stable[0]['major']):
        if version_installed['minor'] < int(versionlist_stable[0]['minor']):
            version_available = versionlist_stable[0]
            oldversion = 'stable'
            log('Version available  %s' %versionlist_stable[0])
            log('You are running an older minor version')
        # check for <= minor !stable
        elif version_installed['tag'] != 'stable' and version_installed['minor'] <= int(versionlist_stable[0]['minor']):
            version_available = versionlist_stable[0]
            oldversion = True
            log('Version available  %s' %versionlist_stable[0])
            log('You are running an older non stable minor version')
        else:
            log('Version available  %s' %versionlist_stable[0])
            log('There is no newer stable available')
    
    # Already skipped a possible newer stable build. Let's continue with non stable builds.
    # Check also 'oldversion' hasn't been set to 'stable' or true by previous checks because if so,
    # those part need to be skipped
    
    #check for RC builds
    if not oldversion and version_installed['tag'] in ['releasecandidate']:
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0rc3 is newer than:  14.0rc1, 14.0b9, 14.0a15
        if version_installed.get('tagversion','') < versionlist_rc[0]['tagversion']:
            version_available = versionlist_rc[0]
            oldversion = True
            log('Version available  %s' %versionlist_rc[0])
            log('You are running an older RC version')
    # now check if installed !=rc
    elif not oldversion and version_installed['tag'] in ['beta','alpha','prealpha']:
        if version_installed['major'] <= int(versionlist_rc[0]['major']):
            if version_installed['minor'] <= int(versionlist_beta[0]['minor']):
                version_available = versionlist_rc[0]
                oldversion = True
                log('Version available  %s' %versionlist_rc[0])
                log('You are running an older non RC version')

    #check for beta builds
    if not oldversion and version_installed['tag'] == 'beta':
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0b3 is newer than:  14.0b1, 14.0a15
        if version_installed.get('tagversion','') < versionlist_beta[0]['tagversion']:
            version_available = versionlist_beta[0]
            oldversion = True
            log('Version available  %s' %versionlist_beta[0])
            log('You are running an older beta version')
    # now check if installed !=beta
    elif not oldversion and version_installed['tag'] in ['alpha','prealpha']:
        if version_installed['major'] <= int(versionlist_beta[0]['major']):
            if version_installed['minor'] <= int(versionlist_beta[0]['minor']):
                version_available = versionlist_beta[0]
                oldversion = True
                log('Version available  %s' %versionlist_beta[0])
                log('You are running an older non beta version')

    #check for alpha builds and older
    if not oldversion and version_installed['tag'] == 'alpha':
        # check if you are using a RC build lower than current available RC
        # then check if you are using a beta/alpha lower than current available RC
        # 14.0a3 is newer than: 14.0a1 or pre-alpha
        if version_installed['major'] <= int(versionlist_alpha[0]['major']):
            if version_installed.get('tagversion','') < versionlist_alpha[0]['tagversion']:
                version_available = versionlist_alpha[0]
                oldversion = True
                log('Version available  %s' %versionlist_alpha[0])
                log('You are running an older alpha version')
    # now check if installed !=alpha
    elif not oldversion and version_installed['tag'] in ['prealpha']:
        if version_installed['major'] <= int(versionlist_alpha[0]['major']):
            if version_installed['minor'] <= int(versionlist_alpha[0]['minor']):
                version_available = versionlist_alpha[0]
                oldversion = True
                log('Version available  %s' %versionlist_alpha[0])
                log('You are running an older non alpah version')     
    version_stable = versionlist_stable[0]
    return oldversion, version_installed, version_available, version_stable
Пример #52
0
    else:
        log("Unsupported platform %s" %platform.dist()[0])
        sys.exit(0)

# Python cryptography < 1.7 (still shipped with Ubuntu 16.04) has issues with
# pyOpenSSL integration, leading to all sorts of weird bugs - check here to save
# on some troubleshooting. This check may be removed in the future (when switching
# to Python3?)
# See https://github.com/pyca/pyopenssl/issues/542
def _checkcryptography():
    ver = None
    try:
        import cryptography
        ver = cryptography.__version__
    except:
        # If the module is not found - no problem
        return
        
    ver_parts = list(map(int, ver.split('.')))
    if len(ver_parts) < 2 or ver_parts[0] < 1 or (ver_parts[0] == 1 and ver_parts[1] < 7):
        log('Python cryptography module version %s is too old, at least version 1.7 needed' % ver)
        xbmcgui.Dialog().ok(ADDONNAME, localise(32040) % ver, localise(32041), localise(32042))

if (__name__ == "__main__"):
    _checkcryptography()
    if ADDON.getSetting("versioncheck_enable") == "false":
        log("Disabled")
    else:
        log('Version %s started' % ADDONVERSION)
        Main()
Пример #53
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from lib.common import log
from lib.constant import *
from lib.sys import getClipboardText
from lib.file import fileWrite
# print getClipboardText()
from mako.template import Template

log("程序开始")
ftl = '''
#java代码
% for column in columnList:
    obj.put("${column}", jsonObject.get("${column}"));
% endfor

#接口测试json报文
{
% for i,kv in enumerate(kvList):
    % if i!=len(kvList)-1:
    "${kv["key"]}":"${kv["value"]}",
    % else:
    "${kv["key"]}":"${kv["value"]}"
    % endif
% endfor  
}

#序列
% for num in sequence:
Z201708010000${num}
% endfor
Пример #54
0
def compare_version(version_installed, versionlist):
    # Create seperate version lists
    versionlist_stable = versionlist['releases']['stable']
    versionlist_rc = versionlist['releases']['releasecandidate']
    versionlist_beta = versionlist['releases']['beta']
    versionlist_alpha = versionlist['releases']['alpha']
    versionlist_prealpha = versionlist['releases']['prealpha'] 
    ### Check to upgrade to newest available stable version
    # check on smaller major version. Smaller version than available always notify
    oldversion = False
    msg = ''
    if version_installed['major'] < int(versionlist_stable[0]['major']):
        msg = 32003
        oldversion = True
        log("Version available  %s" %versionlist_stable[0])

    # check on same major version installed and available
    elif version_installed['major'] == int(versionlist_stable[0]['major']):
        # check on smaller minor version
        if version_installed['minor'] < int(versionlist_stable[0]['minor']):
            msg = 32003
            oldversion = True
            log("Version available  %s" %versionlist_stable[0])
        # check if not installed a stable so always notify
        elif version_installed['minor'] == int(versionlist_stable[0]['minor']) and version_installed['tag'] != "stable":
            msg = 32008
            oldversion = True
            log("Version available  %s" %versionlist_stable[0])
        else:
            log("Last available stable installed")

    ### Check to upgrade to newest available RC version if not installed stable
    ## Check also oldversion hasn't been set true by previous check because if so this need to be skipped
    if not oldversion and version_installed['tag'] != "stable":
        # only check on equal or lower major because newer installed beta/alpha/prealpha version will be higher
        if versionlist_rc and version_installed['major'] <= int(versionlist_rc[0]['major']):
            if version_installed['revision'] <= versionlist_rc[0]['revision']:
                msg = 32004
                oldversion = True
                log("Version available  %s" %versionlist_rc[0])

        # exclude if installed RC on checking for newer beta
        if not oldversion and versionlist_beta and version_installed['tag'] not in ["releasecandidate"]:
            if version_installed['major'] <= int(versionlist_beta[0]['major']):
                if version_installed['revision'] < versionlist_beta[0]['revision']:
                    msg = 32005
                    oldversion = True
                    log("Version available  %s" %versionlist_beta[0])
    
        # exclude if installed RC or beta on checking for newer alpha
        if not oldversion and versionlist_alpha and version_installed['tag'] not in ["releasecandidate", "beta"]:
            if version_installed['major'] <= int(versionlist_alpha[0]['major']):
                if version_installed['revision'] < versionlist_alpha[0]['revision']:
                    msg = 32006
                    oldversion = True
                    log("Version available  %s" %versionlist_alpha[0])

        # exclude if installed RC, beta or alpha on checking for newer prealpha
        if not oldversion and versionlist_prealpha and version_installed['tag'] not in ["releasecandidate", "beta", "alpha"]:
            if version_installed['major'] <= int(versionlist_prealpha[0]['major']):
                if version_installed['revision'] < versionlist_prealpha[0]['revision']:
                    msg = 32007
                    oldversion = True
                    log("Version available  %s" %versionlist_prealpha[0])

        log("Nothing to see here, move along. Running a latest non stable release")
        # Nothing to see here, move along
    else:
        log("Nothing to see here, move along. Running a stable release")
        # Nothing to see here, move along
        pass
    return oldversion, msg
Пример #55
0
 def onClose(self):
     common.log('Socket closed')
Пример #56
0
                            break
                if isMovie:
                    self.type = "movie"
            elif xbmc.getCondVisibility('VideoPlayer.Content(episodes)'):
                # Check for tv show title and season to make sure it's really an episode
                if xbmc.getInfoLabel(
                        'VideoPlayer.Season') != "" and xbmc.getInfoLabel(
                            'VideoPlayer.TVShowTitle') != "":
                    self.type = "episode"

    def onPlayBackEnded(self):
        self.onPlayBackStopped()

    def onPlayBackStopped(self):
        if self.type == 'movie':
            self.action('movie')
        elif self.type == 'episode':
            self.action('episode')
        elif self.type == 'music':
            self.action('music')
        self.type = ""


if (__name__ == "__main__"):
    log('script version %s started' % __version__)
    Main()
    del Widgets_Monitor
    del Widgets_Player
    del Main
    log('script version %s stopped' % __version__)
 def onError(self, error):
     common.log(error, xbmc.LOGERROR)
     common.showNotification(common.localise(30101), error, self.notificationTime, self.notificationIcon)
 def onClose(self):
     common.log('Socket closed')
Пример #59
0
                pass
            elif dialog_yesno(32009, 32010):
                log("disabling addon by user request")
                ADDON.setSetting("versioncheck_enable", 'false')
                return

        if handler:
            if handler.check_upgrade_available(packages[0]):
                if _upgrademessage(32012, oldversion, True):
                    if ADDON.getSetting("upgrade_system") == "false":
                        result = handler.upgrade_package(packages[0])
                    else:
                        result = handler.upgrade_system()
                    if result:
                        from lib.common import message_upgrade_success, message_restart
                        message_upgrade_success()
                        message_restart()
                    else:
                        log("Error during upgrade")
        else:
            log("Error: no handler found")
    else:
        log("Unsupported platform %s" %platform.dist()[0])
        sys.exit(0)



if (__name__ == "__main__"):
    log('Version %s started' % ADDONVERSION)
    Main()
Create SQL script from population data

'''
from lib.common import pop_geo_levels, read_file, get_geo_field_name, log
import argparse
import csv

parser = argparse.ArgumentParser(description='Generate SQL to import population file from csv data file')

parser.add_argument('year', metavar='Y', type=int, nargs=1, help='year to import')

args = parser.parse_args()

year = int(args.year[0])

log("Importing year " + str(year))


def make_field_name(column):
  """
  Transform R based named (with .) to DB fields name 
  """
  column = column.replace('.', '_')
  return column

def create_query(fn, columns, table_name):
    data = read_file(fn)
    if data:
        values = []
        for row in data:
            v = '('