Пример #1
0
def GetMovieDBData(url="", cache_days=14):
    from base64 import b64encode

    global base_url
    global poster_size
    global fanart_size
    if not base_url:
        log("fetching base_url and size (MovieDB config)")
        base_url = True
        base_url, poster_size, fanart_size = GetMovieDBConfig()
    filename = b64encode(url).replace("/", "XXXX")
    path = Addon_Data_Path + "/" + filename + ".txt"
    log("trying to load " + path)
    if xbmcvfs.exists(path) and ((time.time() - os.path.getmtime(path)) < (cache_days * 86400)):
        return read_from_file(path)
    else:
        url = "http://api.themoviedb.org/3/" + url + "api_key=%s" % moviedb_key
        log("Downloading MovieDB Data: " + url)
        headers = {"Accept": "application/json"}
        succeed = 0
        while succeed < 3:
            try:
                request = Request(url, headers=headers)
                response = urlopen(request).read()
                log("saved file " + filename)
                response = json.loads(response)
                save_to_file(response, filename, Addon_Data_Path)
                return response
            except:
                log("could not get data from %s" % url)
                xbmc.sleep(1000)
                succeed += 1
        return []
Пример #2
0
def GetDirectorMovies(Id):
    response = GetMovieDBData("person/%s/credits?language=%s&" % (Id, __addon__.getSetting("LanguageID")), 14)
    # return HandleTheMovieDBMovieResult(response["crew"]) + HandleTheMovieDBMovieResult(response["cast"])
    if "crew" in response:
        return HandleTheMovieDBMovieResult(response["crew"])
    else:
        log("No JSON Data available")
Пример #3
0
 def start (self, username, password):
     self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.soc.connect((self.server, self.port))
     log("client started")
     self.socthread = HellocConnection(self.soc, self.handle_message)
     self.login(username, password)
     self.get_friends()
Пример #4
0
    def _import_skinsettings( self ):
        import xbmcvfs
        # Set path
        self.backup_path = get_browse_dialog(dlg_type=1)
        # Check to see if file exists
        if xbmcvfs.exists( self.backup_path ):
            log("backup found")
            with open(self.backup_path) as f: fc = simplejson.load(f)
            progressDialog = xbmcgui.DialogProgress(__language__(32010))
            progressDialog.create(__language__(32010))
            xbmc.sleep(200)
            for count, skinsetting in enumerate(fc):
                if progressDialog.iscanceled():
                    return
                if skinsetting[1].startswith(xbmc.getSkinDir()):
                    progressDialog.update( (count * 100) / len(fc)  , __language__(32011) + ' %s' % skinsetting[1])
                    setting = skinsetting[1].replace(xbmc.getSkinDir() + ".","")
                    if skinsetting[0] == "string":
                        if skinsetting[2] <> "":
                            xbmc.executebuiltin( "Skin.SetString(%s,%s)" % (setting,skinsetting[2]) )
                        else:
                            xbmc.executebuiltin( "Skin.Reset(%s)" % setting )
                    elif skinsetting[0] == "bool":
                        if skinsetting[2] == "true":
                            xbmc.executebuiltin( "Skin.SetBool(%s)" % setting )
                        else:
                            xbmc.executebuiltin( "Skin.Reset(%s)" % setting )
                xbmc.sleep(30)
            xbmcgui.Dialog().ok(__language__(32005),__language__(32009))

        else:
            log("backup not found")
Пример #5
0
def GetSimiliarInLibrary(id):
    simi_artists = GetSimiliarById(id)
    if simi_artists == None:
         Notify('Last.fm didn\'t return proper response - check debug log for more details')
         return None
    
    xbmc_artists = GetXBMCArtists()
    artists = []
    
    start = time.clock()
    
    for (count, simi_artist) in enumerate(simi_artists):
        for (count, xbmc_artist) in enumerate(xbmc_artists):
            
            hit = False
            
            if xbmc_artist['mbid'] != '':
                #compare music brainz id
                if xbmc_artist['mbid'] == simi_artist['mbid']:
                    hit = True
            else:
                #compare names
                if xbmc_artist['name'] == simi_artist['name']:
                    hit = True
            
            if hit:
                xbmc_artist['thumb'] = GetThumbForArtistName(xbmc_artist['name'])
                artists.append(xbmc_artist)
    
    finish = time.clock()
            
    log('%i of %i artists found in last.FM is in XBMC database' % (len(artists), len(simi_artists)))
    Notify('Joining xbmc library and last.fm similiar artists', 'took %f seconds)' % (finish - start))
    
    return artists    
