class RestfulAPI(object):
    def __init__(self, ip, port):
        self.__server = HttpClient()
        self.__url = "http://%s:%s"%(ip, port)
        self.JSON = JSONDecoder()
    def __createUrl(self, service):
        return self.__url + "/" + service
    
    def isCutterActive(self):
        data = self.__server.GET(self.__createUrl("recordings/cut.json"))
        json = self.JSON.decode(data)
        return json["active"]
    
    def getRecordings(self):
        data = self.__server.GET(self.__createUrl("recordings.json?marks=true"))
        json = self.JSON.decode(data)
        recs = []
        for recdata in json["recordings"]:
            recs.append(VDRRecording(recdata["number"], recdata["name"], recdata["file_name"], recdata["relative_file_name"], recdata["duration"]))
        return recs
    
    def cutRecording(self, recordingnumber):
        service = self.__createUrl("recordings/cut/" + str(recordingnumber))
        return self.__server.POST(service, ' ')
    
    def getMarks(self, recordingnumber):
        data = self.__server.GET(self.__createUrl("recordings/"+str(recordingnumber)+".json?marks=true"))
        json = self.JSON.decode(data)
        marks = []
        for mark in json["recordings"][0]["marks"]:
            marks.append(VDRMark(mark))
        return marks
    
    def saveMarks(self, recordingnumber, marks):
        url = self.__createUrl("recordings/marks/" + str(recordingnumber))
        json = self.__serializeMarks(marks)
        self.__server.POST(url, json)
    
    def deleteMarks(self, recordingnumber):
        self.__server.DELETE(self.__createUrl("recordings/marks/" + str(recordingnumber)))
    
    def refreshRecording(self, recording):
        if type(recording) == VDRRecording:
            recs = self.getRecordings()
            for rec in recs:
                if rec.FileName == recording.FileName:
                    recording.RecordingId = rec.RecordingId
        
    def __serializeMarks(self, marks):
        json = "{'marks':["
        counter = 0
        for mark in marks:
            if type(mark) is VDRMark:
                json += "'" + mark.toString() +"'"
                if len(marks)-1 != counter:
                    json += ", "
            counter += 1 
        json += "]}"
        print json
        return json
Пример #2
0
	def query(self, argument):
		decoder = JSONDecoder()
		argument = utility.escape(argument)
		api_url = u"http://www.imdbapi.com/?t=%(search_term)s&r=json&plot=short" % \
				{"search_term": argument}
		site_search_url = u"http://akas.imdb.com/find?s=all&q=" + argument
		response = utility.read_url(api_url)

		if not response:
			return u"Couldn't connect to the API :( | Manual search: " + site_search_url

		try:
			data = decoder.decode(response['data'])
		except Exception:
			return u"Couldn't parse the API output :( | Manual search: " + site_search_url
		
		if data.get(u"Response") != u"True":
			return u"No results found! Maybe you should try searching manually: " + \
					site_search_url

		return \
				(u"%(title)s (%(year)s) - Rating: %(rating)s out of 10 - Genre: %(genre)s - " + \
				u"http://akas.imdb.com/title/%(id)s/ | More results: %(site_search_url)s") % \
				{u"title": data.get(u"Title", u"Missing title :S"),
					u"year": data.get(u"Year", u"Unknown year"),
					u"rating": data.get(u"Rating", u"N/A"),
					u"genre": data.get(u"Genre", u"Unknown"),
					u"id": data.get(u"ID", u"tt0107838"),
					u"site_search_url": site_search_url}
Пример #3
0
 def decode(self, s, *args, **kwargs):
     o = JSONDecoder.decode(self, s, *args, **kwargs)
     return schema_resolve_refs(
         o,
         partial(self.client.instance,
                 cls=JSONSchemaReference,
                 client=self.client))
Пример #4
0
    def query(self, argument):
        decoder = JSONDecoder()
        argument = utility.escape(argument)
        api_url = u"http://www.imdbapi.com/?t=%(search_term)s&r=json&plot=short" % \
          {"search_term": argument}
        site_search_url = u"http://akas.imdb.com/find?s=all&q=" + argument
        response = utility.read_url(api_url)

        if not response:
            return u"Couldn't connect to the API :( | Manual search: " + site_search_url

        try:
            data = decoder.decode(response['data'])
        except Exception:
            return u"Couldn't parse the API output :( | Manual search: " + site_search_url

        if data.get(u"Response") != u"True":
            return u"No results found! Maybe you should try searching manually: " + \
              site_search_url

        return \
          (u"%(title)s (%(year)s) - Rating: %(rating)s out of 10 - Genre: %(genre)s - " + \
          u"http://akas.imdb.com/title/%(id)s/ | More results: %(site_search_url)s") % \
          {u"title": data.get(u"Title", u"Missing title :S"),
           u"year": data.get(u"Year", u"Unknown year"),
           u"rating": data.get(u"Rating", u"N/A"),
           u"genre": data.get(u"Genre", u"Unknown"),
           u"id": data.get(u"ID", u"tt0107838"),
           u"site_search_url": site_search_url}
