Roku Developer Program

Join our online forum to talk to Roku developers and fellow channel creators. Ask questions, share tips with the community, and find helpful resources.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
kjg
Visitor

Re: number of viewers query

I think I have it about figured out. it was a late night last night. I have the server side script now.
0 Kudos
kjg
Visitor

Re: number of viewers query

it almost there!
I get a " 200" back from server and a "1" for  transfer complete. But the count never shows up. Please, can someone suggest where my error is?  here is my code and server script.
Please disregard above info on channel. I scrapped the original code and started fresh. This is the part of the channel that communicates with the server. Thanks!!!

here is request task:
<?xml version="1.0" encoding="utf-8" ?>
<component name="NumTransfer" extends="Task">


    
  <script type="text/brightscript">
    <![CDATA[
sub init()
      print " in NumTransfer"
      'Print " Pin is "m.global.NumViewers
        m.top.functionName = "go3"
      end sub

      sub go3()
    timeout%  = 5000
    roRequest = CreateObject("roURLTransfer")    
    roRequest.setUrl("http://test.com:8080/formprocessor.php")
    print "In NumTransfer"      
    roPort = CreateObject("roMessagePort")  
    roRequest.setPort(roPort)
    'roRequest.AddHeader("customMethod","numviewers")
    'roRequest.EnableEncodings(true)
    numviewers = m.global.NumViewers
    customMethod = m.global.NumViewers
    print "after setting the port"
    sleep(2000)
        
    if (roRequest.AsyncPostFromString("numviewers"))
            roEvent = wait(timeout%, roRequest.GetPort())
            print "roEvent " roEvent
            print "numviewers =" numviewers
            if type(roEvent) = "roUrlEvent"
                str = roEvent.GetString()
                int = roEvent.GetInt()
                print "I am Transferring NumViewers"
                print "roEvent.GetResponseCode()" roEvent.GetResponseCode()
                print "str = " str
                print "Int =" int
            else if roEvent = invalid
                roRequest.AsyncCancel()  'reset the connection on timeouts
                print "Unknown"
            else
                print "roUrlTransfer::AsyncPostFromString(): unknown event"
            endif
     end if
    
    
     DeviceInfo  = CreateObject("roDeviceInfo")
        IPAddr      = DeviceInfo.getIPAddrs()
        transfer    = createObject("roUrlTransfer")
        for each item in IPAddr
        
          url       = "http://" + IPAddr[item]  + ":8060/keypress/Back"
          transfer.setUrl(url)
          transfer.PostFromString("")
          
          url       = "http://" + IPAddr[item]  + ":8060/keypress/Back"
          transfer.setUrl(url)
          transfer.PostFromString("")
        end for
    end sub
]]>
    
  </script>
   
  </component>






next is server side script:
<?php
    if(isset($_POST['customMethod']))
    {
        if(isset($_POST['numviewers']))
        {
            //Write the data to the file
            $file = @fopen("count.txt", "r+");
            
            if($file == false)
            {
                $file = fopen("count.txt", "w+");
            }
            
            $numViewers = $_POST['numviewers'];
            
            $count = fgets($file);
            
            if(($count == NULL) || ($count == ""))
            {
                //First entry in the file, just write to it
                fwrite($file, $numViewers);
            }
            
            else
            {
                //Increment and then write to the file
                $count = intval($count);
                $count += $numViewers;
                
                //Write back to the file
                fclose($file);
                $file = fopen("count.txt", "w+");
                fwrite($file, $count);
            }
            
            fclose($file);
        }
        
        else
        {
            echo "<h2>Incorrect Call</h2>";
        }
    }
    
    else
    {
        echo "<h2>Incorrect Call</h2>";
    }
?>


here is web form that works with the above script:
<html>
<head>
<title>Input Number Of Viewers</title>