Пример #6
0
    def yourturn(self, data):
        data = self.strip_data(data)
        if isinstance(data, int):
            return

        player = self.find_player(data['user'])
        if not player:
            self.sendmsg('error', {'detail': "no such player"})
            return

        if not player.state == 'trick_before_play':
            log(player.state, l=2)
            return
        player.state = 'play_a_card'

        start_time = time.time()
        card = player.pick_a_card()
        end_time = time.time()
        all_time = float(end_time) - float(start_time)

        try:
            if all_time < 1 and not player.train:
                time.sleep(1 - all_time)
        except:
            if all_time < 1:
                time.sleep(1 - all_time)
        self.sendmsg('my_choice', {'user': player.name, 'card': card})
Пример #7
0
 def start(self, username, password):
     self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.soc.connect((self.server, self.port))
     log("client started")
     self.socthread = HellocConnection(self.soc, self.handle_message)
     self.login(username, password)
     self.get_friends()
Пример #8
0
 def close_family(self):
     name_list = copy.deepcopy(self.members)
     for rb in name_list:
         self.cancel_player()
     if len(self.members) == 0:
         self.sio.disconnect()
     log("disconnect from server")
Пример #9
0
def search_movie(medianame, year=''):
    log('TMDB API search criteria: Title['
        '%s'
        '] | Year['
        '%s'
        ']' % (medianame, year))
    medianame = urllib.quote_plus(medianame.encode('utf8', 'ignore'))
    response = GetMovieDBData(
        "search/movie?query=%s+%s&language=%s&" %
        (medianame, year, __addon__.getSetting("LanguageID")), 1)
    tmdb_id = ''
    try:
        if response == "Empty":
            tmdb_id = ''
        else:
            for item in response['results']:
                if item['id']:
                    tmdb_id = item['id']
                    log(tmdb_id)
                    break
    except Exception as e:
        log(e)
    if tmdb_id == '':
        log('TMDB API search found no ID')
    else:
        log('TMDB API search found ID: %s' % tmdb_id)
    return tmdb_id
Пример #10
0
def GetMovieDBData(url="", cache_days=14):
    from base64 import b64encode
    global base_url
    global poster_size
    global fanart_size
    if not base_url:
        log("fetching base_url and size (MovieDB config)")
        base_url = True
        base_url, poster_size, fanart_size = GetMovieDBConfig()
    filename = b64encode(url).replace("/", "XXXX")
    path = Addon_Data_Path + "/" + filename + ".txt"
    log("trying to load " + path)
    if xbmcvfs.exists(path) and ((time.time() - os.path.getmtime(path)) <
                                 (cache_days * 86400)):
        return read_from_file(path)
    else:
        url = "http://api.themoviedb.org/3/" + url + "api_key=%s" % moviedb_key
        log("Downloading MovieDB Data: " + url)
        headers = {"Accept": "application/json"}
        succeed = 0
        while succeed < 3:
            try:
                request = Request(url, headers=headers)
                response = urlopen(request).read()
                log("saved file " + filename)
                response = json.loads(response)
                save_to_file(response, filename, Addon_Data_Path)
                return response
            except:
                log("could not get data from %s" % url)
                xbmc.sleep(1000)
                succeed += 1
        return []
Пример #11
0
def GetMovieDBTVShows(type):
    response = GetMovieDBData(
        "tv/%s?language=%s&" % (type, __addon__.getSetting("LanguageID")), 2)
    if "results" in response:
        return HandleTheMovieDBTVShowResult(response["results"])
    else:
        log("No JSON Data available")
Пример #12
0
   def __init__( self ):
       log("version %s started" % __addonversion__ )
       self._init_vars()
       self._parse_argv()
       # run in backend if parameter was set
       if self.info:
           GetLastFMInfo()
       elif self.exportsettings:
           self._export_skinsettings()        
       elif self.importsettings:
           self._import_skinsettings()
       elif self.importextrathumb:
           self._AddArtToLibrary("extrathumb","Movie","extrathumbs",extrathumb_limit)
       elif self.importextrafanart:
           self._AddArtToLibrary("extrafanart","Movie","extrafanart",extrafanart_limit)
  #     elif self.importextrathumbtv:
 #          self._AddArtToLibrary("extrathumb","TVShow","extrathumbs")
       elif self.importextrafanarttv:
           self._AddArtToLibrary("extrafanart","TVShow","extrafanart",extrafanart_limit)
       elif self.backend and xbmc.getCondVisibility("IsEmpty(Window(home).Property(extendedinfo_backend_running))"):
           xbmc.executebuiltin('SetProperty(extendedinfo_backend_running,true,home)')
           self.run_backend()
       # only set new properties if artistid is not smaller than 0, e.g. -1
       elif self.artistid and self.artistid > -1:
           self._set_details(self.artistid)
       # else clear old properties
       elif not len(sys.argv) >1:
           self._selection_dialog()
