Lukas Z's Blog

Custom Wrapper-DIV in Octopress

After writing the last post I wanted to add a div that would wrap the email I pasted so I can add some custom style to it. But if I just surrounded the markdown that made up the email with div-tags, then markdown would no longer render the contents and everything inside the div would be displayed as plaintext.

So enter Liquid::Block. The plan was to wrap the source that I wanted wrapped in a div using a liquid-tag.

I dug trough the source of Tobias Lütke’s Liquid to understand how to do it, but I obviously have some more digging to do. However, it’s probably quite clever. Basically, liquid allows to write secure markup that doesn’t eval anything. Everything that inherits from Liquid classes seem to have all methods unset which allows only calls to specifically defined methods.

Well, anyway. I’m sure there’s much more to it, but here’s my tiny little Octopress-plugin that just wraps the contents in a div. Since I’m using markdown, it will only work with markdown.

module Jekyll
        class CustomDivBlock < Liquid::Block
                def initialize(name, params, tokens)
                        @klass = params.strip
                        super
                end

                def render(context)
                        output = RDiscount.new( super ).to_html
                        "<div class='#{@klass}'>#{output}</div><div class='after_#{@klass}'></div>"
                end
        end
end

Liquid::Template.register_tag('customdiv', Jekyll::CustomDivBlock)

It can be now used like this is an Octopress source-file (the quote is from William Gibsons “Neuromancer”, btw.):

{% customdiv paper %}
“All the speed he took, all the turns he'd taken and the corners he'd cut in Night City, and still he'd see the matrix in his sleep, bright lattices of logic unfolding across that colorless void...” 
{% endcustomdiv %}

Here’s the result of the above:

“All the speed he took, all the turns he’d taken and the corners he’d cut in Night City, and still he’d see the matrix in his sleep, bright lattices of logic unfolding across that colorless void…”

It’s probably the “Hello World” of Octopress-plugins, but hey. Next time I have some time off, I’ll just read some more and revise / awesomify this plugin.

Encrypt Your Email With GPG

It’s 2013 and the way we use technology is moving in the wrong direction when it comes to privacy.

We should not accept that in the era of Facebook and Google Search privacy is a thing of the past. Because we cannot blindly trust corporations to handle our private data. Because we cannot assume the government does what is best for us, either. On the contrary. My understanding of democracy is that the public keeps an eye on what the government and public authorities do.

The fact that we live in a mostly peaceful world with a high living standard and low corruption (I am talking of western European countries here) is a huge achievement and a consequence of horrible wars (which had a huge impact on mentalities) and positive economic development afterwards. But looking at history it is an exception. An unlikely thing that happened. Meaning: Because things went well for my generation there is no guarantee that it will continue to be so.

I am an optimist and I do not expect a big catastrophy or another Adolf Hitler in Europe any time soon. But that does not mean that we can be lazy, put our fates (and our data!) in the government’s (or some corporation’s) hands and hope for the best. That would be a stupid thing to do. Our private information should remain private.

Some people still say things like: “I don’t have anything to hide anyway, so I don’t care.” This infuriates me. Especially when it is coming from educated people that should know better.

It is hard to maintain privacy nowadays. For example, last week Facebook suggested in an E-Mail that I “friend” some people that are only in my GMail contacts. - Wait. How did Facebook access my contacts? I haven’t given them the permission. But, and that’s the thing, my contacts gave theirs. In the end it seems that one cannot escape the data collection.

But we should do what we can, without missing out on all the benefits the Internet gives us.

So let me talk about email-encryption.

Why should you encrypt your email?

The Internet works, because many computers form a network of connections. Data is passed from point A to point B by sending it from one intermediary computer to the next. An email will pass through 10 to 20 computers before it reaches its destination.

Those computers include the switch of your DSL provider, their backbone routers, border gateway routers that connect larger regions (countries), the computers of the recipient’s email provider and so forth. Not to mention the guy that sits next table from you in the cafe, using the same unencrypted wireless network.

