コード例 #1
0
def setup_pocket():
    pocket = ''
    f = os.path.expanduser(os.path.join('~', '.config', 'pocket.txt'))
    if os.path.exists(f):
        with file(f, 'r') as target:
            data = pickle.load(target)
        consumerkey = data['consumer_key']
        pocket = api.API(consumerkey)
        pocket.authenticate(data['access_token'])
    elif 'POCKET_ACCESS_KEY' in os.environ:
        pocket = api.API(ckey)
        pocket.authenticate(os.environ['POCKET_ACCESS_KEY'])
    else:
        print "AUTHENTICATION FAILED - UNDEFINED FOR NOW"
        pocket = api.API(ckey)
        pocket.authenticate()
        data = {
            'consumer_key': ckey,
            'access_token': api.access_token,
            'contentType': 'article',
            'detailType': 'complete'
        }
        with file(f, 'w') as target:
            pickle.dump(data, target)
    return pocket
コード例 #2
0
ファイル: gui.py プロジェクト: JoriKos/wikitranslator
    def __init__(self):
        self.context = core.Context(tf2_api=api.API(TF2_WIKI_API),
                                    wikipedia_api=api.API(WIKIPEDIA_API))
        self.last_input = ''

        super().__init__()

        self.title('wikitranslator')
        self.protocol('WM_DELETE_WINDOW', self.exit)

        self.frame = ttk.Frame(self, padding='3 3 3 3', style='Wat.TFrame')

        self.text_input = tk.Text(self.frame,
                                  width=90,
                                  height=40,
                                  wrap='char',
                                  undo=True,
                                  maxundo=100)
        self.scrollbar_input = ttk.Scrollbar(self.frame,
                                             orient='vertical',
                                             command=self.text_input.yview)

        self.text_output = tk.Text(self.frame,
                                   width=90,
                                   height=40,
                                   wrap='char',
                                   state=tk.DISABLED)
        self.scrollbar_output = ttk.Scrollbar(self.frame,
                                              orient='vertical',
                                              command=self.text_output.yview)

        self.control_panel = ControlPanel(self.frame,
                                          self.translate,
                                          padding='3 3 3 3')

        self.frame.grid(column=0, row=0, sticky='nwes')

        self.control_panel.grid(column=0, row=0, sticky='nwes')
        self.text_input.grid(column=0, row=1, sticky='nwes')
        self.scrollbar_input.grid(column=1, row=1, sticky='nwes')
        self.text_output.grid(column=2, row=1, sticky='nwes')
        self.scrollbar_output.grid(column=3, row=1, sticky='nwes')

        self.text_input['yscrollcommand'] = self.scrollbar_input.set
        self.text_output['yscrollcommand'] = self.scrollbar_output.set

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=1, minsize=150)
        self.frame.columnconfigure(0, weight=2, minsize=400)
        self.frame.columnconfigure(2, weight=2, minsize=400)

        self.bind('<Control-Z>', self.text_input.edit_undo)
        self.bind('<Control-Shift-Z>', self.text_input.edit_redo)

        self.after(1000, self.input_tick)
コード例 #3
0
    def _resume(self):

        ''' Resume item if available.
            Returns bool or raise an exception if resume was cancelled by user.
        '''
        seektime = window('emby.resume')
        seektime = seektime == 'true' if seektime else None
        auto_play = window('emby.autoplay.bool')
        window('emby.resume', clear=True)

        if auto_play:

            seektime = False
            LOG.info("[ skip resume for auto play ]")

        elif seektime is None and self.info['Item']['MediaType'] in ('Video', 'Audio'):
            resume = self.info['Item']['UserData'].get('PlaybackPositionTicks')

            if resume:

                adjusted = api.API(self.info['Item'], self.info['Server']).adjust_resume((resume or 0) / 10000000.0)
                seektime = self.actions.resume_dialog(adjusted, self.info['Item'])
                LOG.info("Resume: %s", adjusted)

                if seektime is None:
                    raise Exception("User backed out of resume dialog.")

            window('emby.autoplay.bool', True)

        return seektime
