Exemplo n.º 1
0
	def download_song(self, song_id, requested_type="mp3", cover_as_file=False):
			### Prepare/Get Meta ###
			requested_type = u(requested_type)
			if self and isinstance(self, PonyFM) and self.session:
				json = get_json(API_URL.format(songid=song_id), cookies=self.session.cookies, verify=False)
			else:
				json = get_json(API_URL.format(songid=song_id), verify=False)


			### FILE Download ###

			download_src = None
			if "formats" in json.track:
				for download_format in json.track.formats:
					logger.debug("Found {extension} download.".format(extension=download_format.extension))
					if u(download_format.extension) == requested_type:
						download_src = download_format.url
						logger.debug("Got what we need. Skipping rest.")
						break
					#end if
				#end for
			#end if
			if download_src is None:  # not found > try streams
				if int(json.track.is_downloadable) != 1:
					logger.warn("Song is marked as 'not downloadable'! The downloaded stream might be bad quality!")
				else:
					logger.warn("Did not found the requested download type, searching in the stream formats. They might be bad quality!")
				#end if
				for extension, url in json.track.streams.items():  # for python 2 this should use iteritems() ... but meh.
					logger.debug("Found {extension} stream.".format(extension=extension))
					if u(extension) == requested_type:
						logger.debug("Got what we need. Skipping rest.")
						download_src = url
						break
				else:  # neither dl, nor streams > ERROR!
					logger.error("Did not (at all) found requested type ({requested_type})!".format(requested_type=requested_type))
					raise AssertionError("Could not find download.")  # TODO: custom DL Exception
				#end for-else
			#end if
			assert(download_src is not None)

			# Got download link.
			# Now Download song.

			if self and isinstance(self, PonyFM) and self.session:
				file_path, file_mime = download_file(download_src, temp_folder_name=SHORT_NAME, return_mime=True, progress_bar=True, cookies=self.session.cookies, verify=False)
			else:
				file_path, file_mime = download_file(download_src, temp_folder_name=SHORT_NAME, return_mime=True, progress_bar=True, verify=False)
			logger.info("Downloaded mp3 from '{url}' to '{path}'".format(url=download_src, path=file_path))

			if u(file_mime) not in [u("audio/mp3"),u("audio/mpeg")]:
				raise AssertionError("mp3 is not mp3..")  # TODO: custom exception
			else:
				extension = "mp3"  # very dynamic, such future-prove!

			### META ###

			audiofile = eyed3.load(file_path)
			if audiofile.tag is None:
				audiofile.initTag()
			artist = u(json.track.user.name)
			logger.debug("")
			if not audiofile.tag.title:
				logger.debug("Title was empty.")
				audiofile.tag.title = u(json.track.title)
			overwrite_if_not(audiofile.tag, "artist", artist)
			overwrite_if_not(audiofile.tag, "audio_file_url", u("https://github.com/luckydonald/pon3downloader/"))
			overwrite_if_not(audiofile.tag, "artist_url", u(json.track.user.url))
			overwrite_if_not(audiofile.tag, "genre", u(json.track.genre.name))
			overwrite_if_not(audiofile.tag, "lyrics", [u(json.track.lyrics)])
			overwrite_if_not(audiofile.tag, "audio_source_url", u(json.track.url))
			#if audiofile.tag.comments.get(u""):
			#	text = audiofile.tag.comments.get(u"").text
			#	text += u("\n-----\nDownloaded from https://pony.fm/ with Pon3Downloader (https://github.com/luckydonald/pon3downloader/).")
			#	audiofile.tag.comments.set(text)
			#else:
			audiofile.tag.comments.set(u("Downloaded from {track_url} with Pon3Downloader (https://github.com/luckydonald/pon3downloader/)".format(track_url = json.track.url)))
			audiofile.tag.comments.set(u("https://github.com/luckydonald/pon3downloader"), u("Downloader"))
			audiofile.tag.save()

			### COVER ART ###
			if self and isinstance(self, PonyFM) and self.session:
				imageData, imageMine = download_file(json.track.covers.normal, return_mime=True, return_buffer=True, progress_bar=True, cookies=self.session.cookies, verify=False)
			else:
				imageData, imageMine = download_file(json.track.covers.normal, return_mime=True, return_buffer=True, progress_bar=True, verify=False)
			imageType = eyed3.id3.frames.ImageFrame.FRONT_COVER
			audiofile.tag.images.set(imageType, imageData, b(imageMine), description=u(" "))
			### SAVE ###

			audiofile.tag.save()
			logger.debug("wrote file meta.")
			new_file_name = "{artist} - {title}".format(artist=artist,title=json.track.title)
			new_file_name = do_a_filename(new_file_name)
			music_file_name = new_file_name + "." + extension
			logger.info("Renaming to '{filename}'".format(filename=music_file_name))
			file_folder = os.path.dirname(file_path)
			music_file_path = os.path.join(file_folder, music_file_name)
			logger.debug("Full new path will be '{path}'.".format(path=music_file_path))
			os.rename(file_path, music_file_path)
			if cover_as_file:
				logger.debug("Trying also writing the cover file.")
				cover_file_name = new_file_name + guess_extension(imageMine)
				cover_file_path = os.path.join(file_folder, cover_file_name)
				with open(cover_file_path, mode="wb+") as cover_file:
					cover_file.write(imageData)

			### FAVE ###
			if json.track.user_data:
				if json.track.user_data.is_favourited == 0:
					if self and isinstance(self, PonyFM) and self.session and self.token:
						logger.debug("Favouriting it now.")
						self.toggle_fave(json.track.id)
					else:
						logger.debug("User is not logged in.")
				else:
					logger.info("Song already is favorite.")
			return music_file_path
