forked from xbmc/xbmc
/
JSONServiceDescription.cpp
1937 lines (1706 loc) · 72.3 KB
/
JSONServiceDescription.cpp
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
/*
* Copyright (C) 2005-2012 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "ServiceDescription.h"
#include "JSONServiceDescription.h"
#include "utils/log.h"
#include "utils/StdString.h"
#include "utils/JSONVariantParser.h"
#include "JSONRPC.h"
#include "PlayerOperations.h"
#include "PlaylistOperations.h"
#include "FileOperations.h"
#include "AudioLibrary.h"
#include "VideoLibrary.h"
#include "GUIOperations.h"
#include "SystemOperations.h"
#include "InputOperations.h"
#include "XBMCOperations.h"
#include "ApplicationOperations.h"
using namespace std;
using namespace JSONRPC;
std::map<std::string, CVariant> CJSONServiceDescription::m_notifications = std::map<std::string, CVariant>();
CJSONServiceDescription::CJsonRpcMethodMap CJSONServiceDescription::m_actionMap;
std::map<std::string, JSONSchemaTypeDefinition> CJSONServiceDescription::m_types = std::map<std::string, JSONSchemaTypeDefinition>();
CJSONServiceDescription::IncompleteSchemaDefinitionMap CJSONServiceDescription::m_incompleteDefinitions = CJSONServiceDescription::IncompleteSchemaDefinitionMap();
JsonRpcMethodMap CJSONServiceDescription::m_methodMaps[] = {
// JSON-RPC
{ "JSONRPC.Introspect", CJSONRPC::Introspect },
{ "JSONRPC.Version", CJSONRPC::Version },
{ "JSONRPC.Permission", CJSONRPC::Permission },
{ "JSONRPC.Ping", CJSONRPC::Ping },
{ "JSONRPC.GetConfiguration", CJSONRPC::GetConfiguration },
{ "JSONRPC.SetConfiguration", CJSONRPC::SetConfiguration },
{ "JSONRPC.NotifyAll", CJSONRPC::NotifyAll },
// Player
{ "Player.GetActivePlayers", CPlayerOperations::GetActivePlayers },
{ "Player.GetProperties", CPlayerOperations::GetProperties },
{ "Player.GetItem", CPlayerOperations::GetItem },
{ "Player.PlayPause", CPlayerOperations::PlayPause },
{ "Player.Stop", CPlayerOperations::Stop },
{ "Player.SetSpeed", CPlayerOperations::SetSpeed },
{ "Player.Seek", CPlayerOperations::Seek },
{ "Player.MoveLeft", CPlayerOperations::MoveLeft },
{ "Player.MoveRight", CPlayerOperations::MoveRight },
{ "Player.MoveDown", CPlayerOperations::MoveDown },
{ "Player.MoveUp", CPlayerOperations::MoveUp },
{ "Player.ZoomOut", CPlayerOperations::ZoomOut },
{ "Player.ZoomIn", CPlayerOperations::ZoomIn },
{ "Player.Zoom", CPlayerOperations::Zoom },
{ "Player.Rotate", CPlayerOperations::Rotate },
{ "Player.Open", CPlayerOperations::Open },
{ "Player.GoPrevious", CPlayerOperations::GoPrevious },
{ "Player.GoNext", CPlayerOperations::GoNext },
{ "Player.GoTo", CPlayerOperations::GoTo },
{ "Player.Shuffle", CPlayerOperations::Shuffle },
{ "Player.UnShuffle", CPlayerOperations::UnShuffle },
{ "Player.Repeat", CPlayerOperations::Repeat },
{ "Player.SetAudioStream", CPlayerOperations::SetAudioStream },
{ "Player.SetSubtitle", CPlayerOperations::SetSubtitle },
// Playlist
{ "Playlist.GetPlaylists", CPlaylistOperations::GetPlaylists },
{ "Playlist.GetProperties", CPlaylistOperations::GetProperties },
{ "Playlist.GetItems", CPlaylistOperations::GetItems },
{ "Playlist.Add", CPlaylistOperations::Add },
{ "Playlist.Insert", CPlaylistOperations::Insert },
{ "Playlist.Clear", CPlaylistOperations::Clear },
{ "Playlist.Remove", CPlaylistOperations::Remove },
{ "Playlist.Swap", CPlaylistOperations::Swap },
// Files
{ "Files.GetSources", CFileOperations::GetRootDirectory },
{ "Files.GetDirectory", CFileOperations::GetDirectory },
{ "Files.PrepareDownload", CFileOperations::PrepareDownload },
{ "Files.Download", CFileOperations::Download },
// Music Library
{ "AudioLibrary.GetArtists", CAudioLibrary::GetArtists },
{ "AudioLibrary.GetArtistDetails", CAudioLibrary::GetArtistDetails },
{ "AudioLibrary.GetAlbums", CAudioLibrary::GetAlbums },
{ "AudioLibrary.GetAlbumDetails", CAudioLibrary::GetAlbumDetails },
{ "AudioLibrary.GetSongs", CAudioLibrary::GetSongs },
{ "AudioLibrary.GetSongDetails", CAudioLibrary::GetSongDetails },
{ "AudioLibrary.GetRecentlyAddedAlbums", CAudioLibrary::GetRecentlyAddedAlbums },
{ "AudioLibrary.GetRecentlyAddedSongs", CAudioLibrary::GetRecentlyAddedSongs },
{ "AudioLibrary.GetRecentlyPlayedAlbums", CAudioLibrary::GetRecentlyPlayedAlbums },
{ "AudioLibrary.GetRecentlyPlayedSongs", CAudioLibrary::GetRecentlyPlayedSongs },
{ "AudioLibrary.GetGenres", CAudioLibrary::GetGenres },
{ "AudioLibrary.SetArtistDetails", CAudioLibrary::SetArtistDetails },
{ "AudioLibrary.SetAlbumDetails", CAudioLibrary::SetAlbumDetails },
{ "AudioLibrary.SetSongDetails", CAudioLibrary::SetSongDetails },
{ "AudioLibrary.Scan", CAudioLibrary::Scan },
{ "AudioLibrary.Export", CAudioLibrary::Export },
{ "AudioLibrary.Clean", CAudioLibrary::Clean },
// Video Library
{ "VideoLibrary.GetGenres", CVideoLibrary::GetGenres },
{ "VideoLibrary.GetMovies", CVideoLibrary::GetMovies },
{ "VideoLibrary.GetMovieDetails", CVideoLibrary::GetMovieDetails },
{ "VideoLibrary.GetMovieSets", CVideoLibrary::GetMovieSets },
{ "VideoLibrary.GetMovieSetDetails", CVideoLibrary::GetMovieSetDetails },
{ "VideoLibrary.GetTVShows", CVideoLibrary::GetTVShows },
{ "VideoLibrary.GetTVShowDetails", CVideoLibrary::GetTVShowDetails },
{ "VideoLibrary.GetSeasons", CVideoLibrary::GetSeasons },
{ "VideoLibrary.GetEpisodes", CVideoLibrary::GetEpisodes },
{ "VideoLibrary.GetEpisodeDetails", CVideoLibrary::GetEpisodeDetails },
{ "VideoLibrary.GetMusicVideos", CVideoLibrary::GetMusicVideos },
{ "VideoLibrary.GetMusicVideoDetails", CVideoLibrary::GetMusicVideoDetails },
{ "VideoLibrary.GetRecentlyAddedMovies", CVideoLibrary::GetRecentlyAddedMovies },
{ "VideoLibrary.GetRecentlyAddedEpisodes", CVideoLibrary::GetRecentlyAddedEpisodes },
{ "VideoLibrary.GetRecentlyAddedMusicVideos", CVideoLibrary::GetRecentlyAddedMusicVideos },
{ "VideoLibrary.SetMovieDetails", CVideoLibrary::SetMovieDetails },
{ "VideoLibrary.SetTVShowDetails", CVideoLibrary::SetTVShowDetails },
{ "VideoLibrary.SetEpisodeDetails", CVideoLibrary::SetEpisodeDetails },
{ "VideoLibrary.SetMusicVideoDetails", CVideoLibrary::SetMusicVideoDetails },
{ "VideoLibrary.RemoveMovie", CVideoLibrary::RemoveMovie },
{ "VideoLibrary.RemoveTVShow", CVideoLibrary::RemoveTVShow },
{ "VideoLibrary.RemoveEpisode", CVideoLibrary::RemoveEpisode },
{ "VideoLibrary.RemoveMusicVideo", CVideoLibrary::RemoveMusicVideo },
{ "VideoLibrary.Scan", CVideoLibrary::Scan },
{ "VideoLibrary.Export", CVideoLibrary::Export },
{ "VideoLibrary.Clean", CVideoLibrary::Clean },
// GUI operations
{ "GUI.GetProperties", CGUIOperations::GetProperties },
{ "GUI.ShowNotification", CGUIOperations::ShowNotification },
{ "GUI.SetFullscreen", CGUIOperations::SetFullscreen },
// System operations
{ "System.GetProperties", CSystemOperations::GetProperties },
{ "System.EjectOpticalDrive", CSystemOperations::EjectOpticalDrive },
{ "System.Shutdown", CSystemOperations::Shutdown },
{ "System.Suspend", CSystemOperations::Suspend },
{ "System.Hibernate", CSystemOperations::Hibernate },
{ "System.Reboot", CSystemOperations::Reboot },
// Input operations
{ "Input.SendText", CInputOperations::SendText },
{ "Input.ExecuteAction", CInputOperations::ExecuteAction },
{ "Input.Left", CInputOperations::Left },
{ "Input.Right", CInputOperations::Right },
{ "Input.Down", CInputOperations::Down },
{ "Input.Up", CInputOperations::Up },
{ "Input.Select", CInputOperations::Select },
{ "Input.Back", CInputOperations::Back },
{ "Input.ContextMenu", CInputOperations::ContextMenu },
{ "Input.Info", CInputOperations::Info },
{ "Input.Home", CInputOperations::Home },
{ "Input.ShowCodec", CInputOperations::ShowCodec },
{ "Input.ShowOSD", CInputOperations::ShowOSD },
// Application operations
{ "Application.GetProperties", CApplicationOperations::GetProperties },
{ "Application.SetVolume", CApplicationOperations::SetVolume },
{ "Application.SetMute", CApplicationOperations::SetMute },
{ "Application.Quit", CApplicationOperations::Quit },
// XBMC operations
{ "XBMC.GetInfoLabels", CXBMCOperations::GetInfoLabels },
{ "XBMC.GetInfoBooleans", CXBMCOperations::GetInfoBooleans }
};
JSONSchemaTypeDefinition::JSONSchemaTypeDefinition()
: missingReference(""),
type(AnyValue), minimum(-std::numeric_limits<double>::max()), maximum(std::numeric_limits<double>::max()),
exclusiveMinimum(false), exclusiveMaximum(false), divisibleBy(0),
minLength(-1), maxLength(-1),
minItems(0), maxItems(0), uniqueItems(false),
hasAdditionalProperties(false), additionalProperties(NULL)
{ }
bool JSONSchemaTypeDefinition::Parse(const CVariant &value, bool isParameter /* = false */)
{
bool isReferenceType = false;
bool hasReference = false;
// Check if the type of the parameter defines a json reference
// to a type defined somewhere else
if (value.isMember("$ref") && value["$ref"].isString())
{
// Get the name of the referenced type
std::string refType = value["$ref"].asString();
// Check if the referenced type exists
JSONSchemaTypeDefinition *referencedType = CJSONServiceDescription::GetType(refType);
if (refType.length() <= 0 || referencedType == NULL)
{
CLog::Log(LOGDEBUG, "JSONRPC: JSON schema type %s references an unknown type %s", name.c_str(), refType.c_str());
missingReference = refType;
return false;
}
std::string typeName = name;
*this = *referencedType;
if (!typeName.empty())
name = typeName;
hasReference = true;
}
else if (value.isMember("id") && value["id"].isString())
{
ID = GetString(value["id"], "");
isReferenceType = true;
}
// Check if the "required" field has been defined
optional = value.isMember("required") && value["required"].isBoolean() ? !value["required"].asBoolean() : true;
// Get the "description"
if (!hasReference || (value.isMember("description") && value["description"].isString()))
description = GetString(value["description"], "");
if (hasReference)
{
// If there is a specific default value, read it
if (value.isMember("default") && IsType(value["default"], type))
{
bool ok = false;
if (enums.size() <= 0)
ok = true;
// If the type has an enum definition we must make
// sure that the default value is a valid enum value
else
{
for (std::vector<CVariant>::const_iterator itr = enums.begin(); itr != enums.end(); itr++)
{
if (value["default"] == *itr)
{
ok = true;
break;
}
}
}
if (ok)
defaultValue = value["default"];
}
return true;
}
// Check whether this type extends an existing type
if (value.isMember("extends"))
{
if (value["extends"].isString())
{
std::string extendsName = GetString(value["extends"], "");
if (!extendsName.empty())
{
JSONSchemaTypeDefinition *referencedType = CJSONServiceDescription::GetType(extendsName);
if (referencedType == NULL)
{
CLog::Log(LOGDEBUG, "JSONRPC: JSON schema type %s extends an unknown type %s", name.c_str(), extendsName.c_str());
missingReference = extendsName;
return false;
}
type = referencedType->type;
extends.push_back(*referencedType);
}
}
else if (value["extends"].isArray())
{
JSONSchemaType extendedType = AnyValue;
for (unsigned int extendsIndex = 0; extendsIndex < value["extends"].size(); extendsIndex++)
{
std::string extendsName = GetString(value["extends"][extendsIndex], "");
if (!extendsName.empty())
{
JSONSchemaTypeDefinition *referencedType = CJSONServiceDescription::GetType(extendsName);
if (referencedType == NULL)
{
extends.clear();
CLog::Log(LOGDEBUG, "JSONRPC: JSON schema type %s extends an unknown type %s", name.c_str(), extendsName.c_str());
missingReference = extendsName;
return false;
}
if (extendsIndex == 0)
extendedType = referencedType->type;
else if (extendedType != referencedType->type)
{
extends.clear();
CLog::Log(LOGDEBUG, "JSONRPC: JSON schema type %s extends multiple JSON schema types of mismatching types", name.c_str());
return false;
}
extends.push_back(*referencedType);
}
}
type = extendedType;
}
}
// Only read the "type" attribute if it's
// not an extending type
if (extends.size() <= 0)
{
// Get the defined type of the parameter
if (!CJSONServiceDescription::parseJSONSchemaType(value["type"], unionTypes, type, missingReference))
return false;
}
if (HasType(type, ObjectValue))
{
// If the type definition is of type "object"
// and has a "properties" definition we need
// to handle these as well
if (value.isMember("properties") && value["properties"].isObject())
{
// Get all child elements of the "properties"
// object and loop through them
for (CVariant::const_iterator_map itr = value["properties"].begin_map(); itr != value["properties"].end_map(); itr++)
{
// Create a new type definition, store the name
// of the current property into it, parse it
// recursively and add its default value
// to the current type's default value
JSONSchemaTypeDefinition propertyType;
propertyType.name = itr->first;
if (!propertyType.Parse(itr->second))
{
missingReference = propertyType.missingReference;
return false;
}
defaultValue[itr->first] = propertyType.defaultValue;
properties.add(propertyType);
}
}
hasAdditionalProperties = true;
additionalProperties = new JSONSchemaTypeDefinition();
if (value.isMember("additionalProperties"))
{
if (value["additionalProperties"].isBoolean())
{
hasAdditionalProperties = value["additionalProperties"].asBoolean();
if (!hasAdditionalProperties)
{
delete additionalProperties;
additionalProperties = NULL;
}
}
else if (value["additionalProperties"].isObject() && !value["additionalProperties"].isNull())
{
if (!additionalProperties->Parse(value["additionalProperties"]))
{
missingReference = additionalProperties->missingReference;
hasAdditionalProperties = false;
delete additionalProperties;
additionalProperties = NULL;
CLog::Log(LOGDEBUG, "JSONRPC: Invalid additionalProperties schema definition in type %s", name.c_str());
return false;
}
}
else
{
CLog::Log(LOGDEBUG, "JSONRPC: Invalid additionalProperties definition in type %s", name.c_str());
return false;
}
}
}
// If the defined parameter is an array
// we need to check for detailed definitions
// of the array items
if (HasType(type, ArrayValue))
{
// Check for "uniqueItems" field
if (value.isMember("uniqueItems") && value["uniqueItems"].isBoolean())
uniqueItems = value["uniqueItems"].asBoolean();
else
uniqueItems = false;
// Check for "additionalItems" field
if (value.isMember("additionalItems"))
{
// If it is an object, there is only one schema for it
if (value["additionalItems"].isObject())
{
JSONSchemaTypeDefinition additionalItem;
if (additionalItem.Parse(value["additionalItems"]))
additionalItems.push_back(additionalItem);
else
{
CLog::Log(LOGDEBUG, "Invalid \"additionalItems\" value for type %s", name.c_str());
missingReference = additionalItem.missingReference;
return false;
}
}
// If it is an array there may be multiple schema definitions
else if (value["additionalItems"].isArray())
{
for (unsigned int itemIndex = 0; itemIndex < value["additionalItems"].size(); itemIndex++)
{
JSONSchemaTypeDefinition additionalItem;
if (additionalItem.Parse(value["additionalItems"][itemIndex]))
additionalItems.push_back(additionalItem);
else
{
CLog::Log(LOGDEBUG, "Invalid \"additionalItems\" value (item %d) for type %s", itemIndex, name.c_str());
missingReference = additionalItem.missingReference;
return false;
}
}
}
// If it is not a (array of) schema and not a bool (default value is false)
// it has an invalid value
else if (!value["additionalItems"].isBoolean())
{
CLog::Log(LOGDEBUG, "Invalid \"additionalItems\" definition for type %s", name.c_str());
return false;
}
}
// If the "items" field is a single object
// we can parse that directly
if (value.isMember("items"))
{
if (value["items"].isObject())
{
JSONSchemaTypeDefinition item;
if (!item.Parse(value["items"]))
{
CLog::Log(LOGDEBUG, "Invalid item definition in \"items\" for type %s", name.c_str());
missingReference = item.missingReference;
return false;
}
items.push_back(item);
}
// Otherwise if it is an array we need to
// parse all elements and store them
else if (value["items"].isArray())
{
for (CVariant::const_iterator_array itemItr = value["items"].begin_array(); itemItr != value["items"].end_array(); itemItr++)
{
JSONSchemaTypeDefinition item;
if (!item.Parse(*itemItr))
{
CLog::Log(LOGDEBUG, "Invalid item definition in \"items\" array for type %s", name.c_str());
missingReference = item.missingReference;
return false;
}
items.push_back(item);
}
}
}
minItems = (unsigned int)value["minItems"].asUnsignedInteger(0);
maxItems = (unsigned int)value["maxItems"].asUnsignedInteger(0);
}
if (HasType(type, NumberValue) || HasType(type, IntegerValue))
{
if ((type & NumberValue) == NumberValue)
{
minimum = value["minimum"].asDouble(-numeric_limits<double>::max());
maximum = value["maximum"].asDouble(numeric_limits<double>::max());
}
else if ((type & IntegerValue) == IntegerValue)
{
minimum = (double)value["minimum"].asInteger(numeric_limits<int>::min());
maximum = (double)value["maximum"].asInteger(numeric_limits<int>::max());
}
exclusiveMinimum = value["exclusiveMinimum"].asBoolean(false);
exclusiveMaximum = value["exclusiveMaximum"].asBoolean(false);
divisibleBy = (unsigned int)value["divisibleBy"].asUnsignedInteger(0);
}
if (HasType(type, StringValue))
{
minLength = (int)value["minLength"].asInteger(-1);
maxLength = (int)value["maxLength"].asInteger(-1);
}
// If the type definition is neither an
// "object" nor an "array" we can check
// for an "enum" definition
if (value.isMember("enum") && value["enum"].isArray())
{
// Loop through all elements in the "enum" array
for (CVariant::const_iterator_array enumItr = value["enum"].begin_array(); enumItr != value["enum"].end_array(); enumItr++)
{
// Check for duplicates and eliminate them
bool approved = true;
for (unsigned int approvedIndex = 0; approvedIndex < enums.size(); approvedIndex++)
{
if (*enumItr == enums.at(approvedIndex))
{
approved = false;
break;
}
}
// Only add the current item to the enum value
// list if it is not duplicate
if (approved)
enums.push_back(*enumItr);
}
}
if (type != ObjectValue)
{
// If there is a definition for a default value and its type
// matches the type of the parameter we can parse it
bool ok = false;
if (value.isMember("default") && IsType(value["default"], type))
{
if (enums.size() <= 0)
ok = true;
// If the type has an enum definition we must make
// sure that the default value is a valid enum value
else
{
for (std::vector<CVariant>::const_iterator itr = enums.begin(); itr != enums.end(); itr++)
{
if (value["default"] == *itr)
{
ok = true;
break;
}
}
}
}
if (ok)
defaultValue = value["default"];
else
{
// If the type of the default value definition does not
// match the type of the parameter we have to log this
if (value.isMember("default") && !IsType(value["default"], type))
CLog::Log(LOGDEBUG, "JSONRPC: Parameter %s has an invalid default value", name.c_str());
// If the type contains an "enum" we need to get the
// default value from the first enum value
if (enums.size() > 0)
defaultValue = enums.at(0);
// otherwise set a default value instead
else
SetDefaultValue(defaultValue, type);
}
}
if (isReferenceType)
CJSONServiceDescription::addReferenceTypeDefinition(*this);
return true;
}
JSONRPC_STATUS JSONSchemaTypeDefinition::Check(const CVariant &value, CVariant &outputValue, CVariant &errorData) const
{
if (!name.empty())
errorData["name"] = name;
SchemaValueTypeToJson(type, errorData["type"]);
CStdString errorMessage;
// Let's check the type of the provided parameter
if (!IsType(value, type))
{
CLog::Log(LOGDEBUG, "JSONRPC: Type mismatch in type %s", name.c_str());
errorMessage.Format("Invalid type %s received", ValueTypeToString(value.type()));
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
else if (value.isNull() && !HasType(type, NullValue))
{
CLog::Log(LOGDEBUG, "JSONRPC: Value is NULL in type %s", name.c_str());
errorData["message"] = "Received value is null";
return InvalidParams;
}
// Let's check if we have to handle a union type
if (unionTypes.size() > 0)
{
bool ok = false;
for (unsigned int unionIndex = 0; unionIndex < unionTypes.size(); unionIndex++)
{
CVariant dummyError;
CVariant testOutput = outputValue;
if (unionTypes.at(unionIndex).Check(value, testOutput, dummyError) == OK)
{
ok = true;
outputValue = testOutput;
break;
}
}
if (!ok)
{
CLog::Log(LOGDEBUG, "JSONRPC: Value in type %s does not match any of the union type definitions", name.c_str());
errorData["message"] = "Received value does not match any of the union type definitions";
return InvalidParams;
}
}
// First we need to check if this type extends another
// type and if so we need to check against the extended
// type first
if (extends.size() > 0)
{
for (unsigned int extendsIndex = 0; extendsIndex < extends.size(); extendsIndex++)
{
JSONRPC_STATUS status = extends.at(extendsIndex).Check(value, outputValue, errorData);
if (status != OK)
{
CLog::Log(LOGDEBUG, "JSONRPC: Value does not match extended type %s of type %s", extends.at(extendsIndex).ID.c_str(), name.c_str());
errorMessage.Format("value does not match extended type %s", extends.at(extendsIndex).ID.c_str(), name.c_str());
errorData["message"] = errorMessage.c_str();
return status;
}
}
}
// If it is an array we need to
// - check the type of every element ("items")
// - check if they need to be unique ("uniqueItems")
if (HasType(type, ArrayValue) && value.isArray())
{
outputValue = CVariant(CVariant::VariantTypeArray);
// Check the number of items against minItems and maxItems
if ((minItems > 0 && value.size() < minItems) || (maxItems > 0 && value.size() > maxItems))
{
CLog::Log(LOGDEBUG, "JSONRPC: Number of array elements does not match minItems and/or maxItems in type %s", name.c_str());
if (minItems > 0 && maxItems > 0)
errorMessage.Format("Between %d and %d array items expected but %d received", minItems, maxItems, value.size());
else if (minItems > 0)
errorMessage.Format("At least %d array items expected but only %d received", minItems, value.size());
else
errorMessage.Format("Only %d array items expected but %d received", maxItems, value.size());
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
if (items.size() == 0)
outputValue = value;
else if (items.size() == 1)
{
JSONSchemaTypeDefinition itemType = items.at(0);
// Loop through all array elements
for (unsigned int arrayIndex = 0; arrayIndex < value.size(); arrayIndex++)
{
CVariant temp;
JSONRPC_STATUS status = itemType.Check(value[arrayIndex], temp, errorData["property"]);
outputValue.push_back(temp);
if (status != OK)
{
CLog::Log(LOGDEBUG, "JSONRPC: Array element at index %u does not match in type %s", arrayIndex, name.c_str());
errorMessage.Format("array element at index %u does not match", arrayIndex);
errorData["message"] = errorMessage.c_str();
return status;
}
}
}
// We have more than one element in "items"
// so we have tuple typing, which means that
// every element in the value array must match
// with the type at the same position in the
// "items" array
else
{
// If the number of elements in the value array
// does not match the number of elements in the
// "items" array and additional items are not
// allowed there is no need to check every element
if (value.size() < items.size() || (value.size() != items.size() && additionalItems.size() == 0))
{
CLog::Log(LOGDEBUG, "JSONRPC: One of the array elements does not match in type %s", name.c_str());
errorMessage.Format("%d array elements expected but %d received", items.size(), value.size());
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
// Loop through all array elements until there
// are either no more schemas in the "items"
// array or no more elements in the value's array
unsigned int arrayIndex;
for (arrayIndex = 0; arrayIndex < min(items.size(), (size_t)value.size()); arrayIndex++)
{
JSONRPC_STATUS status = items.at(arrayIndex).Check(value[arrayIndex], outputValue[arrayIndex], errorData["property"]);
if (status != OK)
{
CLog::Log(LOGDEBUG, "JSONRPC: Array element at index %u does not match with items schema in type %s", arrayIndex, name.c_str());
return status;
}
}
if (additionalItems.size() > 0)
{
// Loop through the rest of the elements
// in the array and check them against the
// "additionalItems"
for (; arrayIndex < value.size(); arrayIndex++)
{
bool ok = false;
for (unsigned int additionalIndex = 0; additionalIndex < additionalItems.size(); additionalIndex++)
{
CVariant dummyError;
if (additionalItems.at(additionalIndex).Check(value[arrayIndex], outputValue[arrayIndex], dummyError) == OK)
{
ok = true;
break;
}
}
if (!ok)
{
CLog::Log(LOGDEBUG, "JSONRPC: Array contains non-conforming additional items in type %s", name.c_str());
errorMessage.Format("Array element at index %u does not match the \"additionalItems\" schema", arrayIndex);
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
}
}
}
// If every array element is unique we need to check each one
if (uniqueItems)
{
for (unsigned int checkingIndex = 0; checkingIndex < outputValue.size(); checkingIndex++)
{
for (unsigned int checkedIndex = checkingIndex + 1; checkedIndex < outputValue.size(); checkedIndex++)
{
// If two elements are the same they are not unique
if (outputValue[checkingIndex] == outputValue[checkedIndex])
{
CLog::Log(LOGDEBUG, "JSONRPC: Not unique array element at index %u and %u in type %s", checkingIndex, checkedIndex, name.c_str());
errorMessage.Format("Array element at index %u is not unique (same as array element at index %u)", checkingIndex, checkedIndex);
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
}
}
}
return OK;
}
// If it is an object we need to check every element
// against the defined "properties"
if (HasType(type, ObjectValue) && value.isObject())
{
unsigned int handled = 0;
JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator propertiesEnd = properties.end();
JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator propertiesIterator;
for (propertiesIterator = properties.begin(); propertiesIterator != propertiesEnd; propertiesIterator++)
{
if (value.isMember(propertiesIterator->second.name))
{
JSONRPC_STATUS status = propertiesIterator->second.Check(value[propertiesIterator->second.name], outputValue[propertiesIterator->second.name], errorData["property"]);
if (status != OK)
{
CLog::Log(LOGDEBUG, "JSONRPC: Invalid property \"%s\" in type %s", propertiesIterator->second.name.c_str(), name.c_str());
return status;
}
handled++;
}
else if (propertiesIterator->second.optional)
outputValue[propertiesIterator->second.name] = propertiesIterator->second.defaultValue;
else
{
CLog::Log(LOGDEBUG, "JSONRPC: Missing property \"%s\" in type %s", propertiesIterator->second.name.c_str(), name.c_str());
errorData["property"]["name"] = propertiesIterator->second.name.c_str();
errorData["property"]["type"] = SchemaValueTypeToString(propertiesIterator->second.type);
errorData["message"] = "Missing property";
return InvalidParams;
}
}
// Additional properties are not allowed
if (handled < value.size())
{
// If additional properties are allowed we need to check if
// they match the defined schema
if (hasAdditionalProperties && additionalProperties != NULL)
{
CVariant::const_iterator_map iter;
CVariant::const_iterator_map iterEnd = value.end_map();
for (iter = value.begin_map(); iter != iterEnd; iter++)
{
if (properties.find(iter->first) != properties.end())
continue;
// If the additional property is of type "any"
// we can simply copy its value to the output
// object
if (additionalProperties->type == AnyValue)
{
outputValue[iter->first] = value[iter->first];
continue;
}
JSONRPC_STATUS status = additionalProperties->Check(value[iter->first], outputValue[iter->first], errorData["property"]);
if (status != OK)
{
CLog::Log(LOGDEBUG, "JSONRPC: Invalid additional property \"%s\" in type %s", iter->first.c_str(), name.c_str());
return status;
}
}
}
// If we still have unchecked properties but additional
// properties are not allowed, we have invalid parameters
else if (!hasAdditionalProperties || additionalProperties == NULL)
{
errorData["message"] = "Unexpected additional properties received";
errorData.erase("property");
return InvalidParams;
}
}
return OK;
}
// It's neither an array nor an object
// If it can only take certain values ("enum")
// we need to check against those
if (enums.size() > 0)
{
bool valid = false;
for (std::vector<CVariant>::const_iterator enumItr = enums.begin(); enumItr != enums.end(); enumItr++)
{
if (*enumItr == value)
{
valid = true;
break;
}
}
if (!valid)
{
CLog::Log(LOGDEBUG, "JSONRPC: Value does not match any of the enum values in type %s", name.c_str());
errorData["message"] = "Received value does not match any of the defined enum values";
return InvalidParams;
}
}
// If we have a number or an integer type, we need
// to check the minimum and maximum values
if ((HasType(type, NumberValue) && value.isDouble()) || (HasType(type, IntegerValue) && value.isInteger()))
{
double numberValue;
if (value.isDouble())
numberValue = value.asDouble();
else
numberValue = (double)value.asInteger();
// Check minimum
if ((exclusiveMinimum && numberValue <= minimum) || (!exclusiveMinimum && numberValue < minimum) ||
// Check maximum
(exclusiveMaximum && numberValue >= maximum) || (!exclusiveMaximum && numberValue > maximum))
{
CLog::Log(LOGDEBUG, "JSONRPC: Value does not lay between minimum and maximum in type %s", name.c_str());
if (value.isDouble())
errorMessage.Format("Value between %f (%s) and %f (%s) expected but %f received",
minimum, exclusiveMinimum ? "exclusive" : "inclusive", maximum, exclusiveMaximum ? "exclusive" : "inclusive", numberValue);
else
errorMessage.Format("Value between %d (%s) and %d (%s) expected but %d received",
(int)minimum, exclusiveMinimum ? "exclusive" : "inclusive", (int)maximum, exclusiveMaximum ? "exclusive" : "inclusive", (int)numberValue);
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
// Check divisibleBy
if ((HasType(type, IntegerValue) && divisibleBy > 0 && ((int)numberValue % divisibleBy) != 0))
{
CLog::Log(LOGDEBUG, "JSONRPC: Value does not meet divisibleBy requirements in type %s", name.c_str());
errorMessage.Format("Value should be divisible by %d but %d received", divisibleBy, (int)numberValue);
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
}
// If we have a string, we need to check the length
if (HasType(type, StringValue) && value.isString())
{
int size = value.asString().size();
if (size < minLength)
{
CLog::Log(LOGDEBUG, "JSONRPC: Value does not meet minLength requirements in type %s", name.c_str());
errorMessage.Format("Value should have a minimum length of %d but has a length of %d", minLength, size);
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
if (maxLength >= 0 && size > maxLength)
{
CLog::Log(LOGDEBUG, "JSONRPC: Value does not meet maxLength requirements in type %s", name.c_str());
errorMessage.Format("Value should have a maximum length of %d but has a length of %d", maxLength, size);
errorData["message"] = errorMessage.c_str();
return InvalidParams;
}
}
// Otherwise it can have any value
outputValue = value;
return OK;
}
void JSONSchemaTypeDefinition::Print(bool isParameter, bool isGlobal, bool printDefault, bool printDescriptions, CVariant &output) const
{
bool typeReference = false;
// Printing general fields
if (isParameter)
output["name"] = name;
if (isGlobal)
output["id"] = ID;
else if (!ID.empty())
{
output["$ref"] = ID;
typeReference = true;
}
if (printDescriptions && !description.empty())
output["description"] = description;
if (isParameter || printDefault)
{
if (!optional)
output["required"] = true;
if (optional && type != ObjectValue && type != ArrayValue)
output["default"] = defaultValue;
}
if (!typeReference)
{
if (extends.size() == 1)
{
output["extends"] = extends.at(0).ID;
}
else if (extends.size() > 1)
{
output["extends"] = CVariant(CVariant::VariantTypeArray);
for (unsigned int extendsIndex = 0; extendsIndex < extends.size(); extendsIndex++)
output["extends"].append(extends.at(extendsIndex).ID);
}
else if (unionTypes.size() > 0)
{
output["type"] = CVariant(CVariant::VariantTypeArray);
for (unsigned int unionIndex = 0; unionIndex < unionTypes.size(); unionIndex++)
{
CVariant unionOutput = CVariant(CVariant::VariantTypeObject);
unionTypes.at(unionIndex).Print(false, false, false, printDescriptions, unionOutput);
output["type"].append(unionOutput);
}
}
else
CJSONUtils::SchemaValueTypeToJson(type, output["type"]);
// Printing enum field
if (enums.size() > 0)
{
output["enums"] = CVariant(CVariant::VariantTypeArray);
for (unsigned int enumIndex = 0; enumIndex < enums.size(); enumIndex++)
output["enums"].append(enums.at(enumIndex));
}
// Printing integer/number fields
if (CJSONUtils::HasType(type, IntegerValue) || CJSONUtils::HasType(type, NumberValue))
{
if (CJSONUtils::HasType(type, NumberValue))
{
if (minimum > -numeric_limits<double>::max())
output["minimum"] = minimum;
if (maximum < numeric_limits<double>::max())
output["maximum"] = maximum;
}
else
{