Tweaking Minidlna Media Server on AsusWRT Merlin

usb storage, disable album arts, performance

You’re running AsusWRT Merlin and have some trouble with minidlna, e.g. bad media indexing performance or broken media databases ?

This can be caused by using an USB Stick as media database storage! Internally, minidlna is using an SQLite database to store the media file index – and sometime this database may broke (slow, unsynced file operations, user terminated processes).

As a workaround, it’s possible to move the media database to the temporary filesystem (ramdisk). As a disadvantage, on every system shutdown (reboot/power cycle) the database will be destroyed. But it only takes a view minutes to recreate it, because the ramdisk storage is a lot faster than the attached USB drive!

Just create an additional user config file in your JFFS /jffs/configs/minidlna.conf.add (will be automatically appended to the system generated minidlna.conf file!)

# Move the database to the tmp directory (ramdisk, will be recreated on reboot !!)
db_dir=/tmp/.minidlna

# create a custom minidlna logfile
log_dir=/var/log

# disable album art indexing
album_art_names=NO_ALBUM_ARTS.x

 

Ubuntu 15.10 with Dell Wireless 5570 HSPA+ (42Mbps) Mobile Broadband Card

mbmi to qmi modeswitch, magical ffc-auth sequence

A several days ago, i’ve replaced the Gobi 2000 WWAN Card with a newer version, a Dell 5570 Module. It’s a branded Sierra Wireless card, so i hoped it will work out of the box on Ubuntu 15.10 – but nothing. After some investigations if figured out, that the card is locked in “low-power” / […]

Ubuntu 15.10 – Disable Wake on LAN (WOL) permanently

ubuntu, systemd, Wily Werewolf, notebook, battery power drain

Preface# In some cases, Wake on LAN is enabled by default and you cannot disable it in your BIOS/UEFI because the setting is not available. On notebooks/ultrabooks, WOL can drain/discharge your battery even your device is powered-off! There are a several guides out there, which didn’t even work. The general mistake is, that the WOL […]

Single File ReCaptcha 2 PHP Client

leading captcha system, curl, php, json-response

Today, a web-form without a proven captcha system generates a lot of spam entries and data-trash in your database. One of the best is ReCaptcha (even the latest v2).

Google provides an easy to use ReCaptcha PHP Client – but it’s a bit over engineered! You need a bunch of PHP files and a composer based environment to use it out of the box. This can cause some trouble in highly customized/optimized projects.

Therefore, here is a “one-file” solution which works without any configuration overhead:

Usage#

require('ReCaptcha.php');

// register your secret
ReCaptcha::setSecret('<your-secret>');

// some code ...

// check user form
if (ReCaptcha::isValid()){ ...

One-File Solution#

// Developer Guide: https://developers.google.com/recaptcha/docs/verify
class ReCaptcha{

    // ReCaptcha API Endpoint
    const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';

    // the last result
    private static $_result = null;

    // client secret
    private static $_secret = null;

    // validate
    public static function isValid(){
        // token available ?
        if (!isset($_POST['g-recaptcha-response'])){
            return false;
        }

        // extract token
        $token = trim($_POST['g-recaptcha-response']);

        // generate url
        $params = http_build_query(array(
            'secret' => self::$_secret,
            'response' => $token,
            'remoteIp' => $_SERVER['REMOTE_ADDR']
        ), '', '&');

        // create curl based post request
        $handle = curl_init(self::SITE_VERIFY_URL);
        $options = array(
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $params,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),
            CURLINFO_HEADER_OUT => false,
            CURLOPT_HEADER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true
        );
        curl_setopt_array($handle, $options);
        $response = curl_exec($handle);
        curl_close($handle);

        // decode response
        self::$_result = json_decode($response, true);

        // check
        return (self::$_result['success'] === true);
    }

    // error occurred ?
    public static function isError(){
        return (self::$_result['success'] === false);
    }

    // get error message from last request
    public static function getErrorMessages(){
        return self::$_result['error-codes'];
    }

    // set client secret
    public static function setSecret($s){
        self::$_secret = $s;
    }
}

 

Node.js Simple Command Line Confirm Messages

user confirmation, terminal actions, yes, no

Sometime, special terminal commands can be dangerous for your users. To ensure that they are really want to run the command the proven “best practise” is to wait for an explicit user confirmation by typing yes/no into the terminal.

Install “prompt” using NPM#