コード例 #4
0
	def __init__(self, server, config, log, wrapper, address, port, nickname, channels):
		self.socket = False
		self.server = server
		self.config = config
		self.wrapper = wrapper
		self.address = address
		self.port = port
		self.nickname = nickname
		self.originalNickname = nickname[0:]
		self.nickAttempts = 0
		self.channels = channels
		self.log = log
		self.timeout = False
		self.ready = False
		self.msgQueue = []
		
		self.api = api.API(self.wrapper, "IRC", internal=True)
		self.api.registerEvent("server.starting", self.onServerStarting)
		self.api.registerEvent("server.started", self.onServerStarted)
		self.api.registerEvent("server.stopping", self.onServerStopping)
		self.api.registerEvent("server.stopped", self.onServerStopped)
		self.api.registerEvent("player.login", self.onPlayerLogin)
		self.api.registerEvent("player.message", self.onPlayerMessage)
		self.api.registerEvent("player.action", self.onPlayerAction)
		self.api.registerEvent("player.logout", self.onPlayerLogout)
		self.api.registerEvent("player.achievement", self.onPlayerAchievement)
		self.api.registerEvent("player.death", self.onPlayerDeath)
		self.api.registerEvent("wrapper.backupBegin", self.onBackupBegin)
		self.api.registerEvent("wrapper.backupEnd", self.onBackupEnd)
		self.api.registerEvent("wrapper.backupFailure", self.onBackupFailure)
		self.api.registerEvent("server.say", self.onPlayerSay)
コード例 #5
0
ファイル: predict.py プロジェクト: brunowenzel07/pyhounds
def predict():
    click.echo("--> Starting predict script...")
    tracks = t.Tracks(t_="predict")
    api = connection.API()

    for future in tracks.future():

        race = r.Races(future, webdriver, "predict")
        infos = race.future_informations()
        infos["dogs"] = []
        stats = list()
        # For each dog present in race, calculate the stats
        for dog in race.future_dogs():
            dogs = d.Dogs(dog, infos, webdriver, "predict")
            infos["w_track"], infos["w_trap"], infos[
                "w_grade"] = dogs.extra_infos()
            dog["probability"] = round(random.uniform(1, 99), 2)
            dog["best_time"] = round(random.uniform(25, 30), 2)
            dog.pop("date")
            infos["dogs"].append(dog)

            s_ = dogs.stats()
            print(s_)
            if len(s_) == 19:
                stats.append(np.append(s_, dog["trap"]))
        hp.generated_predicts(stats, infos)
        break
コード例 #6
0
    def updateUserdata(self, item):
        # This updates: Favorite, LastPlayedDate, Playcount, PlaybackPositionTicks
        # Poster with progress bar
        emby_db = self.emby_db
        API = api.API(item)

        # Get emby information
        itemid = item['Id']
        checksum = API.get_checksum()
        userdata = API.get_userdata()
        runtime = API.get_runtime()

        # Get Kodi information
        emby_dbitem = emby_db.getItem_byId(itemid)
        try:
            mvideoid = emby_dbitem[0]
            fileid = emby_dbitem[1]
            log.info("Update playstate for musicvideo: %s fileid: %s", item['Name'], fileid)
        except TypeError:
            return

        # Process favorite tags
        if userdata['Favorite']:
            self.kodi_db.get_tag(mvideoid, "Favorite musicvideos", "musicvideo")
        else:
            self.kodi_db.remove_tag(mvideoid, "Favorite musicvideos", "musicvideo")

        # Process playstates
        playcount = userdata['PlayCount']
        dateplayed = userdata['LastPlayedDate']
        resume = API.adjust_resume(userdata['Resume'])
        total = round(float(runtime), 6)

        self.kodi_db.add_playstate(fileid, resume, total, playcount, dateplayed)
        emby_db.updateReference(itemid, checksum)
コード例 #7
0
    def __init__(self):

        self.emby = embyserver.Read_EmbyServer()

        self.kodi_id = xbmc.getInfoLabel('ListItem.DBID').decode('utf-8')
        self.item_type = self._get_item_type()
        self.item_id = self._get_item_id(self.kodi_id, self.item_type)

        log.info("Found item_id: %s item_type: %s", self.item_id,
                 self.item_type)

        if self.item_id:

            self.item = self.emby.getItem(self.item_id)
            self.api = api.API(self.item)

            if self._select_menu():
                self._action_menu()

                if self._selected_option in (OPTIONS['Delete'],
                                             OPTIONS['AddFav'],
                                             OPTIONS['RemoveFav'],
                                             OPTIONS['RateSong']):
                    log.info("refreshing container")
                    xbmc.sleep(500)
                    xbmc.executebuiltin('Container.Refresh')
