Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Managing Streams and Data in the FlashCom Application

Once the Flash client movie can engage two users in a live audio/video chat, you're ready to tap the power of the FlashCom server to record data and streams published by each participant. At this point, you may want to reread the overview of the application earlier in this chapter. You will create or modify the following ASC files in this section:

  • main.asc : You created the first version of this document in the last section.The main.asc document is automatically loaded for each instance of a FlashCom application.The main.asc is responsible for loading the components.asc file, as well as the other documents in this list.The application.onConnect() and application. onDisconnect() handlers are the only methods directly defined in the main.asc file; all other methods of the application are defined in the other ASC files.

  • formdate.asc : This document contains a method that returns the current date, formatted with the syntax described earlier in this chapter.

  • timer.asc : This ASC document is responsible for creating and maintaining an instance timer, which tracks the amount of time an instance of the conference application has been running.

  • startup.asc : This file contains the server-side ActionScript code that is initialized when the first user of an application instance connects to the FlashCom server. All remote SharedObjects and server-side Stream objects are created in the methods defined in this document.

  • shutdown.asc : This ASC document defines the server-side methods that are invoked when the last user disconnects from an instance of the conference application. All connections to remote SharedObjects and server-side streams are closed.

In the following sections, you will build the server-side ActionScript code necessary for each of these documents.

TIP

While it's feasible to combine the code from all these individual ASC files into one large ASC document, you can more easily manage the scope of your FlashCom application by breaking the functionality into smaller files.

Initializing Each Instance of the Conference Application

When the first user connects to an instance of the conference application, several parameters need to be created; these help the session keep track of data associated with the streams published by each user. This data is later used to identify each stream for playback in the retrieval client.

RETRIEVING THE CURRENT DATE

One of the first tasks is to create a string that represents the current date, including the year, month, day of the month, hour, and minutes. In this section, you create a formDate() method for the application object to build this date identifier. The string is used in the names of persistent remote SharedObjects and saved streams.

TO ESTABLISH THE CURRENT DATE:

  1. In Macromedia Dreamweaver MX, create a new ASC document. Save this document as formdate.asc in the conference folder of your FlashCom server.

  2. Add the code in Listing 13.3 to the formdate.asc document.

    Listing 13.3 formDate() method

    1. application.formDate = function(dateStamp) {
    2.     var year = dateStamp.getFullYear();
    3.     var month = dateStamp.getMonth() + 1;
    4.     var day = dateStamp.getDate();
    5.     var hour = dateStamp.getHours();
    6.     var minute = dateStamp.getMinutes();
    7.     minute = (minute < 10) ? ("0" + minute) : minute;
    8.     hour = (hour < 10) ? ("0" + hour) : hour;
    9.     day = (day < 10) ? ("0" + day) : day;
    10.    month = (month < 10) ? ("0" + month) : month;
    11.    var fullDate = year + "_" + month + "_" + day + "_" + hour + "_"
           + minute;
    12.    trace("fullDate = " + fullDate);
    13.    return fullDate;
    14. };

    The formDate() method accepts a Date object instance as its only argument. From this Date object, the year, month, day, hour, and minute are extracted (lines 2-6). Lines 7-10 add a leading 0 to the value of each local variable, if the variable value is less than 10. Line 11 concatenates all the local variable values into one long string named fullDate. Each variable's value is separated by an underscore ( _ ) character. The formDate() method returns this value (line 13) whenever the method is invoked.

  3. Save the document.


    The completed formdate.asc document can be found in the chapter_13 folder of this book's CD-ROM.

ACCEPTING EACH CLIENT CONNECTION AND CONNECTING TO THE DEFAULT APPLICATION INSTANCE

Granted, the formDate() method has only been defined in the formdate.asc document. You have yet to implement the date string into other aspects of the conference application. In this section, you create the onConnect() handler of the application object. The onConnect() handler is responsible for setting up the application instance when the first user connects.