Пример #5
0
 def decode(self, s, *args, **kwargs):
     o = JSONDecoder.decode(self, s, *args, **kwargs)
     return self._decode(o)
Пример #6
0
    def lookup_direct(self, reference):
        decoder = JSONDecoder()
        api_url = self.api_base_url + u"lookup/1/.json?uri=" + reference.URI()
        response = utility.read_url(api_url)

        if not response:
            return None

        try:
            data = decoder.decode(response['data'])
        except StandardError:
            return None

        if not data.get(u"info"):
            return None

        # Album reference
        if reference.type == u"album":
            metadata = data.get(u"album", {})
            album = metadata.get(u"name", u"Unknown album")
            artist = metadata.get(u"artist", u"Unknown artist")
            year = metadata.get(u"released", u"Unknown year")
            return u"%s: %s (%s)" % (artist, album, year)

        # Artist reference
        elif reference.type == u"artist":
            metadata = data.get(u"artist", {})
            artist = metadata.get(u"name", u"Unknown artist")
            return u"%s" % artist

        # Track reference
        elif reference.type == u"track":

            # Extract some dicts from the data
            metadata = data.get(u"track", {})
            metadata_album = metadata.get(u"album", {})
            metadata_artists = metadata.get(u"artists", [{}])

            # Extract info from the dicts
            album = metadata_album.get(u"name", u"Unknown album")
            artists = map(
                lambda artist: artist.get(u"name", u"Unknown artist"),
                metadata_artists)
            artist = ", ".join(artists)
            duration = metadata.get(u"length", u"0.0")
            popularity = metadata.get(u"popularity", u"0.0")
            track = metadata.get(u"name", u"Unknown track")
            year = metadata_album.get(u"released", u"Unknown year")

            # Convert strings to floats
            try:
                duration = float(duration)
            except ValueError:
                duration = 0.0
            try:
                popularity = float(popularity)
            except ValueError:
                popularity = 0.0

            # Construct result
            return u"%s: %s | %s (%s) | Track popularity %d%%, Track duration %d:%02d" % \
              (artist, track, album, year, int(round(popularity*100)), duration / 60, duration % 60)

        # Unsupported reference
        else:
            return None
Пример #7
0
 def decode(self, s, *args, **kwargs):
     o = JSONDecoder.decode(self, s, *args, **kwargs)
     return schema_resolve_refs(o, partial(self.client.instance,
                                           cls=JSONSchemaReference,
                                           client=self.client))
Пример #8
0
 def decode(self, s, *args, **kwargs):
     o = JSONDecoder.decode(self, s, *args, **kwargs)
     return self._decode(o)
Пример #9
0
	def lookup_direct(self, reference):
		decoder = JSONDecoder()
		api_url = self.api_base_url + u"lookup/1/.json?uri=" + reference.URI()
		response = utility.read_url(api_url)

		if not response:
			return None

		try:
			data = decoder.decode(response['data'])
		except StandardError:
			return None

		if not data.get(u"info"):
			return None

		# Album reference
		if reference.type == u"album":
			metadata = data.get(u"album", {})
			album = metadata.get(u"name", u"Unknown album")
			artist = metadata.get(u"artist", u"Unknown artist")
			year = metadata.get(u"released", u"Unknown year")
			return u"%s: %s (%s)" % (artist, album, year)

		# Artist reference
		elif reference.type == u"artist":
			metadata = data.get(u"artist", {})
			artist = metadata.get(u"name", u"Unknown artist")
			return u"%s" % artist

		# Track reference
		elif reference.type == u"track":
			
			# Extract some dicts from the data
			metadata = data.get(u"track", {})
			metadata_album = metadata.get(u"album", {})
			metadata_artists = metadata.get(u"artists", [{}])

			# Extract info from the dicts
			album = metadata_album.get(u"name", u"Unknown album")
			artists = map(lambda artist: artist.get(u"name", u"Unknown artist"), metadata_artists)
			artist = ", ".join(artists)
			duration = metadata.get(u"length", u"0.0")
			popularity = metadata.get(u"popularity", u"0.0")
			track = metadata.get(u"name", u"Unknown track")
			year = metadata_album.get(u"released", u"Unknown year")

			# Convert strings to floats
			try:
				duration = float(duration)
			except ValueError:
				duration = 0.0;
			try:
				popularity = float(popularity)
			except ValueError:
				popularity = 0.0;

			# Construct result
			return u"%s: %s | %s (%s) | Track popularity %d%%, Track duration %d:%02d" % \
					(artist, track, album, year, int(round(popularity*100)), duration / 60, duration % 60)

		# Unsupported reference
		else:
			return None