Exemplo n.º 2
0
 def search(self, string, inline_query_id, offset):
     if not string:  # nothing entered.
         string = "littlepip"
     results = []
     next_offset=None
     if offset is None or len(str(offset).strip()) < 1:
         offset = 0
     else:
         offset = int(offset)
     valid_tag_names = []
     for string_part in string.split(","):
         string_part = string_part.strip()
         valid_tag_obj = get_json(self.tag_search, params=dict(format="json", name__startswith=string_part, limit=1))
         if "error" in valid_tag_obj:
             error_message = InlineQueryResultArticle(
                 id="404e:"+string,
                 title=u"\"{tag}\" not found.".format(tag=string),
                 input_message_content=InputTextMessageContent(string),
                 description=valid_tag_obj.error, thumb_url=self.error_image
             )
             try:
                 logger.debug("Sending result: {}".format((inline_query_id, [error_message])))
                 result = self.check_result(self.bot.answer_inline_query(inline_query_id, [error_message]))
                 logger.success(result)
             except TgApiException:
                 logger.exception("Answering query failed.")
             return
         for tag_obj in valid_tag_obj.objects:
             valid_tag_names.append(tag_obj.name)
     if len(valid_tag_names) == 0:
         result = InlineQueryResultArticle(
                 id="404t:"+string,
                 title=u"\"{tag}\" not found.".format(tag=string),
                 input_message_content=InputTextMessageContent(string),
                 description="No similar tag found.",
                 thumb_url=self.error_image
         )
         try:
             logger.debug("Sending result: {}".format((inline_query_id, result)))
             result = self.check_result(self.bot.answer_inline_query(inline_query_id, result))
             logger.success(result)
         except TgApiException as e:
             logger.exception("Answering query failed: {e}".format(e=e))
         return
     logger.info("tags: {}".format(valid_tag_names))
     logger.debug("offset: {}".format(offset))
     images_of_tag = get_json(self.tag_info, params=dict(search=dumps(valid_tag_names), format="json", limit=10, offset=offset))
     logger.debug(images_of_tag)
     if images_of_tag.meta.total_count < 1 or len(images_of_tag.objects) < 1:
         error_message = InlineQueryResultArticle(
             id="404i:"+string,
             title=u"\"{tag}\" not found.".format(tag=string),
             input_message_content=InputTextMessageContent(string),
             description="Search results no images.",
             thumb_url=self.error_image
         )
         try:
             logger.debug("Sending result: {}".format((inline_query_id, [error_message])))
             result = self.check_result(self.bot.answer_inline_query(inline_query_id, [error_message]))
             logger.success(result)
         except TgApiException as e:
             logger.exception("Answering query failed: {e}".format(e=e))
         return
     if images_of_tag.meta.next:
         next_offset = offset+10
     for img in images_of_tag.objects:
         # image = self.root + tag.objects[0].resizes.small
         image_full = self.root + img.image
         image_small = image_full
         if "resizes" in img and "small" in img.resizes:
             image_small = self.root + img.resizes.small
         if "thumbnails" in img:
             if "png" in img.thumbnails:
                 image_small = self.root + img.thumbnails.png
             elif "jpg" in img.thumbnails:
                 image_small = self.root + img.thumbnails.jpg
         image_gif = self.root + img.thumbnails.gif if "gif" in img.thumbnails else None
         tag_total_count = images_of_tag.meta.total_count
         id = "mlfw-{id}".format(id=img.id)
         if not id:
             logger.error("NO ID: {}".format(img))
             continue
         logger.debug("id: {id}".format(id=id))
         # results.append(InlineQueryResultArticle(id=id, thumb_url=image_small, title=u"{tag}".format(tag=img.title), message_text=image_full, description=img.description))
         if image_gif:
             results.append(InlineQueryResultGif(id=id, title=img.title, gif_url=image_full, thumb_url=image_small, caption=self.str_to_caption(string)))
         else:
             results.append(InlineQueryResultPhoto(id=id, title=img.title, photo_url=image_full, thumb_url=image_small, caption=self.str_to_caption(string)))
     for res in results:
         logger.debug(res.to_array())
     logger.debug("next_offset=" + str(next_offset))
     try:
         logger.debug("Sending result: {}, cache_time=300, next_offset={next_offset}".format((inline_query_id, results), next_offset=next_offset))
         result = self.check_result(self.bot.answer_inline_query(inline_query_id, results, cache_time=300, next_offset=next_offset))
         logger.success(result)
     except TgApiException as e:
         logger.exception("Answering query failed: {e}".format(e=e))