As a methaphor you can imagine this: You want to send the tax office your income statement. But the mail system doesn’t exist. So you write it with a black marker in big letters on a sheet of paper. For example: “I earned 1000 Euros last month.” Then you give that letter to your neighbor and ask him to give it to the lady next door, so she can then take it to her friend, who works at a store where an accountant from the tax office comes to do his shopping. Of course everyone in that chain can read your income statement. And this is basically how email works.

Your email is sent in plaintext.

Theoretically it can be read, copied and archived forever at any computer it passes through. It’s like sending a postcard. You would put a letter in an envelope, but the postcard can be read by anyone that takes a look. There’s basically no protection against eavesdropping. And no, the fact that you have to use your password to login to your webmail means nothing. The message still travels in plaintext through wires that you have no control over until it reaches your webmail provider’s servers.

(Technically email providers can secure the communication between each other, but this would only work if both sides support that functionality. I assume that is not a widespread practice yet. And besides, even then you would still have to trust the email provider..)

Think about what is being sent in emails. Invoices, contracts, company secrets, passwords and so forth. We rely heavily on email being secure, yet it is, by design, absolutely not. There’s no protection against eavesdropping at the transport layer.

Thus it’s prudent to put in some protection at the application layer. Enter email encryption.

It’s not complicated. Read on.

How can you encrypt your email?

Sadly, encryption was not built in as a default when email was invented. But that was in the 1960s and I guess they did not anticipate that something like the World Wide Web with billions of users would exist in the future. Therefore users have to take extra steps to encrypt their emails. But luckily there are good tools for that.

Using GPG, which is a standard open source encryption software, we can encrpyt every email using public key encryption.

It just means that one key is used to encrypt a message and another is used to decrypt a message. If somebody wants to send you an encrypted message, you just send him your public key first. He can use it to scramble the text. But he cannot use your public key to unscramble it. That can only be accomplished with your private key, which you never send to anyone.

Simple enough.

So basically to have encrypted email you need a key-store on your computer where you store all the keys of your recipients, and your two keys. You can upload your public key to a keyserver, where other people can just look it up if they want to send you something. For example, here’s the new one I just created if you want to email me.

And you also need the encryption software.

I am using OSX, so these instructions are for that OS. You can find the same information for Linux and Windows, it’s equally simple to do.

Here we go.

  1. Download and install GPGTools
  2. Follow their tutorial

That’s it.

Now, they will install an addon to the Mac’s Mail application that allows easy encryption and decryption. But it seems like it’s not done yet for Mountain Lion.

And besides, perhaps, like me, you prefer your email in the browser. In that case you will have to copy the email text out of the message and decrypt it manually. And the same vice versa when you want to encrypt a message. Write, encrypt, copy and paste into the browser.

I wrote these two short bash functions to help with that. They are aliases for gpg commands combined with using the clipboard. It saves me some typing. You can just put those in a file called “cryptobash.sh” or something similar, and then add “source ~/.cryptobash.sh” to your .bash_profile so they are available each time you open a terminal.

function decryptc(){
  pbpaste > /tmp/encrypted_message.txt; gpg -d /tmp/encrypted_message.txt | pbcopy; rm /tmp/encrypted_message; pbpaste
}

function encryptc(){
  pbpaste | gpg -e -a -r $1 | pbcopy
}

Now all I have to do is copy the encrypted email into the clipbard, and run decryptc (c stands for clipboard) in the terminal to see the plaintext. (If you are in on Linux, then you can use xclip instead of pbcopy and pbpaste.)

And voila, encryption isn’t such a big chore any more.

Key Storage

Keeping your keys safe and moving them between computers can be annoying. You have to protect your private key by all means, but you might want to have it available on another computer, for example in the office of your employer.