Пример #13
0
def receive_message(connection):
    try:
        # Receive header
        message_header = connection.recv(
            const["HEADER_LENGTH"]).decode('utf-8').strip()

        # If no data was received, client closed the connection
        if message_header == "":
            # log(f"Empty header", "INFO")
            return None

        # Get message length from the received header
        message_length = int(message_header)

        # log(f"Valid header, expecting message length of {message_header} bytes...", "INFO")

        # Receive all data for whole message
        request = connection.recv(message_length).decode('utf-8').strip()

        # log(f"Request received! {str(request)}", "INFO")

        return request
    except Exception as e:
        log(f"Error while receiving data: {str(e)}", "ERROR")
        return False
Пример #14
0
def passHomeDataToSkin(data, debug = True):
    wnd = xbmcgui.Window(Window)
    if data != None:
        for (key,value) in data.iteritems():
            wnd.setProperty('%s' % (str(key)), unicode(value))
            if debug:
                log('%s' % (str(key)) + unicode(value))
Пример #15
0
def HandleTheMovieDBTVShowResult(results):
    tvshows = []
    log("starting HandleTheMovieDBTVShowResult")
    for tv in results:
        newtv = {
            'Art(fanart)':
            base_url + fanart_size + str(tv.get('backdrop_path', "")),
            'Art(poster)':
            base_url + poster_size + str(tv.get('poster_path', "")),
            'Title':
            tv.get('name', ""),
            'OriginalTitle':
            tv.get('original_name', ""),
            'ID':
            tv.get('id', ""),
            'Path':
            "",
            'Play':
            "",
            'DBID':
            "",
            'Rating':
            tv.get('vote_average', ""),
            'Votes':
            tv.get('vote_count', ""),
            'Premiered':
            tv.get('first_air_date', "")
        }
        if not str(tv['id']) in str(tvshows):  # too dirty
            tvshows.append(newtv)
    tvshows = CompareWithLibrary(tvshows)
    return tvshows
Пример #16
0
 def strip_data(self, data):
     try:
         data = json.loads(data)
     except:
         log("parse data error: %s" % (data), l=2)
         self.sendmsg('error', {'detail': 'json.load(data) error'})
         return 1
     return data
Пример #17
0
 def onClientAccepeted(self, client_soc, client_addr):
     log("Server clientAccepted", client_soc)
     client_port = ClientPort(client_soc, \
         logout_listener = self.client_logout)
     self.client_ports.append(client_port)
     socthread = HellocConnection(client_soc, client_port.handle_message, \
         soc_closed=client_port.handle_soc_closed)
     client_port.set_socthread(socthread)
Пример #18
0
def GetSetMovies(Id):
    response = GetMovieDBData(
        "collection/%s?language=%s&" %
        (Id, __addon__.getSetting("LanguageID")), 14)
    if "parts" in response:
        return HandleTheMovieDBMovieResult(response["parts"])
    else:
        log("No JSON Data available")
Пример #19
0
def GetEvents(id): # converted to api 2.0
    url = 'http://api.bandsintown.com/artists/mbid_%s/events.json?api_version=2.0&app_id=%s' % (id, bandsintown_apikey)
    try:
        response = GetStringFromUrl(url)
        results = json.loads(response)
    except:
        log("Error when finding artist-related events from" + url)
    return HandleResult(results)
Пример #20
0
 def onClientAccepeted(self, client_soc, client_addr):
     log("Server clientAccepted", client_soc)
     client_port = ClientPort(client_soc, \
         logout_listener = self.client_logout)
     self.client_ports.append(client_port)
     socthread = HellocConnection(client_soc, client_port.handle_message, \
         soc_closed=client_port.handle_soc_closed)
     client_port.set_socthread(socthread)
Пример #21
0
def GetDirectorMovies(Id):
    response = GetMovieDBData(
        "person/%s/credits?language=%s&" %
        (Id, __addon__.getSetting("LanguageID")), 14)
    # return HandleTheMovieDBMovieResult(response["crew"]) + HandleTheMovieDBMovieResult(response["cast"])
    if "crew" in response:
        return HandleTheMovieDBMovieResult(response["crew"])
    else:
        log("No JSON Data available")
Пример #22
0
def GetSimilarMovies(Id):
    response = GetMovieDBData(
        "movie/%s?append_to_response=trailers,casts,releases,keywords,similar_movies,lists&language=%s&"
        % (Id, __addon__.getSetting("LanguageID")), 30)
    if "similar_movies" in response:
        return HandleTheMovieDBMovieResult(
            response["similar_movies"]["results"])
    else:
        log("No JSON Data available")