コード例 #8
0
    def __init__(self,
                 model_file,
                 data_file,
                 out_file,
                 attack_type,
                 is_training,
                 verbosity,
                 featurizer=None):
        """
        This class will eventually simulate real communication between
        the api, method, and monitor. This behavior only makes sense for
        when the system is "deployed" aka making requests in real time.

        Currently, it serves to stitch together the method and monitor
        (train/test and display) of static data.
        """
        self.model_file = model_file
        self.data_file = data_file
        self.out_file = out_file
        self.attack_type = attack_type
        self.is_training = is_training
        self.verbosity = verbosity
        self.featurizer = featurizer

        # requires sudo to send and receive real packets
        self.api = api.API()
コード例 #9
0
def main(logger):
    envse = ['DISCORD_TOKEN', 'DISCORD_CHANNEL_NAME', 'DISCORDBOT_TOKEN']
    envsc = [
        'LOCATION', 'XRAIN_ZOOM', 'MANET', 'GOOGLE_MAPS_API_KEY',
        'DARK_SKY_API_KEY', 'CADVISOR', 'CONTAINERS', 'MORNING', 'EVENING',
        'XRAIN_LAT', 'XRAIN_LON', 'PORT'
    ]

    f = util.environ(envse, 'error')
    util.environ(envsc, 'warning')
    if f:
        logger.error('error: some environment variables are not set. exiting.')
        sys.exit(1)

    sendqueue = queue.Queue()

    httploop = asyncio.new_event_loop()
    ap = api.API(httploop, sendqueue, logger,
                 os.environ.get('DISCORDBOT_TOKEN'))
    threading.Thread(target=ap.run, name='api', daemon=True).start()

    wea = weather.Weather(sendqueue, logger)
    mon = monitoring.Monitoring(sendqueue, logger)
    scheduleloop = asyncio.new_event_loop()
    sched = Scheduler(sendqueue, wea, mon, logger, scheduleloop)
    threading.Thread(target=sched.run, name='scheduler', daemon=True).start()

    logger.debug('launch discord client')
    client = discordbot.DiscordClient(os.environ.get('DISCORD_CHANNEL_NAME'),
                                      sendqueue, wea, mon, logger)
    client.run(os.environ.get('DISCORD_TOKEN'))
コード例 #10
0
    def direct_play(self, source):

        API = api.API(self.info['Item'], self.info['ServerAddress'])
        self.info['Method'] = "DirectPlay"
        self.info['Path'] = API.get_file_path(source.get('Path'))

        return self.info['Path']
コード例 #11
0
 def __init__(self, options, config):
     """Initializes all of the submodules bitHopper uses"""
     
     #Logging
     
     logging.basicConfig(stream=sys.stdout, format="%(asctime)s|%(module)s: %(message)s", datefmt="%H:%M:%S", level = logging.INFO)
     
     self.options = options
     self.config = config        
     altercoins = ConfigParser.ConfigParser()
     altercoins.read(os.path.join(sys.path[0], "whatevercoin.cfg"))
     self.altercoins = {}
     for coin in altercoins.sections():
         self.altercoins[coin] = dict(altercoins.items(coin))
         self.altercoins[coin]['recent_difficulty'] = float(self.altercoins[coin]['recent_difficulty'])
     self.scheduler = None
     self.lp_callback = lp_callback.LP_Callback(self)
     self.difficulty = diff.Difficulty(self)  
     self.exchange = exchange.Exchange(self)
     self.pool = None        
     self.db = database.Database(self)                       
     self.pool = pool.Pool_Parse(self)
     self.api = api.API(self) 
     self.pool.setup(self)
     self.work = work.Work(self)
     self.speed = speed.Speed()
     self.getwork_store = getwork_store.Getwork_store(self)
     self.data = data.Data(self)       
     self.lp = lp.LongPoll(self)
     self.auth = None
     
     self.website = website.bitSite(self)
     self.pile = greenpool.GreenPool()
     self.plugin = plugin.Plugin(self)
     self.pile.spawn_n(self.delag_server)
