class vk_user: """ __vk_session __vk __vk_audio __audio_list """ def __init__(self, login='', password=''): self.__vk_session = vk_api.VkApi(login, password) try: self.__vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return self.__vk = self.__vk_session.get_api() self.__vk_audio = VkAudio(self.__vk_session) def make_post(self, msg=''): self.__vk.wall.post(message=msg) def get_audio_list(self): try: self.__audio_list except AttributeError: self.__audio_list = self.__vk_audio.get() return self.__audio_list def print_audio_list(self): try: self.__audio_list except AttributeError: self.__audio_list = self.__vk_audio.get() for entry in self.__audio_list: print('Owner', entry['owner_id'], 'Artist:', entry['artist'], 'Title:', entry['title']) def search_audio(self, templ=''): try: self.__audio_list except AttributeError: self.__audio_list = self.__vk_audio.get() artists = [ track for track in self.__audio_list if templ in track['artist'] ] titles = [ track for track in self.__audio_list if templ in track['title'] ] return [artists, titles]
def main(): """ Пример отображения 5 последних альбомов пользователя """ login, password = '******', 'password' vk_session = vk_api.VkApi(login, password) try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vkaudio = VkAudio(vk_session) albums = vkaudio.get_albums(194957739) print('\nLast 5:') for album in albums[:5]: print(album['title']) # Ищем треки последнего альбома print('\nSearch for', albums[0]['title']) tracks = vkaudio.get(album_id=albums[0]['id']) for n, track in enumerate(tracks, 1): print('{}. {} {}'.format(n, track['title'], track['url']))
def get_audio_by_link(update, context): global playlist_type global vk_session global vk global user_tracks global playlist_page playlist_page = 1 loop_message = update.message.reply_text('Wait a few seconds...') owner_id = update.message.text response = vk.utils.resolveScreenName(screen_name=owner_id.split('/')[-1]) owner_id = response['object_id'] vkaudio = VkAudio(vk_session) try: user_tracks = vkaudio.get(owner_id=owner_id) except: update.message.reply_text("User's audios are closed.") playlist_type = 'user' playlist = make_playlist(playlist_type) update.message.reply_text('Playlist:', reply_markup=playlist)
class VkMusic: def authVk(self, login, password, flag): try: self.session = vk_api.VkApi(login, password) self.session.auth() self.setVkAudio() except Exception: flag.append(0) else: self.api = self.session.get_api() flag.append(1) def setVkAudio(self): self.vkAudio = VkAudio(self.session) def getUserPhoto(self): return self.api.photos.get( album_id='profile')["items"][-1]["sizes"][0]["url"] def getUserInfo(self): return self.api.users.get()[0] def getUserMusic(self, userList): music = [] music.extend(self.vkAudio.get()) userList[0] = music def getMusic(self, name, findedMusic): music = [] music.extend(self.vkAudio.search(name, count=500)) findedMusic[0] = music
def main(): login, password = input('Login: '******'id'] audios = vkaudio.get(owner_id=id) for audio in audios: artist = audio['artist'].replace('/', '') title = audio['title'].replace('/', '') url = audio['url'] file_name = '/'.join( (DOWNLOAD_DIR, '{} - {}.mp3'.format(artist, title))) if not os.path.isfile(file_name): response = requests.get(url, stream=True) print('Downloading: {}'.format(file_name)) with open(file_name, 'wb') as f: shutil.copyfileobj(response.raw, f) print('OK') time.sleep(2)
def get_vk_mus(): vk_session = vk_api.VkApi(vkNumber, vkPass, auth_handler=auth_handler) vk_session.auth() vk = vk_session.get_api() vkaudio = VkAudio(vk_session) with open("vktracks.txt", "w", encoding='utf-8') as f: for track in vkaudio.get(): print(track['artist'] + '|' + track['title'] + "\n") f.write(track['artist'] + '|' + track['title'] + "\n")
def audio_parsing(): global vk_session global vk owner_id = update.message.text response = vk.utils.resolveScreenName(screen_name=owner_id.split('/')[-1]) owner_id = response['object_id'] vkaudio = VkAudio(vk_session) global user_tracks user_tracks = vkaudio.get(owner_id=owner_id)
def main(): vk_session = vk_api.VkApi("login", "pass", auth_handler=auth_handler) print(vk_session) try: vk_session.auth() except vk_api.AuthError as err: print(err) return vkaudio = VkAudio(vk_session) a = vkaudio.get() output_file = open('D:\\vk.txt', 'w') #st="" #des="" #n="" dirname = 'D:\\vk_music\\' filename = n for i in a: des = "" n = "" st = "" for k, v in i.items(): if k == 'url': for j in v: if j == "?": break st += j des = k #output_file.write(str(v)+' ') if k == 'title': v = v.replace("\"", "'") v += ".mp3" r = requests.get(st, stream=True) if r.status_code == 200: with open(dirname + v, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) print(v) n = k output_file.write(str(v) + '\n') filename = n
def main(): import time start_time = time.time() """ Пример составления топа исполнителей для профиля вк """ login, password = '******', '********' vk_session = vk_api.VkApi(login, password) try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return #tok = 'e7f58f6f518f881010ac59905851c9d0d6a5722a0669ce0e1af3bb8e611392497d386df245d16dbb8c55f' #vk_session = vk_api.VkApi(token=tok, app_id=6240100) vkaudio = VkAudio(vk_session) artists = collections.Counter() offset = 0 urls = [] while True: audios = vkaudio.get(owner_id=86071988, offset=offset) if not audios: break for audio in audios: artists[audio['artist']] += 1 urls.append({audio['url']: (audio['artist'] + ' - ' + audio['title'])[0:120].replace('/','')}) #urls = set(urls) offset += len(audios) count = len(urls) for i in urls: for k, v in i.items(): ufr = requests.get(k, stream=True) # делаем запрос if ufr.status_code == 200: with open(('music/'+ v + '.mp3'), 'wb') as f: f.write(ufr.content) else: print('Error') print('time: ' + str(time.time() - start_time) + ' count: ' + str(count))
def get(user_id=None, album_id=None): login, password = '******', 'kek1488kek' vk_session = vk_api.VkApi(login, password) try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return regulator = VkAudio(vk_session) audio_url = regulator.get(owner_id=user_id, album_id=album_id) f = open('audio.txt', 'a') for item in audio_url: audioWrite = 'audio' + str(user_id) + '_' + str(item['id']) + '\n' f.write(audioWrite) print('Запись успешно завершена') f.close()
def main(): """ Пример составления топа исполнителей для профиля вк """ login, password = '******', 'password' vk_session = vk_api.VkApi(login, password) try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vkaudio = VkAudio(vk_session) artists = collections.Counter() offset = 0 while True: audios = vkaudio.get(owner_id=-99463083, offset=offset) if not audios: break for audio in audios: artists[audio['artist']] += 1 offset += len(audios) # Составляем рейтинг первых 15 print('\nTop 15:') for artist, tracks in artists.most_common(15): print('{} - {} tracks'.format(artist, tracks)) # Ищем треки самого популярного most_common_artist = artists.most_common(1)[0][0] print('\nSearch for', most_common_artist) tracks = vkaudio.search(q=most_common_artist)[:10] for n, track in enumerate(tracks, 1): print('{}. {} {}'.format(n, track['title'], track['url']))
def main(): """ Пример составления топа исполнителей для профиля вк """ login, password = '******', 'password' vk_session = vk_api.VkApi(login, password) try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vkaudio = VkAudio(vk_session) artists = collections.Counter() offset = 0 while True: audios = vkaudio.get(owner_id=-99463083, offset=offset) if not audios: break for audio in audios: artists[audio['artist']] += 1 offset += len(audios) # Составляем рейтинг первых 15 print('\nTop 15:') for artist, tracks in artists.most_common(15): print('{} - {} tracks'.format(artist, tracks)) # Ищем треки самого популярного most_common_artist = artists.most_common(1)[0][0] print('\nSearch for', most_common_artist) tracks = vkaudio.search(q=most_common_artist)[:10] for n, track in enumerate(tracks, 1): print('{}. {} {}'.format(n, track['title'], track['url']))
def get_users_audio(self, session, vk_page): result = cache.get(str(vk_page)) if result: logger.info('return from cache') return pickle.loads(result) vkaudio = VkAudio(session) all_audios = vkaudio.get(owner_id=vk_page) logger.info('got {} audios'.format(len(all_audios))) if all_audios: all_audios = pd.DataFrame(all_audios) all_audios['user_id'] = vk_page all_audios[['user_id', 'title', 'artist']].to_csv(DATASET_PATH, mode='a', index=None, header=None) all_audios = list(all_audios['artist'])[::-1] cache.setex(name=str(vk_page), value=pickle._dumps(all_audios), time=CACHE_LIFETIME) return all_audios
def main(): """ Пример отображения 5 последних альбомов пользователя """ login, password = '******', 'password' vk_session = vk_api.VkApi(login, password) try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vkaudio = VkAudio(vk_session) albums = [] offset = 0 while True: temp_albums = vkaudio.get_albums(owner_id='194957739', offset=offset) if not temp_albums: break albums += temp_albums offset += len(temp_albums) print('\nLast 5:') for album in albums[:5]: print(album['title']) # Ищем треки последнего альбома print('\nSearch for', albums[0]['title']) tracks = vkaudio.get(album_id=albums[0]['id']) for n, track in enumerate(tracks, 1): print('{}. {} {}'.format(n, track['title'], track['url']))
def get_music(): login, password = data['vk']['login'], data['vk']['pass'] vk_session = vk_api.VkApi(login, password) try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vkaudio = VkAudio(vk_session) offset = 0 tracks = [] while True: audios = vkaudio.get(owner_id=66475832, offset=offset) if not audios: break offset += len(audios) tracks.extend(audios) return jsonify(tracks)
class VkSongs(object): """VK-Songs downloads VK audio files""" def __init__(self): self.logger = VkSongs.get_logger(level=logging.DEBUG) # TODO: Configurable log self.session = requests.Session() self.is_logged_in = False self.vk = None self.vk_audio = None def login(self, login_user, login_pass): """Logs in to VK""" vk_session = vk_api.VkApi( login_user, login_pass, auth_handler=self.two_factor_handler, captcha_handler=self.captcha_handler, app_id=6692066, ) try: vk_session.auth() except vk_api.AuthError as error_msg: self.logger.error('Login failed for {0}. Reason: {1}'.format(login_user, error_msg)) return self.vk = vk_session.get_api() self.vk_audio = VkAudio(vk_session) self.is_logged_in = True @staticmethod def two_factor_handler(): key = input("♫ Enter authentication code: ") remember_device = True return key, remember_device @staticmethod def captcha_handler(captcha): # TODO: Implement it using PyInquirer key = input("♫ Enter captcha code {0}: ".format(captcha.get_url())).strip() return captcha.try_again(key) @staticmethod def get_color(level): print(level) if level == 'ERROR': return Fore.RED elif level == 'WARNING': return Fore.YELLOW else: return '' @staticmethod def get_logger(level=logging.DEBUG): """Returns a logger""" logger = logging.getLogger(__name__) fh = logging.FileHandler('vk-songs.log', 'w') fh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')) fh.setLevel(level) logger.addHandler(fh) import sys sh = logging.StreamHandler(sys.stdout) sh.setFormatter(logging.Formatter(Fore.RED + '%(levelname)s: %(message)s')) sh.setLevel(logging.ERROR) logger.addHandler(sh) return logger def download(self, song, save_dir='./', tag=False): """Downloads the media file""" from pathvalidate import sanitize_filename import eyed3 from eyed3.id3 import ID3_V2_4 url = song.url base_name = '{0} - {1}.mp3'.format(song.artist.strip(), song.title.strip()) # TODO: Configurable file mask base_name = sanitize_filename(base_name, replacement_text='_') file_path = os.path.join(save_dir, base_name) if not os.path.isfile(file_path): import time with open(file_path, 'wb') as media_file: try: content = self.session.get(url).content except requests.exceptions.ConnectionError: time.sleep(5) content = self.session.get(url).content media_file.write(content) file_time = time.time() os.utime(file_path, (file_time, file_time)) if tag: audio_file = eyed3.load(file_path) eyed3.core.log.disabled = True eyed3.id3.log.disabled = True if audio_file: if not audio_file.tag: audio_file.initTag(version=ID3_V2_4) audio_file.tag.artist = song.artist audio_file.tag.album_artist = song.artist audio_file.tag.title = song.title if song.album is not None: audio_file.tag.album = song.album audio_file.tag.save(version=ID3_V2_4, encoding='utf_8') return True else: return False def search(self, query): search = self.vk_audio.search(q=query) # TODO: Generator result = [] for audio in search: audio['url'] = audio['url'].split('?', 1)[0] result.append(VkSong(num=audio['id'], artist=audio['artist'], title=audio['title'], url=audio['url'])) if len(result) == 0: self.logger.error('No songs found') return result def search_user(self, owner_id, query): search = self.vk_audio.search_user(owner_id=owner_id, q=query) result = [] for audio in search: audio['url'] = audio['url'].split('?', 1)[0] result.append(VkSong(num=audio['id'], artist=audio['artist'], title=audio['title'], url=audio['url'])) if len(result) == 0: self.logger.error('No songs found') return result def get_albums(self, owner_id): albums = self.vk_audio.get_albums(owner_id=owner_id) # TODO: Generator result = [] for album in albums: result.append(VkAlbum(title=album['title'], album_id=album['id'], owner_id=album['owner_id'])) if len(result) == 0: self.logger.error('No albums found') return result def get(self, owner_id=None, album_id=None, album_title=None): songs = self.vk_audio.get(owner_id=owner_id, album_id=album_id) # TODO: Generator result = [] for audio in songs: audio['url'] = audio['url'].split('?', 1)[0] result.append(VkSong(num=audio['id'], artist=audio['artist'], title=audio['title'], url=audio['url'], album=album_title)) if len(result) == 0: self.logger.error('No songs found') return result @staticmethod def should_login(dict): # TODO: Implement user session caching return True @staticmethod def make_dst_dir(destination='./', artist='/'): """Creates the destination directory.""" destination = destination + artist try: os.makedirs(destination) except OSError as err: import errno if err.errno == errno.EEXIST and os.path.isdir(destination): # Directory already exists pass else: # Target dir exists as a file, or a different error raise return destination
class AudioList_Form(QWidget): def __init__(self, parent=None): super().__init__(parent) self.parent = parent self.vk = parent.vk self.vk_audio = VkAudio(self.vk) self.folder = None self.pool = Pool(1) self.setupUi() def setupUi(self): self.resize(771, 553) self.layoutWidget = QtWidgets.QWidget(self) self.layoutWidget.setGeometry(QtCore.QRect(15, 20, 741, 521)) self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.label = QtWidgets.QLabel(self.layoutWidget) self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.label_2 = QtWidgets.QLabel(self.layoutWidget) sizePolicy = QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label_2.sizePolicy().hasHeightForWidth()) self.label_2.setSizePolicy(sizePolicy) self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1) self.label_4 = QtWidgets.QLabel(self.layoutWidget) sizePolicy = QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label_4.sizePolicy().hasHeightForWidth()) self.label_4.setSizePolicy(sizePolicy) self.gridLayout.addWidget(self.label_4, 1, 2, 1, 1) self.label_3 = QtWidgets.QLabel(self.layoutWidget) sizePolicy = QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label_3.sizePolicy().hasHeightForWidth()) self.label_3.setSizePolicy(sizePolicy) self.gridLayout.addWidget(self.label_3, 1, 1, 1, 1) self.listWidget = QtWidgets.QListWidget(self.layoutWidget) self.gridLayout.addWidget(self.listWidget, 2, 0, 1, 3) self.lineEdit = QtWidgets.QLineEdit(self.layoutWidget) self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1) self.pushButton = QtWidgets.QPushButton(self.layoutWidget) self.gridLayout.addWidget(self.pushButton, 0, 2, 1, 1) self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget) self.gridLayout.addWidget(self.pushButton_2, 3, 1, 1, 1) self.pushButton_2.setVisible(False) self.retranslateUi() self.setupHandlers() QtCore.QMetaObject.connectSlotsByName(self) def setupHandlers(self): self.pushButton.clicked.connect(self.loadAudioList) self.listWidget.itemClicked.connect(self.itemClick) self.pushButton_2.clicked.connect(self.downloadAll) @staticmethod def chunkify(lst, n): return [lst[i::n] for i in range(n)] @staticmethod def download(audios, folder='vk_music'): for audio in audios: url = audio['url'] file_name = '{}-{}.mp3'.format(audio['artist'], audio['title']) file_name = re.sub(r'[ \|/:*?"<>+%!@]', '_', file_name) try: urlretrieve(url, os.path.join(folder, file_name)) except Exception as e: errMsgBox = QErrorMessage() errMsgBox.showMessage(repr(e)) errMsgBox.exec_() def downloadAll(self): if not os.path.exists(self.folder): os.mkdir(self.folder) func = partial(self.download, folder=self.folder) self.pool.map_async(func, self.chunkify(self.audios, 10)) self.parent.statusbar.showMessage( 'Начинается скачивание всех композиций пользователя: {}'.format(self.user_id), 2000) def loadAudioList(self): self.parent.statusbar.showMessage('Загрузка...') self.parent.statusbar.repaint() try: text = self.lineEdit.text() if not text: user = self.vk.method('users.get')[0] self.user_id = user['id'] self.lineEdit.setText(str(self.user_id)) else: user = self.vk.method('users.get', {'user_ids': text})[0] self.user_id = user['id'] self.folder = os.path.join( get_download_folder(), '{}_audio'.format(self.user_id)) self.audios = self.vk_audio.get(owner_id=self.user_id) self.label_2.setText('Имя: {}'.format( user['first_name'].encode('utf-8', 'ignore').decode())) self.label_3.setText('Фамилия: {}'.format( user['last_name'].encode('utf-8', 'ignore').decode())) self.label_4.setText( 'Всего аудиозаписей: {}'.format(len(self.audios))) self.listWidget.clear() for audio in self.audios: item = QtWidgets.QListWidgetItem('{} - {} ({})'.format( audio['artist'], audio['title'], str(datetime.timedelta(seconds=int(audio['duration'])))) ) item.url = audio['url'] item.artist = audio['artist'] item.title = audio['title'] self.listWidget.addItem(item) self.pushButton_2.setVisible(True) self.parent.statusbar.clearMessage() except Exception as e: self.parent.statusbar.clearMessage() errMsgBox = QErrorMessage() errMsgBox.showMessage(repr(e)) errMsgBox.exec_() def itemClick(self, item): if not os.path.exists(self.folder): os.mkdir(self.folder) file_name = '{}-{}.mp3'.format(item.artist, item.title) file_name = re.sub(r'[ \|/:*?"<>+%!@]', '_', file_name) try: self.pool.apply_async(urlretrieve, args=( item.url, os.path.join(self.folder, file_name))) self.parent.statusbar.showMessage( 'Начинается скачивание композиции: {} - {}'.format(item.artist, item.title), 2000) except Exception as e: errMsgBox = QErrorMessage() errMsgBox.showMessage(repr(e)) errMsgBox.exec_() def retranslateUi(self): self.label.setText("Введите id пользователя или короткое имя:") self.pushButton.setText("Получить список аудио") self.pushButton_2.setText("Скачать всё")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' from config import LOGIN, PASSWORD import vk_api vk_session = vk_api.VkApi(login=LOGIN, password=PASSWORD) vk_session.auth() vk = vk_session.get_api() owner_id = vk.users.get()[0]['id'] from vk_api.audio import VkAudio vk_audio = VkAudio(vk_session) # Без использования offset не получить все, если их больше 50 audio_list = vk_audio.get(owner_id=owner_id) print('Audio list ({}):'.format(len(audio_list))) for i, audio in enumerate(audio_list, 1): print( ' {0}. "{1[title]}" by "{1[artist]}", duration: {1[dur]} secs, url: {1[url]}' .format(i, audio))
class VkDownloader(): def __init__(self): self._session: vk_api.VkApi = None self._audio: VkAudio = None self._cache: list = [] self._albums: list = [] def login(self, username, password, exception_handler=None, bad_password_handler=None, success_handler=None, captcha_handler=None): self._session = vk_api.VkApi(username, password, config=MemoryConfig, captcha_handler=captcha_handler) try: self._session.auth() except vk_api.BadPassword: if bad_password_handler: bad_password_handler() return False except Exception: if exception_handler: exception_handler() return False self._audio = VkAudio(self._session) return True def get_tracks(self): if self._audio and not self._cache: self._cache = self._audio.get() return self._cache def get_albums(self): if self._audio and not self._albums: self._albums = self._audio.get_albums() return self._albums def get_album(self, album_number): return self._audio.get(album_id=self._albums[album_number]['id']) def refresh(self): self._cache = self._audio.get() self._albums = self._audio.get_albums() def download(self, songs, folder, condition="True", overrite=False, start_func=None, end_func=None, while_func=None): class DownloadThread(threading.Thread): def run(self): if not os.path.exists(folder): while_func(("Creating folder...", )) os.makedirs(folder) try: eval(condition) except Exception: if (while_func): while_func(("Invalid condition!", )) if (end_func): end_func() return while_func(("Starting download...", )) for i in songs: name = "%s - %s" % (i['artist'], i['title']) if (eval(condition) or (condition == None)): song = requests.get(i['url'], stream=True) size = int(song.headers['Content-Length']) i = 0 if os.path.exists(folder + name + ".mp3") and not overrite: while_func(("Downloading %s..." % name, "File already downloaded.")) continue file = open(folder + name + ".mp3", "wb") for chunk in song.iter_content(chunk_size=1024): if chunk: i += 1 file.write(chunk) if while_func: while_func(("Downloading %s..." % name, "Downloaded %d" % (i * 1024 * 100 // size) + r'%')) file.close() if end_func: end_func() DownloadThread().start() if start_func: start_func()
raise Exception('Password required!') if not namespace.ids: raise Exception('Users ids required!') login = namespace.login password = namespace.password user_ids = namespace.ids processes = int(namespace.processes) vk = vk_api.VkApi(login=login, password=password) try: vk.auth() except: vk = vk_api.VkApi(login=login, password=password, auth_handler=auth_handler) vk.auth() vk_audio = VkAudio(vk) for user_id in user_ids: folder = '{}_audio'.format(user_id) audios = vk_audio.get(owner_id=user_id) print('Будет скачано {} композиций пользователя {}.'.format( len(audios), user_id)) if not os.path.exists(folder): os.mkdir(folder) func = partial(download, folder=folder) p = Pool(processes) p.map(func, chunkify(audios, processes)) print( 'Завершено скачивание композиций пользователя {}.'.format(user_id))
print(e) exit(1) vkaudio = VkAudio(vk_session) vk_song_list = [] def cleanup(str): str = re.sub(r'\([^)]*\)', '', str) str = re.sub(r'\[[^\]]*\]', '', str) str = re.sub(r'^[^\w]*', '', str) str = re.sub(r'[^\w]*$', '', str) return str for track in vkaudio.get(): artist = cleanup(track['artist']) title = cleanup(track['title']) song = artist + ' ' + title vk_song_list.append(song) gapi = gmusicapi.Mobileclient() creds = gapi.perform_oauth(open_browser=True) if not gapi.oauth_login(gmusicapi.Mobileclient.FROM_MAC_ADDRESS, oauth_credentials=creds): print('Failed to login to google') exit(1) vk_playlist_id = gapi.create_playlist('VK') for song in vk_song_list:
def process(): print('First, log in to vk.com') login = getpass('Enter login: '******'Enter password: '******'id']) try: user_id = str(sys.argv[1]) except IndexError: print('ID not set - working with your profile') print('Downloading audios from ' + user_id) vkaudio = VkAudio(vk_session) offset = 0 audios = [] last_chunk = [] chunk = None while chunk != last_chunk: last_chunk = chunk chunk = vkaudio.get(user_id, offset) audios.extend(chunk) offset += 50 total = len(audios) print() if not os.path.exists(folderName + user_id): os.mkdir(folderName + user_id) downloaded = 0 for i, track in enumerate(audios[::-1]): filename = track['artist'] + ' - ' + track['title'] # remove bad characters filename = filename.replace('?', '') filename = filename.replace('|', '') filename = filename.replace('*', '') filename = filename.replace('[', '') filename = filename.replace(']', '') filename = filename.replace('"', '') filename = filename.replace('/', '') filename = filename.replace('\\', '') filename = filename.replace('<', '') filename = filename.replace('>', '') filename = filename.replace(':', '') if os.path.isfile(folderName + user_id + '/' + filename + '.mp3'): print('Skipping [' + filename + ' ' + str(i + 1) + '/' + str(total) + ']') downloaded += 1 continue print('Downloading [' + filename + ' ' + str(i + 1) + '/' + str(total) + ']') try: save(track['url'], filename + '.mp3', user_id) downloaded += 1 except HTTPError as err: if err.code == 404: print('NOT FOUND: ' + filename) else: print('ERROR: ' + filename) except ssl.SSLError: print('SSL ERROR: ' + filename + ' try launching again') sys.stdout.flush() print() print('Done! Downloaded ' + str(downloaded) + '/' + str(total)) if downloaded < total: print('Try to launch again to to download missing files')
def main(): file_name = "%s_%s.txt" % (str(time.strftime("%Y-%m-%d")),str(time.strftime("%H%M%S"))) sys.stdout=open(file_name,"w") print(file_name) login, password = extract_credentials('credentials.txt') vk_session = vk_api.VkApi(login, password) try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vkaudio = VkAudio(vk_session) audios = None artists_by_people = collections.Counter() artists_by_tracks = collections.Counter() vk = vk_session.get_api() age_from=17 age_to=17 len_of_response = 0 while True: response = vk.users.search(city = 198, count=1000, age_from = age_from, age_to = age_to) time.sleep(0.33) if response['items']: print("age_is " + str(age_from)) print("\r\n") print("len_of_current_age_is " + str(len(response['items']))) print("\r\n") len_of_response+=len(response['items']) print("summ_len_of_response_is " + str(len_of_response)) print("\r\n") else: print("breaking.......") print(len(response['items'])) break if response['items']: for item in response['items']: print(item) print(item['id']) sys.stdout.flush() #print(response['items'][0]) try: audios = vkaudio.get(owner_id=item['id']) #определяем самого популярного исполнителя и юзера local_artists = collections.Counter() for audio in audios: local_artists[audio['artist']] += 1 local_most_common_artist = local_artists.most_common(1)[0][0] print("local_most_common_artist " + local_most_common_artist) artists_by_people[local_most_common_artist] += 1 #делаем срез последних 15 треков юзера и добавляем в общий список по исполнителям audios = audios[:15] for audio in audios: artists_by_tracks[audio['artist']] += 1 #print(audio) except: pass # Составляем рейтинг первых 30 артистов по фанатам print('\nTop 30:') #print(artists_by_people) print("for users in age from 17 to " + str(age_from)) for artist, tracks in artists_by_people.most_common(30): print('{} - {} peoples'.format(artist, tracks)) # Составляем рейтинг первых 30 артистов по количеству добавленных треков в 15 последних у юзеров print('\nTop 30:') #print(artists_by_tracks) print("for users in age from 17 to " + str(age_from)) for artist, tracks in artists_by_tracks.most_common(30): print('{} - {} tracks'.format(artist, tracks)) print(str(time.strftime("%Y-%m-%d"))+"_"+str(time.strftime("%H%M%S"))) sys.stdout.flush() age_from+=1 age_to+=1 if age_from > 35: sys.stdout.close() break
def my_search(self): vkaudio = VkAudio(self.vk_session) audio = vkaudio.get(owner_id=34442400) return audio
class GetAudioListThread(QThread): signal = pyqtSignal("PyQt_PyObject") str_signal = pyqtSignal(str) image_signal = pyqtSignal("QImage") def __init__(self, cookie, window): QThread.__init__(self) self.login = "" self.password = "" self.user_link = "" self.statusBar = None self.save_password = False self.authorized = False self.cookie = cookie self.window = window def __del__(self): self.wait() def _user_auth(self): if self.login: self.session = VkApi( login=self.login, password=self.password, auth_handler=self.auth_handler, captcha_handler=self.captcha_handler, config_filename=self.cookie, ) self.statusBar.showMessage("Авторизация.") self.session.auth() else: self.statusBar.showMessage( "Логин не указан, использование пароля в качестве токена") self.session = VkApi(token=self.password, captcha_handler=self.captcha_handler) self.vk_audio = VkAudio(self.session) self.authorized = True def _get_audio(self): tracks = [] albums = [] string = str() # Try to get post audio list post = self.get_group_and_post_id(self.user_link) album = self.get_album_id(self.user_link) if isinstance(post, tuple): owner_id, post_id = post self.statusBar.showMessage("Получение списка аудиозаписей поста.") string = "Аудиозаписи поста" tracks = self.vk_audio.get_post_audio(owner_id, post_id) audios = ",".join(["{owner_id}_{id}".format(**i) for i in tracks]) tracks = self.session.method(method="audio.getById", values={"audios": audios}) elif isinstance(album, tuple): owner_id, album_id, *_ = album self.statusBar.showMessage( "Получение списка аудиозаписей альбома.") string = "Аудиозаписи альбома" tracks = self._get_tracks(owner_id, album_id) else: user_id = self.get_user_id(self.user_link) # Try to get user or group audio list # noinspection PyBroadException try: owner_id = self.session.method("users.get", dict(user_ids=user_id))[0] self.statusBar.showMessage( "Получение списка аудиозаписей пользователя: {first_name} {last_name}" .format(**owner_id)) string = "Музыка пользователя: {first_name} {last_name}".format( **owner_id) except Exception: group_id = self.session.method("groups.getById", dict(group_id=user_id))[0] self.statusBar.showMessage( "Получение списка аудиозаписей сообщества: {name}".format( **group_id)) string = "Музыка сообщества: {}".format(group_id["name"]) albums = self._get_albums(-group_id["id"]) tracks = self._get_tracks(-group_id["id"]) else: albums = self._get_albums(owner_id["id"]) tracks = self._get_tracks(owner_id["id"]) for album in albums: try: album["tracks"] = self.vk_audio.get( owner_id=album["owner_id"], album_id=album["id"], access_hash=album["access_hash"], ) except: album["tracks"] = self._get_tracks(owner_id["id"], album["id"]) return tracks, string, albums def _get_tracks(self, owner_id, album_id=None, access_hash=None): try: tracks = self.vk_audio.get(owner_id, album_id, access_hash) except: values = {"owner_id": owner_id} if album_id: values.update({"album_id": album_id}) res = self.session.method( method="audio.get", values=values, ) count = res["count"] offset = 0 tracks = [] while count != 0: audios = ",".join( ["{owner_id}_{id}".format(**i) for i in res["items"]]) tracks.extend( self.session.method(method="audio.getById", values={"audios": audios})) offset += 200 if count >= 200 else count % 200 count -= 200 if count >= 200 else count % 200 values.update({"offset": offset}) res = self.session.method( method="audio.get", values=values, ) return tracks def _get_albums(self, owner_id): try: albums = self.vk_audio.get_albums(owner_id["id"]) except: res = self.session.method( method="audio.getPlaylists", values={"owner_id": owner_id}, ) count = res["count"] offset = 0 albums = [] while count != 0: albums.extend(res["items"]) offset += 10 if count >= 10 else count % 10 count -= 10 if count >= 10 else count % 10 res = self.session.method( method="audio.getPlaylists", values={ "owner_id": owner_id, "offset": offset }, ) return albums def auth_handler(self): """ При двухфакторной аутентификации вызывается эта функция. :return: key, remember_device """ self.str_signal.emit("Введите код авторизации:") while not self.window.key: pass return self.window.key, self.save_password def captcha_handler(self, captcha): url = captcha.get_url() file = TemporaryFile() res = self.session.http.get(url, stream=True) res.raw.decode_content = True shutil.copyfileobj(res.raw, file) file.seek(0) image = QImage() image.loadFromData(file.read()) self.image_signal.emit(image) while not self.window.key: pass return captcha.try_again(self.window.key) def run(self): try: if not self.authorized: self._user_auth() result = self._get_audio() self.signal.emit(result) except exceptions.BadPassword: self.signal.emit("Неверный логин или пароль.") except exceptions.LoginRequired: self.signal.emit("Требуется логин.") except exceptions.PasswordRequired: self.signal.emit("Требуется пароль.") except (IndexError, AttributeError): self.signal.emit( "Невозможно получить список аудиозаписей. Проверьте, открыты ли они у пользователя." ) except exceptions.ApiError as e: if "113" in str(e): self.signal.emit( "Неверная ссылка на профиль пользователя (неверный ID пользователя)." ) elif "100" in str(e): self.signal.emit( "Неверная ссылка на профиль пользователя (сообщества).") else: self.signal.emit(str(e)) except Exception as e: self.signal.emit(str(type(e)) + str(e)) @staticmethod def get_user_id(link): result = findall(r"(https?://m?\.?vk\.com/)?(.*)$", link)[0][1] return result if result else None @staticmethod def get_group_and_post_id(link): result = findall(r"wall(.*?)_(.*?)$", link) return result[0] if result else None @staticmethod def get_album_id(link): link = link.replace("%2F", "/") result = findall(r"playlist/(.*)_(.*)_(.*)\?", link) if not result: result = findall(r"playlist/(.*)_(.*)_(.*)", link) if not result: result = findall(r"audio_playlist(.*)_(.*)&access_hash=(.*)", link) if not result: result = findall(r"audio_playlist(.*)_(.*)/(.*)", link) if not result: result = findall(r"audio_playlist(.*)_(.*)", link) return result[0] if result else None