<script type="text/javascript">
function processForm()
{
//Get the number of viewers from the entry in the form
var numViewers = document.getElementById("numviewers").value;

if(numViewers.length > 0)
{
if(numViewers.match(/^[0-9]+$/g))
{
//Send the report to the php processor
var xmlhttp = new XMLHttpRequest();
var url = "formprocessor.php";

var data = new FormData();
data.append('customMethod', 'updateCounter');
data.append('numviewers', numViewers);

   xmlhttp.onreadystatechange = function()
   {
       if (xmlhttp.readyState == XMLHttpRequest.DONE )
       {
          if (xmlhttp.status == 200)
          {
              window.location.href = "hls_progressive.html";
          }
         
          else if (xmlhttp.status == 400)
          {
             alert('There was an error 400');
          }
         
          else
          {
              alert('something else other than 200 was returned');
          }
       }
   };

   xmlhttp.open("POST", url, false);
   xmlhttp.send(data);
}
}

return false;
}
</script>

<style>
.content
{
position: relative;
}

.formdiv
{
background: #CCC;
border: 1px solid #000;
left: 30%;
height: 150px;
margin: 0 auto;
padding: 0 0;
position: absolute;
text-align: center;
top: 50%;
transform: translateY(100%);
width: 40%;
}
</style>
</head>

<body>
<div class="content">
<div class="formdiv">
<form class="viewerform" method="POST" onsubmit="return processForm();">
<p>Please Enter the Number of People that will be Viewing this Meeting</p>
<label for="numviewers">Number Of Viewers: <input type="text" name="numviewers" id="numviewers"></label><br><br>
<span class="viewerformbuttonspan"><input type="submit" value="Submit"></span>
</form>
</div>
</div>
</body>
</html>


here is what my roku shows:
------ Compiling dev 'channel test' ------

------ Running dev 'channel test' main ------
Main Function 1 SGScreen
 in NumTransfer
 in Exiter1
in Init pindialogscene
In OnKey Event
key pressed =OK
in Show Dialog
m.valuepin in onKeyEvent =
m.top.dialog.buttonSelected in onKeyEvent  =  0
In OnKey Event
In OnKey Event
in onKeyPress Function
M.TOP.DIALOG.PIN 2
m.global.NumViewers = 2
m.top.dialog.buttonSelected =  0
In NumTransfer
after setting the port
In OnKey Event
roEvent <h2>Incorrect Call</h2>
numviewers =2
I am Transferring NumViewers
roEvent.GetResponseCode() 200
str = <h2>Incorrect Call</h2>
Int = 1
In OnKey Event
In OnKey Event
key pressed =back
in Show Dialog
m.valuepin in onKeyEvent =
m.top.dialog.buttonSelected in onKeyEvent  =  0
you are here! in SG Function Main not in While
button Selected:  0
In Exiter
In AppExiter
in SimpleVideoScene.xml onKeyEvent OK false



0 Kudos
renojim
Community Streaming Expert

Re: number of viewers query

You're never actually POSTing a number.  You're just POSTing the string "numviewers".  I do this sort of thing all the time and I never bother with POST; I always use GET.  I'm sure someone will tell me why this is wrong, but what I do is this:
roRequest.setUrl("http://test.com:8080/formprocessor.php?numviewers="+numviewers.toStr())
print roRequest.getToString()

And then my PHP looks something like:
if (@isset($_GET['numviewers']))
  {
  $numviewers = $_GET['numviewers'];
  ...
  echo "OK";
  }

Keep in mind, it's late, I've had too much to drink, and I'm in a bad mood after a bad day at the casino, so the above may contain errors.  🙂

-JT
Roku Community Streaming Expert

Help others find this answer and click "Accept as Solution."
If you appreciate my answer, maybe give me a Kudo.

I am not a Roku employee.
0 Kudos
EnTerr
Roku Guru

Re: number of viewers query

"renojim" wrote:
You're never actually POSTing a number.  You're just POSTing the string "numviewers".  I do this sort of thing all the time and I never bother with POST; I always use GET.  I'm sure someone will tell me why this is wrong...

It's in bad taste, that's all. You are offending the RESTful gods. :mrgreen:
But if you don't mind being iconoclastic and clearly understand the differences, it's up to you. E.g. web crawlers use GET - are you concerned that GoogleBot may reboot your connected home devices by crawling down a page links? I remember back in the days there were histories of browsers deleting documents/emails because they were trying to pre-cache content and one of the links on the page was "Delete" working via GET.
0 Kudos
renojim
Community Streaming Expert