コード例 #12
0
ファイル: tvshows.py プロジェクト: jimyx17/Emby.Kodi.AddOn
    def updateUserdata(self, item):
        # This updates: Favorite, LastPlayedDate, Playcount, PlaybackPositionTicks
        # Poster with progress bar
        emby_db = self.emby_db
        API = api.API(item)

        # Get emby information
        itemid = item['Id']
        checksum = API.get_checksum()
        userdata = API.get_userdata()
        runtime = API.get_runtime()
        dateadded = API.get_date_created()

        # Get Kodi information
        emby_dbitem = emby_db.getItem_byId(itemid)
        try:
            kodiid = emby_dbitem[0]
            fileid = emby_dbitem[1]
            mediatype = emby_dbitem[4]
            log.info("Update playstate for %s: %s fileid: %s", mediatype,
                     item['Name'], fileid)
        except TypeError:
            return

        # Process favorite tags
        if mediatype == "tvshow":
            if userdata['Favorite']:
                self.kodi_db.get_tag(kodiid, "Favorite tvshows", "tvshow")
            else:
                self.kodi_db.remove_tag(kodiid, "Favorite tvshows", "tvshow")
        elif mediatype == "episode":
            # Process playstates
            playcount = userdata['PlayCount']
            dateplayed = userdata['LastPlayedDate']
            resume = API.adjust_resume(userdata['Resume'])
            total = round(float(runtime), 6)

            log.debug("%s New resume point: %s", itemid, resume)

            self.kodi_db.add_playstate(fileid, resume, total, playcount,
                                       dateplayed)
            if not self.direct_path and not resume:
                # Make sure there's no other bookmarks created by widget.
                filename = self.kodi_db.get_filename(fileid)
                self.kodi_db.remove_file("plugin://plugin.video.emby.tvshows/",
                                         filename)

            if not self.direct_path and resume:
                # Create additional entry for widgets. This is only required for plugin/episode.
                filename = self.kodi_db.get_filename(fileid)
                temppathid = self.kodi_db.get_path(
                    "plugin://plugin.video.emby.tvshows/")
                tempfileid = self.kodi_db.add_file(filename, temppathid)
                self.kodi_db.update_file(tempfileid, filename, temppathid,
                                         dateadded)
                self.kodi_db.add_playstate(tempfileid, resume, total,
                                           playcount, dateplayed)

        emby_db.updateReference(itemid, checksum)
コード例 #13
0
ファイル: dataset.py プロジェクト: sethlarweh/Hella
    def __init__(self, asset_file, data_file):
        self.asset_file = asset_file
        self.data_file = data_file

        raw_asset = self.read_asset_file(self.asset_file)
        self.data_points = self.process_asset(raw_asset)
        self.config = self.read_config_file()

        self.api = api.API()
コード例 #14
0
ファイル: AfterburnNode.py プロジェクト: domenicw/afterburn
 def __init__(self, nodeid, token):
     self.nodeid = nodeid
     self.index = 1
     self.api = netAPI.API(nodeid, token)
     self.location = self.makeLocation()
     self.tempMax = randrange(40, 65)
     self.coMax = randrange(400, 700)
     self.o2Max = randrange(18, 20)
     self.humMax = randrange(10, 20)
コード例 #15
0
    def __init__(self):
        LOG.debug("JellyfinClient initializing...")

        self.config = Config()
        self.http = HTTP(self)
        self.wsc = WSClient(self)
        self.auth = ConnectionManager(self)
        self.jellyfin = api.API(self.http)
        self.callback_ws = callback
        self.callback = callback
コード例 #16
0
    def __init__(self, wrapper):
        self.wrapper = wrapper
        self.config = wrapper.config
        self.log = wrapper.log
        self.api = api.API(wrapper, "Backups", internal=True)

        self.interval = 0
        self.time = time.time()
        self.backups = []
        self.api.registerEvent("timer.second", self.onTick)
コード例 #17
0
ファイル: controller.py プロジェクト: mbrar8/amsen
 def __init__(self):
     self.sensors = sensors.Sensors()
     self.map = map.Map(240, 240, 10)
     self.api = api.API()
     self.driver = driver.Driver()
     self.turns = 0
     self.direction = True
     self.LANE_WIDTH = 12
     self.FORWARD_DIST = 120
     self.PROXIMITY_DIST = 10
     self.MIN_UNVISITED_AREA = 10