The way I do this is simply by storing it in KeePass. The KeePass-database file itself is encrypted, so I just put it into my Dropbox and have everything handy wherever I am.

Finally

There’s some downsides to all this of course. If you are using GMail, you cannot search the contents of your encrypted messages anymore. (Unless you specifically save the plaintext in GMail.) You can’t read your encrypted email on your phone as easily either.

But it’s probably not neccesary to encrypt everything. I won’t try to convince my parents to use GPG for example. And I don’t need to encrypt a link to a funny picture that I send to friends either.

However, I wish that people will start encrypt important things. Bank statements. Insurance documents. Spicy love letters. :) And so forth.

To be honest, I do not have much hope for that to happen soon. But who knows, a few privacy scandals, governments messing up (the Internet IS a threat to governments) and the general public might start to ask for secure email. Then perhaps companies will make a greater effort to make it easy (and fun?) to use.

Until that happens we can still send encrypted email already.

So we don’t have to send important things using the equivalent of postcards.

Does Email still matter?

Teenagers probably hardly use email at all. They have things like Skype, Whatsapp, Snapchat etc. But I think email will stay as the main communication tool in business and as a fallback and authentication method for all the other services. So when these teenagers grow up and get jobs they will use email. So yes, it still matters and will continue to do so.

Use Media Queries in Your CSS Now

So far CSS3 has given web developers some great new features. One of the newest W3C standards are Media Queries. And they should be used right now.

The idea is that you can specify style rules in your stylesheets that only apply to devices with certain characteristics. Thus, for example, you can make the same HTML-element render one way in the desktop browser, and another way on the smartphone.

This is fantastic. Some time ago the webserver would parse the HTTP-request to figure out what device the request comes from and serve a different stylesheet. Now we can let the user’s browser worry about that.

How it works

There’s several ways to define device-specific CSS:

  • In the link (or ?xml-stylesheet)-element, by adding a media-attribute to the tag.
  • In the @import-statement, by attaching a media type.
  • As a selector in the CSS-file.

The first two look like this:

<link rel="stylesheet" type="text/css" href="/stylesheet.css" media="print">

or

<?xml-stylesheet media="print" rel="stylesheet" href="stylesheet.css" ?>

And they instruct the browser to use a certain stylesheet under certain conditions. But let’s focus on the third way.

Basically, you just wrap certain elements in @media selectors. For example, let’s say you have a rule like this in your stylesheet:

#somediv {
  width: 900px;
  font-size: 16px;
}

This would probably look crappy on a handheld, because it would require horizontal scrolling. But now you can simply add another rule that makes the div render differently on a device with a smaller screen. So for example we now have this:

#somediv {
  width: 900px;
  font-size: 16px;
}

@media screen and (max-device-width: 800px) { // or something like this
  #somediv {
    width: 90%;
    font-size: 13px;
  }
}

Voilà, this will render a div with 90% parent div-width (let’s say screen width) on an iPhone, but exactly 900px on a desktop. Fantastic. And you can use these queries to change your whole layout, too. Just access this blog with a handheld, and you will see a different layout, without the sidebar etc. Or just make the browser window smaller. You should see the layout change at some point.

I’ve been writing HTML since the 90s, but lately it’s really getting good. Media Queries are definitely one of the reasons.

Media Features

There’s more than just “max-device-with”. The list includes:

  • color (interesting when considering that your page might be displayed on something like a Kindle.)
  • device-aspect-ratio
  • orientation (landscape or portrait)

..and so forth. Check out this list. Scroll a little bit up on this page to see a list of media types.

Read more

For more information do visit the official W3C recommendation page for media queries.

Twitter Cards and Open Graph Metatags in Octopress

To continue on the topic from the last post, here is how I added Twitter-cards and open graph metadata to this blog.

It runs on Octopress so to add the new html-tags I edited source/_includes/head.html like this:


<!-- ... omitted beginning of head.html -->

