Encoding for OAuth using AS3

 

AS3 has a few useful URL-related methods, like escape/unescape and encodeURI/decodeURI, but it doesn’t have a plain-and-simple encodeUTF8 function. The encodeURIComponent method encodes a string to UTF-8, but URL-encodes it as well, requiring the unescape method to wrap the call. Many developers have resorted to writing their own encodeUTF8 method, looping through each character and converting with bitwise. I’ve found this to be unreliable at times after pinpointing an issue with the OAuth lib I use(d) with TwitterAspirin. I came across a number of problems, specifically dealing with POST methods and incorrect signatures, so I decided to take a night to write my own OAuth request signer.

In a search to better understand the OAuth spec, I came across this terrific tutorial on OAuth by Eran Hammer-Lahav on Hueniverse. It is hands-down the most useful tutorial I have found on the subject, translating the OAuth spec for the “English-speaking” and providing a foolproof explanation for each step. The tutorial also provides input fields for each step, so you can manually input your keys, secrets, and tokens, and see if your result matches up.

The main reason this tutorial is so helpful is its emphasis on the UTF-8 encoding. Sure, the OAuth spec indicates the unreserved characters, but this tutorial stresses that most languages do not share the same unreserved characters—this is true for AS3. The following characters are listed as unreserved in the OAuth Core 1.0 spec:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 - . _ ~

Compare this with the unreserved characters of AS3′s escape method:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 @ - _ . * + /

And again with the unreserved characters of AS3′s encodeURIComponent method:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 - _ . ! ~ * ' ( )

As you can see, a solid amount of work is needed to match the unreserved characters listed in the OAuth spec. At the moment, this is the gargantuan series of method calls I use to properly encode the parameters used in an OAuth-related request:

