-
Notifications
You must be signed in to change notification settings - Fork 50
/
qqmusic.php
executable file
·368 lines (312 loc) · 12.3 KB
/
qqmusic.php
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<?php
// Must set to false when running on DS Station
const DEBUG = true;
// Set to TURE is Chinese translation is needed
const NEED_TRANSLATION = true;
/**
* Implements the functions required by Audio Station/DSAudio.
* <p>
* Features:
* - Sort result according to similarity of artist and title.
* - Add Chinese translated lyric if {@code NEED_TRANSLATION} is {@code TRUE}.
*
* @author PsychoPass (https://github.com/psychopasss/Synology-Lrc-Plugin-For-QQ-Music)
* @see https://global.download.synology.com/download/Document/DeveloperGuide/AS_Guide.pdf
*/
class QQLrc {
private $mArtist = "";
private $mTitle = "";
public $mOriginTitle = "";
///////////////////////////// Synology API ///////////////////////////////////////
/**
* Searches for a song with the artist and title, and returns the matching result list. Result is sorted based on similarity of artist and title.
*/
public function getLyricsList($artist, $title, $info) {
$this->mOriginTitle = $title;
$artist = trim($artist);
$title = trim($title);
$this->mArtist = $artist;
$this->mTitle = $title;
if ($this->isNullOrEmptyString($title)) {
return 0;
}
$response = $this->search($title);
if ($this->isNullOrEmptyString($response)) {
return 0;
}
$json = json_decode($response, true);
$songArray = $json['data']['song']['itemlist'];
// var_dump($songArray);
if(count($songArray) == 0) {
return 0;
}
// Try to find the titles that match exactly
$exactMatchArray = array();
$partialMatchArray = array();
foreach ($songArray as $song) {
$lowTitle = strtolower($title);
// var_dump("源歌名:".$lowTitle);
$lowResult = strtolower($song['name']);
// var_dump("匹配歌名:".$lowResult."<br>");
if (strtolower($lowTitle) === strtolower($lowResult)) {
array_push($exactMatchArray, $song);
} else if (strpos($lowResult, $lowTitle) !== FALSE || strpos($lowTitle, $lowResult) !== FALSE) {
array_push($partialMatchArray, $song);
}
}
if (count($exactMatchArray) != 0) {
$songArray = $exactMatchArray;
} else if (count($partialMatchArray) != 0) {
$songArray = $partialMatchArray;
}
// Get information from songs
$foundArray = array();
foreach ($songArray as $song) {
$elem = array(
'id' => key_exists('id',$song)?$song['id']:'',
'artist' => key_exists('singer',$song)?$song['singer']:'',
'title' => key_exists('name',$song)?$song['name']:'',
'alt' => key_exists('alias',$song)?$song['alias'][0] . "; ":''
);
// Find the best match artist from all artists belong to a song
$max = 0;
foreach ($song['singer'] as $item) {
$score = $this->getStringSimilarity($artist, $item['name']);
if ($score > $max) {
$max = $score;
$elem['artist'] = $item['name'];
}
}
array_push($foundArray, $elem);
}
// Sort by best match according to similarity of artist and title
usort($foundArray, array($this,'cmp'));
foreach ($foundArray as $song) {
// add artist, title, id, lrc preview (or additional comment)
$info->addTrackInfoToList($song['artist'], $song['title'], $song['id'], $song['id'] . "; " . $song['alt']);
}
return count($foundArray);
}
/**
* Downloads a lyric with the specific ID. Will have Chinese translation if {@code NEED_TRANSLATION} is {@code TRUE}.
*/
public function getLyrics($id, $info) {
$lrc = $this->downloadLyric($id);
if ($this->isNullOrEmptyString($lrc)) {
return FALSE;
}
$info->addLyrics($lrc, $id);
// save lrc file
// $myfile = fopen($this->mOriginTitle.".lrc","w");
// fwrite($myfile, $lrc);
return true;
}
///////////////////////////// Utils ///////////////////////////////////////
/**
* Gets all lyrics, apart from original one, translated and karaoke versions will also be returned if available.
*/
private function downloadLyric($music_id) {
$response = $this->download($music_id);
if ($this->isNullOrEmptyString($response)) {
return NULL;
}
$json = json_decode($response, true);
$orgLrc = $json['lyric'];
$transLrc = $json['trans']; // Chinese translation lyric, but only some songs have
$resultLrc = $orgLrc;
if (NEED_TRANSLATION && !$this->isNullOrEmptyString($transLrc)) {
$resultLrc = "";
$orgLines = $this->processLrcLine($orgLrc);
$transLines = $this->processLrcLine($transLrc);
$transCursor = 0;
foreach ($orgLines as $elem) {
$key = $elem['tag']; // time tag
$value = $elem['lrc']; // lyric line
$resultLrc .= $key . $value;
// Find matching translation
$trans = "";
// error_log("key=".$key);
if (!$this->isNullOrEmptyString($key)) {
$time = $this->getTimeFromTag($key);
for ($i = $transCursor; $i < count($transLines); $i++) {
$tKey = $transLines[$i]['tag'];
// error_log(json_encode($transLines[$i]));
// error_log("tKey=".$tKey);
if ($this->getTimeFromTag($tKey) > $time) { // trans time tag is greater than org, no match found
$transCursor = $i;
break;
}
$tValue = $transLines[$i]['lrc'];
// Check for matching time tag
if ($key === $tKey) {
$transCursor = $i + 1;
$trans = $tValue;
break;
}
}
} else {
$transCursor++;
}
if (!$this->isNullOrEmptyString($trans)) { // $key is empty when it's not time tag, just metadata
$resultLrc .= "\n".$key.$trans;
}
$resultLrc .= "\n";
}
}
// return $resultLrc;
$r = html_entity_decode($resultLrc, ENT_QUOTES | ENT_HTML5);
return $r;
}
// Comparator that determines which matches better
private function cmp($lhs, $rhs) {
$scoreArtistL = $this->getStringSimilarity($this->mArtist, $lhs['artist']);
$scoreArtistR = $this->getStringSimilarity($this->mArtist, $rhs['artist']);
$scoreTitleL = $this->getStringSimilarity($this->mTitle, $lhs['title']);
$scoreTitleR = $this->getStringSimilarity($this->mTitle, $rhs['title']);
// printf("artist " . $lhs['artist'] . " vs " . $rhs['artist'] . " | " . $scoreArtistL . " vs " . $scoreArtistR . "</br>");
// printf("title " . $lhs['title'] . " vs " . $rhs['title'] . " | " . $scoreTitleL . " vs " . $scoreTitleR. "</br>");
return $scoreArtistR + $scoreTitleR - $scoreArtistL - $scoreTitleL;
}
/**
* Gets similarity score of 0-100 between 2 strings, the bigger the score is, the more similarity.
*/
private static function getStringSimilarity($lhs, $rhs) {
similar_text($lhs, $rhs, $percent);
return $percent;
}
private function getTimeFromTag($tag) {
$min = substr($tag, 1, 2);
$sec = substr($tag, 4, 2);
$milli = substr($tag, 7, 2);
return $milli + $sec * 100 + $min * 60 * 100;
}
private function processLrcLine($lrc) {
$result = array();
foreach (explode("\n", $lrc) as $line) {
$key = substr($line, 0, 10);
$value = substr($line, 10, strlen($line) - 10);
if (!$this->isValidLrcTime($key)) {
$key = "";
$value = $line;
}
array_push($result, array(
'tag' => $key,
'lrc' => $value=='//'?'':$value
));
}
return $result;
}
private function isValidLrcTime($str) {
if ($this->isNullOrEmptyString($str) || strlen($str) != 10 || $str[0] !== "[" || $str[9] != "]") {
return FALSE;
}
for ($count = 1; $count < 9; $count++) {
$ch = $str[$count];
if ($ch !== ":" && $ch !== "." && !is_numeric($ch)) {
return FALSE;
}
}
return TRUE;
}
// Function for basic field validation (present and neither empty nor only white space
private static function isNullOrEmptyString($question){
return (!isset($question) || trim($question)==='');
}
///////////////////////////// QQ-Music API ///////////////////////////////////////
/**
* Searches for a song based on title.
*/
private static function search($word) {
$params = array(
'key' => $word,
'format' => 'json',
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => "https://c.y.qq.com/splcloud/fcgi-bin/smartbox_new.fcg?".http_build_query($params)
));
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
/**
* Downloads a lyric for a given music_id.
*/
private static function download($music_id) {
$url = "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?nobase64=1&g_tk=5381&musicid=" . $music_id . "&format=json";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array(
"Referer: http://y.qq.com/"
),
CURLOPT_RETURNTRANSFER => true
));
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
} // End of class
////////////////////////// DEBUG ////////////////////////////////////
if (DEBUG == true) {
class TestObj {
private $items;
function __construct() {
$this->items = array();
}
public function addLyrics($lyric, $id) {
printf("</br>");
printf("song id: %s\n", $id);
printf("</br>\n");
printf("== lyric ==\n");
printf("%s\n", $lyric);
printf("** END of lyric **\n\n");
}
public function addTrackInfoToList($artist, $title, $id, $prefix) {
printf("</br>\n");
printf("song id: %s\n", $id);
printf("artist [%s]\n", $artist);
printf("title [%s]\n", $title);
printf("prefix [%s]\n", $prefix);
printf("</br>\n");
array_push($this->items, array(
'artist' => $artist,
'title' => $title,
'id' => $id
));
}
function getItems() {
return $this->items;
}
function getFirstItem() {
if (count($this->items) > 0) {
return $this->items[0];
} else {
return NULL;
}
}
}
/**
* Main
*/
$title = "封茗囧菌 - マインドブランド";
$artist = "";
echo "Trying to find lyrics for ['$title'] by artist ['$artist'] ...</br>\n";
$testObj = new TestObj();
$downloader = (new ReflectionClass("QQLrc"))->newInstance();
$count = $downloader->getLyricsList($artist, $title, $testObj);
if ($count > 0) {
$item = $testObj->getFirstItem();
if (array_key_exists('id', $item)) {
$downloader->mOriginTitle = $title;
$downloader->getLyrics($item['id'], $testObj);
} else {
echo "\nno id to query lyric\n";
}
} else {
echo " ****************************\n";
echo " *** Failed to find lyric ***\n";
echo " ****************************\n";
}
}