コード例 #18
0
	def __init__(self, wrapper):
		self.api = api.API(wrapper, "Scripts", internal=True)
		self.wrapper = wrapper
		
		# Register the events
		self.api.registerEvent("server.start", self._startServer)
		self.api.registerEvent("server.stopped", self._stopServer)
		self.api.registerEvent("wrapper.backupBegin", self._backupBegin)
		self.api.registerEvent("wrapper.backupEnd", self._backupEnd)
		
		self.createDefaultScripts()
コード例 #19
0
    def _set_playlist(self, listitem):
        ''' Verify seektime, set intros, set main item and set additional parts.
            Detect the seektime for video type content.
            Verify the default video action set in Kodi for accurate resume behavior.
        '''
        seektime = window('emby.resume')
        window('emby.resume', clear=True)
        seektime = seektime == 'true' if seektime else None

        if seektime is None and self.info['Item']['MediaType'] in ('Video',
                                                                   'Audio'):
            resume = self.info['Item']['UserData'].get('PlaybackPositionTicks')

            if resume:
                choice = self.actions.resume_dialog(
                    api.API(self.info['Item'],
                            self.info['Server']).adjust_resume(
                                (resume or 0) / 10000000.0), self.info['Item'])

                if choice is None:
                    raise Exception("User backed out of resume dialog.")

                seektime = False if not choice else True

        if settings('enableCinema.bool') and not seektime:
            self._set_intros()

        LOG.info("[ main/%s/%s ] %s", self.info['Item']['Id'],
                 self.info['Index'], self.info['Item']['Name'])
        play = playutils.PlayUtilsStrm(self.info['Item'],
                                       self.info['Transcode'],
                                       self.info['ServerId'],
                                       self.info['Server'])
        source = play.select_source(play.get_sources())

        if not source:
            raise Exception("Playback selection cancelled")

        play.set_external_subs(source, listitem)
        self.set_listitem(self.info['Item'], listitem, self.info['DbId'],
                          seektime)
        listitem.setPath(self.info['Item']['PlaybackInfo']['Path'])
        playutils.set_properties(self.info['Item'],
                                 self.info['Item']['PlaybackInfo']['Method'],
                                 self.info['ServerId'])

        self.info['KodiPlaylist'].add(
            url=self.info['Item']['PlaybackInfo']['Path'],
            listitem=listitem,
            index=self.info['Index'])
        self.info['Index'] += 1

        if self.info['Item'].get('PartCount'):
            self._set_additional_parts()
コード例 #20
0
ファイル: service.py プロジェクト: wiqram/microservice-demo
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    address = os.getenv("HOST") + ":" + os.getenv("PORT")
    server.add_insecure_port(address)

    model.create_tables()

    service.add_ProjectSvcServicer_to_server(api.API(), server)

    server.start()
    logging.info("Server started at: http://" + address)
    server.wait_for_termination()
コード例 #21
0
    def __init__(self, item):

        self.item = item
        self.API = api.API(self.item)

        self.doUtils = downloadutils.DownloadUtils().downloadUrl

        self.userid = window('emby_currUser')
        self.server = window('emby_server%s' % self.userid)

        self.artwork = artwork.Artwork()
        self.emby = embyserver.Read_EmbyServer()
        self.pl = playlist.Playlist()
コード例 #22
0
ファイル: weather.py プロジェクト: cbondurant/cathacks-2020
 def __init__(self, **kwargs):
     self.api = api.API("https://api.weather.gov/")
     self.coordinate = kwargs["coordinates"]
     station_data = json.loads(
         self.api.get("/points/{}".format(self.coordinate)).text)
     self.gridId = station_data["properties"]["gridId"]
     self.gridX = station_data["properties"]["gridX"]
     self.gridY = station_data["properties"]["gridY"]
     self.cacheTime = 0
     if "cacheTTL" in kwargs:
         self.cacheTTL = float(kwargs["cacheTTL"]) * 60
     else:
         self.cacheTTL = 1800
     self.cache = {}
