]> git.sesse.net Git - vlc/blob - modules/services_discovery/upnp_intel.cpp
Finish the playlist API transition (hopefully)
[vlc] / modules / services_discovery / upnp_intel.cpp
1 /*****************************************************************************
2  * Upnp_intell.cpp :  UPnP discovery module (Intel SDK)
3  *****************************************************************************
4  * Copyright (C) 2004-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: RĂ©mi Denis-Courmont <rem # videolan.org> (original plugin)
8  *          Christian Henz <henz # c-lab.de>
9  *
10  * UPnP Plugin using the Intel SDK (libupnp) instead of CyberLink
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*
28   \TODO: Debug messages: "__FILE__, __LINE__" ok ???, Wrn/Err ???
29   \TODO: Change names to VLC standard ???
30 */
31
32 #include <stdlib.h>
33
34 #include <vector>
35 #include <string>
36
37 #include <upnp/upnp.h>
38 #include <upnp/upnptools.h>
39
40 #undef PACKAGE_NAME
41 #include <vlc/vlc.h>
42 #include <vlc/intf.h>
43
44 #include "vlc_strings.h"
45
46
47 // VLC handle
48
49 struct services_discovery_sys_t
50 {
51     playlist_item_t *p_node_cat;
52     playlist_item_t *p_node_one;
53 };
54
55
56 // Constants
57
58 const char* MEDIA_SERVER_DEVICE_TYPE = "urn:schemas-upnp-org:device:MediaServer:1";
59 const char* CONTENT_DIRECTORY_SERVICE_TYPE = "urn:schemas-upnp-org:service:ContentDirectory:1";
60
61
62 // Classes
63
64 class MediaServer;
65 class MediaServerList;
66 class Item;
67 class Container;
68
69 // Cookie that is passed to the callback
70
71 typedef struct
72 {
73     services_discovery_t* serviceDiscovery;
74     UpnpClient_Handle clientHandle;
75     MediaServerList* serverList;
76 } Cookie;
77
78
79 // Class definitions...
80
81 class Lockable
82 {
83 public:
84
85     Lockable( Cookie* c )
86     {
87     vlc_mutex_init( c->serviceDiscovery, &_mutex );
88     }
89
90     ~Lockable()
91     {
92     vlc_mutex_destroy( &_mutex );
93     }
94
95     void lock() { vlc_mutex_lock( &_mutex ); }
96     void unlock() { vlc_mutex_unlock( &_mutex ); }
97
98 private:
99
100     vlc_mutex_t _mutex;
101 };
102
103
104 class Locker
105 {
106 public:
107     Locker( Lockable* l )
108     {
109     _lockable = l;
110     _lockable->lock();
111     }
112
113     ~Locker()
114     {
115     _lockable->unlock();
116     }
117
118 private:
119     Lockable* _lockable;
120 };
121
122
123 class MediaServer
124 {
125 public:
126
127     static void parseDeviceDescription( IXML_Document* doc, const char* location, Cookie* cookie );
128
129     MediaServer( const char* UDN, const char* friendlyName, Cookie* cookie );
130     ~MediaServer();
131
132     const char* getUDN() const;
133     const char* getFriendlyName() const;
134
135     void setContentDirectoryEventURL( const char* url );
136     const char* getContentDirectoryEventURL() const;
137
138     void setContentDirectoryControlURL( const char* url );
139     const char* getContentDirectoryControlURL() const;
140
141     void subscribeToContentDirectory();
142     void fetchContents();
143
144     void setPlaylistNode( playlist_item_t* node );
145
146     bool compareSID( const char* sid );
147
148 private:
149
150     bool _fetchContents( Container* parent );
151     void _buildPlaylist( Container* container );
152     IXML_Document* _browseAction( const char*, const char*, const char*, const char*, const char*, const char* );
153
154     Cookie* _cookie;
155
156     Container* _contents;
157     playlist_item_t* _playlistNode;
158
159     std::string _UDN;
160     std::string _friendlyName;
161
162     std::string _contentDirectoryEventURL;
163     std::string _contentDirectoryControlURL;
164
165     int _subscriptionTimeOut;
166     Upnp_SID _subscriptionID;
167 };
168
169
170 class MediaServerList
171 {
172 public:
173
174     MediaServerList( Cookie* cookie );
175     ~MediaServerList();
176
177     bool addServer( MediaServer* s );
178     void removeServer( const char* UDN );
179
180     MediaServer* getServer( const char* UDN );
181     MediaServer* getServerBySID( const char* );
182
183 private:
184
185     Cookie* _cookie;
186
187     std::vector<MediaServer*> _list;
188 };
189
190
191 class Item
192 {
193 public:
194
195     Item( Container* parent, const char* objectID, const char* title, const char* resource );
196
197     const char* getObjectID() const;
198     const char* getTitle() const;
199     const char* getResource() const;
200
201     void setPlaylistNode( playlist_item_t* node );
202     playlist_item_t* getPlaylistNode() const ;
203
204 private:
205
206     playlist_item_t* _playlistNode;
207
208     Container* _parent;
209     std::string _objectID;
210     std::string _title;
211     std::string _resource;
212 };
213
214
215 class Container
216 {
217 public:
218
219     Container( Container* parent, const char* objectID, const char* title );
220     ~Container();
221
222     void addItem( Item* item );
223     void addContainer( Container* container );
224
225     const char* getObjectID() const;
226     const char* getTitle() const;
227
228     unsigned int getNumItems() const;
229     unsigned int getNumContainers() const;
230
231     Item* getItem( unsigned int i ) const;
232     Container* getContainer( unsigned int i ) const;
233
234     void setPlaylistNode( playlist_item_t* node );
235     playlist_item_t* getPlaylistNode() const;
236
237 private:
238
239     playlist_item_t* _playlistNode;
240
241     Container* _parent;
242
243     std::string _objectID;
244     std::string _title;
245     std::vector<Item*> _items;
246     std::vector<Container*> _containers;
247 };
248
249
250 // VLC callback prototypes
251
252 static int Open( vlc_object_t* );
253 static void Close( vlc_object_t* );
254 static void Run( services_discovery_t *p_sd );
255
256 // Module descriptor
257
258 vlc_module_begin();
259 set_shortname( "UPnP" );
260 set_description( _( "Universal Plug'n'Play discovery ( Intel SDK )" ) );
261 set_category( CAT_PLAYLIST );
262 set_subcategory( SUBCAT_PLAYLIST_SD );
263 set_capability( "services_discovery", 0 );
264 set_callbacks( Open, Close );
265 vlc_module_end();
266
267
268 // More prototypes...
269
270 static Lockable* CallbackLock;
271 static int Callback( Upnp_EventType eventType, void* event, void* pCookie );
272
273 const char* xml_getChildElementValue( IXML_Element* parent, const char* tagName );
274 IXML_Document* parseBrowseResult( IXML_Document* doc );
275
276
277 // VLC callbacks...
278
279 static int Open( vlc_object_t *p_this )
280 {
281     services_discovery_t *p_sd = ( services_discovery_t* )p_this;
282     services_discovery_sys_t *p_sys  = ( services_discovery_sys_t * )
283     malloc( sizeof( services_discovery_sys_t ) );
284
285     p_sd->pf_run = Run;
286     p_sd->p_sys = p_sys;
287
288     /* Create our playlist node */
289     playlist_NodesPairCreate( pl_Get( p_sd ), _("Devices"),
290                               &p_sys->p_node_cat, &p_sys->p_node_one,
291                               VLC_TRUE );
292
293     return VLC_SUCCESS;
294 }
295
296 static void Close( vlc_object_t *p_this )
297 {
298     services_discovery_t *p_sd = ( services_discovery_t* )p_this;
299     services_discovery_sys_t *p_sys = p_sd->p_sys;
300
301     playlist_NodeDelete( pl_Get( p_sd ), p_sys->p_node_one, VLC_TRUE,
302                          VLC_TRUE );
303     playlist_NodeDelete( pl_Get( p_sd ), p_sys->p_node_cat, VLC_TRUE,
304                          VLC_TRUE );
305
306     free( p_sys );
307 }
308
309 static void Run( services_discovery_t* p_sd )
310 {
311     int res;
312
313     res = UpnpInit( 0, 0 );
314     if( res != UPNP_E_SUCCESS )
315     {
316         msg_Err( p_sd, "%s", UpnpGetErrorMessage( res ) );
317         return;
318     }
319
320     Cookie cookie;
321     cookie.serviceDiscovery = p_sd;
322     cookie.serverList = new MediaServerList( &cookie );
323
324     CallbackLock = new Lockable( &cookie );
325
326     res = UpnpRegisterClient( Callback, &cookie, &cookie.clientHandle );
327     if( res != UPNP_E_SUCCESS )
328     {
329         msg_Err( p_sd, "%s", UpnpGetErrorMessage( res ) );
330         goto shutDown;
331     }
332
333     res = UpnpSearchAsync( cookie.clientHandle, 5, MEDIA_SERVER_DEVICE_TYPE, &cookie );
334     if( res != UPNP_E_SUCCESS )
335     {
336         msg_Err( p_sd, "%s", UpnpGetErrorMessage( res ) );
337         goto shutDown;
338     }
339
340     msg_Dbg( p_sd, "UPnP discovery started" );
341     while( !p_sd->b_die )
342     {
343         msleep( 500 );
344     }
345
346     msg_Dbg( p_sd, "UPnP discovery stopped" );
347
348  shutDown:
349     UpnpFinish();
350     delete cookie.serverList;
351     delete CallbackLock;
352 }
353
354
355 // XML utility functions:
356
357 // Returns the value of a child element, or 0 on error
358 const char* xml_getChildElementValue( IXML_Element* parent, const char* tagName )
359 {
360     if ( !parent ) return 0;
361     if ( !tagName ) return 0;
362
363     char* s = strdup( tagName );
364     IXML_NodeList* nodeList = ixmlElement_getElementsByTagName( parent, s );
365     free( s );
366     if ( !nodeList ) return 0;
367
368     IXML_Node* element = ixmlNodeList_item( nodeList, 0 );
369     ixmlNodeList_free( nodeList );
370     if ( !element ) return 0;
371
372     IXML_Node* textNode = ixmlNode_getFirstChild( element );
373     if ( !textNode ) return 0;
374
375     return ixmlNode_getNodeValue( textNode );
376 }
377
378 // Extracts the result document from a SOAP response
379 IXML_Document* parseBrowseResult( IXML_Document* doc )
380 {
381     if ( !doc ) return 0;
382
383     IXML_NodeList* resultList = ixmlDocument_getElementsByTagName( doc, "Result" );
384     if ( !resultList ) return 0;
385
386     IXML_Node* resultNode = ixmlNodeList_item( resultList, 0 );
387
388     ixmlNodeList_free( resultList );
389
390     if ( !resultNode ) return 0;
391
392     IXML_Node* textNode = ixmlNode_getFirstChild( resultNode );
393     if ( !textNode ) return 0;
394
395     const char* resultString = ixmlNode_getNodeValue( textNode );
396     char* resultXML = strdup( resultString );
397
398     resolve_xml_special_chars( resultXML );
399
400     IXML_Document* browseDoc = ixmlParseBuffer( resultXML );
401
402     free( resultXML );
403
404     return browseDoc;
405 }
406
407
408 // Handles all UPnP events
409 static int Callback( Upnp_EventType eventType, void* event, void* pCookie )
410 {
411     Locker locker( CallbackLock );
412
413     Cookie* cookie = ( Cookie* )pCookie;
414
415     switch( eventType ) {
416
417     case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
418     case UPNP_DISCOVERY_SEARCH_RESULT:
419     {
420         struct Upnp_Discovery* discovery = ( struct Upnp_Discovery* )event;
421
422         IXML_Document *descriptionDoc = 0;
423
424         int res;
425         res = UpnpDownloadXmlDoc( discovery->Location, &descriptionDoc );
426         if ( res != UPNP_E_SUCCESS )
427         {
428           msg_Dbg( cookie->serviceDiscovery, "%s:%d: Could not download device description!", __FILE__, __LINE__ );
429           return res;
430         }
431
432         MediaServer::parseDeviceDescription( descriptionDoc, discovery->Location, cookie );
433
434         ixmlDocument_free( descriptionDoc );
435     }
436     break;
437
438     case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE:
439     {
440         struct Upnp_Discovery* discovery = ( struct Upnp_Discovery* )event;
441
442         cookie->serverList->removeServer( discovery->DeviceId );
443     }
444     break;
445
446     case UPNP_EVENT_RECEIVED:
447     {
448         Upnp_Event* e = ( Upnp_Event* )event;
449
450         MediaServer* server = cookie->serverList->getServerBySID( e->Sid );
451         if ( server ) server->fetchContents();
452     }
453     break;
454
455     case UPNP_EVENT_AUTORENEWAL_FAILED:
456     case UPNP_EVENT_SUBSCRIPTION_EXPIRED:
457     {
458         // Re-subscribe...
459
460         Upnp_Event_Subscribe* s = ( Upnp_Event_Subscribe* )event;
461
462         MediaServer* server = cookie->serverList->getServerBySID( s->Sid );
463         if ( server ) server->subscribeToContentDirectory();
464     }
465     break;
466
467     case UPNP_EVENT_SUBSCRIBE_COMPLETE:
468         msg_Warn( cookie->serviceDiscovery, "subscription complete" );
469         break;
470         
471     case UPNP_DISCOVERY_SEARCH_TIMEOUT:
472         msg_Warn( cookie->serviceDiscovery, "search timeout" );
473         break;
474         
475     default:
476     msg_Dbg( cookie->serviceDiscovery, "%s:%d: DEBUG: UNHANDLED EVENT ( TYPE=%d )", __FILE__, __LINE__, eventType );
477     break;
478     }
479
480     return UPNP_E_SUCCESS;
481 }
482
483
484 // Class implementations...
485
486 // MediaServer...
487
488 void MediaServer::parseDeviceDescription( IXML_Document* doc, const char* location, Cookie* cookie )
489 {
490     if ( !doc ) { msg_Dbg( cookie->serviceDiscovery, "%s:%d: NULL", __FILE__, __LINE__ ); return; }
491     if ( !location ) { msg_Dbg( cookie->serviceDiscovery, "%s:%d: NULL", __FILE__, __LINE__ ); return; }
492
493     const char* baseURL = location;
494
495     // Try to extract baseURL
496
497     IXML_NodeList* urlList = ixmlDocument_getElementsByTagName( doc, "baseURL" );
498     if ( urlList )
499     {
500     if ( IXML_Node* urlNode = ixmlNodeList_item( urlList, 0 ) )
501     {
502         IXML_Node* textNode = ixmlNode_getFirstChild( urlNode );
503         if ( textNode ) baseURL = ixmlNode_getNodeValue( textNode );
504     }
505
506     ixmlNodeList_free( urlList );
507     }
508
509     // Get devices
510
511     IXML_NodeList* deviceList = ixmlDocument_getElementsByTagName( doc, "device" );
512     if ( deviceList )
513     {
514
515     for ( unsigned int i = 0; i < ixmlNodeList_length( deviceList ); i++ )
516     {
517         IXML_Element* deviceElement = ( IXML_Element* )ixmlNodeList_item( deviceList, i );
518
519         const char* deviceType = xml_getChildElementValue( deviceElement, "deviceType" );
520         if ( !deviceType ) { msg_Dbg( cookie->serviceDiscovery, "%s:%d: no deviceType!", __FILE__, __LINE__ ); continue; }
521         if ( strcmp( MEDIA_SERVER_DEVICE_TYPE, deviceType ) != 0 ) continue;
522
523         const char* UDN = xml_getChildElementValue( deviceElement, "UDN" );
524         if ( !UDN ) { msg_Dbg( cookie->serviceDiscovery, "%s:%d: no UDN!", __FILE__, __LINE__ ); continue; }
525         if ( cookie->serverList->getServer( UDN ) != 0 ) continue;
526
527         const char* friendlyName = xml_getChildElementValue( deviceElement, "friendlyName" );
528         if ( !friendlyName ) { msg_Dbg( cookie->serviceDiscovery, "%s:%d: no friendlyName!", __FILE__, __LINE__ ); continue; }
529
530         MediaServer* server = new MediaServer( UDN, friendlyName, cookie );
531         if ( !cookie->serverList->addServer( server ) ) {
532
533         delete server;
534         server = 0;
535         continue;
536         }
537
538         // Check for ContentDirectory service...
539
540         IXML_NodeList* serviceList = ixmlElement_getElementsByTagName( deviceElement, "service" );
541         if ( serviceList )
542         {
543             for ( unsigned int j = 0; j < ixmlNodeList_length( serviceList ); j++ )
544         {
545             IXML_Element* serviceElement = ( IXML_Element* )ixmlNodeList_item( serviceList, j );
546
547             const char* serviceType = xml_getChildElementValue( serviceElement, "serviceType" );
548             if ( !serviceType ) continue;
549             if ( strcmp( CONTENT_DIRECTORY_SERVICE_TYPE, serviceType ) != 0 ) continue;
550
551             const char* eventSubURL = xml_getChildElementValue( serviceElement, "eventSubURL" );
552             if ( !eventSubURL ) continue;
553
554             const char* controlURL = xml_getChildElementValue( serviceElement, "controlURL" );
555             if ( !controlURL ) continue;
556
557             // Try to subscribe to ContentDirectory service
558
559             char* url = ( char* )malloc( strlen( baseURL ) + strlen( eventSubURL ) + 1 );
560             if ( url )
561             {
562                 char* s1 = strdup( baseURL );
563                 char* s2 = strdup( eventSubURL );
564
565                 if ( UpnpResolveURL( s1, s2, url ) == UPNP_E_SUCCESS )
566                 {
567                 // msg_Dbg( cookie->serviceDiscovery, "CDS EVENT URL: %s", url );
568
569                 server->setContentDirectoryEventURL( url );
570                 server->subscribeToContentDirectory();
571                 }
572
573                 free( s1 );
574                 free( s2 );
575                 free( url );
576             }
577
578             // Try to browse content directory...
579
580             url = ( char* )malloc( strlen( baseURL ) + strlen( controlURL ) + 1 );
581             if ( url )
582             {
583             char* s1 = strdup( baseURL );
584             char* s2 = strdup( controlURL );
585
586             if ( UpnpResolveURL( s1, s2, url ) == UPNP_E_SUCCESS )
587             {
588                 // msg_Dbg( cookie->serviceDiscovery, "CDS CTRL URL: %s", url );
589
590                 server->setContentDirectoryControlURL( url );
591                 server->fetchContents();
592             }
593
594             free( s1 );
595             free( s2 );
596             free( url );
597             }
598         }
599
600         ixmlNodeList_free( serviceList );
601         }
602     }
603
604     ixmlNodeList_free( deviceList );
605     }
606 }
607
608 MediaServer::MediaServer( const char* UDN, const char* friendlyName, Cookie* cookie )
609 {
610     _cookie = cookie;
611
612     _UDN = UDN;
613     _friendlyName = friendlyName;
614
615     _contents = 0;
616     _playlistNode = 0;
617 }
618
619 MediaServer::~MediaServer()
620 {
621     if ( _contents )
622     {
623         playlist_NodeDelete( pl_Get( _cookie->serviceDiscovery ) ,
624                              _playlistNode, VLC_TRUE, VLC_TRUE );
625     }
626
627     delete _contents;
628 }
629
630 const char* MediaServer::getUDN() const
631 {
632   const char* s = _UDN.c_str();
633   return s;
634 }
635
636 const char* MediaServer::getFriendlyName() const
637 {
638     const char* s = _friendlyName.c_str();
639     return s;
640 }
641
642 void MediaServer::setContentDirectoryEventURL( const char* url )
643 {
644     _contentDirectoryEventURL = url;
645 }
646
647 const char* MediaServer::getContentDirectoryEventURL() const
648 {
649     const char* s =  _contentDirectoryEventURL.c_str();
650     return s;
651 }
652
653 void MediaServer::setContentDirectoryControlURL( const char* url )
654 {
655     _contentDirectoryControlURL = url;
656 }
657
658 const char* MediaServer::getContentDirectoryControlURL() const
659 {
660     return _contentDirectoryControlURL.c_str();
661 }
662
663 void MediaServer::subscribeToContentDirectory()
664 {
665     const char* url = getContentDirectoryEventURL();
666     if ( !url || strcmp( url, "" ) == 0 )
667     {
668     msg_Dbg( _cookie->serviceDiscovery, "No subscription url set!" );
669     return;
670     }
671
672     int timeOut = 1810;
673     Upnp_SID sid;
674
675     int res = UpnpSubscribe( _cookie->clientHandle, url, &timeOut, sid );
676
677     if ( res == UPNP_E_SUCCESS )
678     {
679     _subscriptionTimeOut = timeOut;
680     memcpy( _subscriptionID, sid, sizeof( Upnp_SID ) );
681     }
682     else
683     {
684     msg_Dbg( _cookie->serviceDiscovery, "%s:%d: WARNING: '%s': %s", __FILE__, __LINE__, getFriendlyName(), UpnpGetErrorMessage( res ) );
685     }
686 }
687
688 IXML_Document* MediaServer::_browseAction( const char* pObjectID, const char* pBrowseFlag, const char* pFilter,
689                        const char* pStartingIndex, const char* pRequestedCount, const char* pSortCriteria )
690 {
691     IXML_Document* action = 0;
692     IXML_Document* response = 0;
693
694     const char* url = getContentDirectoryControlURL();
695     if ( !url || strcmp( url, "" ) == 0 ) { msg_Dbg( _cookie->serviceDiscovery, "No subscription url set!" ); return 0; }
696
697     char* ObjectID = strdup( pObjectID );
698     char* BrowseFlag = strdup( pBrowseFlag );
699     char* Filter = strdup( pFilter );
700     char* StartingIndex = strdup( pStartingIndex );
701     char* RequestedCount = strdup( pRequestedCount );
702     char* SortCriteria = strdup( pSortCriteria );
703
704     char* serviceType = strdup( CONTENT_DIRECTORY_SERVICE_TYPE );
705
706     int res;
707
708     res = UpnpAddToAction( &action, "Browse", serviceType, "ObjectID", ObjectID );
709     if ( res != UPNP_E_SUCCESS ) { /* msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR: %s", __FILE__, __LINE__, UpnpGetErrorMessage( res ) ); */ goto browseActionCleanup; }
710
711     res = UpnpAddToAction( &action, "Browse", serviceType, "BrowseFlag", BrowseFlag );
712     if ( res != UPNP_E_SUCCESS ) { /* msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR: %s", __FILE__, __LINE__, UpnpGetErrorMessage( res ) ); */ goto browseActionCleanup; }
713
714     res = UpnpAddToAction( &action, "Browse", serviceType, "Filter", Filter );
715     if ( res != UPNP_E_SUCCESS ) { /* msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR: %s", __FILE__, __LINE__, UpnpGetErrorMessage( res ) ); */ goto browseActionCleanup; }
716
717     res = UpnpAddToAction( &action, "Browse", serviceType, "StartingIndex", StartingIndex );
718     if ( res != UPNP_E_SUCCESS ) { /* msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR: %s", __FILE__, __LINE__, UpnpGetErrorMessage( res ) ); */ goto browseActionCleanup; }
719
720     res = UpnpAddToAction( &action, "Browse", serviceType, "RequestedCount", RequestedCount );
721     if ( res != UPNP_E_SUCCESS ) { /* msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR: %s", __FILE__, __LINE__, UpnpGetErrorMessage( res ) ); */ goto browseActionCleanup; }
722
723     res = UpnpAddToAction( &action, "Browse", serviceType, "SortCriteria", SortCriteria );
724     if ( res != UPNP_E_SUCCESS ) { /* msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR: %s", __FILE__, __LINE__, UpnpGetErrorMessage( res ) ); */ goto browseActionCleanup; }
725
726     res = UpnpSendAction( _cookie->clientHandle,
727               url,
728               CONTENT_DIRECTORY_SERVICE_TYPE,
729               0,
730               action,
731               &response );
732     if ( res != UPNP_E_SUCCESS )
733     {
734     msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR: %s", __FILE__, __LINE__, UpnpGetErrorMessage( res ) );
735     ixmlDocument_free( response );
736     response = 0;
737     }
738
739  browseActionCleanup:
740
741     free( ObjectID );
742     free( BrowseFlag );
743     free( Filter );
744     free( StartingIndex );
745     free( RequestedCount );
746     free( SortCriteria );
747
748     free( serviceType );
749
750     ixmlDocument_free( action );
751     return response;
752 }
753
754 void MediaServer::fetchContents()
755 {
756     Container* root = new Container( 0, "0", getFriendlyName() );
757     playlist_t * p_playlist = pl_Get( _cookie->serviceDiscovery );
758     _fetchContents( root );
759
760     if ( _contents )
761     {
762         PL_LOCK;
763         playlist_NodeEmpty( p_playlist, _playlistNode, VLC_TRUE );
764         PL_UNLOCK;
765         delete _contents;
766     }
767
768     _contents = root;
769     _contents->setPlaylistNode( _playlistNode );
770
771     _buildPlaylist( _contents );
772 }
773
774 bool MediaServer::_fetchContents( Container* parent )
775 {
776     if (!parent) { msg_Dbg( _cookie->serviceDiscovery, "%s:%d: parent==NULL", __FILE__, __LINE__ ); return false; }
777
778     IXML_Document* response = _browseAction( parent->getObjectID(), "BrowseDirectChildren", "*", "0", "0", "" );
779     if ( !response ) { msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR!", __FILE__, __LINE__ ); return false; }
780
781     IXML_Document* result = parseBrowseResult( response );
782     ixmlDocument_free( response );
783     if ( !result ) { msg_Dbg( _cookie->serviceDiscovery, "%s:%d: ERROR!", __FILE__, __LINE__ ); return false; }
784
785     IXML_NodeList* containerNodeList = ixmlDocument_getElementsByTagName( result, "container" );
786     if ( containerNodeList )
787     {
788     for ( unsigned int i = 0; i < ixmlNodeList_length( containerNodeList ); i++ )
789     {
790               IXML_Element* containerElement = ( IXML_Element* )ixmlNodeList_item( containerNodeList, i );
791
792         const char* objectID = ixmlElement_getAttribute( containerElement, "id" );
793         if ( !objectID ) continue;
794
795         const char* childCountStr = ixmlElement_getAttribute( containerElement, "childCount" );
796         if ( !childCountStr ) continue;
797         int childCount = atoi( childCountStr );
798
799         const char* title = xml_getChildElementValue( containerElement, "dc:title" );
800         if ( !title ) continue;
801
802         const char* resource = xml_getChildElementValue( containerElement, "res" );
803
804         if ( resource && childCount < 1 )
805         {
806         Item* item = new Item( parent, objectID, title, resource );
807         parent->addItem( item );
808         }
809         else
810         {
811         Container* container = new Container( parent, objectID, title );
812         parent->addContainer( container );
813
814         if ( childCount > 0 ) _fetchContents( container );
815         }
816     }
817
818     ixmlNodeList_free( containerNodeList );
819     }
820
821     IXML_NodeList* itemNodeList = ixmlDocument_getElementsByTagName( result, "item" );
822     if ( itemNodeList )
823     {
824         for ( unsigned int i = 0; i < ixmlNodeList_length( itemNodeList ); i++ )
825     {
826         IXML_Element* itemElement = ( IXML_Element* )ixmlNodeList_item( itemNodeList, i );
827
828         const char* objectID = ixmlElement_getAttribute( itemElement, "id" );
829         if ( !objectID ) continue;
830
831         const char* title = xml_getChildElementValue( itemElement, "dc:title" );
832         if ( !title ) continue;
833
834         const char* resource = xml_getChildElementValue( itemElement, "res" );
835         if ( !resource ) continue;
836
837         Item* item = new Item( parent, objectID, title, resource );
838         parent->addItem( item );
839     }
840
841     ixmlNodeList_free( itemNodeList );
842     }
843
844     ixmlDocument_free( result );
845
846     return true;
847 }
848
849 void MediaServer::_buildPlaylist( Container* parent )
850 {
851     playlist_t *p_playlist = pl_Get( _cookie->serviceDiscovery );
852     for ( unsigned int i = 0; i < parent->getNumContainers(); i++ )
853     {
854         Container* container = parent->getContainer( i );
855         playlist_item_t* parentNode = parent->getPlaylistNode();
856
857         char* title = strdup( container->getTitle() );
858         playlist_item_t* node = playlist_NodeCreate( p_playlist, title, parentNode );
859         free( title );
860
861         container->setPlaylistNode( node );
862         _buildPlaylist( container );
863     }
864
865     for ( unsigned int i = 0; i < parent->getNumItems(); i++ )
866     {
867         Item* item = parent->getItem( i );
868         playlist_item_t* parentNode = parent->getPlaylistNode();
869
870         input_item_t* p_input = input_ItemNew( _cookie->serviceDiscovery,
871                                                item->getResource(),
872                                                item->getTitle() );
873         int i_cat;
874         playlist_BothAddInput( p_playlist, p_input, parentNode,
875                                PLAYLIST_APPEND, PLAYLIST_END, &i_cat, NULL );
876         /* TODO: do this better by storing ids */
877         playlist_item_t *p_node = playlist_ItemGetById( p_playlist, i_cat, VLC_FALSE );
878         assert( p_node );
879         item->setPlaylistNode( p_node );
880     }
881 }
882
883 void MediaServer::setPlaylistNode( playlist_item_t* playlistNode )
884 {
885     _playlistNode = playlistNode;
886 }
887
888 bool MediaServer::compareSID( const char* sid )
889 {
890     return ( strncmp( _subscriptionID, sid, sizeof( Upnp_SID ) ) == 0 );
891 }
892
893
894 // MediaServerList...
895
896 MediaServerList::MediaServerList( Cookie* cookie )
897 {
898     _cookie = cookie;
899 }
900
901 MediaServerList::~MediaServerList()
902 {
903     for ( unsigned int i = 0; i < _list.size(); i++ )
904     {
905     delete _list[i];
906     }
907 }
908
909 bool MediaServerList::addServer( MediaServer* s )
910 {
911     if ( getServer( s->getUDN() ) != 0 ) return false;
912
913     msg_Dbg( _cookie->serviceDiscovery, "Adding server '%s'", s->getFriendlyName() );
914
915     _list.push_back( s );
916
917     char* name = strdup( s->getFriendlyName() );
918     playlist_item_t* node = playlist_NodeCreate( pl_Get( _cookie->serviceDiscovery ),
919                                                  name,
920                                           _cookie->serviceDiscovery->p_sys->p_node_cat );
921     free( name );
922     s->setPlaylistNode( node );
923
924     return true;
925 }
926
927 MediaServer* MediaServerList::getServer( const char* UDN )
928 {
929     MediaServer* result = 0;
930
931     for ( unsigned int i = 0; i < _list.size(); i++ )
932     {
933         if( strcmp( UDN, _list[i]->getUDN() ) == 0 )
934     {
935         result = _list[i];
936         break;
937     }
938     }
939
940     return result;
941 }
942
943 MediaServer* MediaServerList::getServerBySID( const char* sid )
944 {
945     MediaServer* server = 0;
946
947     for ( unsigned int i = 0; i < _list.size(); i++ )
948     {
949     if ( _list[i]->compareSID( sid ) )
950     {
951         server = _list[i];
952         break;
953     }
954     }
955
956     return server;
957 }
958
959 void MediaServerList::removeServer( const char* UDN )
960 {
961     MediaServer* server = getServer( UDN );
962     if ( !server ) return;
963
964     msg_Dbg( _cookie->serviceDiscovery, "Removing server '%s'", server->getFriendlyName() );
965
966     std::vector<MediaServer*>::iterator it;
967     for ( it = _list.begin(); it != _list.end(); it++ )
968     {
969         if ( *it == server )
970     {
971               _list.erase( it );
972         delete server;
973         break;
974     }
975     }
976 }
977
978
979 // Item...
980
981 Item::Item( Container* parent, const char* objectID, const char* title, const char* resource )
982 {
983     _parent = parent;
984
985     _objectID = objectID;
986     _title = title;
987     _resource = resource;
988
989     _playlistNode = 0;
990 }
991
992 const char* Item::getObjectID() const
993 {
994     return _objectID.c_str();
995 }
996
997 const char* Item::getTitle() const
998 {
999     return _title.c_str();
1000 }
1001
1002 const char* Item::getResource() const
1003 {
1004     return _resource.c_str();
1005 }
1006
1007 void Item::setPlaylistNode( playlist_item_t* node )
1008 {
1009     _playlistNode = node;
1010 }
1011
1012 playlist_item_t* Item::getPlaylistNode() const
1013 {
1014     return _playlistNode;
1015 }
1016
1017
1018 // Container...
1019
1020 Container::Container( Container* parent, const char* objectID, const char* title )
1021 {
1022     _parent = parent;
1023
1024     _objectID = objectID;
1025     _title = title;
1026
1027     _playlistNode = 0;
1028 }
1029
1030 Container::~Container()
1031 {
1032     for ( unsigned int i = 0; i < _containers.size(); i++ )
1033     {
1034     delete _containers[i];
1035     }
1036
1037     for ( unsigned int i = 0; i < _items.size(); i++ )
1038     {
1039     delete _items[i];
1040     }
1041 }
1042
1043 void Container::addItem( Item* item )
1044 {
1045     _items.push_back( item );
1046 }
1047
1048 void Container::addContainer( Container* container )
1049 {
1050     _containers.push_back( container );
1051 }
1052
1053 const char* Container::getObjectID() const
1054 {
1055     return _objectID.c_str();
1056 }
1057
1058 const char* Container::getTitle() const
1059 {
1060     return _title.c_str();
1061 }
1062
1063 unsigned int Container::getNumItems() const
1064 {
1065     return _items.size();
1066 }
1067
1068 unsigned int Container::getNumContainers() const
1069 {
1070     return _containers.size();
1071 }
1072
1073 Item* Container::getItem( unsigned int i ) const
1074 {
1075     if ( i < _items.size() ) return _items[i];
1076     return 0;
1077 }
1078
1079 Container* Container::getContainer( unsigned int i ) const
1080 {
1081     if ( i < _containers.size() ) return _containers[i];
1082     return 0;
1083 }
1084
1085 void Container::setPlaylistNode( playlist_item_t* node )
1086 {
1087     _playlistNode = node;
1088 }
1089
1090 playlist_item_t* Container::getPlaylistNode() const
1091 {
1092     return _playlistNode;
1093 }