Exemplo n.º 3
0
    def download_song(self,
                      song_id,
                      requested_type="mp3",
                      cover_as_file=False):
        ### Prepare/Get Meta ###
        requested_type = u(requested_type)
        if self and isinstance(self, PonyFM) and self.session:
            json = get_json(API_URL.format(songid=song_id),
                            cookies=self.session.cookies,
                            verify=False)
        else:
            json = get_json(API_URL.format(songid=song_id), verify=False)

        ### FILE Download ###

        download_src = None
        if "formats" in json.track:
            for download_format in json.track.formats:
                logger.debug("Found {extension} download.".format(
                    extension=download_format.extension))
                if u(download_format.extension) == requested_type:
                    download_src = download_format.url
                    logger.debug("Got what we need. Skipping rest.")
                    break
                #end if
            #end for
        #end if
        if download_src is None:  # not found > try streams
            if int(json.track.is_downloadable) != 1:
                logger.warn(
                    "Song is marked as 'not downloadable'! The downloaded stream might be bad quality!"
                )
            else:
                logger.warn(
                    "Did not found the requested download type, searching in the stream formats. They might be bad quality!"
                )
            #end if
            for extension, url in json.track.streams.items(
            ):  # for python 2 this should use iteritems() ... but meh.
                logger.debug(
                    "Found {extension} stream.".format(extension=extension))
                if u(extension) == requested_type:
                    logger.debug("Got what we need. Skipping rest.")
                    download_src = url
                    break
            else:  # neither dl, nor streams > ERROR!
                logger.error(
                    "Did not (at all) found requested type ({requested_type})!"
                    .format(requested_type=requested_type))
                raise AssertionError(
                    "Could not find download.")  # TODO: custom DL Exception
            #end for-else
        #end if
        assert (download_src is not None)

        # Got download link.
        # Now Download song.

        if self and isinstance(self, PonyFM) and self.session:
            file_path, file_mime = download_file(download_src,
                                                 temp_folder_name=SHORT_NAME,
                                                 return_mime=True,
                                                 progress_bar=True,
                                                 cookies=self.session.cookies,
                                                 verify=False)
        else:
            file_path, file_mime = download_file(download_src,
                                                 temp_folder_name=SHORT_NAME,
                                                 return_mime=True,
                                                 progress_bar=True,
                                                 verify=False)
        logger.info("Downloaded mp3 from '{url}' to '{path}'".format(
            url=download_src, path=file_path))

        if u(file_mime) not in [u("audio/mp3"), u("audio/mpeg")]:
            raise AssertionError("mp3 is not mp3..")  # TODO: custom exception
        else:
            extension = "mp3"  # very dynamic, such future-prove!

        ### META ###

        audiofile = eyed3.load(file_path)
        if audiofile.tag is None:
            audiofile.initTag()
        artist = u(json.track.user.name)
        logger.debug("")
        if not audiofile.tag.title:
            logger.debug("Title was empty.")
            audiofile.tag.title = u(json.track.title)
        overwrite_if_not(audiofile.tag, "artist", artist)
        overwrite_if_not(audiofile.tag, "audio_file_url",
                         u("https://github.com/luckydonald/pon3downloader/"))
        overwrite_if_not(audiofile.tag, "artist_url", u(json.track.user.url))
        overwrite_if_not(audiofile.tag, "genre", u(json.track.genre.name))
        overwrite_if_not(audiofile.tag, "lyrics", [u(json.track.lyrics)])
        overwrite_if_not(audiofile.tag, "audio_source_url", u(json.track.url))
        #if audiofile.tag.comments.get(u""):
        #	text = audiofile.tag.comments.get(u"").text
        #	text += u("\n-----\nDownloaded from https://pony.fm/ with Pon3Downloader (https://github.com/luckydonald/pon3downloader/).")
        #	audiofile.tag.comments.set(text)
        #else:
        audiofile.tag.comments.set(
            u("Downloaded from {track_url} with Pon3Downloader (https://github.com/luckydonald/pon3downloader/)"
              .format(track_url=json.track.url)))
        audiofile.tag.comments.set(
            u("https://github.com/luckydonald/pon3downloader"),
            u("Downloader"))
        audiofile.tag.save()

        ### COVER ART ###
        if self and isinstance(self, PonyFM) and self.session:
            imageData, imageMine = download_file(json.track.covers.normal,
                                                 return_mime=True,
                                                 return_buffer=True,
                                                 progress_bar=True,
                                                 cookies=self.session.cookies,
                                                 verify=False)
        else:
            imageData, imageMine = download_file(json.track.covers.normal,
                                                 return_mime=True,
                                                 return_buffer=True,
                                                 progress_bar=True,
                                                 verify=False)
        imageType = eyed3.id3.frames.ImageFrame.FRONT_COVER
        audiofile.tag.images.set(imageType,
                                 imageData,
                                 b(imageMine),
                                 description=u(" "))
        ### SAVE ###

        audiofile.tag.save()
        logger.debug("wrote file meta.")
        new_file_name = "{artist} - {title}".format(artist=artist,
                                                    title=json.track.title)
        new_file_name = do_a_filename(new_file_name)
        music_file_name = new_file_name + "." + extension
        logger.info(
            "Renaming to '{filename}'".format(filename=music_file_name))
        file_folder = os.path.dirname(file_path)
        music_file_path = os.path.join(file_folder, music_file_name)
        logger.debug(
            "Full new path will be '{path}'.".format(path=music_file_path))
        os.rename(file_path, music_file_path)
        if cover_as_file:
            logger.debug("Trying also writing the cover file.")
            cover_file_name = new_file_name + guess_extension(imageMine)
            cover_file_path = os.path.join(file_folder, cover_file_name)
            with open(cover_file_path, mode="wb+") as cover_file:
                cover_file.write(imageData)

        ### FAVE ###
        if json.track.user_data:
            if json.track.user_data.is_favourited == 0:
                if self and isinstance(self,
                                       PonyFM) and self.session and self.token:
                    logger.debug("Favouriting it now.")
                    self.toggle_fave(json.track.id)
                else:
                    logger.debug("User is not logged in.")
            else:
                logger.info("Song already is favorite.")
        return music_file_path