TO CONNECT AN APPLICATION INSTANCE TO THE DEFAULT INSTANCE:

  1. In Macromedia Dreamweaver MX (or your preferred text editor), open the main.asc document that you created earlier in this chapter. This file should be located in the conference folder on your FlashCom server.

  2. Enable the instance of the conference application to load the server-side code contained within the formdate.asc document you created in the previous section. Insert the following code after the existing code in the main.asc document.

    load("formdate.asc"); 
  3. Define the onConnect() handler for the application instance. This handler is invoked whenever a client connects to an instance of the conference application. Add the code in Listing 13.4 to the main.asc document. Note that the line numbers shown below are relative; the numbers are not intended to match those shown in the document.

    TIP

    The application object is a reference to the current instance of a FlashCom application. The FlashCom server automatically keeps track of each of the properties and methods associated with each instance of an application. When you see references to the application object in server-side code throughout this chapter, keep in mind that each instance has its own application object.

    Listing 13.4 onConnect() handler

    1. application.onConnect = function(newClient) {
    2.    this.acceptConnection(newClient);
    3.    if (this.name.indexOf("_definst_") == -1 && !this.inited) {
    4.       this.appName = this.name.substr(this.name.indexOf("/") 
             + 1);
    5.       this.currentDate = this.formDate(new Date());
    6.       trace("currentDate = " + this.currentDate);
    7.       this.parentConn_nc = new NetConnection();
    8.       this.parentConn_nc.onStatus = function(info) {
    9.          trace("parentConn_nc: info.code = " + info.code);
    10.         if (info.code == "NetConnection.Connect.Success") {
    11.            trace("---Successful connection to default 
                   instance");
    12.            application.initSO(this);
    13.            application.initStreams();
    14.            application.inited = true;
    15.         } else if (info.code ==
                "NetConnection.Connect.Closed") {
    16.            trace("---Default instance connection closed. All
                   SharedObjects should be cleared.");
    17.            application.clearSharedObjects("/");
    18.            application.inited = false;
    19.         }
    20.      };
    21.      this.parentConn_nc.connect("rtmp://localhost/conference");
    22.    }
    23. };

    Line 1 defines the onConnect() handler for the application object. This usage of the method only uses one argument, newClient, which represents the Client object connecting to the application instance. Line 2 allows the client to connect to the application instance; if this line were omitted, the client's request to connect would be rejected.

    Line 3 checks the application instance name to which the client is connecting and checks the inited property of the application instance. If the application instance does not contain the text "_definst_" and if the inited property doesn't exist (or is equal to false), the code in lines 4-22 is processed. If the application instance is the default instance ( _definst_ ), then this code should not be invoked. The default instance should only be directly accessed by the conference retrieval client, not the conference recording client. The conference retrieval client does not need to initialize the code in lines 4-22. The inited property tracks whether the code in lines 4-22 has been initialized. If a Flash client movie has already invoked this code for a given instance of the conference application, then another client connecting to the same instance should not invoke it.

    Line 4 establishes a property named appName, which stores the instance name of the application. The name property of the application object returns the full name of the application instance. For example, the application name of the default instance of the conference application is "conference/_definst_". The appName property in line 4 extracts the string after the forward slash. The app-Name property is used to form the name of remote SharedObjects and stored streams.

    Line 5 creates a property named currentDate, which is set to the string returned from the formDate() method. A new Date object is created as the argument of this method in line 5.

    The most important aspect of the application instance's initialization occurs within lines 7-21. This code creates a server-side NetConnection object to the default instance of the conference application. Why? Even though each live conference session needs to occur within uniquely named application instances, the persistent remote SharedObjects and recorded streams from each session need to be saved in a common location. By creating a common location, or instance (such as the default instance), the conference retrieval client will know where to find data related to every session. Line 21 specifies the URI of the new NetConnection. You can implicitly connect to the default instance of any FlashCom application by simply referring to the application name (that is, conference) without any additional instance name specified.

    NOTE

    Depending on the setup of your FlashCom server, you may need to change the localhost server path to a fully qualified domain name. If the localhost is listening on the ports assigned to the FlashCom server, you shouldn't have a problem using the localhost name. However, you cannot use a relative path, such as rtmp:/conference with server-side NetConnection objects.

    When a successful connection to the default instance is made, lines 10-14 are invoked. The initSO() and initStreams() methods of the application object are defined in the following sections. The inited property of the application object is also set to true, preventing the code in lines 3-22 from being processed by any other users who connect to the same instance.

  4. Save the main.asc document.


    This version of the main.asc document is saved as main_101.asc in the chapter_13 folder of this book's CD-ROM.

CREATING THE INSTANCE'S SharedObjects

During the initialization of the application instance in the onConnect() handler, the instance creates a secondary connection to the default instance of the conference application. Once this connection is made, the initSO() and init-Streams() methods of the application object are invoked. The initSO() method, discussed in this section, creates persistent and temporary remote SharedOb-jects for the conference session. The persistent SharedObjects are stored with the namespace of the default instance, defined by the parentConn_nc object.

TO CREATE THE SharedObjects:

  1. In Macromedia Dreamweaver MX, create a new ActionScript Communications document. Save this document as startup.asc in the conference folder of your FlashCom server.

  2. Define the initSO() method of the application object. This method is invoked once a successful connection is made to the default instance of the conference application. Add the code in Listing 13.5 to the startup.asc document:

    Listing 13.5 initSO() method

    1. application.initSO = function(nc) {
    2.    for (var i = 1; i <= 2; i++) {
    3.       var avNum = "av_" + i;
    4.       var soName = this.appName + "_" + avNum + "_" + 
             this.currentDate;
    5.       this[avNum + "_timeTracker_so"] = SharedObject.get(soName, 
             true, nc);
    6.       this[avNum + "_timeTracker_so"].onSync = this.syncTracker;
    7.       this[avNum + "_so"] =
             SharedObject.get("FCAVPresence.speaker_" + i +
             "_mc.av", false);
    8.    }
    9.    this.savedCalls_so = SharedObject.get("savedCalls", true, nc);
    10.   this.savedCalls_so.onSync = this.syncTracker;
    11.   this.sessionName_so = SharedObject.get("sessionName", false);
    12. };

    Line 1 defines the initSO() method, specifying one argument, nc. The argument nc is the NetConnection object reference to the default instance, parent-Conn_nc. Line 2 iterates the code within lines 3-7 two times; because there are two users (or clients) that can participate in a live conference session, two sets of SharedObject references are created.

    Line 3 creates a simple string value to refer to each user's stream (av_1 or av_2), which is also used in the names of persistent SharedObjects for the session as defined in line 4. The application instance's name and current date help to form the unique name of each persistent SharedObject. Line 5 creates av_1_tracker_so and av_2_tracker_so, the persistent SharedObject instances that store the information for each user's stream. Note that the nc reference to the parentConn_nc object is specified as a parameter of the SharedObject.get() method. When you create a SharedObject within the space of another application instance, the SharedObject is called a proxied SharedObject.

    Line 6 defines the onSync() handler for each proxied SharedObject created for the user streams. This method, syncTracker(), is defined in step 3.

    Line 7 creates a reference to the SharedObject created by each user's AVPres-ence component. You retrieve the user's name from this SharedObject whenever a user begins to publish audio and/or video with the AVPres-ence component in the Flash client movie.

    Line 9 creates another proxied persistent SharedObject named savedCalls. This data stores the general information from every recorded conference. The data within savedCalls is used by the conference retrieval client to populate the combo box. Line 10 sets the onSync() handler of this SharedObject to the syncTracker() method as well (defined in the next step).

    Line 11 creates a reference to the sessionName SharedObject. If you recall, this is the name of the SharedObject in which the conference's title is stored from the conference recording client. Data from sessionName is later stored in the savedCalls SharedObject when the recording session has finished.

  3. Define the syncTracker() method of the application object, which is used as the onSync() handler for the persistent remote SharedObjects created in the previous step. In the startup.asc document, add the code in Listing 13.6 after the existing code:

    Listing 13.6 syncTracker() method

    1. application.syncTracker = function(list) {
    2.    for (var i in list) {
    3.       trace(i + ": name: " + list[i].name + ", code: " +
             list[i].code);
    4.       if (list[i].name == application.soPropName && list[i].code ==
             "success" && application.clients.length < 1) {
    5.          trace("closed savedCalls_so");
    6.          //close savedCalls_so instance
    7.          application.savedCalls_so.flush();
    8.          application.savedCalls_so.close();
    9.          //close client connection to default instance
    10.         application.parentConn_nc.close();
    11.      }
    12.   }
    13. };

    The syncTracker() method handles the updates and changes for all the Share-dObject instances in the application instance: av_1_tracker_so, av_2_tracker_so, and savedCalls_so. Actually, only lines 1 through 3 are invoked for all three instances. Line 3 outputs the messages from each synchronization cycle to the Live Log tab of the Communication App Inspector in Flash MX. Lines 4-11 are invoked for the savedCalls_so instance when the final update is made to the savedCalls data at the end of the conference session. At that time, the data written to savedCalls is saved (line 7), and the connection to this data is closed (line 8). In line 10, the connection to the default instance of the application instance, parentConn_nc, is also closed. You will learn more about how this code comes into play later in this chapter.

  4. Save the startup.asc document. You will continue to add code to this document in the next section.

  5. Go back to the main.asc document, and add the following highlighted line of code before the application.onConnect() handler. Note that only the first line of the onConnect() handler is displayed in the following code.

    load("components.asc"); 
    
    load("formdate.asc");
    load("startup.asc"); 
    
    application.onConnect = function(newClient){ ... 

    The highlighted line of code loads the server-side ActionScript code from the startup.asc document when an instance of the conference application runs.

  6. Save the main.asc document.

STARTING THE SERVER-SIDE Stream OBJECTS

Part of the initialization process involves the creation of two server-side Stream objects, one for each stream that can be published from each AVPresence instance in the conference recording client. When the recording client is on the chat frame, two streams are automatically set up by the AVPresence instances:

FCAVPresence.speaker_1_mc.av and FCAVPresence.speaker_2_mc.av, the same names used for the SharedObject data. There are two possibilities for recording the stream published by the AVPresence component:

  • Modify the client-side code of the AVPresence component to use a "record" or "append" parameter in its publish() method, instead of a "live" parameter. By doing this, you save the av_1 and av_2 streams in specific application instance folders of the conference application. This method only allows you to store two streams per instance at any given time. As such, if any users return to the same application instance, the previous streams will be overwritten and deleted.

  • Create a server-side Stream object that subscribes to (that is, plays) and records the stream published by the AVPresence component. Using the application instance's appName and currentDate properties, the server-side Stream object can have a separate and distinct name from the AVPresence stream. This stream "copy" can be saved in a common location, where all applications (and all application instances) can play the stream. Moreover, because each server-side Stream object has a unique name, users can return the same application instance to record new sessions, without losing the previous recordings within the instance.

    Tip

    This application only explores the capability of Stream objects to copy and record the data from another publishing stream. Server-side Stream objects are incredibly versatile and can be used to create self-running playlists and to manage streams to which users have access.

    In this next section, you will start the process of implementing method #2 for the conference application.

TO CREATE A METHOD THAT INITIALIZES THE SERVER-SIDE STREAMS:

  1. In the startup.asc document, define the initStreams() method of the application object. This method is invoked from the onStatus() handler of the parentConn_nc object initialized in the onConnect() handler of the application object (see the main.asc document). The initStreams() method creates two server-side Stream objects that subscribe to the stream names published by the AVPresence components in the conference recorder Flash movie. After the existing code in the startup.asc file, add the lines of code in Listing 13.7:

    Listing 13.7 initStreams() method

    1. application.initStreams = function(){
    2.    // redirect a conference streams to new server streams
    3.    for (var i = 1; i <= 2; i++) {
    4.       var avNum = "av_" + i;
    5.       var streamInstanceName = "stream_" + avNum;
    6.       var streamName = "callStreams/" + this.appName + "_" + avNum
             + "_" + this.currentDate;
    7.       this[streamInstanceName] = Stream.get(streamName);
    8.       this[streamInstanceName].ref = avNum;
    9.       this[streamInstanceName].onStatus = this.streamStatus;
    10.      //start the default streams
    11.      this[streamInstanceName].play("FCAVPresence.speaker_"+ i +
             "_mc.av");
    12.   }
    13. };

    When the initStreams() method is invoked, the for() loop in lines 3-12 creates two Stream objects. The instance names of these objects are stream_av_1 and stream_av_2. The actual stream name for each recorded FLV file is formed in line 6. Notice that this name starts with "callStreams/". This prefix designates a stream alias location, which you will define in the next section. A stream alias allows you to publish or store streams in a location that is accessible by all application instances running on the FlashCom server. Line 7 creates the new stream and Stream object, and line 8 creates a property named ref for each Stream object. The ref property is a reference to the AVP-resence stream name subscribed to by the respective Stream object. In line 11, the Stream instance subscribes to the AVPresence stream. For example, the stream_av_1 instance plays the stream named FCAVPresence.speaker_1_mc.av, which is published by the speaker_1_mc instance of the AVPresence component in the conference recording client.

    Line 9 defines the onStatus() handler of each Stream object, using a method named streamStatus of the application object. You will create the streamSta-tus() method in the section "Monitoring Activity on the AVPresence Streams," later in this chapter.

  2. Save the startup.asc document.

ADDING A STREAM ALIAS TO THE VHOST.XML DOCUMENT

The Vhost.xml configuration document of your FlashCom server controls many aspects of each virtual host running on the server. A virtual host is a specific domain name to which the FlashCom server responds. The Vhost.xml document controls the settings that are applied to each domain. One of the nodes, <Vir-tualDirectory>, allows you to create aliases for stream locations. An alias is a shortcut term that can be used in client- and server-side ActionScript to store streams in a specific location. In this section, you will create the callStreams alias referenced in the initStreams() method. All the streams (or FLV files) recorded by each session are stored in this common location.

TO CREATE A STREAM ALIAS:

  1. On your FlashCom server, locate the configuration files for Flash Communication Server MX. With a default installation of FlashCom on a Windows computer, the configuration files are stored in the following folder:

    C:\Program Files\Macromedia\Flash Communication Server MX\conf\ 
  2. Inside of the conf folder, open the _defaultRoot_\_defaultVHost_ folder, and you will find the Vhost.xml file. Open this document in Macromedia Dreamweaver MX.

    Note

    If you are using FlashCom on an operating system other than Windows, locate the Vhost.xml in the conf folder on that machine. You may require specific administrator privileges to access and/or modify this document. Also, if you have configured more than one virtual host, open the Vhost.xml for the domain hosting the conference application.

  3. In the Vhost.xml document, locate the <VirtualDirectory> node. An empty <Streams></Streams> node should already exist within this node. Add the following text between the <Streams></Streams> tags, replacing path_to_ conference_folder with the full path to the conference folder of your FlashCom server:

    callStreams;path_to_conference_folder\callStreams 

    For example, if you had chosen a default Developer Install FlashCom Server on a Windows server running IIS, the <Streams> node should contain the following text:

    callStreams;C:\Inetpub\wwwroot\flashcom\applications\conference\ 
    callStreams
  4. Save the Vhost.xml document.

  5. Create a callStreams folder in the conference folder of your FlashCom server.

  6. To make the changes available immediately, restart your FlashCom server.

With this stream alias in place, you can now publish or play streams located in the callStreams folder from any application or application instance running from this virtual host on your FlashCom server. Specify the alias name followed by a forward slash ( / ) to the stream name parameter used in a publish() or play() method of a client-side NetStream object, or a get() or play() method of a server-side Stream object. Refer to the code added in step 1 of the previous section to see how the callStreams/ prefix is used with the server-side Stream objects of the conference application.


You can find a sample Vhost.xml document in the chapter_13 folder of this book's CD-ROM.

Monitoring Activity on the AVPresence Streams

After the application instance's SharedObjects and streams have been initialized, the application needs to know when a participant begins to publish a stream with one of the AVPresence components. This stream is recorded by the server-side Stream object that is subscribed to the publishing stream (FCAVPres-ence.speaker_1_mc.av or FCAVPresence.speaker_2_mc.av). However, the application must do more than record the stream. It needs to track the times at which recording started and stopped. In this section, you will learn how to track the recording time and enable the Stream objects to record the publishing streams.

TRACKING THE INSTANCE'S TIME

Because the conference recording session occurs in real time, you will need to create a technique that allows the FlashCom application to keep track of time, and more importantly, when each user sends audio/video with the AVPresence component. This information is saved in the data that is linked in the av_1_ timeTracker_so, av_1_timeTracker_so, and savedCalls_so instances. The time tracker

SharedObjects store the start time, stop time, and user name of each recording segment. A user can start and stop publishing as many times as he wants during a call. The savedCalls_so instance stores the overall length of the entire recording session, from the moment the first stream starts to the moment when the last user stops streaming and closes the Flash movie.

TO TRACK TIME WITHIN THE APPLICATION INSTANCE:

  1. In Macromedia Dreamweaver MX, create a new ActionScript Communications document. Save this document as timer.asc in the conference folder of your FlashCom server.

  2. Define a method of the application object that stores the time when the method is invoked. This method is only invoked once during the conference session, when the first user begins to publish a stream with an instance of the AVPresence component. (You will learn more about this stream detection in the next section.) At the beginning of the timer.asc document, add the following lines of code:

    application.beginTimer = function() {
       this.startTime = new Date().getTime(); 
    }; 

    The startTime property of the application instance stores the current time, in milliseconds. This value is used as a baseline; throughout the recording session, new Date objects are created and compared to the startTime value.

  3. Define a method of the application object that returns the number of milliseconds elapsed since the beginTimer() method was invoked. By subtracting the startTime value from a new Date object, you can determine how many milliseconds have elapsed. Add the following code after the begin-Timer() method in the timer.asc document:

    application.fetchTime = function() {
       var currentTime = new Date().getTime();
       var elapsedTime = currentTime - this.startTime;
       return elapsedTime; 
    }; 

    The fetchTime() method is invoked from code within the streamStatus() method, discussed in the next section.

  4. Save the timer.asc document.

  5. Go back to the main.asc document and add the code that will load the timer.asc document when the application instance starts. Insert the following highlighted line of code, before the onConnect() handler:

    load("components.asc");
    
    load("formdate.asc");
    load("timer.asc"); 
    load("startup.asc"); 
    
    application.onConnect = function(newClient) {
     ... 
  6. Save the main.asc document.

DETECTING STREAM ACTIVITY

Now you are ready to add the code that determines when publishing has started or stopped over the av_1 or av_2 streams created by the AVPresence component instances. Remember, in the startup.asc document, you created two Stream instances—named stream_av_1 and stream_av_2—that subscribe to the av_1 and av_2 streams, respectively. Any events that occur with the av_1 and av_2 streams are passed along to the stream_av_1 and stream_av_2 instances.

TO DETECT EVENTS OCCURRING WITHIN EACH STREAM:

  1. Open the startup.asc document in Macromedia Dreamweaver MX.

  2. Create the onStatus() handler, streamStatus, which is defined for each server-side Stream object in the initStreams() method from the startup.asc document. This handler records any audio/video published by each user to the respective server-side Stream object. Add the code in Listing 13.8 at the end of the startup.asc document:

    Listing 13.8 streamStatus() handler

    1. application.streamStatus = function(info) {
    2.    trace("---Current stream: " + this.ref);
    3.    var currentTime = application.fetchTime();
    4.    var currentTracker = application[this.ref + "_timeTracker_so"];
    5.    if (!currentTracker.getProperty("recordTimes"))
    6.       currentTracker.setProperty("recordTimes", new Array());
    7.       var timeArray = currentTracker.getProperty("recordTimes");
    8.       trace(this.ref + " info.code = " + info.code + ", " +
             currentTime);
    9.       if (info.code == "NetStream.Play.PublishNotify") {
    10.         trace(this.ref + ": Publishing started.");
    11.         this.record("append");
    12.   } else if (info.code == "NetStream.Record.Start") {
    13.      trace(this.ref + ": Recording started.");
    14.      this.isRecording = true;
    15.      if (!application.startTime){
    16.         application.beginTimer();
    17.         currentTime = application.fetchTime();
    18       }
    19.      var currentUser = application[this.ref + 
             "_so"].getProperty("speaker");
    20.      trace("currentTime = " + currentTime + ", currentUser = " + 
             currentUser);
    21.      //save start time of recording in SO for stream
    22.      timeArray.push({start: currentTime, user: currentUser});
    23.      currentTracker.setProperty("recordTimes", timeArray);
    24.   } else if (info.code == "NetStream.Play.UnpublishNotify") {
    25.      trace(this.ref + ": Publishing stopped.");
    26.      this.record(false);
    27.   } else if (info.code == "NetStream.Record.Stop") {
    28.      trace(this.ref + ": Recording stopped.");
    29.      this.isRecording = false;
    30.      //save stop time of recording in SO for stream
    31.      timeArray[timeArray.length - 1].end = currentTime;
    32.      currentTracker.setProperty("recordTimes", timeArray);
    33.      if(this.callBack)
    34.         application[this.callBack]();
    35.   }
    36. };

    The streamStatus() method essentially checks the info.code value for each message sent to the onStatus() handler of the av_1 and av_2 streams. Because the stream_av_1 and stream_av_2 instances subscribe to these stream names, any events that occur to the FCAVPresence.speaker_1_mc.av and FCAVPresence.speaker_2_mc.av streams are directed to the streamStatus() method.

    Line 2 sends a trace() message to the Live Log of the Communication App Inspector, indicating which stream is currently receiving an event. Remember, the ref property was assigned to each Stream object in the initStreams() method.

    Line 3 establishes a local variable named currentTime, whose value is retrieved from the fetchTime() method. This value, in milliseconds, indicates when the onStatus() handler (or streamStatus() method) was invoked. Line 4 creates a local variable named currentTracker, representing the persistent SharedObject that is responsible for tracking the current stream's recording information. Using the ref property, the proper SharedObject instance is identified (that is, av_1_timeTracker_so or av_2_timeTracker_so). Line 5 checks for the existence of a recordTimes array within the current-Tracker instance. If the array doesn't exist, line 6 creates a new empty array. This Array object stores the start time, stop time, and user name associated with each recording segment for the respective stream.

    Line 7 creates a local reference, timeArray, which retrieves the current values in the recordTimes array of the currentTracker instance.

    Lines 9-11 are invoked when publishing is detected on the stream. The server-side Stream instance begins to record the publishing stream from the respective AVPresence component stream (line 11).

    Lines 12-23 are invoked when the recording initiated in line 11 actually begins. In line 14, a property named isRecording within the Stream instance is set to true. In line 15, the value of the startTime property is checked; if it doesn't exist, the beginTimer() method is invoked and the currentTime variable is retrieved from the fetchTime() method. Line 19 retrieves the value of the speaker property assigned to the SharedObject created by the AVPresence component (see the initSO() method in the startup.asc document). This value contains the string representing the user's login name as designated in the SimpleConnect instance of the recording client movie. In line 22, this value and the currentTime value retrieved in line 3 or line 17 are used to create the user and start properties, respectively, of an Object object added to the timeArray instance. Each start and stop process adds a new index to the user's recordTimes array in the appropriate time tracker SharedObject. In line 23, the recordTimes array is updated with the new values of the timeArray instance.

    Lines 24-26 are invoked when a user stops sending audio and/or video with an AVPresence instance. In line 26, recording on the server-side Stream instance is stopped.

    Lines 27-34 are processed when the Stream instance stops recording. The isRecording property is set to false (line 29), and the end property of the object at the last index of the timeArray instance is set to the currentTime value. The end property indicates the time at which recording stopped. In line 32, the updated timeArray value is applied to the recordTimes data. In lines 33 and 34, a callback handler is invoked if one has been set by the exit routine. This operation will be explored in the next section.

  3. Save the startup.asc document.


    You can find the completed version of the startup.asc document in the chapter_13 folder of this book's CD-ROM.

Shutting Down the Conference Session

So far, you've created the server-side ActionScript code necessary to initialize an application instance and record any published streams from the AVPres-ence component instances. When each user has logged out of the conference application instance or has closed the Flash movie, the application instance should save the conference session information to the savedCalls SharedObject and close all connections to the server-side NetConnection object, parentConn_nc, and other SharedObjects.

DETECTING THE LOGOUT OF THE LAST USER

The application instance follows a shutdown routine when the last user disconnects. In this section, you will begin the process of defining the methods of the application object that enable this routine.

TO DEFINE THE ON Disconnect() HANDLER:

  1. In Macromedia Dreamweaver MX, open the main.asc document from the conference folder of your FlashCom server.

  2. Create an onDisconnect() handler for the application object. This method is automatically invoked by the application instance whenever a client disconnects from the instance. After the onConnect() handler of the application object, add the following code:

    application.onDisconnect = function(oldClient) { 
       trace("application.clients.length = " + this.clients.length); 
       if(this.name.indexOf("_definst_") == -1 && this.clients.length < 1) 
          this.exitApp(); 
    }; 

    If the application instance name (the name property) does not contain the text "_definst_" and the number of connected clients is less than 1, then another method named exitApp is invoked. With the conditions that are specified in the if() statement, the exitApp() method is only invoked when the last user connected to any instance except the default instance disconnects. You will define the exitApp() method in the next section.

  3. Save the main.asc document.

CHECKING ACTIVITY ON THE STREAMS, CLOSING CONNECTIONS, AND SAVING THE FINAL DATA

If indeed the last user is disconnecting from an application instance, the server-side SharedObject, Stream, and NetConnection objects should close their connections. You also need to account for the situation wherein a user closes or quits the Flash movie while he is publishing an AV stream. If one of the Stream objects is still recording when a participant disconnects, the stream needs to stop recording and save the stop time (as an end property in the recordTimes array) before the application instance starts to close any server-side connections.

TO SAVE THE FINAL SESSION DATA AFTER THE LAST USER DISCONNECTS:

  1. In Macromedia Dreamweaver MX, create a new ActionScript Communications document. Save this document as shutdown.asc in the conference folder of your FlashCom server.

  2. Create a function that checks the isRecording values of each stream. This function returns a true or false value. If either user's stream is recording at the time the last user closes the Flash movie client, tell that stream to stop recording. Add the code in Listing 13.9 to the shutdown.asc document:

    Listing 13.9 checkStreams() function

    1. application.checkStreams = function(){
    2.  for(var i = 1; i <= 2; i++){
    3.   var currentStream = this["stream_av_" + i];
    4.   if(currentStream.isRecording){
    5.    var streamActive = true;
    6.    currentStream.callBack = "exitApp";
    7.    currentStream.record(false);
    8.   }
    9.  }
    10. return (streamActive) ? streamActive : false;
    11. };

    Lines 2-9 use a for loop to check each server-side Stream object, stream_av_1 and stream_av_2. Each instance is represented by the currentStream variable in line 3. If the isRecording property of the instance is true, a streamActive variable is set to true (line 5), and a callBack property is set to the string "exitApp" (line 6). This string represents the exitApp() method, which is described in the next step. If you recall from the streamStatus() method defined in the startup.asc document, each Stream instance checks for the existence of a callBack property when recording is stopped. By declaring the callBack property, the exitApp() method will be now be invoked by the streamStatus() method. The Stream instance stops recording in line 7. When the for loop completes, the checkStreams() method returns true (a stream was in the middle of recording) or false (the stream was not recording).

  3. The checkStreams() method will be invoked by the exitApp() method, which is invoked when the last client disconnects from the current instance of the conference application (see the onDisconnect() handler in the previous section). After the checkStreams() method, add the code in Listing 13.10 to the shutdown.asc document:

    Listing 13.10 exitApp() method

    1. application.exitApp = function(){
    2.   if(!this.checkStreams()){
    3.      trace("exitApp() invoked and checkStreams() returned false");
    4.      var title = this.sessionName_so.getProperty("title");
    5.      trace("title = " + title);
    6.      this.sessionTitle = (!title) ? "(No name)" : title;
    7.      this.checkTracker_1 = 
            this.av_1_timeTracker_so.getProperty("recordTimes");
    8.      this.checkTracker_2 = 
            this.av_2_timeTracker_so.getProperty("recordTimes");
    9.      this.closeSO();
    10.     this.stream_av_1.play(false);
    11.     this.stream_av_2.play(false);
    12.     this.shutDownApp();
    13.  }
    14. };

    In line 2 of the exitApp() method, the checkStreams() method is invoked. If the method returns a false value, lines 3-12 are processed. If checkStreams() returns a true value, the streamStatus() method of the recording stream instance will reinvoke the exitApp() method.

    Line 4 retrieves the current title property of the sessionName SharedObject. This is the SharedObject that each client can update by using the confName_txt field and the Change button in the recording client. Line 6 creates an application instance property named sessionTitle, which is equal to the title property if one exists. If a title has not been created, a title of "(No name)" is used.

    Lines 7 and 8 create references to the recordTimes array that stored each user's stream data. checkTracker_1 and checkTracker_2 are checked in the shutDownApp() method, discussed in step 5.

    Line 9 invokes a method named closeSO(). As its name implies, this method is responsible for closing the connections for most of the server-side Share-dObject instances. You will create the closeSO() method in the next step. Lines 10 and 11 tell the server-side Stream instances to stop subscribing to the streams created by the client-side AVPresence components.

    Line 12 invokes the shutDownApp() method, which will be described in step 5. This method saves the conference session's general information to the savedCalls SharedObject and begins the process of shutting down the remaining server-side SharedObject and NetConnection instances.

  4. Define the closeSO() method, which is invoked by the exitApp() method. The closeSO() method is responsible for closing all the server-side SharedObjects instances, except savedCalls_so. This SharedObject instance is closed later in the process. After the exitApp() method declaration in the shutdown.asc document, add the following lines of code:

    application.closeSO = function() { 
       trace("closeSO() invoked");
       this.sessionName_so.close();
       for (var i = 1; i <= 2; i++) {
          var avNum = "av_" + i;
          this[avNum + "_timeTracker_so"].flush();
          this[avNum + "_timeTracker_so"].close();
          this[avNum + "_so"].close(); 
       } 
    }; 

    This method closes the connection with the sessionName_so, av_1_timeTracker_so, av_2_timeTracker_so, av_1_so, and av_2_so instances.These instances were created (or initialized) in the initSO() method of the startup.asc document.

  5. Define the shutDownApp() method, which is also invoked by the exitApp() method. The shutDownApp() method stores all the remaining session data in the savedCalls remote SharedObject. Add the code in Listing 13.11 to the shut-down.asc document, after the closeSO() method declaration:

    Listing 13.11 shutDownApp() method

    1. application.shutDownApp = function() {
    2.    trace("shutDownApp() invoked.");
    3.    if(this.checkTracker_1.length > 0 || this.checkTracker_2.length 
          > 0){
    4.       var sessionObj = {
    5.          confTitle: this.sessionTitle,
    6.          confDate: this.currentDate,
    7.          confLength: this.fetchTime(),
    8.          confInstance: this.appName
    9.       };
    10.      this.soPropName = this.appName + "_" + this.currentDate;
    11.      this.savedCalls_so.setProperty(this.soPropName, sessionObj);
    12.    } else {
    13.      this.savedCalls_so.close();
    14.      this.parentConn_nc.close();
    15.    }
    16.    this.startTime = null;
    17. };

    If start and stop times were stored in either time tracker SharedObject instance, lines 4-11 are processed. A sessionObj instance is created, storing the sessionTime, currentDate, elapsed time, and application instance name values as properties of the object. This data is specific to each recording session, and the name for this data object must be unique. In line 10, a property named soPropName is formed, using the application instance name and the current date string. soPropName is then used as the name of a new property in the savedCalls data, which is connected by the savedCalls_so instance. The sessionObj data is specified as the value of the new property. As you will learn later in this chapter, the retrieval client uses each property name in the savedCalls data as a new item in a ComboBox component instance, so that a user can choose from a list of recorded sessions.

    At this point, you may want to revisit the syncTracker() method code in the startup.asc document. This method has the following if statement: if (list[i].name == application.soPropName && list[i].code == "success"

    if (list[i].name == application.soPropName && list[i].code == "success"
    && application.clients.length < 1) {
       trace("closed savedCalls_so");
       //close remaining SharedObject instances
       application.savedCalls_so.flush();
       application.savedCalls_so.close();
    
       //close client connection to default instance
       application.parentConn_nc.close();
    }

    When the soPropName property is created in the shutDownApp() method and added to the savedCalls SharedObject data, the onSync() handler for the saved-Calls_so instance is invoked after the data update occurs. Remember, the onSync() handler uses the syncTracker() method. As such, the if statement evaluates to true when the soPropName data and sessionObj data have been added to the savedCalls SharedObject, and the last user has disconnected from the application instance. At this time, the connection created by the savedCalls_so and parentConn_nc instances can be safely closed.

    Note

    You can also review the code in the onConnect() handler of the application object in the main.asc document. Any lingering SharedObject instances are closed in the onStatus() handler for the parentConn_nc instance, and the inited property of the application instance is set to false.

    Back in the shutDownApp() method, lines 12-15 are invoked if neither user published any streams with the AVPresence component instances. The connections created with the savedCalls_so and parentConn_nc instances are closed.

    In line 16, the startTime property is set to null. This property is reset for the next use of the application instance, just in case another pair of users connects to the instance before the FlashCom server unloads the instance (and all its properties).

  6. Save the shutdown.asc document.

  7. Go back to the main.asc document. Insert a load() action, indicating the name of the shutdown.asc file. Add the following highlighted line of code:

    load("components.asc"); 
    
    load("formdate.asc"); 
    load("timer.asc"); 
    load("startup.asc"); 
    load("shutdown.asc"); 
    
    application.onConnect = function(newClient) { 
     ... 
  8. Save the main.asc document.


    You can find the shutdown.asc document in the chapter_13 folder of this book's CD-ROM. The completed main.asc document is also in this location.

Testing the Conference Recording Client

You're ready to test all the server-side code that you have created in the previous sections. Make sure you have saved all the ASC files in the conference folder of your FlashCom server.

To quickly check the syntax of each ASC document for errors, you can copy and paste the ActionScript code into the Actions panel for a new temporary untitled Flash MX document. Create a new document (File > New) in Macromedia Flash MX, select the first frame of the timeline, and open the Actions panel (F9). Paste each ASC document's code into the panel, and click the Check Syntax button on the panel's toolbar. If an error is reported, the Output window will display some additional information about the error.

After you have checked each ASC document, restart your FlashCom server. In a Web browser, open the confRecord.html document created from the confRecord_101.fla document. Before you type a room name and click the Proceed button in the client, go back to Macromedia Flash MX and open the Communication App Inspector (Window > Communication App Inspector). In the inspector, log in to your FlashCom server. Go back to the Web browser containing the Flash client, type a room name, and click the Proceed button. If the ConnectionLight component instance turns green on the chat frame, your ASC documents did not contain any immediate syntax errors. If the light turns red, then it's likely that you have a syntax error in one of your ASC files for the conference application. If this occurs, you'll need to double-check your code.

TIP

Using the technique described earlier, copy and paste your ASC document's code into the Actions panel of a Flash MX document to check the syntax of your code.

Once you have a successful connection to an instance of the conference application, go to the Communication App Inspector, select the application instance name in the Active Application Instances list, and click the View Detail button. When the new details appear, leave the Live Log tab selected.

In the Web browser running the Flash client, make sure you have typed a name into the SimpleConnect instance and clicked the Login button. Start publishing a stream with the left AVPresence instance, speaker_1_mc. As the stream is publishing, look at the Live Log information in the Communication App Inspector. You should have data similar to the following trace() messages:

Publishing FCAVPresence.speaker_1_mc.av.---Current stream: av_1 
elapsedTime = NaN 
av_1 info.code = NetStream.Play.PublishNotify, NaN 
av_1: Publishing started. 
---Current stream: av_1 
elapsedTime = NaN 
av_1 info.code = NetStream.Record.Start, NaN 
av_1: Recording started. 
currentTime = 0, currentUser = Robert 
elapsedTime = 0 
0: name: recordTimes, code: success 

As you can see, when the first onStatus() calls are made on the stream_av_1 instance, the elapsedTime value returns NaN because the startTime value has not been initialized yet. However, when recording begins, currentTime and elapsed-Time report values of 0. The last trace() message is from the syncTracker() method, which is reporting the new data added to the recordTimes array for the av_1_timeTracker_so instance.

In the Communication App Inspector details, you should also see four streams active in the Streams tab: the two from the client-side AVPresence component instance and the two server-side Stream instances that are subscribing to the client-side streams. The Shared Objects tab should show seven SharedObjects, three persistent (Stored) and four temporary (Figure 13.21). The names of the two-time tracker persistent SharedObjects will vary, depending on the instance name of the application and the current date.

Figure 13.21Figure 13.21 The Shared Objects tab of the Communication App Inspector reveals the names of persistent and temporary remote SharedObjects.

Go back to the Web browser with the Flash client movie. Stop sending audio and video with the left AVPresence component by clicking the red circle "X" in the lower-left corner of the component (you have to roll over this area first with the mouse for the circle to appear). When the video no longer appears in the instance, go back to the Communication App Inspector's Live Log tab. You should see information similar to the following data. Note that the elapsedTime values will be different in your tests.

---Current stream: av_1
elapsedTime = 501812
FCAVPresence.speaker_1_mc.av is now unpublished.
av_1 info.code = NetStream.Play.UnpublishNotify, 501812
av_1: Publishing stopped.
---Current stream: av_1
elapsedTime = 501859
av_1 info.code = NetStream.Record.Stop, 501859
av_1: Recording stopped.
0: name: recordTimes, code: success

Now, if you test the right instance of the AVPresence component in the Flash client movie, you should see data similar to the trace() messages of the av_1 stream for the av_2 stream name. When you close the Flash movie (or close the Web browser window), the Live Log window displays the trace() messages associated with the shutdown routine. Again, the time values will be different in your own tests.

application.clients.length = 0
exitApp() invoked and checkStreams() returned false
title = Sun Nov 3 15:21:14
closeSO() invoked
shutDownApp() invoked.
elapsedTime = 823458
---Current stream: av_1
elapsedTime = 1036366509100
av_1 info.code = NetStream.Play.Stop, 1036366509100
---Current stream: av_1
elapsedTime = 1036366509100
av_1 info.code = NetStream.Unpublish.Success, 1036366509100
---Current stream: av_2
elapsedTime = 1036366509100
av_2 info.code = NetStream.Play.Stop, 1036366509100
---Current stream: av_2
elapsedTime = 1036366509100
av_2 info.code = NetStream.Unpublish.Success, 1036366509100
0: name: test_2002_11_03_15_21, code: success
closed savedCalls_so
parentConn_nc: info.code = NetConnection.Connect.Closed
---Default instance connection closed. All SharedObjects should be
.cleared.

If you see any errors reported in the Live Log output, check the syntax in your ASC documents again. If your code has introduced errors, you may see additional errors reported by server-side methods of Communication Component instances.

Once you have successfully tested the conference application by yourself, invite someone else to test the application with you. Check the Live Log output for errors while each person is publishing a stream.

  • + Share This
  • 🔖 Save To Your Account