コード例 #23
0
    def __init__(self, resource):
        '''
            Lua-based interpreter for handler files.
        '''
        self.resource = resource
        self.runtime = lupa.LuaRuntime()
        self.api = api.API(self.document)

        # Provide the deje module
        bootstrapfunc = self.runtime.execute(bootstrap)
        bootstrapfunc(self.api.export())
        self.runtime.execute('load_deje = nil')

        self.reload()
コード例 #24
0
ファイル: main.py プロジェクト: ShiftCipher/Polymath
def download():
    header = request.Head()
    header.addHeader('X-EBAY-API-CALL-NAME', 'GetCategories')
    header.addHeader('X-EBAY-API-APP-NAME', env('APP_NAME'))
    header.addHeader('X-EBAY-API-CERT-NAME', env('CERT_NAME'))
    header.addHeader('X-EBAY-API-DEV-NAME', env('EBAY_API_DEV_NAME'))
    header.addHeader('X-EBAY-API-SITEID', '0')
    header.addHeader('X-EBAY-API-COMPATIBILITY-LEVEL', '989')
    header.addHeader('Content-Type', 'text/xml')
    body = request.Body('ebayGetCategories', 'EBAY_AUTH_TOKEN').getXML()
    headers = header.getAll()
    ebayAPI = api.API('EBAY_API_URL')
    ebayAPI.requestXML(headers, body)
    ebayAPI.exportXML('GetCategories')
    return ebayAPI
コード例 #25
0
    def __init__(self, item):

        self.item = item
        self.API = api.API(self.item)

        self.clientInfo = clientinfo.ClientInfo()
        self.addonName = self.clientInfo.getAddonName()
        self.doUtils = downloadutils.DownloadUtils().downloadUrl

        self.userid = utils.window('emby_currUser')
        self.server = utils.window('emby_server%s' % self.userid)

        self.artwork = artwork.Artwork()
        self.emby = embyserver.Read_EmbyServer()
        self.pl = playlist.Playlist()
コード例 #26
0
ファイル: music.py プロジェクト: emlove/plugin.video.emby
    def compare_artists(self, view):

        all_embyartistsIds = set()
        update_list = list()

        if self.pdialog:
            self.pdialog.update(heading=lang(29999),
                                message="%s Artists..." % lang(33031))

        artists = dict(self.emby_db.get_checksum('MusicArtist'))
        album_artists = dict(self.emby_db.get_checksum('AlbumArtist'))
        emby_artists = self.emby.getArtists(view['id'], dialog=self.pdialog)

        for item in emby_artists['Items']:

            if self.should_stop():
                return False

            item_id = item['Id']
            API = api.API(item)

            all_embyartistsIds.add(item_id)
            if item_id in artists:
                if artists[item_id] != API.get_checksum():
                    # Only update if artist is not in Kodi or checksum is different
                    update_list.append(item_id)
            elif album_artists.get(item_id) != API.get_checksum():
                # Only update if artist is not in Kodi or checksum is different
                update_list.append(item_id)

            #compare_to.pop(item_id, None)

        log.info("Update for Artist: %s", update_list)

        emby_items = self.emby.getFullItems(update_list)
        total = len(update_list)

        if self.pdialog:
            self.pdialog.update(heading="Processing Artists / %s items" %
                                total)

        # Process additions and updates
        if emby_items:
            self.process_all("MusicArtist", "update", emby_items, total)
        # Process removals
        for artist in artists:
            if artist not in all_embyartistsIds and artists[artist] is not None:
                self.remove(artist)