Re: number of viewers query

I'm not too worried about bots or crawlers since none of my PHP links appear on any pages. I'll admit, I took the easy way out (using query strings). I suppose you could do the same thing with a POST (using the same URI with query strings, but doing a POST instead of a GET) to get around the crawlers. It seems like too much work to me to put the data into a form or body and POSTing that. Then you have to parse that (I haven't looked into what it takes in PHP, but it may be trivial). I like the simplicity of the query strings. Isn't that how google-analytics works? They don't seem to be concerned with using GETs.

-JT
Roku Community Streaming Expert

Help others find this answer and click "Accept as Solution."
If you appreciate my answer, maybe give me a Kudo.

I am not a Roku employee.
0 Kudos
kjg
Visitor

Re: number of viewers query

thank you for your posts thus far. still not quite there. I had someone add the suggestion to the php script on the server as a secondary script. the original script needs to be in place since multiple devices access it through a web page.

I am trying to work out the exact way to send as a number and not as a string.

I was actually hoping to use original script but we are trying the suggestion.

thanks renojim
0 Kudos
EnTerr
Roku Guru

Re: number of viewers query

"renojim" wrote:
I'm not too worried about bots or crawlers since none of my PHP links appear on any pages.  I'll admit, I took the easy way out (using query strings).  I suppose you could do the same thing with a POST (using the same URI with query strings, but doing a POST instead of a GET) to get around the crawlers.  [...] I like the simplicity of the query strings.

Yes, you can totally use POST with query strings. As exemplified by our beloved ECP. I think it's "properly" RESTful, as in, uses POST for mutators and GET to request info. Calling with " -d '' " nudges CURL to use POST.

Isn't that how google-analytics works?  They don't seem to be concerned with using GETs.

I am not an expert. I just had a look https://developers.google.com/analytics ... /reference and while they prefer POST, they will benevolently allow you to use GET - while instructing to add "cache buster" to the query string.

The theological element comes with HTTP GET being defined as idempotent - which is a fancy way to say that there should be no difference on the server if GET on the same URL is invoked 1 or 2 or 5 times. The reason for that "strange" mandate is to allow for web proxies to insert themselves midstream and serve information they have heard before (from the same server but maybe different client) and cached.
0 Kudos
renojim
Community Streaming Expert

Re: number of viewers query

I admit it makes more sense to use POST. Maybe someday I'll change my approach, but I'll probably stick with queries. Then again, does it make sense to POST nothing in a query or to even POST a query in the first place? 🙂

-JT
Roku Community Streaming Expert

Help others find this answer and click "Accept as Solution."
If you appreciate my answer, maybe give me a Kudo.

I am not a Roku employee.
0 Kudos
renojim
Community Streaming Expert

Re: number of viewers query

Ok, I think I'm going to change my code to use AsyncPostFromString. Even though I don't think caching of my GETs is occurring, EnTerr's comments got me thinking POST is really the way to go. I'm still going to use the query string approach which requires no changes to my server PHP code. In case anyone is wondering about the $_GET vs $_POST PHP superglobals and why no PHP code changes are needed to switch from GET to POST when using query strings, here's a good explanation of the two: https://www.sitepoint.com/on-get-and-post/

-JT
Roku Community Streaming Expert

Help others find this answer and click "Accept as Solution."
If you appreciate my answer, maybe give me a Kudo.

I am not a Roku employee.
0 Kudos
kjg
Visitor

Re: number of viewers query

OK- I'm still stuck.
I am still getting incorrect call no matter what I do.
Cant use renojims code as it returns 500 errors.

um - help???

🙂
0 Kudos
Need Assistance?
Welcome to the Roku Community! Feel free to search our Community for answers or post your question to get help.

Become a Roku Streaming Expert!

Share your expertise, help fellow streamers, and unlock exclusive rewards as part of the Roku Community. Learn more.