<head>
  <meta charset="utf-8">
  <title>{% if page.title %}{{ page.title }} - {% endif %}{{ site.title }}</title>
  <meta name="author" content="{{ site.author }}">

  {% capture description %}{% if page.description %}{{ page.description }}{% else %}{{ content | raw_content }}{% endif %}{% endcapture %}
  <meta name="description" content="{{ description | strip_html | condense_spaces | truncate:150 }}">
  {% if page.keywords %}<meta name="keywords" content="{{ page.keywords }}">{% endif %}

  {% capture canonical %}{{ site.url }}{% if site.permalink contains '.html' %}{{ page.url }}{% else %}{{ page.url | remove:'index.html' }}{% endif %}{% endcapture %}
  {% capture ogtype %}{% if page.title %}article{% else %}blog{% endif %}{% endcapture %}

  <!-- twitter card -->
  <meta name="twitter:card" content="summary">
  <meta name="twitter:site" content="@lukaszielinski">
  <meta name="twitter:creator" content="@lukaszielinski">
  <meta name="twitter:title" content="{% if page.title %}{{ page.title }} - {% endif %}{{ site.title }}">
  <meta name="twitter:url" content="{{ canonical }}">
  <meta name="twitter:description" content="{{ description | strip_html | condense_spaces | truncate:150 }}">

  <!-- open graph -->
  <meta property="og:title" content="{% if page.title %}{{ page.title }} - {% endif %}{{ site.title }}"/>
  <meta property="og:type" content="{{ ogtype }}"/>
  <meta property="og:url" content="{{ canonical }}"/>
  <meta property="og:site_name" content="Blog of Lukas Zielinski"/>
  <meta property="og:description" content="{{ description | strip_html | condense_spaces | truncate:150 }}"/>

  <!-- ... omitted rest of head.html -->
</head>

If you are using a theme you will probably have to edit the file .themes/theme_name/_includes/head.html.

Reminder: Put Semantic Data on All Your Pages

Just a quick reminder for all you web-devs out there: Put semantic metadata on all your pages.

Here’s the three usual suspects that I consider most important:

  1. Rich Snippets, there is a handy testing tool from Google
  2. Twitter Cards, there is a Twitter preview tool
  3. OpenGraph

In case you don’t know why you should care: If someone posts a link to your page or if it shows up in search results, it will look better and give the user more information on what to expect when they click it.

Just for fun, you can create a helper to do that. Here’s my crappy version (which doesn’t support Rich Snippets, because they have a different purpose and usage):

require 'rubygems'
require 'action_view'
require 'erb'

class MetadataHelper

  include ActionView::Helpers::TagHelper

  def initialize( opts = {} )
    @title        = opts[:title]
    @url          = opts[:url]
    @description  = opts[:description]
    @image_url    = opts[:image]
    @author       = opts[:author]
    @name         = opts[:name]
    @type         = opts[:type]
  end

  def old_school
    Array.new.tap do |arr| 
      arr << ttag( @title )
      arr << mtag( 'description', @description )
      arr << mtag( 'author', @name )
    end.compact
  end
  
  def twitter_card
    Array.new.tap do |arr| 
      arr << mtag( 'twitter:card', 'summary' )
      arr << mtag( 'twitter:url',  @url )
      arr << mtag( 'twitter:title', @title )
      arr << mtag( 'twitter:description', @description )
      arr << mtag( 'twitter:image', @image_url )
      arr << mtag( 'twitter:author', @author )
    end.compact
  end

  def open_graph
    Array.new.tap do |arr| 
      arr << mtag( 'og:type', @type )
      arr << mtag( 'og:url',  @url )
      arr << mtag( 'og:title', @title )
      arr << mtag( 'og:description', @description )
      arr << mtag( 'og:image', @image_url )
    end.compact
  end

  def all
    [ old_school, twitter_card, open_graph ].flatten.join( "\n" )
  end

  private

  def mtag( name, content )
    tag( :meta, { name: name, content: content }, false, false ) if name && content
  end
  
  def ttag( content )
    content_tag( :title, content ) if content
  end