First of all, you have to install prompt – a powerfull package for command line prompts & user interactions. The “–save” option will add this package to your package.json file.

npm install prompt --save

Confirm Dialog#

After installing the prompt package you can use the following code to show a confirm dialog to your users.

var _prompt = require('prompt');

// user confirmation required!
_prompt.start();

// disable prefix message & colors
_prompt.message = '';
_prompt.delimiter = '';
_prompt.colors = false;

// wait for user confirmation
_prompt.get({
    properties: {
        
        // setup the dialog
        confirm: {
            // allow yes, no, y, n, YES, NO, Y, N as answer
            pattern: /^(yes|no|y|n)$/gi,
            description: 'Do you really want to format the filesystem and delete all file ?',
            message: 'Type yes/no',
            required: true,
            default: 'no'
        }
    }
}, function (err, result){
    // transform to lower case
    var c = result.confirm.toLowerCase();

    // yes or y typed ? otherwise abort
    if (c!='y' && c!='yes'){
        console.log('ABORT');
        return;
    }
    
    // your code
    console.log('Action confirmed');
    
});

 

Maybe your wondering about some HTTP Headers sent to your browser which are not set in your script by the header() function ? Especially these Cache-Control headers:

Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

First of all: everything is ok! These headers are automatically set by the PHP Session module to prevent browser/proxy based caching of your pages. Depending on your environment setup, it’s possible to control these headers by using the session_cache_limiter() function or use the php.ini

To disable these behaviour just pass an empty string to the session_cache_limiter() function as mentioned in the documentation:

Solution#

// add this line to the beginning of your php script to disable the cache limiter funktion:
session_cache_limiter('');

Create Static Social-Media “Share” Buttons without Javascript

no external resources required, corporate privacy compliance

Social-Media Share Buttons are everywhere, but most of them are working with external hosted javascript resources which are loaded on each page request. Depending on the servers cache settings this can cause multiple additional http request for your visitors. Additionally it can raise some privacy issues becaue of the possibility that your users can be […]

MooTools: A modern Element.highlight() implementation

using CSS3 Transisitons instead of Fx.Tween

Use the following code as Element.highlight() replacement:

Element.implement({
    /**
     * Custom Element Highlighting Function
     * @param color
     */
    highlight: function(color){
        // get current background color
        var originalColor = this.getStyle('background-color');

        // set new background color
        this.setStyle('background-color', color);

        // restore background color after 300ms
        (function(){
            this.setStyle('background-color', originalColor);
        }).delay(300, this);
    }
});

It will only change the background color to the given value and reverse this after a time of 300ms. To get a fading-effect you need to add the following css, matching the elements you wish to apply the highlight() method:

.autocomplete-input{
    transition: background-color 200ms;
}

That’s it ;)

Are you using a Yubikey and want to create your custom Keyserver written in Node.js ? In this case this piece of code might be useful :)

/**
 * Convert the Yubico MODHEX encoded Strings to hex
 * @param modhex String
 * @returns hex String
 */
var modhex2hex = function(modhex){
    // strip whitespaces and string cleanup - all non matching characters are 0x00 (c in modhex)
    modhex = modhex.replace(/\s*/g, '').replace(/[^cbdefghijklnrtuv]/g, 'c');

    // even length ?
    if (modhex.length%2 !== 0){
        return null;
    }

    // modhex mapping base; c.....v => 0x0 ... 0xF
    var modhexBase = 'cbdefghijklnrtuv'.split('');

    // tmp
    var output = '';

    // convert
    for (var i=0;i<modhex.length;i++){
        // convert index to hex
        output += modhexBase.indexOf(modhex.charAt(i)).toString(16);
    }

    return output;
};

console.log(modhex2hex('te vt hh fg ue dk gv rt lv hb lu gf nk ge ng cv'));

Bootstrap Dismissible alerts with MooTools

use .alert-dismissible without jQuery

Bootstrap & MooTool#

Using Dismissible alerts with pure MooTools code. Just insert the following code within your domready startup:

Alert.js Replacement#

// get all elements with the .alert-dismissible class
document.getElements('.alert-dismissible').each(function(el){
  // add a onclick event to each element
  el.getElement('button.close').addEvent('click', function(){
    // hide the element on click
    el.setStyle('display', 'none');
  });
});

Dismissible alerts Example#

<div class="alert alert-danger alert-dismissible" id="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <strong>Invalid Regex Rule: </strong> <code class="txt"></code>
</div>