radiojavanapi 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,106 @@
1
+ from radiojavanapi.helper import extract_cookie
2
+ from radiojavanapi.mixins.private import PrivateRequest
3
+ from radiojavanapi.constants import BASE_HEADERS
4
+
5
+ class AuthMixin(PrivateRequest):
6
+ def __init__(self) -> None:
7
+ super().__init__()
8
+ self.cookie = None
9
+
10
+ def initial(self):
11
+ """
12
+ Initialize Login/SignUp helpers
13
+
14
+ """
15
+ if self.authorized:
16
+ self.logout()
17
+
18
+ self.private.cookies.clear()
19
+ self.private.headers.update(BASE_HEADERS)
20
+ self.cookie = None
21
+ self.authorized = False
22
+ self.email = None
23
+ self.password = None
24
+ self.update_cookie(self.private_request('app_config'))
25
+
26
+ def update_cookie(self, response):
27
+ """
28
+ Extract cookie and update headers
29
+
30
+ """
31
+ self.cookie = extract_cookie(response.headers.get('Set-Cookie'))
32
+ self.private.headers.update({'Cookie': self.cookie})
33
+
34
+ def login(self, email: str, password: str) -> bool:
35
+ """
36
+ Log in to RadioJavan
37
+
38
+ Arguments
39
+ ----------
40
+ email: Your account email
41
+ password: Your account password
42
+
43
+ Returns
44
+ -------
45
+ bool: login result
46
+
47
+ """
48
+ self.initial()
49
+ self.email = email
50
+ self.password = password
51
+
52
+ payload = {
53
+ "login_email": email,
54
+ "login_password": password
55
+ }
56
+
57
+ response = self.private_request('login', json=payload)
58
+ response_json = response.json()
59
+
60
+ if response_json.get('success'):
61
+ self.update_cookie(response)
62
+ self.authorized = True
63
+
64
+ return self.authorized
65
+
66
+ def logout(self) -> bool:
67
+ return self.private_request('logout', need_login=True).json()["success"]
68
+
69
+ def signup(self,
70
+ firstname: str, lastname: str,
71
+ username: str, email: str, password: str,
72
+ auto_login: bool = False) -> bool:
73
+
74
+ """
75
+ Sign up to RadioJavan
76
+
77
+ Arguments
78
+ ----------
79
+ firstname: Your account firstname
80
+ lastname: Your account lastname
81
+ username: Your account username
82
+ email: Your account email
83
+ password: Your account password
84
+ auto_login [optional]: login to account after sign up
85
+
86
+ Returns
87
+ -------
88
+ bool: sign up result
89
+
90
+ """
91
+ self.initial()
92
+
93
+ payload = {
94
+ "email": email,
95
+ "password": password,
96
+ "username": username,
97
+ "email_confirm": email,
98
+ "firstname": firstname,
99
+ "lastname": lastname
100
+ }
101
+
102
+ is_success = self.private_request('signup_mobile', json=payload).json()['success']
103
+ if is_success and auto_login:
104
+ self.login(email, password)
105
+
106
+ return is_success
@@ -0,0 +1,89 @@
1
+ from radiojavanapi.mixins.album import AlbumMixin
2
+ from radiojavanapi.mixins.artist import ArtistMixin
3
+ from radiojavanapi.models import (
4
+ Album, Artist, Podcast, Song, Story, Video
5
+ )
6
+ from radiojavanapi.extractors import (
7
+ extract_song, extract_podcast,
8
+ extract_story, extract_video,
9
+ )
10
+
11
+ from typing import Dict, List
12
+
13
+ class BrowseMixin(ArtistMixin, AlbumMixin):
14
+ def __browse_req__(self, endpoint, type):
15
+ extractor = None
16
+ if type == 'albums':
17
+ extractor = self.get_album_by_id
18
+ elif endpoint == "mp3s":
19
+ extractor = extract_song
20
+ elif endpoint == "videos":
21
+ extractor = extract_video
22
+ elif endpoint == "podcasts":
23
+ extractor = extract_podcast
24
+
25
+ page, items, response = 1, [], {""}
26
+ while bool(response):
27
+ response = self.private_request(endpoint,
28
+ params=f'url={endpoint}&type={type}&page={page}').json()
29
+ items.extend([extractor(item['id'] if type=='albums' else item) for item in response])
30
+ page+=1
31
+ return items
32
+
33
+ def get_latest_stories(self) -> List[Story]:
34
+ """Get list of latest stories"""
35
+ response = self.private_request('selfies_browse',
36
+ params='url=selfies_browse').json()
37
+ return [extract_story(story) for story in response]
38
+
39
+ def get_trending_songs(self) -> List[Song]:
40
+ """Get list of trending songs"""
41
+ return self.__browse_req__('mp3s','trending')
42
+
43
+ def get_popular_songs(self) -> List[Song]:
44
+ """Get list of popular songs"""
45
+ return self.__browse_req__('mp3s','popular')
46
+
47
+ def get_featured_songs(self) -> List[Song]:
48
+ """Get list of featured songs"""
49
+ return self.__browse_req__('mp3s','featured')
50
+
51
+ def get_latest_albums(self) -> List[Album]:
52
+ """Get list of latest albums"""
53
+ return self.__browse_req__('mp3s','albums')
54
+
55
+ def get_trending_videos(self) -> List[Video]:
56
+ """Get list of trending videos"""
57
+ return self.__browse_req__('videos','trending')
58
+
59
+ def get_popular_videos(self) -> List[Video]:
60
+ """Get list of popular videos"""
61
+ return self.__browse_req__('videos','popular')
62
+
63
+ def get_featured_videos(self) -> List[Video]:
64
+ """Get list of featured videos"""
65
+ return self.__browse_req__('videos','featured')
66
+
67
+ def get_latest_videos(self) -> List[Video]:
68
+ """Get list of latest videos"""
69
+ return self.__browse_req__('videos','latest')
70
+
71
+ def get_popular_podcasts(self) -> List[Podcast]:
72
+ """Get list of popular podcasts"""
73
+ return self.__browse_req__('podcasts','popular')
74
+
75
+ def get_featured_podcasts(self) -> List[Podcast]:
76
+ """Get list of featured podcasts"""
77
+ return self.__browse_req__('podcasts','featured')
78
+
79
+ def get_talk_podcasts(self) -> List[Podcast]:
80
+ """Get list of talk podcasts"""
81
+ return self.__browse_req__('podcasts','talk')
82
+
83
+ def get_shows_podcasts(self) -> List[Podcast]:
84
+ """Get list of shows podcasts"""
85
+ return self.__browse_req__('podcasts','shows')
86
+
87
+ def get_tv_stream(self) -> str:
88
+ """Get RJ tv stream link"""
89
+ return self.private_request('app_config').json()['config']['tv']['hls']
@@ -0,0 +1,312 @@
1
+ from radiojavanapi.mixins.private import PrivateRequest
2
+ from radiojavanapi.extractors import extract_video_playlist, extract_music_playlist
3
+ from radiojavanapi.helper import url_to_id
4
+ from radiojavanapi.models import MusicPlaylist, VideoPlaylist
5
+
6
+ from typing import Optional, Union
7
+ from pydantic import HttpUrl
8
+
9
+ class MusicPlayListMixin(PrivateRequest):
10
+ def get_music_playlist_by_url(self, url: HttpUrl) -> MusicPlaylist:
11
+ """
12
+ Get music playlist info by site url (e.g. `play.radiojavan.com/playlist/mp3/...` or `play.radiojavan.com/redirect?r=radiojavan://playlist/mp3/...`)
13
+
14
+ Arguments
15
+ ----------
16
+ url: Site url of music playlist
17
+
18
+ Returns
19
+ -------
20
+ MusicPlaylist: An object of Music Playlist type
21
+
22
+ """
23
+ return self.get_music_playlist_by_id(url_to_id(url))
24
+
25
+ def get_music_playlist_by_id(self, id: str) -> MusicPlaylist:
26
+ """
27
+ Get music playlist info by id
28
+
29
+ Arguments
30
+ ----------
31
+ id: Unique id of music playlist
32
+
33
+ Returns
34
+ -------
35
+ MusicPlaylist: An object of Music Playlist type
36
+
37
+ """
38
+ response = self.private_request('mp3_playlist_with_items',
39
+ params=f'id={id}').json()
40
+ return extract_music_playlist(response)
41
+
42
+ def follow_music_playlist(self, id: str) -> bool:
43
+ """
44
+ Follow a music playlist
45
+
46
+ Arguments
47
+ ----------
48
+ id: An id of music playlist
49
+
50
+ Returns
51
+ -------
52
+ bool: RJ api result
53
+
54
+ """
55
+ response = self.private_request('mp3_playlist_follow',
56
+ params=f'id={id}&type=mp3',
57
+ need_login=True).json()
58
+ return response['success'] == True
59
+
60
+ def unfollow_music_playlist(self, id: str) -> bool:
61
+ """
62
+ UnFollow a music playlist
63
+
64
+ Arguments
65
+ ----------
66
+ id: An id of music playlist
67
+
68
+ Returns
69
+ -------
70
+ bool: RJ api result
71
+
72
+ """
73
+ response = self.private_request('mp3_playlist_unfollow',
74
+ params=f'id={id}&type=mp3',
75
+ need_login=True).json()
76
+ return response['success'] == True
77
+
78
+ def create_music_playlist(self, name: str, song_id: Union[int, str]) -> Optional[str]:
79
+ """
80
+ Create a music playlist
81
+ Note: in RJ you can't create empty playlist , so you need a song for creating playlist
82
+
83
+ Arguments
84
+ ----------
85
+ name: Name of playlist
86
+ song_id: A digit id of Song
87
+
88
+ Returns
89
+ -------
90
+ str: Playlist's id
91
+
92
+ """
93
+ response = self.private_request('mp3_playlist_add',
94
+ params=f'type=mp3&mp3={song_id}&name={name}',
95
+ need_login=True).json()
96
+ return response['playlist'] if response['success'] else None
97
+
98
+ def delete_music_playlist(self, id: str) -> bool:
99
+ """
100
+ Delete your music playlist
101
+
102
+ Arguments
103
+ ----------
104
+ id: An id of music playlist
105
+
106
+ Returns
107
+ -------
108
+ bool: Returns true if success
109
+
110
+ """
111
+ return self.private_request('mp3_playlist_remove',
112
+ params=f'type=mp3&id={id}',
113
+ need_login=True).json()['success']
114
+
115
+ def rename_music_playlist(self, id: str, name: str) -> bool:
116
+ """
117
+ Rename your music playlist
118
+
119
+ Arguments
120
+ ----------
121
+ id: An id of music playlist
122
+ name: The name you want to set for a playlist
123
+
124
+ Returns
125
+ -------
126
+ bool: Returns true if success
127
+
128
+ """
129
+ return self.private_request('mp3_playlist_rename',
130
+ params=f'type=mp3&id={id}&name={name}',
131
+ need_login=True).json()['success']
132
+
133
+ def add_to_music_playlist(self, id: str, song_id: Union[int, str]) -> bool:
134
+ """
135
+ Add a song to your music playlist
136
+
137
+ Arguments
138
+ ----------
139
+ id: An id of music playlist
140
+ song_id: A digit id of Song
141
+
142
+ Returns
143
+ -------
144
+ bool: Returns false if song had been added already
145
+
146
+ """
147
+ songs = self.get_music_playlist_by_id(id).songs
148
+ for sng in songs:
149
+ if song_id == sng.id:
150
+ return False
151
+
152
+ return self.private_request('mp3_playlist_add',
153
+ params=f'id={id}&mp3={song_id}&start=0',
154
+ need_login=True).json()['success']
155
+
156
+ def remove_from_music_playlist(self, id: str, song_id: Union[int, str]) -> bool:
157
+ """
158
+ Remove a song from your music playlist
159
+
160
+ Arguments
161
+ ----------
162
+ id: An id of music playlist
163
+ song_id: A digit id of Song
164
+
165
+ Returns
166
+ -------
167
+ bool: Returns false if song hadn't been added before
168
+
169
+ """
170
+ songs = self.get_music_playlist_by_id(id).songs
171
+ for sng in songs:
172
+ if song_id == sng.id:
173
+ return self.private_request('mp3_playlist_item_remove',
174
+ params=f'type=mp3&id={id}&item={sng.item}',
175
+ need_login=True).json()['success']
176
+ return False
177
+
178
+ class VideoPlayListMixin(PrivateRequest):
179
+ def get_video_playlist_by_url(self, url: HttpUrl) -> VideoPlaylist:
180
+ """
181
+ Get video playlist info by site url (e.g. `play.radiojavan.com/playlist/video/...` or `play.radiojavan.com/redirect?r=radiojavan://playlist/video/...`)
182
+
183
+ Arguments
184
+ ----------
185
+ url: Site url of video playlist
186
+
187
+ Returns
188
+ -------
189
+ VideoPlaylist: An object of Video Playlist type
190
+
191
+ """
192
+ return self.get_video_playlist_by_id(url_to_id(url))
193
+
194
+ def get_video_playlist_by_id(self, id: str) -> VideoPlaylist:
195
+ """
196
+ Get video playlist info by id
197
+
198
+ Arguments
199
+ ----------
200
+ id: Unique id of video playlist
201
+
202
+ Returns
203
+ -------
204
+ VideoPlaylist: An object of Video Playlist type
205
+
206
+ """
207
+ response = self.private_request('video_playlist_with_items',
208
+ params=f'id={id}').json()
209
+ return extract_video_playlist(response)
210
+
211
+ def create_video_playlist(self, name: str, video_id: Union[int, str]) -> Optional[str]:
212
+ """
213
+ Create a video playlist
214
+ Note: in RJ you can't create empty playlist , so you need a video for creating playlist
215
+
216
+ Arguments
217
+ ----------
218
+ name: Name of playlist
219
+ video_id: A digit id of Video
220
+
221
+ Returns
222
+ -------
223
+ str: Playlist's id
224
+
225
+ """
226
+ response = self.private_request('video_playlist_add',
227
+ params=f'type=video&video={video_id}&name={name}',
228
+ need_login=True).json()
229
+ return response['playlist'] if response['success'] else None
230
+
231
+ def delete_video_playlist(self, id: str) -> bool:
232
+ """
233
+ Delete your video playlist
234
+
235
+ Arguments
236
+ ----------
237
+ id: An id of video playlist
238
+
239
+ Returns
240
+ -------
241
+ bool: Returns true if success
242
+
243
+ """
244
+ return self.private_request('video_playlist_remove',
245
+ params=f'type=video&id={id}',
246
+ need_login=True).json()['success']
247
+
248
+ def rename_video_playlist(self, id: str, name: str) -> bool:
249
+ """
250
+ Rename your video playlist
251
+
252
+ Arguments
253
+ ----------
254
+ id: An id of video playlist
255
+ name: The name you want to set for a playlist
256
+
257
+ Returns
258
+ -------
259
+ bool: Returns true if success
260
+
261
+ """
262
+ return self.private_request('video_playlist_rename',
263
+ params=f'type=video&id={id}&name={name}',
264
+ need_login=True).json()['success']
265
+
266
+ def add_to_video_playlist(self, id: str, video_id: Union[int, str]) -> bool:
267
+ """
268
+ Add a video to your video playlist
269
+
270
+ Arguments
271
+ ----------
272
+ id: An id of video playlist
273
+ video_id: A digit id of Video
274
+
275
+ Returns
276
+ -------
277
+ bool: Returns false if video had been added already
278
+
279
+ """
280
+ videos = self.get_video_playlist_by_id(id).videos
281
+ for vid in videos:
282
+ if vid.id == video_id:
283
+ return False
284
+
285
+ return self.private_request('video_playlist_add',
286
+ params=f'type=video&video={video_id}&id={id}',
287
+ need_login=True).json()['success']
288
+
289
+ def remove_from_video_playlist(self, id: str, video_id: Union[int, str]) -> bool:
290
+ """
291
+ Remove a video from your video playlist
292
+
293
+ Arguments
294
+ ----------
295
+ id: An id of video playlist
296
+ video_id: A digit id of Video
297
+
298
+ Returns
299
+ -------
300
+ bool: Returns false if video hadn't been added before
301
+
302
+ """
303
+ videos = self.get_video_playlist_by_id(id).videos
304
+ for vid in videos:
305
+ if vid.id == video_id:
306
+ return self.private_request('video_playlist_item_remove',
307
+ params=f'type=video&id={id}&item={vid.item}',
308
+ need_login=True).json()['success']
309
+ return False
310
+
311
+
312
+
@@ -0,0 +1,74 @@
1
+ from radiojavanapi.mixins.private import PrivateRequest
2
+ from radiojavanapi.extractors import extract_podcast
3
+ from radiojavanapi.models import Podcast
4
+ from radiojavanapi.helper import url_to_id
5
+
6
+ from typing import Union
7
+ from pydantic import HttpUrl
8
+
9
+ class PodcastMixin(PrivateRequest):
10
+ LIKE_ENDPOINT = 'podcast_vote'
11
+ TYPE = 'podcast'
12
+
13
+ def get_podcast_by_url(self, url: HttpUrl) -> Podcast:
14
+ """
15
+ Get podcast info by site url (e.g. `play.radiojavan.com/podcast/...` or `play.radiojavan.com/redirect?r=radiojavan://podcast/...`)
16
+
17
+ Arguments
18
+ ----------
19
+ url: Site url of podcast
20
+
21
+ Returns
22
+ -------
23
+ Podcast: An object of Podcast type
24
+
25
+ """
26
+ return self.get_podcast_by_id(url_to_id(url))
27
+
28
+ def get_podcast_by_id(self, id: Union[int, str]) -> Podcast:
29
+ """
30
+ Get podcast info by id
31
+
32
+ Arguments
33
+ ----------
34
+ id: Unique id of podcast
35
+
36
+ Returns
37
+ -------
38
+ Podcast: An object of Podcast type
39
+
40
+ """
41
+ response = self.private_request('podcast',
42
+ params=f'id={id}').json()
43
+ return extract_podcast(response)
44
+
45
+ def like_podcast(self, podcast_id: Union[int, str]) -> bool:
46
+ """
47
+ Like a podcast
48
+
49
+ Arguments
50
+ ----------
51
+ podcast_id: A digit id of podcast
52
+
53
+ Returns
54
+ -------
55
+ bool: Returns false if podcast had been liked already
56
+
57
+ """
58
+ return PodcastMixin.__like__(self, podcast_id)
59
+
60
+ def unlike_podcast(self, podcast_id: Union[int, str]) -> bool:
61
+ """
62
+ UnLike a podcast
63
+
64
+ Arguments
65
+ ----------
66
+ podcast_id: A digit id of podcast
67
+
68
+ Returns
69
+ -------
70
+ bool: Returns false if podcast hadn't been liked before
71
+
72
+ """
73
+ return PodcastMixin.__unlike__(self, podcast_id)
74
+
@@ -0,0 +1,109 @@
1
+ from radiojavanapi.constants import API_DOMAIN, BASE_HEADERS
2
+ from radiojavanapi.exceptions import (
3
+ BadCredentials, ClientJSONDecodeError, ClientConnectionError, DuplicatePassword,
4
+ EmailExists, ClientLoginRequired, InvalidEmail, LongString, InvalidName, DuplicateName,
5
+ UnknownError, UsernameExists, ClientLoginRequired, InvalidMediaId
6
+ )
7
+
8
+ import requests
9
+ from json.decoder import JSONDecodeError
10
+ from requests_toolbelt.multipart.encoder import MultipartEncoder
11
+
12
+ class PrivateRequest():
13
+ def __init__(self) -> None:
14
+ self.private = requests.Session()
15
+ self.private.headers = BASE_HEADERS
16
+ self.authorized = False
17
+ self.email = None
18
+ self.password = None
19
+
20
+ def private_request(self,endpoint,data=None,json=None,fields=None,
21
+ params=None,headers=None,need_login=False):
22
+ if need_login and not self.authorized:
23
+ raise ClientLoginRequired("to use this method, you need to login first.")
24
+
25
+ if headers:
26
+ self.private.headers.update(headers)
27
+
28
+ response = None
29
+ try:
30
+ if data:
31
+ response = self.private.post(API_DOMAIN.format(endpoint), data=data, params=params)
32
+ elif json:
33
+ response = self.private.post(API_DOMAIN.format(endpoint), json=json, params=params)
34
+ elif fields:
35
+ multipart_data = MultipartEncoder(fields=fields)
36
+ response = self.private.post(API_DOMAIN.format(endpoint), data=multipart_data,
37
+ headers={
38
+ **{'Content-Type': multipart_data.content_type},
39
+ **self.private.headers
40
+ }
41
+ )
42
+ else:
43
+ response = self.private.get(API_DOMAIN.format(endpoint), params=params)
44
+
45
+ except requests.exceptions.RequestException:
46
+ raise ClientConnectionError()
47
+
48
+ except Exception as e: # TO DO
49
+ raise UnknownError(e)
50
+
51
+ response_json = None
52
+ try:
53
+ response_json = response.json()
54
+ except JSONDecodeError as e:
55
+ raise ClientJSONDecodeError(f"JSONDecodeError {e} while opening {response.url}")
56
+
57
+ if isinstance(response_json, dict) and response_json.get('success') == False and 'user_subscription' not in response.url:
58
+ msg = response_json.get('msg')
59
+ if msg:
60
+ if 'is too long' in msg:
61
+ raise LongString(msg)
62
+ elif 'Invalid email' in msg or 'The email or password doesn\'t look right' in msg:
63
+ raise BadCredentials(msg)
64
+ elif 'only contain letters' in msg:
65
+ raise InvalidName(msg)
66
+ elif 'already have that email' in msg:
67
+ raise EmailExists(msg)
68
+ elif 'username is not available' in msg:
69
+ raise UsernameExists(msg)
70
+ elif 'Name already exists.' == msg:
71
+ raise DuplicateName('Playlist with this name already exists.')
72
+ elif 'Playlist with this name already exists.' == msg:
73
+ raise DuplicateName(msg)
74
+ elif 'new password cannot be the same' in msg:
75
+ raise DuplicatePassword(msg)
76
+ elif 'need a valid email' in msg:
77
+ raise InvalidEmail(msg)
78
+ else: # TO DO
79
+ raise UnknownError(msg)
80
+
81
+ elif len(response_json) == 1:
82
+ raise InvalidMediaId(f"An invalid media is was provided.")
83
+ else:
84
+ raise UnknownError(response_json)
85
+
86
+ return response
87
+
88
+ #### these are for like song/video/podcast/story:
89
+ @classmethod
90
+ def __like__(cls, self, id):
91
+ if 'vote' in cls.__toggle_like__(self, id):
92
+ return True
93
+ else:
94
+ cls.__toggle_like__(self, id)
95
+ return False
96
+
97
+ @classmethod
98
+ def __unlike__(cls, self, id):
99
+ if 'vote' in cls.__toggle_like__(self, id):
100
+ cls.__toggle_like__(self, id)
101
+ return False
102
+ else:
103
+ return True
104
+
105
+ @classmethod
106
+ def __toggle_like__(cls, self, id):
107
+ return self.private_request(cls.LIKE_ENDPOINT,
108
+ params=f'id={id}&type={cls.TYPE}&vote=5&remove=1',
109
+ need_login=True).json()