end

template = ERB.new <<EOS
<!DOCTYPE HTML>
<html>
  <head>
    <%= helper.all %>
  </head>
  <body>
    <p>Hello people!</p>
  </body>
</html>
EOS

helper = MetadataHelper.new( { 
  title:        'Test', 
  url:          'http://www.lukaszielinski.de', 
  description:  'Just testing',
  type:         'article',
  author:       '@lukaszielinski',
  name:         'Lukas Zielinski',
  image:        'http://mugs.mugbug.co.uk/500/mb.i_love_html_red_love_heart.coaster.jpg'
} )

puts template.result( binding )

And yes, I know, I have to put it on all my pages, too. But the day only has so many hours..

Attach a vCard to Your Emails

I received an email with an attachment the other day. It was a .vcf file and I tapped it. Immediately the dialog for adding new contacts popped up and I could just add this person to my address book. This is of course very convenient.

This is also not new (It’s probably been around longer than http), but somehow I have completely forgotten about it. Thus this post as a little reminder.

I have started attaching a vCard to my emails. But since GMail doesn’t allow me to add a file to my signature, I simply post a link to my vCard, which the user can click or tap to add me.

It looks like this: http://www.lukaszielinski.de/vCard.vcf

I suggest everyone to add this to their signature. Convenience matters, in business and otherwise.

P.S.: Check out vCard Maker to easily create your vCard without having to type it yourself.

Tagging View for iOS

I’ve been working on my iPhone app for the last few days and it requires the ability for users to tag things. For a moment I thought I can do this with built-in controls, but then I quickly realized I needed a custom control.

So I created a little tagging-class that can be pulled into the storyboard, because it’s just a view. It’s always nice to have something self-contained, so I decided to put it on Github.

Screenshot of LZTagView

You can download it here.

It allows the user to enter a new tag, which will be displayed in a nice bubble. Suggested tags can be supplied, in which case they appear above the keyboard and can be tapped to add.

I’ve Released My First iOS-app in the AppStore

My first app has appeared on the iTunes AppStore!

This is somewhat exciting. In part, because it’s a niche product which also has strong competition.

I have no idea if people will like the app and if anyone at all will use it. There could also still be bugs that I haven’t noticed which might turn off users or make them give me a bad rating. All I know is that I use it.

So what is it?

It’s one of those nightstand / alarm clock apps. It basically displays the time and wakes the user up with their own music. As a special feature I have added something that I like to do quite often: It displays images linked to from reddit.com as a slideshow.

Here is a screenshot:

Havana Clock Screenshot

It’s called “Havana Clock” and I have created a tiny rails page here that contains the app-store link.

This page also exposes an API for the app that simply collects usage statistics. From time to time the app will contact the server and supply basic information such as the iOS-version of the device it is running on. I thought it would be interesting to see how quickly users update to a new iOS-version and what app-features they use the most for example. I do not collect any personal information.

Making-of

The reason I started developing this app was that I was reading a book about objective-c programming when I was on holiday in Cuba. I have been using a competitor’s alarm clock app to wake up every morning so it was something that I would use myself. Which is good, because even if nobody ever downloads and uses the app, I will still have a cool alarm clock!

The project also uses a variety of concepts from the iOS-world, so I thought it would be a great app to learn some basics. And it was.

I started about a month ago and at the end of the first day I had an app that could display the time and show alternating background pictures. Because I was entertaining the idea to create a blogpost-reader app before, I already had written some code to fetch data off websites and a parser-wrapper for XML and JSON. So I took those classes and put them into the clock app. Voila, some tweaking later, it would display the images from the reddit-frontpage.