1
2
3
protected function encode(str:String):String {
	return escape(unescape(encodeURIComponent(str))).replace(/%7E/g, '~').replace(/@/g, '%40').replace(/\*/g, '%2A').replace(/\+/g, '%2B').replace(/\//g, '%2F');
}

I know what you’re thinking—Jonnie has lost his marbles and the proof is that unescape method call wrapped in the escape method call. Believe me when I tell you it’s necessary. Why?—because of the additional unreserved characters in the encodeURIComponent method. The unescape method removes the URL encoding, so it’s just UTF-8 encoded at this point. Then, the escape method re-URL-encodes the string, but this time converts the additional unreserved characters as well. Now, I’m left with a half dozen replace method calls to convert the last few characters that aren’t in the OAuth spec. (If you know a way to combine all of these replace method calls into one, let me know! Regular expressions are slow in AS3)

I really hope this helps those venturing into the dark world of OAuth, and as always, my OAuth request signer can be found among the changes pushed to TwitterAspirin on GitHub. I also updated TwitterAspirinDemo to show how to use the library. Feel free to watch or fork either repo—both will see a lot of activity over the next few weeks.

Preparing for travel

 

gitzo

On Sunday, I fly to San Francisco to spend a couple days at the Adobe mothership before heading to Salt Lake City for the Omniture Summit. With each trip to the west coast, I try to learn from the experience, so the next time is smoother. For example, I will never again fly with a suit bag. Of course, “pack light” is a given, but there are other things, like essential pocket occupants, that are a necessity (see travel tissues, Burt’s Beeswax, black Bic pen).

Wherever I fly, I make sure to bring my camera. And, depending on the location, I have a number of decisions to make—which lenses to bring, whether or not I’ll need a tripod, etc. The first time to San Francisco, I brought my tripod—an 11 ft Gitzo with carbon fiber legs. It was obvious afterwords that this was a big mistake, so the next time I packed my Gorillapod. With a height of about a foot, this was pretty limiting, so I rarely used it.

This time, I’m prepared. On Monday, I placed an order on B&H for a Gitzo carbon fiber monopod. It weighs less than a pound and supports 26.4 lbs!—making it the perfect travel companion. It arrived today and I noticed something I wasn’t expecting. Instead of using the ballhead from my tripod and nullifying the lightweight aspect of the monopod, I thought I’d use the quick release system from my DIY steadycam. Unfortunately, the lock on the quick release interferes with the monopod’s base.

To correct this issue, I ordered a swivel/tilt head. It provides one-axis movement to quickly switch between landscape and portrait—perfect for monopods. It’s expected to arrive on Friday, just in time for the trip. I’m excited to see how it performs, so look forward to a follow-up post after the trip.

Dwarf adds unit types and tool position to its arsenal

 

Dwarf unit types

I’ve been working on Dwarf little by little and finally built one of the most requested features—unit types. The five available unit types are pixels, picas, centimeters, inches, and percent. Inches have dotted lines for quarter inches and percent always displays 100% on the ruler, but scales its grid to show ten columns and ten rows. At the moment, the units are based on a 72 dpi screen, but I’ll be adding an option to change the dpi, since most screens aren’t 72. If anyone has suggestions for that other than using a list, let me know.

dwarf_units_toolbar

The unit type is selected by clicking the menu at the right of the toolbar. It prompts a context menu with the options. Dwarf remembers which unit type you used last, so it’ll remain the same next time you startup. Along with unit types, I included positions and dimensions in the toolbar. This is mostly for the position, but I thought dimensions look nice up there too. At the moment, the position is in relation to the main screen, but the next build improves multi-screen support. You will be able to specify which screen to relate the position to. This also comes in handy for moving guides from screen to screen.

If you’re already a Dwarf user, start up for the update, or download it from GitHub. And, as always, let me know what you think in the comments.

Flex bug + Peter DeHaan = workaround + wheels in motion

 

I know, I know—Flex post?! I have been “drinking the Koolaid” these past few months, but this post is for the greater good. I found a bug and it had me panicking for a few solid hours yesterday. I typically would’ve kept my cool, but with a deadline quickly approaching and the fact that I’m still somewhat new to Flex, it was time to sound the alarms.

First, what’s the bug? It occurs when using multiple item renderers with the List component and changing the dataProvider property. The List should recycle the currently used renderers and choose ones that apply to the new data. Instead, the List tries to use the previous renderers on the new content, regardless of whether they match the data.

I resorted to using some internal resources at Adobe and within minutes had a workaround and bug report, courtesy of Peter DeHaan. Simply, reset the itemRendererFunction each time you change the dataProvider property. I know it’s a bit redundant, but it works and is a temporary solution until the fix is in place. If you’re interested in following the bug, you can watch it on JIRA.

Flash Player says n * 0.01 != n / 100

 

[Update] – Thanks to Wendel and everyone else on Twitter who pointed out why I should have gone to school for programming. This isn’t a bug, just “an artifact of float point operations”.

- - -

It’s no secret I’m an performance freak. I get excited whenever I learn of a new way to save a few milliseconds here or there. A few months ago, I learned that multiplication is slightly faster than division. Since then, I’ve been using multiplication over division when possible. Last night, when implementing alternate unit types in Dwarf, I experienced a strange behavior. As I resized a ruler, the size would randomly jump from two decimal points to 16—for example, 0.95 would appear as 0.9500000000000001.

At first, I just accepted it, but after a while, I decided to conduct an experiment. I tried using division instead of multiplication—surprisingly, this results in 0.95 appearing as 0.95. I then took it a step further and looped through a range of values:

Running from 0 to 500, checking each number for differences in multiplication vs division results in 62 instances where the bug occurs. From the test, I can conclude the following:

– The results do not vary from test to test. (ex: 35 * 0.01 = 0.35000000000000003 every time)

– The additional decimal points vary between 15 and 17 digits in length, with the last number ranging from 1 to 5

– The numbers affected are based on the divisor.

The results of the loop seemed to have a loose pattern, so I plugged them into the Google Charts API. The visuals are interesting, but don’t reveal an obvious pattern:

Next steps are to submit the bug to the mothership and hope for a fix!

Intro to Dwarf

 

I’ve been working on Dwarf over the past few days and decided it’s time to give a little introduction on its key features. Be sure to view fullscreen with no scaling to see it at 100%. The prerelease of Dwarf available to download on GitHub and the source code is hosted there as well. I’ll be rolling out the official 1.0 build pretty soon—I just need to add a few more key features.

Dwarf gets new life and is now open source

 

Dwarf on Git

A recent AIR prerelease drop broke Dwarf. I’m actually not surprised, since it uses a pretty ghetto hack—displaying a transparent window fullscreen and using ‘virtual’ windows. Because Dwarf is such an integral part of my everyday workflow and it’s such a small app, I figured I could easily rewrite it within a day or two. I’ve been on such a code-sharing high, that I started a new Git repository for it where you can find my work in progress. So far, I have a single ruler working with a semi-functional Mac toolbar. Everything should be complete either tonight or tomorrow, so keep an eye out.

On a legal note, the source code is provided under the GNU General Public License (GPL), so you can reuse and modify the code all you want as long as it’s still free. If you’d like to use it for commercial purposes, let’s talk.

Luke Williams of LukeLukeLuke.com launches a weblog

 

lukelukeluke_blog

My good friend, Luke Williams, finally launched his weblog—yes, I used the full word. Even though it has only been live for a short time, he already has a solid amount of fresh content. I know Luke is determined to keep this one active—as opposed to his first attempt, which ended up being comment-spammed by myself impersonating some of the more interesting people from MICA. Check it out and let him know what you think.

EventMap.mapListener bug (and fix!) in RobotLegs

 

This past week, I experienced a bug with RobotLegs where the EventMap.mapListener method would add the listener multiple times if called multiple times. Yesterday, I had some free time to dig a little deeper and managed to pinpoint the problematic code. It turns out the method didn’t check to see if the listener existed prior to adding to the array. This explains why a button click handler in my code would respond twice.

Thanks to the oh-so-wonderful GitHub, I was able to fork the repository, implement the fix, write a unit test to verify it’s safe, and find in the morning that it has been integrated into the actual RobotLegs repository—just like that. If you experienced the bug, be sure to pull the latest commit.

Now, if you’re not on GitHub, do yourself a favor and join today. In the few months I’ve been a member, I’ve met a handful of incredible developers and now feel compelled to share code when I can. Everyone benefits when you share what you know.

Introducing TwitterAspirin: an AS3 Twitter API painkiller

 

A couple months ago, I started working on a Twitter component for my current project at Adobe. I went into this knowing I’d have to finally face the beast… OAuth. Just about every well-known Twitter client out there uses Basic Auth—and for a reason. It’s easy, what the user expects, and gives your app more credibility—there’s no requirement to leave to authenticate through the browser like with OAuth.

About five or six months ago, Twitter decided to enforce the transition. From then on, any application that uses the API must use OAuth in order to see “via [your app]” on tweets published with it—otherwise, it would display “via API.” Since “via” is where apps get probably 90% of their referrals, this was a big deal. Luckily for me, DestroyTwitter existed before that time and Twitter decided not to push the change on the veteran apps. Recently, however, the bad news spread that Basic Auth would be deprecated in June. This means every Twitter app must transition to the pain that is OAuth.

After developing the MAX Companion this past fall and now the more generalized version, I found myself rewriting the Twitter component each time. After a while, the Twitter API code I wrote for DestroyTwitter began to merge with the actual implementation, so it was no longer a standalone library that could easily be used by other projects. These past few months, I’ve been learning a great deal about framework architecture and design patterns. It has led me to realize I need to start fresh.

With all that being said, I’d like introduce a library I started working on two days ago. I call it TwitterAspirin. It’s an AS3 Twitter API library that eases the pain, providing developers with a very powerful tool for communicating with Twitter. Though it’s still a newborn at the moment, I see potential already. The library is built on RobotLegs and uses AS3 Signals instead of events. It’s hosted on GitHub, so the source code will always be available to the public. And, after last night’s commit, its OAuth functionality is complete. Here’s how to use it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package {
	import com.destroytoday.twitteraspirin.Twitter;
 
	import flash.display.Sprite;
 
	public class Test extends Sprite {
		// set application consumer key and secret
		public var twitter:Twitter = new Twitter(consumerKey, consumerSecret);
 
		public function Test() {
			// add signal listeners
			twitter.oauth.requestTokenSignal.add(requestTokenHandler);
			twitter.oauth.accessTokenSignal.add(accessTokenHandler);
			twitter.oauth.verifyAccessTokenSignal.add(verifyAccessTokenHandler);
		}
 
		// click the 'Authorize' button to get the request token
		protected function authorizeClickHandler():void {
			twitter.oauth.getRequestToken();
		}
 
		// upon receiving the request token, open Twitter in the browser to authorize
		protected function requestTokenHandler(oauth:OAuth, token:OAuthToken):void {
			navigateToURL(new URLRequest(oauth.getAuthorizeURL()));
		}
 
		// return with the provided pin and click the 'Activate' button to get the access token
		protected function activateClickHandler():void {
			twitter.oauth.getAccessToken(pin);
		}
 
		// upon receiving the access token, verify it
		protected function accessTokenHandler(oauth:OAuth, token:OAuthToken):void {
			oauth.verifyAccessToken(token);
		}
 
		// done
		protected function verifyAccessTokenHandler(oauth:OAuth, token:OAuthToken):void {
		}
	}
}

As you can see, it’s extremely easy to use. Not only that, it provides great flexibility. Many libraries are simple to implement, but don’t allow the developer access to certain aspects of the process. With TwitterAspirin, each method returns the loader involved with the operation, giving developers the ability to listen for errors, cancel the operation, or attain the raw API data. The library also uses loader pools to recycle instances, so you can submit a tweet and, while it’s loading, submit another—you don’t have to wait for the first operation to finish. Then, once the operation is complete, the loader is disposed and returned to the pool, which optimizes performance and memory usage.

I’m really excited to see where TwitterAspirin goes and I have nothing but great expectations. Be sure to follow along with development and fork whenever you like.