Mp3 single play on web page with JavaScript and Cookies

As in my prior post, I had another web site that played media every time someone entered the site,  but this time it was an MP3 file playing using a HTML5 audio player.

So, I adapted the script developed for the YouTube single play purpose to the mp3 HTML5 purpose stated above. I won’t go into specifics since all of that is covered in that article. If you have need for a script like this to limit playback of an mp3 file to once every hour on visiting a page then grab this code and make it work! Enjoy!

<audio controls id=”audioframe” autoplay=””>
<source src=”/audio/somefile.mp3
type=”audio/mpeg”>Your browser does not support the audio element.
</audio>

<script language=”javascript”>
// Autoplay on first load and then expire in one hour on cookie.
// Author: J.F. Almada

// Set the video to play here
var autoplay = “”;
var now = new Date();
var time = now.getTime();
// Expire the cookie in one hour
var expireTime = time + 1000*3600;

if (document.cookie.length == 0 || document.cookie.indexOf(“AUDIOCOOKIENAMEHERE=”) == -1) {
// Set the expiration
now.setTime(expireTime);
// Set the cookie with it’s autoexpiration
document.cookie = ‘AUDIOCOOKIENAMEHERE=true;expires=’+now.toGMTString()+’;path=/’;

autoplay += ‘autoplay’; // append an autoplay tag to the video URL
}
// For debugging – Uncomment to view the setting
// alert(autoplay);

// Pass the link value to the Iframe
document.getElementById(“audioframe”).autoplay = autoplay; // set the iframe autoplay

</script>

Adding YouTube JavaScript For Autoplay

I had a problem on one of the sites I manage where I needed to play a YouTube video once when the page loads but I had to have it only play the first time the viewer got to the page. Subsequent visits to the page should not play the video but I wanted the visitor to have the video play once again the next time they visit the site at some reasonable point in the future. So… I decided on a JavaScript and a cookie to get the job done.

So I hit Google and found a good starter script that sort of worked and decided to modify it to my liking.

The problem was that the code set a cookie that didn’t expire the way I liked. I wanted it to expire one hour from the time of the first visit, after creating the cookie and setting the expiration time one hour from the time of the first visit.

Lets walk through the code – It uses a standard “iframe” to play the video and the JavaScript uses a id named “videoframe” to link it up with the script to control the autoplay.

<iframe title=”YouTube video player”
id=”videoframe” width=”560″ height=”315″
src=”” frameborder=”0″ allowfullscreen>
</iframe>

The next code to add will be the JavaScript and we need to set a few parameters to fit it to our need. I have highlighted the sections you should change to fit your site needs, specifically the video URL and cookie name.

The code I added was to use the current date and time to expire the cookie in one hour. Other than that simple set of modifications, the script is similar to the original version.

<script language=”javascript”>
// Autoplay on first load and then expire in one hour on cookie.

// Set the video to play here
var link = “https://www.youtube.com/embed/-C_3eYj-pOM“;
var now = new Date();
var time = now.getTime();
// Expire the cookie in one hour
var expireTime = time + 1000*3600;

if (document.cookie.length == 0 || document.cookie.indexOf(“COOKIENAME=”) == -1) {
// Set the expiration
now.setTime(expireTime);
// Set the cookie with it’s autoexpiration
document.cookie = ‘COOKIENAME=true;expires=’+now.toGMTString()+’;path=/’;

link += “?autoplay=1”; // append an autoplay tag to the video URL
}
// For debugging – Uncomment to view the setting
// alert(link);

// Pass the link value to the Iframe
document.getElementById(“videoframe”).src = link; // set the iframe src

</script>

That’s it! Just modify what you need to and you’ll have a script that will expire the cookie in one hour and which will play the video once on the first page visit but not thereafter until one hour expires!

Enjoy! — Jon

Fall is here and Light5Media is humming along…

Much has been going on and with the arrival of the first rains of fall, California’s weather has gone from warm to distinctly cool.

I’m working hard on the business and weekly voice-overs and video shoots are part of the routine. I’ve learned a lot about the business of producing content and how YouTube works and am keeping my focus on what is important.

I’ve been getting into animation (in a very primitive way), but they came out good despite my initial thoughts of giving up on it in the following video.

Light5Media is one of the two YouTube channels I am throwing my efforts into and I am not going to quit. This work is paying off and staying the course is the answer.

The studio continues to evolve and improve, with the addition of new hardware to improve our vocals and deliver a better audio product. While voice-overs are an important part of the business, I’m keeping my eye on bigger fish and staying on-mission.

URLRewrite and IIS: Part Two – Introduction to “rewrite”

