/
ApiController.php
1503 lines (1283 loc) · 60.9 KB
/
ApiController.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
class ApiController extends Zend_Controller_Action
{
public function init()
{
$ignoreAuth = array("live-info",
"live-info-v2",
"week-info",
"station-metadata",
"station-logo",
"show-history-feed",
"item-history-feed",
"shows",
"show-tracks",
"show-schedules"
);
$params = $this->getRequest()->getParams();
if (!in_array($params['action'], $ignoreAuth)) {
$this->checkAuth();
}
/* Initialize action controller here */
$context = $this->_helper->getHelper('contextSwitch');
$context->addActionContext('version' , 'json')
->addActionContext('recorded-shows' , 'json')
->addActionContext('calendar-init' , 'json')
->addActionContext('upload-file' , 'json')
->addActionContext('upload-recorded' , 'json')
->addActionContext('media-monitor-setup' , 'json')
->addActionContext('media-item-status' , 'json')
->addActionContext('reload-metadata' , 'json')
->addActionContext('list-all-files' , 'json')
->addActionContext('list-all-watched-dirs' , 'json')
->addActionContext('add-watched-dir' , 'json')
->addActionContext('remove-watched-dir' , 'json')
->addActionContext('set-storage-dir' , 'json')
->addActionContext('get-stream-setting' , 'json')
->addActionContext('status' , 'json')
->addActionContext('register-component' , 'json')
->addActionContext('update-liquidsoap-status' , 'json')
->addActionContext('live-chat' , 'json')
->addActionContext('update-file-system-mount' , 'json')
->addActionContext('handle-watched-dir-missing' , 'json')
->addActionContext('rabbitmq-do-push' , 'json')
->addActionContext('check-live-stream-auth' , 'json')
->addActionContext('update-source-status' , 'json')
->addActionContext('get-bootstrap-info' , 'json')
->addActionContext('get-files-without-replay-gain' , 'json')
->addActionContext('get-files-without-silan-value' , 'json')
->addActionContext('reload-metadata-group' , 'json')
->addActionContext('notify-webstream-data' , 'json')
->addActionContext('get-stream-parameters' , 'json')
->addActionContext('push-stream-stats' , 'json')
->addActionContext('update-stream-setting-table' , 'json')
->addActionContext('update-replay-gain-value' , 'json')
->addActionContext('update-cue-values-by-silan' , 'json')
->initContext();
}
public function checkAuth()
{
$CC_CONFIG = Config::getConfig();
$api_key = $this->_getParam('api_key');
if (!in_array($api_key, $CC_CONFIG["apiKey"]) &&
is_null(Zend_Auth::getInstance()->getStorage()->read())) {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource.');
exit;
}
}
public function versionAction()
{
$this->_helper->json->sendJson( array(
"airtime_version" => Application_Model_Preference::GetAirtimeVersion(),
"api_version" => AIRTIME_API_VERSION));
}
/**
* Allows remote client to download requested media file.
*
* @return void
*
*/
public function getMediaAction()
{
$fileId = $this->_getParam("file");
$media = Application_Model_StoredFile::RecallById($fileId);
if ($media != null) {
$filepath = $media->getFilePath();
// Make sure we don't have some wrong result beecause of caching
clearstatcache();
if (is_file($filepath)) {
$full_path = $media->getPropelOrm()->getDbFilepath();
$file_base_name = strrchr($full_path, '/');
/* If $full_path does not contain a '/', strrchr will return false,
* in which case we can use $full_path as the base name.
*/
if (!$file_base_name) {
$file_base_name = $full_path;
} else {
$file_base_name = substr($file_base_name, 1);
}
//Download user left clicks a track and selects Download.
if ("true" == $this->_getParam('download')) {
//path_info breaks up a file path into seperate pieces of informaiton.
//We just want the basename which is the file name with the path
//information stripped away. We are using Content-Disposition to specify
//to the browser what name the file should be saved as.
header('Content-Disposition: attachment; filename="'.$file_base_name.'"');
} else {
//user clicks play button for track and downloads it.
header('Content-Disposition: inline; filename="'.$file_base_name.'"');
}
$this->smartReadFile($filepath, $media->getPropelOrm()->getDbMime());
exit;
} else {
header ("HTTP/1.1 404 Not Found");
}
}
$this->_helper->json->sendJson(array());
}
/**
* Reads the requested portion of a file and sends its contents to the client with the appropriate headers.
*
* This HTTP_RANGE compatible read file function is necessary for allowing streaming media to be skipped around in.
*
* @param string $location
* @param string $mimeType
* @return void
*
* @link https://groups.google.com/d/msg/jplayer/nSM2UmnSKKA/Hu76jDZS4xcJ
* @link http://php.net/manual/en/function.readfile.php#86244
*/
public function smartReadFile($location, $mimeType = 'audio/mp3')
{
$size= filesize($location);
$time= date('r', filemtime($location));
$fm = @fopen($location, 'rb');
if (!$fm) {
header ("HTTP/1.1 505 Internal server error");
return;
}
$begin = 0;
$end = $size - 1;
if (isset($_SERVER['HTTP_RANGE'])) {
if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
$begin = intval($matches[1]);
if (!empty($matches[2])) {
$end = intval($matches[2]);
}
}
}
if (isset($_SERVER['HTTP_RANGE'])) {
header('HTTP/1.1 206 Partial Content');
} else {
header('HTTP/1.1 200 OK');
}
header("Content-Type: $mimeType");
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Accept-Ranges: bytes');
header('Content-Length:' . (($end - $begin) + 1));
if (isset($_SERVER['HTTP_RANGE'])) {
header("Content-Range: bytes $begin-$end/$size");
}
header("Content-Transfer-Encoding: binary");
header("Last-Modified: $time");
//We can have multiple levels of output buffering. Need to
//keep looping until all have been disabled!!!
//http://www.php.net/manual/en/function.ob-end-flush.php
while (@ob_end_flush());
$cur = $begin;
fseek($fm, $begin, 0);
while (!feof($fm) && $cur <= $end && (connection_status() == 0)) {
echo fread($fm, min(1024 * 16, ($end - $cur) + 1));
$cur += 1024 * 16;
}
}
//Used by the SaaS monitoring
public function onAirLightAction()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$result = array();
$result["on_air_light"] = false;
$result["on_air_light_expected_status"] = false;
$result["station_down"] = false;
$range = Application_Model_Schedule::GetPlayOrderRange();
$isItemCurrentlyScheduled = !is_null($range["current"]) && count($range["currentShow"]) > 0 ? true : false;
$isCurrentItemPlaying = $range["current"]["media_item_played"] ? true : false;
if ($isItemCurrentlyScheduled ||
Application_Model_Preference::GetSourceSwitchStatus("live_dj") == "on" ||
Application_Model_Preference::GetSourceSwitchStatus("master_dj") == "on")
{
$result["on_air_light_expected_status"] = true;
}
if (($isItemCurrentlyScheduled && $isCurrentItemPlaying) ||
Application_Model_Preference::GetSourceSwitchStatus("live_dj") == "on" ||
Application_Model_Preference::GetSourceSwitchStatus("master_dj") == "on")
{
$result["on_air_light"] = true;
}
if ($result["on_air_light_expected_status"] != $result["on_air_light"]) {
$result["station_down"] = true;
}
echo isset($_GET['callback']) ? $_GET['callback'].'('.json_encode($result).')' : json_encode($result);
}
/**
* Retrieve the currently playing show as well as upcoming shows.
* Number of shows returned and the time interval in which to
* get the next shows can be configured as GET parameters.
*
* TODO: in the future, make interval length a parameter instead of hardcode to 48
*
* Possible parameters:
* type - Can have values of "endofday" or "interval". If set to "endofday",
* the function will retrieve shows from now to end of day.
* If set to "interval", shows in the next 48 hours will be retrived.
* Default is "interval".
* limit - How many shows to retrieve
* Default is "5".
*/
public function liveInfoAction()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$request = $this->getRequest();
$utcTimeNow = gmdate("Y-m-d H:i:s");
$utcTimeEnd = ""; // if empty, getNextShows will use interval instead of end of day
// default to the station timezone
$timezone = Application_Model_Preference::GetDefaultTimezone();
$userDefinedTimezone = strtolower($request->getParam('timezone'));
$upcase = false; // only upcase the timezone abbreviations
$this->checkTimezone($userDefinedTimezone, $timezone, $upcase);
$type = $request->getParam('type');
$limit = $request->getParam('limit');
if ($limit == "" || !is_numeric($limit)) {
$limit = "5";
}
/* This is some *extremely* lazy programming that needs to be fixed. For some reason
* we are using two entirely different codepaths for very similar functionality (type = endofday
* vs type = interval). Needs to be fixed for 2.3 - MK */
if ($type == "endofday") {
// make getNextShows use end of day
$end = Application_Common_DateHelper::getTodayStationEndDateTime();
$end->setTimezone(new DateTimeZone("UTC"));
$utcTimeEnd = $end->format("Y-m-d H:i:s");
$result = array(
"env" => APPLICATION_ENV,
"schedulerTime" => $utcTimeNow,
"currentShow" => Application_Model_Show::getCurrentShow($utcTimeNow),
"nextShow" => Application_Model_Show::getNextShows($utcTimeNow, $limit, $utcTimeEnd)
);
} else {
$result = Application_Model_Schedule::GetPlayOrderRangeOld($limit);
}
// XSS exploit prevention
$this->convertSpecialChars($result, array("name", "url"));
// apply user-defined timezone, or default to station
Application_Common_DateHelper::convertTimestampsToTimezone(
$result['currentShow'],
array("starts", "ends", "start_timestamp","end_timestamp"),
$timezone
);
Application_Common_DateHelper::convertTimestampsToTimezone(
$result['nextShow'],
array("starts", "ends", "start_timestamp","end_timestamp"),
$timezone
);
//Convert the UTC scheduler time ("now") to the user-defined timezone.
$result["schedulerTime"] = Application_Common_DateHelper::UTCStringToTimezoneString($result["schedulerTime"], $timezone);
$result["timezone"] = $upcase ? strtoupper($timezone) : $timezone;
$result["timezoneOffset"] = Application_Common_DateHelper::getTimezoneOffset($timezone);
// used by caller to determine if the airtime they are running or widgets in use is out of date.
$result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION;
header("Content-Type: application/json");
if (version_compare(phpversion(), '5.4.0', '<')) {
$js = json_encode($result);
} else {
$js = json_encode($result, JSON_PRETTY_PRINT);
}
// If a callback is not given, then just provide the raw JSON.
echo isset($_GET['callback']) ? $_GET['callback'].'('.$js.')' : $js;
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
/**
* Retrieve the currently playing show as well as upcoming shows.
* Number of shows returned and the time interval in which to
* get the next shows can be configured as GET parameters.
*
* Possible parameters:
* days - How many days to retrieve.
* Default is 2 (today + tomorrow).
* shows - How many shows to retrieve
* Default is 5.
* timezone - The timezone to send the times in
* Defaults to the station timezone
*/
public function liveInfoV2Action()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$request = $this->getRequest();
$utcTimeNow = gmdate("Y-m-d H:i:s");
$utcTimeEnd = ""; // if empty, getNextShows will use interval instead of end of day
// default to the station timezone
$timezone = Application_Model_Preference::GetDefaultTimezone();
$userDefinedTimezone = strtolower($request->getParam('timezone'));
$upcase = false; // only upcase the timezone abbreviations
$this->checkTimezone($userDefinedTimezone, $timezone, $upcase);
$daysToRetrieve = $request->getParam('days');
$showsToRetrieve = $request->getParam('shows');
if ($daysToRetrieve == "" || !is_numeric($daysToRetrieve)) {
$daysToRetrieve = "2";
}
if ($showsToRetrieve == "" || !is_numeric($showsToRetrieve)) {
$showsToRetrieve = "5";
}
// set the end time to the day's start n days from now.
// days=1 will return shows until the end of the current day,
// days=2 will return shows until the end of tomorrow, etc.
$end = Application_Common_DateHelper::getEndDateTime($timezone, $daysToRetrieve);
$end->setTimezone(new DateTimeZone("UTC"));
$utcTimeEnd = $end->format("Y-m-d H:i:s");
$result = Application_Model_Schedule::GetPlayOrderRange($utcTimeEnd, $showsToRetrieve);
// XSS exploit prevention
$this->convertSpecialChars($result, array("name", "url"));
// apply user-defined timezone, or default to station
$this->applyLiveTimezoneAdjustments($result, $timezone, $upcase);
// used by caller to determine if the airtime they are running or widgets in use is out of date.
$result["station"]["AIRTIME_API_VERSION"] = AIRTIME_API_VERSION;
header("Content-Type: application/json");
if (version_compare(phpversion(), '5.4.0', '<')) {
$js = json_encode($result);
} else {
$js = json_encode($result, JSON_PRETTY_PRINT);
}
// If a callback is not given, then just provide the raw JSON.
echo isset($_GET['callback']) ? $_GET['callback'].'('.$js.')' : $js;
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
/**
* Check that the value for the timezone the user gave is valid.
* If it is, override the default (station) timezone.
* If it's an abbreviation (pst, edt) we upcase the output.
*
* @param string $userDefinedTimezone the requested timezone value
* @param string $timezone the default timezone
* @param boolean $upcase whether the timezone output should be upcased
*/
private function checkTimezone($userDefinedTimezone, &$timezone, &$upcase)
{
$delimiter = "/";
// if the user passes in a timezone in standard form ("Continent/City")
// we need to fix the downcased string by upcasing each word delimited by a /
if (strpos($userDefinedTimezone, $delimiter) !== false) {
$userDefinedTimezone = implode($delimiter, array_map('ucfirst', explode($delimiter, $userDefinedTimezone)));
}
// if the timezone defined by the user exists, use that
if (array_key_exists($userDefinedTimezone, timezone_abbreviations_list())) {
$timezone = $userDefinedTimezone;
$upcase = true;
} else if (in_array($userDefinedTimezone, timezone_identifiers_list())) {
$timezone = $userDefinedTimezone;
}
}
/**
* If the user passed in a timezone parameter, adjust timezone-dependent
* variables in the result to reflect the given timezone.
*
* @param object $result reference to the object to send back to the user
* @param string $timezone the user's timezone parameter value
* @param boolean $upcase whether the timezone output should be upcased
*/
private function applyLiveTimezoneAdjustments(&$result, $timezone, $upcase)
{
Application_Common_DateHelper::convertTimestampsToTimezone(
$result,
array("starts", "ends", "start_timestamp","end_timestamp"),
$timezone
);
//Convert the UTC scheduler time ("now") to the user-defined timezone.
$result["station"]["schedulerTime"] = Application_Common_DateHelper::UTCStringToTimezoneString($result["station"]["schedulerTime"], $timezone);
$result["station"]["timezone"] = $upcase ? strtoupper($timezone) : $timezone;
}
public function weekInfoAction()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
//weekStart is in station time.
$weekStartDateTime = Application_Common_DateHelper::getWeekStartDateTime();
$dow = array("monday", "tuesday", "wednesday", "thursday", "friday",
"saturday", "sunday", "nextmonday", "nexttuesday", "nextwednesday",
"nextthursday", "nextfriday", "nextsaturday", "nextsunday");
$result = array();
// default to the station timezone
$timezone = Application_Model_Preference::GetDefaultTimezone();
$userDefinedTimezone = strtolower($this->getRequest()->getParam("timezone"));
// if the timezone defined by the user exists, use that
if (array_key_exists($userDefinedTimezone, timezone_abbreviations_list())) {
$timezone = $userDefinedTimezone;
}
$utcTimezone = new DateTimeZone("UTC");
$weekStartDateTime->setTimezone($utcTimezone);
$utcDayStart = $weekStartDateTime->format("Y-m-d H:i:s");
for ($i = 0; $i < 14; $i++) {
//have to be in station timezone when adding 1 day for daylight savings.
$weekStartDateTime->setTimezone(new DateTimeZone($timezone));
$weekStartDateTime->add(new DateInterval('P1D'));
//convert back to UTC to get the actual timestamp used for search.
$weekStartDateTime->setTimezone($utcTimezone);
$utcDayEnd = $weekStartDateTime->format("Y-m-d H:i:s");
$shows = Application_Model_Show::getNextShows($utcDayStart, "ALL", $utcDayEnd);
$utcDayStart = $utcDayEnd;
// convert to user-defined timezone, or default to station
Application_Common_DateHelper::convertTimestampsToTimezone(
$shows,
array("starts", "ends", "start_timestamp","end_timestamp"),
$timezone
);
$result[$dow[$i]] = $shows;
}
// XSS exploit prevention
$this->convertSpecialChars($result, array("name", "url"));
//used by caller to determine if the airtime they are running or widgets in use is out of date.
$result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION;
header("Content-type: text/javascript");
$js = json_encode($result, JSON_PRETTY_PRINT);
// If a callback is not given, then just provide the raw JSON.
echo isset($_GET['callback']) ? $_GET['callback'].'('.$js.')' : $js;
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
public function scheduleAction()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
header("Content-Type: application/json");
$data = Application_Model_Schedule::getSchedule();
echo json_encode($data, JSON_FORCE_OBJECT);
}
public function notifyMediaItemStartPlayAction()
{
$media_id = $this->_getParam("media_id");
Logging::debug("Received notification of new media item start: $media_id");
Application_Model_Schedule::UpdateMediaPlayedStatus($media_id);
try {
$historyService = new Application_Service_HistoryService();
$historyService->insertPlayedItem($media_id);
//set a 'last played' timestamp for media item
//needed for smart blocks
$mediaType = Application_Model_Schedule::GetType($media_id);
if ($mediaType == 'file') {
$file_id = Application_Model_Schedule::GetFileId($media_id);
if (!is_null($file_id)) {
//we are dealing with a file not a stream
$file = Application_Model_StoredFile::RecallById($file_id);
$now = new DateTime("now", new DateTimeZone("UTC"));
$file->setLastPlayedTime($now);
}
} else {
// webstream
$stream_id = Application_Model_Schedule::GetStreamId($media_id);
if (!is_null($stream_id)) {
$webStream = new Application_Model_Webstream($stream_id);
$now = new DateTime("now", new DateTimeZone("UTC"));
$webStream->setLastPlayed($now);
}
}
} catch (Exception $e) {
Logging::info($e);
}
$this->_helper->json->sendJson(array("status"=>1, "message"=>""));
}
/**
* Go through a given array and sanitize any potentially exploitable fields
* by passing them through htmlspecialchars
*
* @param unknown $arr the array to sanitize
* @param unknown $keys indexes of values to be sanitized
*/
private function convertSpecialChars(&$arr, $keys)
{
foreach ($arr as &$a) {
if (is_array($a)) {
foreach ($keys as &$key) {
if (array_key_exists($key, $a)) {
$a[$key] = htmlspecialchars($a[$key]);
}
}
$this->convertSpecialChars($a, $keys);
}
}
}
/**
* API endpoint to provide station metadata
*/
public function stationMetadataAction()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$CC_CONFIG = Config::getConfig();
$baseDir = Application_Common_OsPath::formatDirectoryWithDirectorySeparators($CC_CONFIG['baseDir']);
$path = 'http://'.$_SERVER['HTTP_HOST'].$baseDir."api/station-logo";
$result["name"] = Application_Model_Preference::GetStationName();
$result["logo"] = $path;
$result["description"] = Application_Model_Preference::GetStationDescription();
$result["timezone"] = Application_Model_Preference::GetDefaultTimezone();
$result["locale"] = Application_Model_Preference::GetDefaultLocale();
// used by caller to determine if the airtime they are running or widgets in use is out of date.
$result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION;
header("Content-type: text/javascript");
$js = json_encode($result, JSON_PRETTY_PRINT);
// If a callback is not given, then just provide the raw JSON.
echo isset($_GET['callback']) ? $_GET['callback'].'('.$js.')' : $js;
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
/**
* API endpoint to display the current station logo
*/
public function stationLogoAction()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$logo = Application_Model_Preference::GetStationLogo();
// if there's no logo, just die - redirects to a 404
if (!$logo || $logo === '') {
return;
}
// we're passing this as an image instead of using it in a data uri, so decode it
$blob = base64_decode($logo);
// use finfo to get the mimetype from the decoded blob
$f = finfo_open();
$mime_type = finfo_buffer($f, $blob, FILEINFO_MIME_TYPE);
finfo_close($f);
header("Content-type: " . $mime_type);
echo $blob;
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
public function recordedShowsAction()
{
$utcTimezone = new DateTimeZone("UTC");
$nowDateTime = new DateTime("now", $utcTimezone);
$endDateTime = clone $nowDateTime;
$endDateTime = $endDateTime->add(new DateInterval("PT2H"));
$this->view->shows =
Application_Model_Show::getShows(
$nowDateTime,
$endDateTime,
$onlyRecord = true);
$this->view->is_recording = false;
$this->view->server_timezone = Application_Model_Preference::GetDefaultTimezone();
$rows = Application_Model_Show::getCurrentShow();
if (count($rows) > 0) {
$this->view->is_recording = ($rows[0]['record'] == 1);
}
}
public function uploadFileAction()
{
$upload_dir = ini_get("upload_tmp_dir");
$tempFilePath = Application_Model_StoredFile::uploadFile($upload_dir);
$tempFileName = basename($tempFilePath);
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
$result = Application_Model_StoredFile::copyFileToStor($upload_dir, $fileName, $tempFileName);
if (!is_null($result)) {
$this->_helper->json->sendJson(
array("jsonrpc" => "2.0", "error" => array("code" => $result['code'], "message" => $result['message']))
);
}
}
public function uploadRecordedAction()
{
$show_instance_id = $this->_getParam('showinstanceid');
$file_id = $this->_getParam('fileid');
$this->view->fileid = $file_id;
$this->view->showinstanceid = $show_instance_id;
$this->uploadRecordedActionParam($show_instance_id, $file_id);
}
// The paramterized version of the uploadRecordedAction controller.
// We want this controller's action to be invokable from other
// controllers instead being of only through http
public function uploadRecordedActionParam($show_instance_id, $file_id)
{
$showCanceled = false;
$file = Application_Model_StoredFile::RecallById($file_id);
//$show_instance = $this->_getParam('show_instance');
try {
$show_inst = new Application_Model_ShowInstance($show_instance_id);
$show_inst->setRecordedFile($file_id);
}
catch (Exception $e) {
//we've reached here probably because the show was
//cancelled, and therefore the show instance does not exist
//anymore (ShowInstance constructor threw this error). We've
//done all we can do (upload the file and put it in the
//library), now lets just return.
$showCanceled = true;
}
// TODO : the following is inefficient because it calls save on both
// fields
$file->setMetadataValue('MDATA_KEY_CREATOR', "Airtime Show Recorder");
$file->setMetadataValue('MDATA_KEY_TRACKNUMBER', $show_instance_id);
if (!$showCanceled && Application_Model_Preference::GetAutoUploadRecordedShowToSoundcloud()) {
$id = $file->getId();
Application_Model_Soundcloud::uploadSoundcloud($id);
}
}
public function mediaMonitorSetupAction()
{
$this->view->stor = Application_Model_MusicDir::getStorDir()->getDirectory();
$watchedDirs = Application_Model_MusicDir::getWatchedDirs();
$watchedDirsPath = array();
foreach ($watchedDirs as $wd) {
$watchedDirsPath[] = $wd->getDirectory();
}
$this->view->watched_dirs = $watchedDirsPath;
}
public function dispatchMetadata($md, $mode)
{
$return_hash = array();
Application_Model_Preference::SetImportTimestamp();
$con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
$con->beginTransaction();
try {
// create also modifies the file if it exists
if ($mode == "create") {
$filepath = $md['MDATA_KEY_FILEPATH'];
$filepath = Application_Common_OsPath::normpath($filepath);
$file = Application_Model_StoredFile::RecallByFilepath($filepath, $con);
if (is_null($file)) {
$file = Application_Model_StoredFile::Insert($md, $con);
} else {
// If the file already exists we will update and make sure that
// it's marked as 'exists'.
$file->setFileExistsFlag(true);
$file->setFileHiddenFlag(false);
$file->setMetadata($md);
}
if ($md['is_record'] != 0) {
$this->uploadRecordedActionParam($md['MDATA_KEY_TRACKNUMBER'], $file->getId());
}
} elseif ($mode == "modify") {
$filepath = $md['MDATA_KEY_FILEPATH'];
$file = Application_Model_StoredFile::RecallByFilepath($filepath, $con);
//File is not in database anymore.
if (is_null($file)) {
$return_hash['error'] = sprintf(_("File does not exist in %s"), PRODUCT_NAME);
}
//Updating a metadata change.
else {
//CC-5207 - restart media-monitor causes it to reevaluate all
//files in watched directories, and reset their cue-in/cue-out
//values. Since media-monitor has nothing to do with cue points
//let's unset it here. Note that on mode == "create", we still
//want media-monitor sending info about cue_out which by default
//will be equal to length of track until silan can take over.
unset($md['MDATA_KEY_CUE_IN']);
unset($md['MDATA_KEY_CUE_OUT']);
$file->setMetadata($md);
}
} elseif ($mode == "moved") {
$file = Application_Model_StoredFile::RecallByFilepath(
$md['MDATA_KEY_ORIGINAL_PATH'], $con);
if (is_null($file)) {
$return_hash['error'] = sprintf(_('File does not exist in %s'), PRODUCT_NAME);
} else {
$filepath = $md['MDATA_KEY_FILEPATH'];
//$filepath = str_replace("\\", "", $filepath);
$file->setFilePath($filepath);
}
} elseif ($mode == "delete") {
$filepath = $md['MDATA_KEY_FILEPATH'];
$filepath = str_replace("\\", "", $filepath);
$file = Application_Model_StoredFile::RecallByFilepath($filepath, $con);
if (is_null($file)) {
$return_hash['error'] = sprintf(_('File does not exist in %s'), PRODUCT_NAME);
Logging::warn("Attempt to delete file that doesn't exist.
Path: '$filepath'");
} else {
$file->deleteByMediaMonitor();
}
} elseif ($mode == "delete_dir") {
$filepath = $md['MDATA_KEY_FILEPATH'];
//$filepath = str_replace("\\", "", $filepath);
$files = Application_Model_StoredFile::RecallByPartialFilepath($filepath, $con);
foreach ($files as $file) {
$file->deleteByMediaMonitor();
}
$return_hash['success'] = 1;
}
if (!isset($return_hash['error'])) {
$return_hash['fileid'] = is_null($file) ? '-1' : $file->getId();
}
$con->commit();
} catch (Exception $e) {
Logging::warn("rolling back");
Logging::warn($e->getMessage());
$con->rollback();
$return_hash['error'] = $e->getMessage();
}
return $return_hash;
}
public function reloadMetadataGroupAction()
{
// extract all file metadata params from the request.
// The value is a json encoded hash that has all the information related to this action
// The key(mdXXX) does not have any meaning as of yet but it could potentially correspond
// to some unique id.
$request = $this->getRequest();
$responses = array();
$params = $request->getParams();
$valid_modes = array('delete_dir', 'delete', 'moved', 'modify', 'create');
foreach ($params as $k => $raw_json) {
// Valid requests must start with mdXXX where XXX represents at
// least 1 digit
if ( !preg_match('/^md\d+$/', $k) ) { continue; }
$info_json = json_decode($raw_json, $assoc = true);
// Log invalid requests
if ( !array_key_exists('mode', $info_json) ) {
Logging::info("Received bad request(key=$k), no 'mode' parameter. Bad request is:");
Logging::info( $info_json );
array_push( $responses, array(
'error' => _("Bad request. no 'mode' parameter passed."),
'key' => $k));
continue;
} elseif ( !in_array($info_json['mode'], $valid_modes) ) {
// A request still has a chance of being invalid even if it
// exists but it's validated by $valid_modes array
$mode = $info_json['mode'];
Logging::info("Received bad request(key=$k). 'mode' parameter was invalid with value: '$mode'. Request:");
Logging::info( $info_json );
array_push( $responses, array(
'error' => _("Bad request. 'mode' parameter is invalid"),
'key' => $k,
'mode' => $mode ) );
continue;
}
// Removing 'mode' key from $info_json might not be necessary...
$mode = $info_json['mode'];
unset( $info_json['mode'] );
try {
$response = $this->dispatchMetadata($info_json, $mode);
} catch (Exception $e) {
Logging::warn($e->getMessage());
Logging::warn(gettype($e));
}
// We tack on the 'key' back to every request in case the would like to associate
// his requests with particular responses
$response['key'] = $k;
array_push($responses, $response);
}
$this->_helper->json->sendJson($responses);
}
public function listAllFilesAction()
{
$request = $this->getRequest();
$dir_id = $request->getParam('dir_id');
$all = $request->getParam('all');
$this->view->files =
Application_Model_StoredFile::listAllFiles($dir_id, $all);
}
public function listAllWatchedDirsAction()
{
$result = array();
$arrWatchedDirs = Application_Model_MusicDir::getWatchedDirs();
$storDir = Application_Model_MusicDir::getStorDir();
$result[$storDir->getId()] = $storDir->getDirectory();
foreach ($arrWatchedDirs as $watchedDir) {
$result[$watchedDir->getId()] = $watchedDir->getDirectory();
}
$this->view->dirs = $result;
}
public function addWatchedDirAction()
{
$request = $this->getRequest();
$path = base64_decode($request->getParam('path'));
$this->view->msg = Application_Model_MusicDir::addWatchedDir($path);
}
public function removeWatchedDirAction()
{
$request = $this->getRequest();
$path = base64_decode($request->getParam('path'));
$this->view->msg = Application_Model_MusicDir::removeWatchedDir($path);
}
public function setStorageDirAction()
{
$request = $this->getRequest();
$path = base64_decode($request->getParam('path'));
$this->view->msg = Application_Model_MusicDir::setStorDir($path);
}
public function getStreamSettingAction()
{
$info = Application_Model_StreamSetting::getStreamSetting();
$this->view->msg = $info;
}
public function statusAction()
{
$request = $this->getRequest();
$getDiskInfo = $request->getParam('diskinfo') == "true";
$status = array(
"platform"=>Application_Model_Systemstatus::GetPlatformInfo(),
"airtime_version"=>Application_Model_Preference::GetAirtimeVersion(),
"services"=>array(
"pypo"=>Application_Model_Systemstatus::GetPypoStatus(),
"liquidsoap"=>Application_Model_Systemstatus::GetLiquidsoapStatus(),
"media_monitor"=>Application_Model_Systemstatus::GetMediaMonitorStatus()
)
);
if ($getDiskInfo) {
$status["partitions"] = Application_Model_Systemstatus::GetDiskInfo();
}
$this->view->status = $status;
}
public function registerComponentAction()
{
$request = $this->getRequest();
$component = $request->getParam('component');
$remoteAddr = Application_Model_ServiceRegister::GetRemoteIpAddr();
Logging::info("Registered Component: ".$component."@".$remoteAddr);
Application_Model_ServiceRegister::Register($component, $remoteAddr);
}
public function updateLiquidsoapStatusAction()
{
$request = $this->getRequest();
$msg = $request->getParam('msg_post');
$stream_id = $request->getParam('stream_id');
$boot_time = $request->getParam('boot_time');
Application_Model_StreamSetting::setLiquidsoapError($stream_id, $msg, $boot_time);
}
public function updateSourceStatusAction()
{
$request = $this->getRequest();
$sourcename = $request->getParam('sourcename');
$status = $request->getParam('status');