コード例 #27
0
    def get(self, source, audio=None, subtitle=None):
        ''' The server returns sources based on the MaxStreamingBitrate value and other filters.
            prop: embyfilename for ?? I thought it was to pass the real path to subtitle add-ons but it's not working?
        '''
        self.info['MediaSourceId'] = source['Id']

        if source.get('RequiresClosing'):
            ''' Server returning live tv stream for direct play is hardcoded with 127.0.0.1.
            '''
            self.info['LiveStreamId'] = source['LiveStreamId']
            source['SupportsDirectPlay'] = False
            source['Protocol'] = "LiveTV"

        if self.info['ForceTranscode']:

            source['SupportsDirectPlay'] = False
            source['SupportsDirectStream'] = False
            source['Protocol'] = 'File'

        if source.get(
                'Protocol') == 'Http' or source['SupportsDirectPlay'] and (
                    self.is_strm(source) or not settings('playFromStream.bool')
                    and self.is_file_exists(source)):

            LOG.info("--[ direct play ]")
            self.direct_play(source)

        elif source['SupportsDirectStream']:

            LOG.info("--[ direct stream ]")
            self.direct_url(source)

        else:
            LOG.info("--[ transcode ]")
            self.transcode(source, audio, subtitle)

        self.info['AudioStreamIndex'] = self.info.get(
            'AudioStreamIndex') or source.get('DefaultAudioStreamIndex')
        self.info['SubtitleStreamIndex'] = self.info.get(
            'SubtitleStreamIndex') or source.get('DefaultSubtitleStreamIndex')
        self.info['Item']['PlaybackInfo'].update(self.info)

        API = api.API(self.info['Item'], self.info['ServerAddress'])
        window('embyfilename',
               value=API.get_file_path(source.get('Path')).encode('utf-8'))
コード例 #28
0
ファイル: _common.py プロジェクト: rogerreeves/sualfreds-repo
    def _compare_checksum(self, items, compare_to):

        update_list = list()

        for item in items:

            if self.should_stop():
                break

            item_id = item['Id']

            if compare_to.get(item_id) != api.API(item).get_checksum():
                # Only update if item is not in Kodi or checksum is different
                update_list.append(item_id)

            compare_to.pop(item_id, None)

        return update_list
コード例 #29
0
ファイル: music.py プロジェクト: emlove/plugin.video.emby
    def updateUserdata(self, item):
        # This updates: Favorite, LastPlayedDate, Playcount, PlaybackPositionTicks
        # Poster with progress bar
        kodicursor = self.kodicursor
        emby_db = self.emby_db
        API = api.API(item)

        # Get emby information
        itemid = item['Id']
        checksum = API.get_checksum()
        userdata = API.get_userdata()
        rating = 0

        # Get Kodi information
        emby_dbitem = emby_db.getItem_byId(itemid)
        try:
            kodiid = emby_dbitem[0]
            mediatype = emby_dbitem[4]
            log.info("Update playstate for %s: %s", mediatype, item['Name'])
        except TypeError:
            return

        if mediatype == "song":

            #should we ignore this item ?
            #happens when userdata updated by ratings method
            if window("ignore-update-%s" % itemid):
                window("ignore-update-%s" % itemid, clear=True)
                return

            # Process playstates
            playcount = userdata['PlayCount']
            dateplayed = userdata['LastPlayedDate']

            #process item ratings
            rating, comment, hasEmbeddedCover = musicutils.getAdditionalSongTags(
                itemid, rating, API, kodicursor, emby_db,
                self.enableimportsongrating, self.enableexportsongrating,
                self.enableupdatesongrating)
            self.kodi_db.rate_song(playcount, dateplayed, rating, kodiid)

        emby_db.updateReference(itemid, checksum)
コード例 #30
0
ファイル: run.py プロジェクト: SeaLoong/xuetangx
async def main():
    global API, info, cookies
    for cks in cookies:
        if len(cks) == 0:
            continue
        try:
            API = api.API(cfg["headers"]["api"], cks)
            info = {"cookies": cks}
            print("================================================================================")
            if not (await get_user_info()):
                print("Invalid Cookies:", cks)
                print("================================================================================")
                await API.close()
                continue
            print("get_user_info:", info)
            print("================================================================================")
            await get_term()
            print("get_term:", info)
            print("================================================================================")
            await get_course()
            print("get_course:", info)
            print("================================================================================")
            for c in info["course_list"]:
                while True:
                    try:
                        print("================================================================================")
                        print(c)
                        await get_courseware(c)
                        print("get_courseware:", c)
                        print("================================================================================")
                        print("watch_course_video")
                        await watch_course_video(c)
                        print("================================================================================")
                        print("do_course_homework")
                        await do_course_homework(c)
                        print("================================================================================")
                        break
                    except Exception as e:
                        print("运行时出现异常,尝试重新完成该课程", e)
            await API.close()
        except Exception as e:
            print("运行时出现异常,将进行下一个Cookie的任务", cks, e)