This is the second in our series about URLRewrite. We are going to focus on another aspect of URLRewrite. Namely the concept of rewriting a url “in-flight” to allow a URLRewrite rule to conduct an action that the administrator wishes to implement on the IIS server.

The subject of rewrites versus redirects immediately comes to mind. As I have worked over the years with IIS and URLRewrite, I found it far easier to use redirect rules, but these come with a penalty, since an incoming request causes additional overhead in the form of a new HTTP request being sent the server. Ideally, if you can avoid this, you should use a Rewrite rule to change the incoming request on the fly rather than overt redirect. The rewrite rule we are going to show you is a “redirect in disguise” and accomplishes the task of a redirect on one succinct operation rather than two.

Lets design the use-case:

Imagine we have a directory on a web site and this directory is no longer used, but you want to inform your users that the directory has been retired. What to do?

In a standard redirect rule, you would match on a particular directory and then redirect to the retired page as follows (Note, we are going to use “/docs” as the example directory that is no longer valid):

Conditionals for redirect rule

 

Action for redirect rule.

The code that is placed into the web root “web.config” file looks like this:

<rule name=”Example Redirect” patternSyntax=”ECMAScript” stopProcessing=”true”>
<match url=”(.*)” />
<action type=”Redirect” url=”/retired.html” />
<conditions logicalGrouping=”MatchAny”>
<add input=”{PATH_INFO}” pattern=”^/docs/(.*)” />
<add input=”{PATH_INFO}” pattern=”/docs” />
</conditions>
</rule>

When run in the browser, the following occurs:

Result of redirect run. Note that the URL changed to point to the “retired.html” page.

 

The rule fires and redirects to the expected url and is shown in the browser.

Note that in this rule, there are two conditions, either of which, when run, will perform the redirect. The first is to match any and all sub-directories of “docs”, while the second rule handles the case where the url of “http:/someserver/docs” is handled as a specific case of it’s own. I am absolutely certain some of you will comment on there being better ways to do this in this example, but for purposes of clarity, this is the format I chose to use. If you do want to send in examples of better ways to do this, visit the “contact” link and I will share your comments and ideas in future articles. Remember, I’m learning everyday too and there is ALWAYS a better way to do things ;>)

So… Our redirect example above is really pretty good. It handles the full range of references to references to the “/docs” directory and sub-directories. But is there a better way to do it? Let’s try the “rewrite” option and see what happens (after first disabling the prior example!):

Conditional at the URL section
Action clause for the rewrite rule.

The code that is placed into the web root “web.config” file looks like this:

<rule name=”Example Rewrite” stopProcessing=”true”>
<match url=”^docs/(.*)$” />
<action type=”Rewrite” url=”/retired.html” />
</rule>

Now let’s execute this rule:

The page loads the same “retired.html” as before, but the URL remains the same on the browser URL bar!

 

This is a three for one benefit. The browser doesn’t have to incur local overhead on a redirect. The server doesn’t have to work harder and the apparent URL doesn’t change on the client end. It is all handled at the server end of things.

Isn’t this a little more efficient? It does everything needed in four lines and with a single transaction. In truth, the redirect rule could have been more efficient, but again, for purposes of clarity, we want to get you to think in new ways about URLRewrite and to, as the character “Morpheous” says in “The Matrix” says, “free your mind”. A hint is to look at the line “<match url=”^docs/(.*)$” />” and perhaps try your own experiments with the redirect. That is the other thing with URLRewrite and, for that matter, mod_rewrite in Apache webservers. You want to try new rules, new ideas and play with them to get a good feel for what works and what does not. Experiment and don’t be afraid to fail.

Back to the rewrite rule. It is efficient and small. The minor penalty for the in-flight rewrite is less than what would be incurred against a redirect rule and provides a first taste of what can be done.

In truth, this is a small taste of the many things the rewrite rules can be used for. We will be covering more rewrite examples in coming articles and also discussing back-references and URLRewrite. These are extremely powerful and useful for helping to construct new urls and are a staple tool you will need to learn to effectively use URLRewrite.

Until next time!

Using IIS URLRewrite – Part 1

One of the tools I use with IIS 7.5 and 8.0 as a web administrator and designer to add functionality to applications like content management systems, document management systems and static web sites is to use URLRewrite.

This module is freely available from Microsoft and allows for creation of unique rules and processing of incoming and outgoing requests on the fly.

So what can it do? Most often, it allows for very simple handling of URL requests using simple to advanced rules that are accessible via the IIS Manager tool or by direct editing of the web.config file hosted under the web site for which the rules will be applied.