Пример #23
0
def test_da():
    global print_level
    print_level = 2
    g0 = MrGreed(room=0, place=0, name="if0")
    g0.cards_list = ['H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'HJ', 'D9', 'DA']
    g0.history = [(2, 'D3', 'D4', 'DJ', 'D6'), (1, 'S2', 'S3', 'S4', 'S5')]
    g0.cards_on_table = [2, 'D7', 'D8']
    g0.scores = [[], [], [], ['DJ']]
    log(g0.pick_a_card())
Пример #24
0
def test_3rd():
    g0 = MrGreed(room=0, place=0, name="if0")
    g0.history = [(0, 'C2', 'C3', 'C4', 'C5'), (3, 'C6', 'C7', 'D2', 'C8'), (2, 'D3', 'D4', 'D5', 'D6'),
                  (1, 'S2', 'S3', 'S4', 'S5')]
    g0.cards_list = ['H6', 'H7', 'HJ', 'HA', 'SQ', 'DJ', 'DK']
    g0.cards_on_table = [2, 'H8', 'HQ']
    # g0.cards_on_table=[2,'CA','CJ']
    log(g0.cards_list)
    log(g0.pick_a_card())
Пример #25
0
def GetPersonID(person):
    Persons = person.split(" / ")
    person = Persons[0]
    response = GetMovieDBData("search/person?query=%s&" % urllib.quote_plus(person),30)
    try:
        return response["results"][0]["id"]
    except:
        log("could not find Person ID")
        return ""
Пример #26
0
 def get_loc(self,name):
     if not name:
         log("empty name is illegal")
         return -1
     try:
         return self.players.index(name)
     except:
         log('no such player')
         return -1
Пример #27
0
 def pick_a_card(self,suit=None):
     suit=self.decide_suit()
     log("%s, %s, %s, %s"%(self.name,suit,self.cards_on_table,self.cards_list))
     while True:
         choice=input("your turn: ")
         if choice in self.cards_list:
             break
         else:
             log("%s is not your cards. "%(choice),end="")
     return choice
Пример #28
0
def GetPersonID(person):
    Persons = person.split(" / ")
    person = Persons[0]
    response = GetMovieDBData(
        "search/person?query=%s&" % urllib.quote_plus(person), 30)
    try:
        return response["results"][0]["id"]
    except:
        log("could not find Person ID")
        return ""
Пример #29
0
 def jr_function(self, name, args):  # Parse a function call
     log(self.verbose,
         "calling function " + name + " with arguments " + str(args))
     code = self.getcode(name, args)
     if code[0].startswith("jiro.lang"):
         Utils.call_native(name, args)
     elif code[0].startswith("jiro.extension"):
         code[3](Utils.create_dict(self.get_args(name, args), args))
     else:
         self.parse_func(self.getfunction(name, args), False,
                         self.get_args(name, args), args)
Пример #30
0
 def close_room(self,roomid):
     thisroom = self.rooms[roomid]
     for pl in thisroom.players_info:
         if thisroom.players_info[pl].is_robot:
             rb_type = self.user_state_dict[pl].robot_type
             self.sendmsg('cancel_player', {'user': pl}, sid=self.robot_dict[rb_type])
             self.send_player_info(roomid)
         else:
             log('user was removed')
             return False
     return True
Пример #31
0
def GetNearEvents():
    settings = xbmcaddon.Addon(id='script.ExtraMusicInfo')
    country = 'Poland' #settings.getSetting('country')
    city = 'Wroclaw' #settings.getSetting('city')
    url = 'http://api.bandsintown.com/events/search?format=json&location=use_geoip&app_id=%s' % (bandsintown_apikey)
    
    log('request: %s' % url)
    
    response = GetStringFromUrl(url)
    results = json.loads(response)
    
    return HandleResult(results)
Пример #32
0
 def _create_musicvideo_list( self ):
     json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMusicVideos", "params": {"properties": ["artist", "file"], "sort": { "method": "artist" } }, "id": 1}')
     json_query = unicode(json_query, 'utf-8', errors='ignore')
     json_response = simplejson.loads(json_query)
     if (json_response['result'] != None) and (json_response['result'].has_key('musicvideos')):
         # iterate through the results
         for item in json_response['result']['musicvideos']:
             artist = item['artist']
             title = item['label']
             path = item['file']
             self.musicvideos.append((artist,title,path))
     log('musicvideos: %s' % self.musicvideos)
Пример #33
0
def GetMovieKeywords(Id):
    response = GetMovieDBData("movie/%s?append_to_response=trailers,casts,releases,keywords,similar_movies,lists&language=%s&" % (Id, __addon__.getSetting("LanguageID")),30)
    keywords = []
    if True:
        for keyword in response["keywords"]["keywords"]:
            newkeyword = {'id': keyword.get('id',""),
                        'name': keyword['name']}
            log(newkeyword)
            keywords.append(newkeyword)
    else:
        pass
    return keywords
Пример #34
0
def GetXKCDInfo():
    settings = xbmcaddon.Addon(id='script.extendedinfo')
    for i in range(0,10):
        try:
            url = 'http://xkcd.com/%i/info.0.json' % random.randrange(1, 1190)
            response = GetStringFromUrl(url)
            results = simplejson.loads(response)
            wnd = xbmcgui.Window(Window)
            wnd.setProperty('XKCD.%i.Image' % i, results["img"])
            wnd.setProperty('XKCD.%i.Title' % i, results["title"])
            wnd.setProperty('XKCD.%i.Description' % i, results["alt"])
        except:
            log("Error when setting XKCD info")
Пример #35
0
def SearchforCompany(Company):
  #  Companies = Company.split(" / ")
   # Company = Companies[0]
    import re
    regex = re.compile('\(.+?\)')
    Company = regex.sub('', Company)
    log(Company)
    response = GetMovieDBData("search/company?query=%s&" % urllib.quote_plus(Company),30)
    try:
        return response["results"][0]["id"]
    except:
        log("could not find Company ID")
        return ""
Пример #36
0
def passDataToSkin(prefix, data):
    #use window properties
    wnd = xbmcgui.Window(Window)

    if data != None:
        wnd.setProperty('%s.Count' % prefix, str(len(data)))
        log( "%s.Count = %s" % (prefix, str(len(data)) ) )
        for (count, result) in enumerate(data):
            log( "%s.%i = %s" % (prefix, count + 1, str(result) ) )
            for (key,value) in result.iteritems():
                wnd.setProperty('%s.%i.%s' % (prefix, count + 1, str(key)), unicode(value))
    else:
        wnd.setProperty('%s.Count' % prefix, '0')
Пример #37
0
def GetMovieKeywords(Id):
    response = GetMovieDBData(
        "movie/%s?append_to_response=trailers,casts,releases,keywords,similar_movies,lists&language=%s&"
        % (Id, __addon__.getSetting("LanguageID")), 30)
    keywords = []
    if "keywords" in response:
        for keyword in response["keywords"]["keywords"]:
            newkeyword = {'id': keyword.get('id', ""), 'name': keyword['name']}
            keywords.append(newkeyword)
        return keywords
    else:
        log("No Keywords in JSON answer")
        return []
Пример #38
0
def GetNearEvents(): # not possible with api 2.0
    settings = xbmcaddon.Addon(id='script.extendedinfo')
    country = 'Poland' #settings.getSetting('country')
    city = 'Wroclaw' #settings.getSetting('city')
    url = 'http://api.bandsintown.com/events/search?format=json&location=use_geoip&api_version=2.0&app_id=%s' % (bandsintown_apikey)
    log('request: %s' % url)
    try:
        response = GetStringFromUrl(url)
        results = json.loads(response)
    except:
        results = []
        log("error getting concert data from " + url)
    return HandleResult(results)
Пример #39
0
def GetXBMCArtists():
    json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetArtists", "params": {"properties": ["musicbrainzartistid", "thumbnail"]}, "id": 1}')
    json_query = unicode(json_query, 'utf-8', errors='ignore')
    log(json_query)
    json_query = simplejson.loads(json_query)
    artists = []        
    if json_query.has_key('result') and json_query['result'].has_key('artists'):
        count = 0
        for item in json_query['result']['artists']:
            mbid = ''
            artist = {"name": item['label'], "xbmc_id": item['artistid'], "mbid": item['musicbrainzartistid'] , "thumb": item['thumbnail'] }
            artists.append(artist)
    return artists
Пример #40
0
def HandleTheMovieDBCompanyResult(results):
    companies = []
    log("starting HandleLastFMCompanyResult")
    for company in results:
        newcompany = {'parent_company': company['parent_company'],
                      'name': company['name'],
                      'description': company['description'],
                      'headquarters': company['headquarters'],
                      'homepage': company['homepage'],
                      'id': company['id'],
                      'logo_path': company['logo_path']}
        companies.append(newcompany)
    return companies
Пример #41
0
def passDataToSkin(prefix, data):
    #use window properties
    wnd = xbmcgui.Window(Window)

    if data != None:
        wnd.setProperty('%s.Count' % prefix, str(len(data)))
        log("%s.Count = %s" % (prefix, str(len(data))))
        for (count, result) in enumerate(data):
            log("%s.%i = %s" % (prefix, count + 1, str(result)))
            for (key, value) in result.iteritems():
                wnd.setProperty('%s.%i.%s' % (prefix, count + 1, str(key)),
                                unicode(value))
    else:
        wnd.setProperty('%s.Count' % prefix, '0')
Пример #42
0
def GetFlickrImages():
    results=[]
    try:
        url = 'http://pipes.yahoo.com/pipes/pipe.run?_id=241a9dca1f655c6fa0616ad98288a5b2&_render=json'
        response = GetStringFromUrl(url)
        results = simplejson.loads(response)
    except:
        log("Error when fetching Flickr data from net")
    count = 1
    if results:
        wnd = xbmcgui.Window(Window)
        for item in results["value"]["items"]:
            wnd.setProperty('Flickr.%i.Background' % count, item["link"])
            count += 1
Пример #43
0
def GetSimilarById(m_id):
    url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&mbid=%s&api_key=%s' % (m_id, lastfm_apikey)
    try:
        ret = GetStringFromUrl(url)
        curXML = xml.dom.minidom.parseString(ret)
        curXMLs = curXML.getElementsByTagName('lfm')
    except:
        log("error when getting info from LastFM")
        return None
    if len(curXMLs) > 0:
        curXML = curXMLs[0]
    else:
        log('No <lfm> found - printing retrieved xml:')
        print ret
        return None    
    curXMLs = curXML.getElementsByTagName('similarartists')
    if len(curXMLs) > 0:
        curXML = curXMLs[0]
    else:
        log('No <similarartists> found - printing retrieved xml:')
        print ret
        return None        
    artistXMLs = curXML.getElementsByTagName('artist')
    similars = []
    for artistXML in artistXMLs:
        artist = {"name": GetValue(artistXML, 'name'), "mbid": GetValue(artistXML, 'mbid')}
        similars.append(artist)
    log('Found %i Similar artists in last.FM' % len(similars))
    return similars
Пример #44
0
def start_server():
    """
    Creates a socket that listens for multiple connections and starts a thread
    that waits for data, then the messages, and displays it.
    """
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    log("Socket created")

    try:
        soc.bind((const["HOSTNAME"], const["LISTEN_PORT"]))
    except:
        log(f"Bind failed. {str(sys.exc_info())}", "ERROR")
        sys.exit(-1)

    soc.listen(
        const["MAX_CONNECTIONS"])  # queue up to MAX_CONNECTIONS requests
    log("Socket now listening")

    # infinite loop - open a new thread for every incoming request
    while True:
        connection, address = soc.accept()
        ip, port = str(address[0]), str(address[1])
        try:
            Thread(target=client_thread, args=(connection, ip, port)).start()
        except:
            log(f"Thread did not start. {traceback.print_exc()}", "ERROR")

    soc.close()
Пример #45
0
    def leave_room(self,name):
        if self.room_state == 'started':
            log('game started')
            return False
        if name not in self.players:
            log('no such player')
            return False

        id = self.players.index(name)
        self.players[id] = ''
        self.players_info.pop(name)
        if self.room_state == 'full':
            self.room_state = 'available'
        return True
Пример #46
0
def SearchforCompany(Company):
    #  Companies = Company.split(" / ")
    # Company = Companies[0]
    import re
    regex = re.compile('\(.+?\)')
    Company = regex.sub('', Company)
    log(Company)
    response = GetMovieDBData(
        "search/company?query=%s&" % urllib.quote_plus(Company), 30)
    try:
        return response["results"][0]["id"]
    except:
        log("could not find Company ID")
        return ""
Пример #47
0
    def play_a_card(self,name,card):
        #return 0 is success
        #check legel
        try:
            usr_loc = self.players.index(name)
        except:
            log('no such player')
            return 1
        if usr_loc != self.now_player:
            return 'error', {'detail': 'not your turn'}

        if card == 'timeout':
            cdlist = self.players_info[name].cards_list
            if usr_loc == self.trick_start:
                card = random.choice(cdlist)
            else:
                lglist = [i for i in cdlist if i[0] == self.cards_on_table[1][0]]
                if not len(lglist):
                    # the first player
                    card = random.choice(cdlist)
                else:
                    card = random.choice(lglist)

        if card not in self.players_info[name].cards_list:
            return 'error', {'detail': 'not your card'}

        if usr_loc == self.trick_start:
            # the first player
            pass
        elif card[0] == self.cards_on_table[1][0]:
            # the same color
            pass
        elif all([not i[0] == self.cards_on_table[1][0] for i in self.players_info[name].cards_list]):
            # do not have this color
            pass
        else:
            return 'my_choice_reply',{'legal':False,'your_remain':self.players_info[name].cards_list}

        #play a card
        cardid = self.players_info[name].cards_list.index(card)
        self.players_info[name].cards_list.pop(cardid)
        self.cards_on_table.append(card)
        self.now_player += 1
        self.now_player %= self.gamemode

        if self.now_player == self.trick_start:
            self.trick_end = True

        return 'my_choice_reply',{'legal':True,'your_remain':self.players_info[name].cards_list}
Пример #48
0
def GetMusicBrainzIdFromNet(artist, xbmc_artist_id = -1):
    url = 'http://musicbrainz.org/ws/1/artist/?type=xml&name=%s' % urllib.quote_plus(artist)
    
    tries = 0
    trylimit = 5
    gotit = False
    while tries < trylimit and not gotit:
        ret = GetStringFromUrl(url)
        
        if 'requests are exceeding the allowable rate limit' in ret:
            log('MusicBrainz limits amount of request per time - we must wait')
            time.sleep(1)
            tries = tries + 1
        else:
            gotit = True
    
    if not gotit:
        return -1
    
    curXML = xml.dom.minidom.parseString(ret)
    
    curXMLs = curXML.getElementsByTagName('metadata')
    if len(curXMLs) > 0:
        curXML = curXMLs[0]
    else:
        return None
    
    curXMLs = curXML.getElementsByTagName('artist-list')
    if len(curXMLs) > 0:
        curXML = curXMLs[0]
    else:
        return None
    
    curXMLs = curXML.getElementsByTagName('artist')
    if len(curXMLs) > 0:
        curXML = curXMLs[0]
    else:
        return None
    
    artistName = GetValue(curXML, 'name') 
    artistMusicBrainzId = curXML.getAttribute('id')
    
    log('Found MusicBrainz ID')
    
    if xbmc_artist_id != -1:
        SetMusicBrainzID(xbmc_artist_id, artistMusicBrainzId)
    
    
    return artistMusicBrainzId
Пример #49
0
def GetMusicBrainzIdFromNet(artist, xbmc_artist_id=-1):
    url = 'http://musicbrainz.org/ws/1/artist/?type=xml&name=%s' % urllib.quote_plus(
        artist)

    tries = 0
    trylimit = 5
    gotit = False
    while tries < trylimit and not gotit:
        ret = GetStringFromUrl(url)

        if 'requests are exceeding the allowable rate limit' in ret:
            log('MusicBrainz limits amount of request per time - we must wait')
            time.sleep(1)
            tries = tries + 1
        else:
            gotit = True

    if not gotit:
        return -1

    curXML = xml.dom.minidom.parseString(ret)

    curXMLs = curXML.getElementsByTagName('metadata')
    if len(curXMLs) > 0:
        curXML = curXMLs[0]
    else:
        return None

    curXMLs = curXML.getElementsByTagName('artist-list')
    if len(curXMLs) > 0:
        curXML = curXMLs[0]
    else:
        return None

    curXMLs = curXML.getElementsByTagName('artist')
    if len(curXMLs) > 0:
        curXML = curXMLs[0]
    else:
        return None

    artistName = GetValue(curXML, 'name')
    artistMusicBrainzId = curXML.getAttribute('id')

    log('Found MusicBrainz ID')

    if xbmc_artist_id != -1:
        SetMusicBrainzID(xbmc_artist_id, artistMusicBrainzId)

    return artistMusicBrainzId
Пример #50
0
def GetLastFMInfo():
    for arg in sys.argv:
        if arg == 'script.extendedinfo':
            continue
        param = arg.lower()
        if param.startswith('info='):
            infos.append(param[5:])
        elif param.startswith('artistname='):
            ArtistName = arg[11:]
            # todo: look up local mbid first -->xbmcid for parameter
            Artist_mbid = GetMusicBrainzIdFromNet(ArtistName)
        elif param.startswith('albumname='):
            AlbumName = arg[10:]
        elif param.startswith('tracktitle='):
            TrackTitle = arg[11:]
        elif param.startswith('window='):
            Window = int(arg[7:])
        elif param.startswith('settuplocation'):
            settings = xbmcaddon.Addon(id='script.extendedinfo')
            country = settings.getSetting('country')
            city = settings.getSetting('city')
            log('stored country/city: %s/%s' % (country, city) )  
            kb = xbmc.Keyboard('', 'Country:')
            kb.doModal()
            country = kb.getText()
            kb = xbmc.Keyboard('', 'City:')
            kb.doModal()
            city = kb.getText()
            log('country/city: %s/%s' % (country, city) )         
            settings.setSetting('location_method', 'country_city')
            settings.setSetting('country',country)
            settings.setSetting('city',city)
            log('done with settings')
        else:
            AdditionalParams.append(param)
    passDataToSkin('SimilarArtists', None)
    passDataToSkin('MusicEvents', None)

    for info in infos:
        if info == 'xkcd':
            log("startin GetXKCDInfo")
            GetXKCDInfo()              
        elif info == 'similarartistsinlibrary':
            artists = GetSimilarInLibrary(Artist_mbid)
            passDataToSkin('SimilarArtistsInLibrary', artists)
        elif info == 'artistevents':
            events = GetEvents(Artist_mbid)
            passDataToSkin('ArtistEvents', events)       
        elif info == 'nearevents':
            events = GetNearEvents()
            passDataToSkin('NearEvents', events)        
        elif info == 'topartistsnearevents':
            artists = GetXBMCArtists()
            events = GetArtistNearEvents(artists[0:15])
            passDataToSkin('TopArtistsNearEvents', events)
        elif info == 'updatexbmcdatabasewithartistmbidbg':
            SetMusicBrainzIDsForAllArtists(False, 'forceupdate' in AdditionalParams)
        elif info == 'updatexbmcdatabasewithartistmbid':
            SetMusicBrainzIDsForAllArtists(True, 'forceupdate' in AdditionalParams)
Пример #51
0
def HandleTheMovieDBCompanyResult(results):
    companies = []
    log("starting HandleLastFMCompanyResult")
    for company in results:
        newcompany = {
            "parent_company": company["parent_company"],
            "name": company["name"],
            "description": company["description"],
            "headquarters": company["headquarters"],
            "homepage": company["homepage"],
            "id": company["id"],
            "logo_path": company["logo_path"],
        }
        companies.append(newcompany)
    return companies
Пример #52
0
def HandleTheMovieDBCompanyResult(results):
    companies = []
    log("starting HandleLastFMCompanyResult")
    for company in results:
        newcompany = {
            'parent_company': company['parent_company'],
            'name': company['name'],
            'description': company['description'],
            'headquarters': company['headquarters'],
            'homepage': company['homepage'],
            'id': company['id'],
            'logo_path': company['logo_path']
        }
        companies.append(newcompany)
    return companies
Пример #53
0
def GetArtistNearEvents(Artists): # not possible with api 2.0
    settings = xbmcaddon.Addon(id='script.extendedinfo')
    ArtistStr = ''
    for art in Artists:
        if len(ArtistStr) > 0:
             ArtistStr = ArtistStr + '&'
        ArtistStr = ArtistStr + 'artists[]=' + urllib.quote(art['name'])     
    url = 'http://api.bandsintown.com/events/search?%sformat=json&location=use_geoip&api_version=2.0&app_id=%s' % (ArtistStr, bandsintown_apikey)
    log('request: %s' % url)
    try:
        response = GetStringFromUrl(url)
        results = json.loads(response)
    except:
        log("error when getting artist data from " + url)
    return HandleResult(results)
Пример #54
0
    def error(self, data):
        data = self.strip_data(data)
        if isinstance(data, int):
            return

        if 'user' in data:
            player = self.find_player(data['user'])
            if not player:
                self.sendmsg('error', {'detail': "no such player"})
                return

            log('%s:%s' % (data['user'], data['detail']), l=1)

        else:
            log(data['detail'], l=1)
Пример #55
0
 def __init__( self ):
     log("version %s started" % __addonversion__ )
     self._init_vars()
     self._parse_argv()
     # run in backend if parameter was set
     if self.info:
         GetLastFMInfo()
     elif self.backend and xbmc.getCondVisibility("IsEmpty(Window(home).Property(extendedinfo_backend_running))"):
         xbmc.executebuiltin('SetProperty(extendedinfo_backend_running,true,home)')
         self.run_backend()
     # only set new properties if artistid is not smaller than 0, e.g. -1
     elif self.artistid and self.artistid > -1:
         self._set_details(self.artistid)
     # else clear old properties
     else:
         self._clear_properties()
Пример #56
0
 def _save_to_file( self, content, suffix, path = "" ):
     try:
         if path == "":
             text_file_path = get_browse_dialog() + xbmc.getSkinDir() +"." + suffix + ".txt"
         else:
             if not xbmcvfs.exists(path):
                 xbmcvfs.mkdir(path)
             text_file_path = path + xbmc.getSkinDir() +"." + suffix + ".txt"
         log("text_file_path:")
         log(text_file_path)
         text_file =  open(text_file_path, "w")
         simplejson.dump(content,text_file)
         text_file.close()
         return True
     except Exception:
         sys.exc_clear()
         return False
Пример #57
0
def HandleTheMovieDBPeopleResult(results):
    people = []
    if True:
        for person in results:
            newperson = {'adult': person['adult'],
                        'name': person['name'],
                        'also_known_as': person['also_known_as'],
                        'biography': person['biography'],
                        'birthday': person['birthday'],
                        'id': person['id'],
                        'deathday': person['deathday'],
                        'place_of_birth': person['place_of_birth'],
                        'thumb': person['profile_path']  }
            people.append(newperson)
    else:
        log("Error when handling TheMovieDB people results")
    return people
Пример #58
0
def GetCandHInfo():
    for i in range(1,10):
        try:
            url = 'http://www.explosm.net/comics/%i/' % random.randrange(1, 3128)
            response = GetStringFromUrl(url)
        except:
            log("Error when fetching CandH data from net")
        count = 1
        if response:
            log(response)
            wnd = xbmcgui.Window(Window)
            regex = ur'src="([^"]+)"'
            matches = re.findall(regex, response)
            if matches:
                for item in matches:
                    if item.startswith('http://www.explosm.net/db/files/Comics/'):
                        wnd.setProperty('CyanideHappiness.%i.Image' % i, item)     
Пример #59
0
 def _detail_selector( self, comparator):
     self.selecteditem = xbmc.getInfoLabel("ListItem.Label")
     if (self.selecteditem != self.previousitem):
         if xbmc.getCondVisibility("!Stringcompare(ListItem.Label,..)"):
             self.previousitem = self.selecteditem
             self._clear_properties()
             count = 1
             for movie in self.movies["result"]["movies"]:
                 log(comparator)
                 if self.selecteditem in str(movie[comparator]):
                     log(movie)
                     self._set_detail_properties(movie,count)
                     count +=1
                 if count > 19:
                     break
         else:
             self._clear_properties()