I added the rest of the app in the next two weeks, mostly working on it in the evenings. It was quite a lot of fun. Fun and learning combined. Also, I was suprised to find programmning objective-c so so enjoyable! (It really is, but that is probably because of the great work Apple put into developing the iOS-APIs, and ARC, which removes some of the housekeeping duties when programming.)

After three weeks it looked almost usable, but then I had this epiphany that I wasn’t happy with some of the design I had come up with. Especially the part that handles persistent storage (users’s alarms and settings). So I took some time to refactor a good part of the codebase.

Then about 90 - 95% was done and the most difficult time began. The time, when the cool, fun stuff is done and the boring, but neccessary, part begins. Polishing the app, tweaking the UI, putting in the in-app purchase payments. I just worked through it until I was at a point where I thought it could be released.

At this point I had 20 feature-ideas or so. Things that would be nice to have. But I decided to stop here and release, because it is easy to get stuck in development forever. And every new feature that seems easy enough might in fact take much longer than anticipated.

So I did a git tag 1.0 and submitted the binary to the AppStore.

Then the app got rejected.

Bummer, I thought. First app ever submitted and they reject it. But it turns out it was because I used a background mode to play music even if the app is not running.

iOS only allows multitasking in certain, limited ways and only for good reasons. One cannot just define a background mode in the .plist-file without a necessity.

So I sent Apple a clarification-email stating why I use that mode together with a step-by-step guide to reproduce and see the effect on their test-devices. I also quickly recorded a short clip with my phone that showed the effect, put it up online and sent them the link.

Two hours later the app was approved.

I think it might have helped to be very explicit with the explanation in order to make their job simpler.

Marketing

I haven’t come up with a marketing plan yet. I’ll wait and see how many users I will have without any marketing (after all, perhaps enough people will find the app using the AppStore search function).

I will probably log on to reddit and tell them that I have made this app. And ask them for feedback.

Which is something I hope I will get in any case. Feedback. So I can learn how to make this application better.

And who knows, right? Perhaps there are many people (incredible amounts, really) who like to have an alarm clock that displays pictures from reddit! And word will spread on its own! :)

But I am not that optimistic. First and foremost this was just about getting some iOS-experience. I am already coding another app, this time for my new iPhone 5 (I love that phone, great piece of hardware and software engineering). And it is as much fun as making the first one.

Updates

I will keep supporting Havana Clock for at least a year and fix bugs should I (or someone else) find any. I will probably release version 1.1 in January with a few improvements that I discarded in order to release before Christmas. And perhaps the 1.1 will also come with a new, super-secret background mode!

Finally

Developing for iOS has been more fun than I would have anticipated. I am still in love with Ruby and she doesn’t have to be jealous, because objective-c cannot match her beauty and elegance. But I would really enjoy to do more iOS-development in the future. Actually, very much so.

Thank you for reading and, again, here is the link: Havana Clock

Panopticlick

There’s a post on Hacker News today about talking about user tracking without them even logging in, accepting any cookies and so forth. It’s accomplished by using a fingerprinting-technique.

Fingerprints are information about your browser that seem to be quite unique (or their combination). Thus, once you enter your information on any website that uses fingerprint tracking, you can be identified on any other website doing the same.

Anyway, there’s a page that shows how this might work: https://panopticlick.eff.org

I just wondered over coffee, if I could manipulate some or all of the values this displays using a browser-extension. Turns out it’s easy to manipulate the things that seem to be most selective when it comes to uniquness: User Agent, Browser Plugins and Fonts.

Anyway, this is just a quick hack, it removes the Flash object that gets the fonts, it spoofs the User-Agent field in the HTTP-Request and nullifies the navigator.plugins-array.

I don’t want to spend more time on it now (I must do other things), but if you like you can continue what I’ve started. Here’s the code.

Du With Depth 1

Just a tiny shell-snippet which I find useful to find things that waste space on my disk:

$ du -h -d 1

This will show you the amount of space the files and subdirectories in your current directory use.