The most common rules URLRewrite is used for is for redirects based on one or more criteria.

In this first article, we will test two specific cases

  1. Single URL Redirect.
  2. Multiple Conditional Match Redirect

Single URL Redirect

Imagine a case where you want a specific page that is available on the web root of a site to no longer be accessible. You may want to use the page later, but you simply need a quick and dirty rule to redirect the page until you need it again later.

Since I use PHP often, I occasionally like to use a classic page called “phpinfo.php” to look at the site environment variables for my site. But it is dangerous to leave this file unprotected since it can give anyone a deep look into your site specifics. So, it makes sense to add a rule to deactivate access to the file until there is a need to use it.

The first step is to insure that URLRewrite is installed. To do so, make sure you have installed IIS on your system along with the IIS Manager tool and then install the “Web Platform Installer” per the instructions from Microsoft.

This tool allows IIS to install a wide range of add-ons from PHP to Perl and of course, URLRewrite 2.0. Simply follow the instructions and once it is installed, then launch Web Platform Installer. See the red colored icon under “Management” to launch the installer:

Launch the Web Platform Installer.

Type “URL” in the search bar and choose URLRewrite 2.0 and press “Add” – Note: In this photo, I have already installed URLRewite.
Type “URL” in the search bar and choose URLRewrite 2.0 and press “Add” – Note: In this photo, I have already installed URLRewite.
URL Rewrite Icon at the Site Level

Double-Click the icon to launch URL Rewrite and examine the screen. There will be no rules installed and the utility is waiting for it’s first rule to be added.

Let’s get back to the phpinfo.php rule.

We want to take any request coming into this site where the file “phpinfo.php” is referenced and to redirect it to another web site.

There are two ways to do this:

  1. From the IIS Manager screen with URL Rewrite Module administration.
  2. Or… by editing the web.config file at the site root.

Let’s start by doing the rule addition with the first option via the GUI. Add a new rule by clicking “Add Rule(s)” at the top right of the screen.

Next, choose “Blank rule” and press “OK”.

Give the rule a name. In this case called it “Example of Redirect”.

Make the following settings:

  • Under “Match URL”  set “Requested URL:” to “Matches the Pattern” and “Using” to “Exact Match”
  • In the “Pattern” box, type “phpinfo,php” or a file in your web root that you wish to redirect.
  • Under “Action”, chose “Action type” of “Redirect”
  • Under “Redirect URL:” enter a URL of choice. I entered http://www.google.com for the URL to redirect to.
  • Now click “Apply” on the top far right.
  • The rule is built and ready to use.
  • Enter the URL http://localhost/phpinfo.php (or whatever site url is appropriate) and your rule should activate.
This rule allows for matching of a single URL to redirect to a new location or site.

If you have trouble making the rule work, go back and check your entries for typos or not selecting the right drop down.

Now, go check your web.config file by editing with notepad or similar editor. You should see the following fragment:

<rule name=”Example of Redirect” enabled=”true” patternSyntax=”ExactMatch” stopProcessing=”true”>
                    <match url=”phpinfo.php” />
                    <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false” />
                    <action type=”Redirect” url=”http://www.google.com” />
</rule>

You can also just cut and paste this into the web.config file as follows:

<?xml version=”1.0″ encoding=”UTF-8″?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />

<rule name=”Example of Redirect” enabled=”true” patternSyntax=”ExactMatch” stopProcessing=”true”>
            <match url=”phpinfo.php” />
             <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false” />
              <action type=”Redirect” url=”http://www.google.com” />
</rule>

</rules>
 </rewrite>

    </system.webServer>
</configuration>

Multiple Conditional Match Direct

Let’s try a different rule. First, we want to go to URLRewrite  at the site list of icons and double click it. Let’s deactivate the first rule we did above. Highlight “Example of Redirect” and then on the right Actions menu, click “Disable Rule”. This is done to prevent it from firing because we are trying a new way to disable the phpinfo.php file from being accessed and to redirect it.

Second rule example

Like we did before, add a new blank rule. Call this one “Example of Redirect with multiple conditions”.

Enter the following:

  • Under “Match URL”, select “Matches the Pattern” for Requested URL and “Regular Expressions” for “Using:”
  • In the “Pattern” box enter (.*)
  • Under Conditions click “Add”
  • For Condition input type {SCRIPT_NAME}
  • For Check if input string: “Matches the Pattern”
  • Under pattern, enter “phpinfo.php”
  • Click OK to close.

