-
Notifications
You must be signed in to change notification settings - Fork 0
/
song_sources.py
69 lines (55 loc) · 2.03 KB
/
song_sources.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import os
import json
import fnmatch
from collections import namedtuple
from os.path import basename
from vk_api import VkApi, AuthorizationError
import requests
Song = namedtuple('Song', ['id', 'title', 'source', 'duration'])
class OnlineSource:
config_file = 'vk_config.json'
def __init__(self):
self.songs = []
self.connection = None
if os.path.isfile(self.config_file):
with open('vk_config.json', 'r') as conf:
data = json.loads(conf.read())
if data:
username = data.keys()[0]
if self.login(username, username):
self.songs = self.get_audios()
def get_audios(self, owner_id=None):
response = self.connection.method('audio.get', {'owner_id': owner_id} if owner_id else None)
return [Song(item['id'], u"{} - {}".format(item['artist'], item['title']), item['url'], item['duration']) for item in response['items']]
def login(self, login, password):
if login and password:
self.connection = VkApi(login, password)
try:
self.connection.authorization()
print('autorization')
except requests.exceptions.ConnectionError:
print('has not connection')
except AuthorizationError as error_msg:
print(error_msg)
except TypeError as fkng_msg:
print(fkng_msg)
else:
return True
return False
def logout(self):
try:
os.remove(self.config_file)
except OSError:
pass
self.connection = None
class OfflineSource:
def __init__(self, directory):
self.songs = []
self.get_files(directory)
def get_files(self, path):
for f in os.listdir(path):
f = os.path.join(path, f)
if os.path.isdir(f):
self.get_files(f) # recurse
if fnmatch.fnmatch(f, '*.mp3'):
self.songs.append(Song(basename(f), f))