Add a new blank condition rule:

  • Under “Match URL”, select “Matches the Pattern” for Requested URL and “Regular Expressions” for “Using:”
  • In the “Pattern” box enter (.*)
  • Under Conditions click “Add”
  • For Condition input type {SCRIPT_NAME}
  • For Check if input string: “Matches the Pattern”
  • Under pattern, enter “somefile.html”
  • Click OK to close.
  • Look under “Conditions” for “Logical grouping” and select “Match Any”

Move down to the “Action” section of the rule

  • Under “Action”, chose “Action type” of “Redirect”
  • Under “Redirect URL:” enter a URL of choice. I entered http://www.google.com for the URL to redirect to.
  • Now click “Apply” on the top far right.
  • The rule is built and ready to use.
  • Enter the URL http://localhost/phpinfo.php or the second URL for the second file – http://localhost/somefile.html.

What should happen is that you can test one of the two files to redirect to the URL you like.

Again, if the rule did not work, then you need to examine the settings and adjust as needed.

You can also cut and paste this code into the web.config file:

<?xml version=”1.0″ encoding=”UTF-8″?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name=”Rewrite test”>
                    <match url=”^article/([0-9]+)/([_0-9a-z-]+)” />
                    <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false” />
                    <action type=”Rewrite” url=”article.aspx?id={R:1}&amp;title={R:2}” />
                </rule>
                <rule name=”wordpress” patternSyntax=”Wildcard”>
                    <match url=”*” />
                    <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false”>
                        <add input=”{REQUEST_FILENAME}” matchType=”IsFile” negate=”true” />
                        <add input=”{REQUEST_FILENAME}” matchType=”IsDirectory” negate=”true” />
                    </conditions>
                    <action type=”Rewrite” url=”index.php” />
                </rule>
                <rule name=”Example of Redirect” enabled=”false” patternSyntax=”ExactMatch” stopProcessing=”true”>
                    <match url=”phpinfo.php” />
                    <conditions logicalGrouping=”MatchAll” trackAllCaptures=”false” />
                    <action type=”Redirect” url=”http://www.google.com” />
                </rule>
                <rule name=”Example of Redirect with multiple conditions” enabled=”true” patternSyntax=”ECMAScript” stopProcessing=”true”>
                    <match url=”(.*)” />
                    <conditions logicalGrouping=”MatchAny” trackAllCaptures=”false”>
                        <add input=”{SCRIPT_NAME}” pattern=”phpinfo.php” />
                        <add input=”{SCRIPT_NAME}” pattern=”404.shtml” />
                    </conditions>
                    <action type=”Redirect” url=”http://www.bing.com” />
                </rule>
            </rules>
        </rewrite>

    </system.webServer>
</configuration>

What have we learned?

In this lesson, we have learned how to configure URLRewrite and to test two rules. One with a single redirect based on a simple configuration and another using multiple conditions to be matched to fire the rule.

This is simply an introduction and we’ll cover an example of a Rewrite operation and also other useful operations that any web administrator would find useful in the next article.

 

 

 

 

 

 

Forwarding domains in Google Domains

As I was building this site, I noted I needed to forward another domain of mine to point to this site. It’s a pretty simple thing to do in any standard DNS configuration, but in this case, I was using Google Domains.

The problem was, I wanted to forward any requests to the root domain to the new destination domain. And Google Domains was NOT friendly about giving me the answer.

So it is really simple, once you think about it. Just add an “@” symbol to the “Subdomain to foward” dropdown (see image below) and enter your destination domain url, press “Add” and it is that simple!

Example of adding a root domain forward for a domain to forward web requests to a new domain – Just add the ampersand and the domain to forward to and voila!

Signs of Spring

This winter has been one for the record books and we were going a little stir-crazy with the amount of bad weather that has kept us from really getting out and enjoying life for the last few months. So when we got the chance to head out, I grabbed the video camera and documented the now prominent signs of Spring that are everywhere to be seen. I hope you enjoy it and also that you get outside and see your own beautiful sights as life reawakens from the Winter slumber.

Introductions…

I’ve worked in and around aerospace for most of my adult life. And now that is all about to end and a new future is opening up.

My expertise is in web based systems as well as many other aspects of computing, but I also have a wide range of outdoor interests and hobbies as well as a ranch I live on and am slowly taking on the role of running now.

This post is more for me than for anyone else. I just want to remember this moment before the site becomes whatever it will be.  All endeavors begin with a simple human desire to express one’s self and I am lucky to have a lot of God-given talents and gifts that make this all possible, so now it is just down to will power and a sense of adventure.

I’m getting started now and hope you’ll come along for the ride ;>)

Jon AKA “Afterburner”