winlin.utility.js 17.2 KB
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
// winlin.utility.js

/**
 * common utilities
 * depends: jquery1.10
 * https://code.csdn.net/snippets/147103
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 * v 1.0.11
 */

/**
 * padding the output.
 * padding(3, 5, '0') is 00003
 * padding(3, 5, 'x') is xxxx3
 * @see http://blog.csdn.net/win_lin/article/details/12065413
 */
function padding(number, length, prefix) {
    if(String(number).length >= length){
        return String(number);
    }
    return padding(prefix+number, length, prefix);
}

/**
 * extends system array, to remove all specified elem.
 * @param arr the array to remove elem from.
 * @param elem the elem to remove.
 * @remark all elem will be removed.
 * for example,
 *      arr = [10, 15, 20, 30, 20, 40]
 *      system_array_remove(arr, 10) // arr=[15, 20, 30, 20, 40]
 *      system_array_remove(arr, 20) // arr=[15, 30, 40]
 */
function system_array_remove(arr, elem) {
    if (!arr) {
        return;
    }

    var removed = true;
    var i = 0;
    while (removed) {
        removed = false;
        for (; i < arr.length; i++) {
            if (elem == arr[i]) {
                arr.splice(i, 1);
                removed = true;
                break;
            }
        }
    }
}

/**
 * whether the array contains specified element.
 * @param arr the array to find.
 * @param elem_or_function the element value or compare function.
 * @returns true contains elem; otherwise false.
 * for example,
 *      arr = [10, 15, 20, 30, 20, 40]
 *      system_array_contains(arr, 10) // true
 *      system_array_contains(arr, 11) // false
 *      system_array_contains(arr, function(elem){return elem == 30;}); // true
 *      system_array_contains(arr, function(elem){return elem == 60;}); // false
 */
function system_array_contains(arr, elem_or_function) {
    return system_array_get(arr, elem_or_function) != null;
}

/**
 * get the specified element from array
 * @param arr the array to find.
 * @param elem_or_function the element value or compare function.
 * @returns the matched elem; otherwise null.
 * for example,
 *      arr = [10, 15, 20, 30, 20, 40]
 *      system_array_get(arr, 10) // 10
 *      system_array_get(arr, 11) // null
 *      system_array_get(arr, function(elem){return elem == 30;}); // 30
 *      system_array_get(arr, function(elem){return elem == 60;}); // null
 */
function system_array_get(arr, elem_or_function) {
    for (var i = 0; i < arr.length; i++) {
        if (typeof elem_or_function == "function") {
            if (elem_or_function(arr[i])) {
                return arr[i];
            }
        } else {
            if (elem_or_function == arr[i]) {
                return arr[i];
            }
        }
    }
    return null;
}

/**
 * to iterate on array.
 * @param arr the array to iterate on.
 * @param pfn the function to apply on it
 * for example,
 *      arr = [10, 15, 20, 30, 20, 40]
 *      system_array_foreach(arr, function(elem, index){
 *          console.log('index=' + index + ',elem=' + elem);
 *      });
 */
function system_array_foreach(arr, pfn) {
    for (var i = 0; i < arr.length; i++) {
        if (pfn) {
            pfn(arr[i], i)
        }
    }
}

/**
 * array sort asc, for example:
 * [a, b] in [10, 11, 9]
 * then sort to: [9, 10, 11]
 * Usage, for example:
 obj.data.data.sort(function(a, b){
            return array_sort_asc(a.metadata.meta_id, b.metadata.meta_id);
        });
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 * @remark, if need desc, use -1*array_sort_asc(a,b)
 */
function array_sort_asc(elem_a, elem_b) {
    if (elem_a > elem_b) {
        return 1;
    }
    return (elem_a < elem_b)? -1 : 0;
}
function array_sort_desc(elem_a, elem_b) {
    return -1 * array_sort_asc(elem_a, elem_b);
}
function system_array_sort_asc(elem_a, elem_b) {
    return array_sort_asc(elem_a, elem_b);
}
function system_array_sort_desc(elem_a, elem_b) {
    return -1 * array_sort_asc(elem_a, elem_b);
}

/**
 * parse the query string to object.
 * parse the url location object as: host(hostname:http_port), pathname(dir/filename)
 * for example, url http://192.168.1.168:1980/ui/players.html?vhost=player.vhost.com&app=test&stream=livestream
 * parsed to object:
 {
     host        : "192.168.1.168:1980",
     hostname    : "192.168.1.168",
     http_port   : 1980,
     pathname    : "/ui/players.html",
     dir         : "/ui",
     filename    : "/players.html",

     vhost       : "player.vhost.com",
     app         : "test",
     stream      : "livestream"
 }
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 */
function parse_query_string(){
    var obj = {};

    // add the uri object.
    // parse the host(hostname:http_port), pathname(dir/filename)
    obj.host = window.location.host;
    obj.hostname = window.location.hostname;
    obj.http_port = (window.location.port == "")? 80:window.location.port;
    obj.pathname = window.location.pathname;
    if (obj.pathname.lastIndexOf("/") <= 0) {
        obj.dir = "/";
        obj.filename = "";
    } else {
        obj.dir = obj.pathname.substr(0, obj.pathname.lastIndexOf("/"));
        obj.filename = obj.pathname.substr(obj.pathname.lastIndexOf("/"));
    }

    // pure user query object.
    obj.user_query = {};

    // parse the query string.
    var query_string = String(window.location.search).replace(" ", "").split("?")[1];
    if(query_string == undefined){
        query_string = String(window.location.hash).replace(" ", "").split("#")[1];
        if(query_string == undefined){
            return obj;
        }
    }

    var queries = query_string.split("&");
    $(queries).each(function(){
        var query = this.split("=");
        obj[query[0]] = query[1];
        obj.user_query[query[0]] = query[1];
    });

    return obj;
}

/**
 * parse the rtmp url,
 * for example: rtmp://demo.srs.com:1935/live...vhost...players/livestream
 * @return object {server, port, vhost, app, stream}
 * for exmaple, rtmp_url is rtmp://demo.srs.com:1935/live...vhost...players/livestream
 * parsed to object:
 {
    server: "demo.srs.com",
    port: 1935,
    vhost: "players",
    app: "live",
    stream: "livestream"
 }
 */
function parse_rtmp_url(rtmp_url) {
    // @see: http://stackoverflow.com/questions/10469575/how-to-use-location-object-to-parse-url-without-redirecting-the-page-in-javascri
    var a = document.createElement("a");
    a.href = rtmp_url.replace("rtmp://", "http://").replace("?", "...").replace("=", "...");

    var vhost = a.hostname;
    var port = (a.port == "")? "1935":a.port;
    var app = a.pathname.substr(1, a.pathname.lastIndexOf("/") - 1);
    var stream = a.pathname.substr(a.pathname.lastIndexOf("/") + 1);

    // parse the vhost in the params of app, that srs supports.
    app = app.replace("...vhost...", "?vhost=");
    if (app.indexOf("?") >= 0) {
        var params = app.substr(app.indexOf("?"));
        app = app.substr(0, app.indexOf("?"));

        if (params.indexOf("vhost=") > 0) {
            vhost = params.substr(params.indexOf("vhost=") + "vhost=".length);
            if (vhost.indexOf("&") > 0) {
                vhost = vhost.substr(0, vhost.indexOf("&"));
            }
        }
    }

    // when vhost equals to server, and server is ip,
    // the vhost is __defaultVhost__
    if (a.hostname == vhost) {
        var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
        if (re.test(a.hostname)) {
            vhost = "__defaultVhost__";
        }
    }

    var ret = {
        server: a.hostname, port: port,
        vhost: vhost, app: app, stream: stream
    };

    return ret;
}

/**
 * get the agent.
 * @return an object specifies some browser.
 *   for example, get_browser_agents().MSIE
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 */
function get_browser_agents() {
    var agent = navigator.userAgent;

    /**
     WindowsPC platform, Win7:
     chrome 31.0.1650.63:
     Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
     (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
     firefox 23.0.1:
     Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101
     Firefox/23.0
     safari 5.1.7(7534.57.2):
     Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2
     (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2
     opera 15.0.1147.153:
     Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
     (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
     OPR/15.0.1147.153
     360 6.2.1.272:
     Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64;
     Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729;
     .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C;
     .NET4.0E)
     IE 10.0.9200.16750(update: 10.0.12):
     Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64;
     Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729;
     .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C;
     .NET4.0E)
     */

    return {
        // platform
        Android: agent.indexOf("Android") != -1,
        Windows: agent.indexOf("Windows") != -1,
        iPhone: agent.indexOf("iPhone") != -1,
        // Windows Browsers
        Chrome: agent.indexOf("Chrome") != -1,
        Firefox: agent.indexOf("Firefox") != -1,
        QQBrowser: agent.indexOf("QQBrowser") != -1,
        MSIE: agent.indexOf("MSIE") != -1,
        // Android Browsers
        Opera: agent.indexOf("Presto") != -1,
        MQQBrowser: agent.indexOf("MQQBrowser") != -1
    };
}

/**
 * format relative seconds to HH:MM:SS,
 * for example, 210s formated to 00:03:30
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 * @usage relative_seconds_to_HHMMSS(210)
 */
function relative_seconds_to_HHMMSS(seconds){
    var date = new Date();
    date.setTime(Number(seconds) * 1000);

    var ret = padding(date.getUTCHours(), 2, '0')
        + ":" + padding(date.getUTCMinutes(), 2, '0')
        + ":" + padding(date.getUTCSeconds(), 2, '0');

    return ret;
}

/**
 * format absolute seconds to HH:MM:SS,
 * for example, 1389146480s (2014-01-08 10:01:20 GMT+0800) formated to 10:01:20
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 * @usage absolute_seconds_to_HHMMSS(new Date().getTime() / 1000)
 */
function absolute_seconds_to_HHMMSS(seconds){
    var date = new Date();
    date.setTime(Number(seconds) * 1000);

    var ret = padding(date.getHours(), 2, '0')
        + ":" + padding(date.getMinutes(), 2, '0')
        + ":" + padding(date.getSeconds(), 2, '0');

    return ret;
}

/**
 * format absolute seconds to YYYY-mm-dd,
 * for example, 1389146480s (2014-01-08 10:01:20 GMT+0800) formated to 2014-01-08
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 * @usage absolute_seconds_to_YYYYmmdd(new Date().getTime() / 1000)
 */
function absolute_seconds_to_YYYYmmdd(seconds) {
    var date = new Date();
    date.setTime(Number(seconds) * 1000);

    var ret = date.getFullYear()
        + "-" + padding(date.getMonth() + 1, 2, '0')
        + "-" + padding(date.getDate(), 2, '0');

    return ret;
}

/**
 * parse the date in str to Date object.
 * @param str the date in str, format as "YYYY-mm-dd", for example, 2014-12-11
 * @returns a date object.
 * @usage YYYYmmdd_parse("2014-12-11")
 */
function YYYYmmdd_parse(str) {
    var date = new Date();
    date.setTime(Date.parse(str));
    return date;
}

/**
 * async refresh function call. to avoid multiple call.
 * @remark AsyncRefresh is for jquery to refresh the speicified pfn in a page;
 *      if angularjs, use AsyncRefresh2 to change pfn, cancel previous request for angularjs use singleton object.
 * @param refresh_interval the default refresh interval ms.
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 * the pfn can be implements as following:
 var async_refresh = new AsyncRefresh(pfn, 3000);
 function pfn() {
            if (!async_refresh.refresh_is_enabled()) {
                async_refresh.request(100);
                return;
            }
            $.ajax({
                type: 'GET', async: true, url: 'xxxxx',
                complete: function(){
                    if (!async_refresh.refresh_is_enabled()) {
                        async_refresh.request(0);
                    } else {
                        async_refresh.request(async_refresh.refresh_interval);
                    }
                },
                success: function(res){
                    // if donot allow refresh, directly return.
                    if (!async_refresh.refresh_is_enabled()) {
                        return;
                    }

                    // render the res.
                }
            });
        }
 */
function AsyncRefresh(pfn, refresh_interval) {
    this.refresh_interval = refresh_interval;

    this.__handler = null;
    this.__pfn = pfn;

    this.__enabled = true;
}
/**
 * disable the refresher, the pfn must check the refresh state.
 */
AsyncRefresh.prototype.refresh_disable = function() {
    this.__enabled = false;
}
AsyncRefresh.prototype.refresh_enable = function() {
    this.__enabled = true;
}
AsyncRefresh.prototype.refresh_is_enabled = function() {
    return this.__enabled;
}
/**
 * start new async request
 * @param timeout the timeout in ms.
 *      user can use the refresh_interval of the AsyncRefresh object,
 *      which initialized in constructor.
 */
AsyncRefresh.prototype.request = function(timeout) {
    if (this.__handler) {
        clearTimeout(this.__handler);
    }

    this.__handler = setTimeout(this.__pfn, timeout);
}

/**
 * async refresh v2, support cancellable refresh, and change the refresh pfn.
 * @remakr for angularjs. if user only need jquery, maybe AsyncRefresh is better.
 * @see: http://blog.csdn.net/win_lin/article/details/17994347
 * Usage:
 bsmControllers.controller('CServers', ['$scope', 'MServer', function($scope, MServer){
            async_refresh2.refresh_change(function(){
                // 获取服务器列表
                MServer.servers_load({}, function(data){
                    $scope.servers = data.data.servers;
                    async_refresh2.request();
                });
            }, 3000);

            async_refresh2.request(0);
        }]);
 bsmControllers.controller('CStreams', ['$scope', 'MStream', function($scope, MStream){
            async_refresh2.refresh_change(function(){
                // 获取流列表
                MStream.streams_load({}, function(data){
                    $scope.streams = data.data.streams;
                    async_refresh2.request();
                });
            }, 3000);

            async_refresh2.request(0);
        }]);
 */
function AsyncRefresh2() {
    /**
     * the function callback before call the pfn.
     * the protype is function():bool, which return true to invoke, false to abort the call.
     * null to ignore this callback.
     *
     * for example, user can abort the refresh by find the class popover:
     *      async_refresh2.on_before_call_pfn = function() {
     *          if ($(".popover").length > 0) {
     *              async_refresh2.request();
     *              return false;
     *          }
     *          return true;
     *      };
     */
    this.on_before_call_pfn = null;

    // use a anonymous function to call, and check the enabled when actually invoke.
    this.__call = {
        pfn: null,
        timeout: 0,
        __enabled: false,
        __handler: null
    };
}
// singleton
var async_refresh2 = new AsyncRefresh2();
/**
 * initialize or refresh change. cancel previous request, setup new request.
 * @param pfn a function():void to request after timeout. null to disable refresher.
 * @param timeout the timeout in ms, to call pfn. null to disable refresher.
 */
AsyncRefresh2.prototype.initialize = function(pfn, timeout) {
    this.refresh_change(pfn, timeout);
}
/**
 * stop refresh, the refresh pfn is set to null.
 */
AsyncRefresh2.prototype.stop = function() {
    this.refresh_change(null, null);
}
/**
 * change refresh pfn, the old pfn will set to disabled.
 */
AsyncRefresh2.prototype.refresh_change = function(pfn, timeout) {
    // cancel the previous call.
    if (this.__call.__handler) {
        clearTimeout(this.__handler);
    }
    this.__call.__enabled = false;

    // setup new call.
    this.__call = {
        pfn: pfn,
        timeout: timeout,
        __enabled: true,
        __handler: null
    };
}
/**
 * start new request, we never auto start the request,
 * user must start new request when previous completed.
 * @param timeout [optional] if not specified, use the timeout in initialize or refresh_change.
 */
AsyncRefresh2.prototype.request = function(timeout) {
    var self = this;
    var this_call = this.__call;

    // clear previous timeout.
    if (this_call.__handler) {
        clearTimeout(this_call.__handler);
    }

    // override the timeout
    if (timeout == undefined) {
        timeout = this_call.timeout;
    }

    // if user disabled refresher.
    if (this_call.pfn == null || timeout == null) {
        return;
    }

    this_call.__handler = setTimeout(function(){
        // cancelled by refresh_change, ignore.
        if (!this_call.__enabled) {
            return;
        }

        // callback if the handler installled.
        if (self.on_before_call_pfn) {
            if (!self.on_before_call_pfn()) {
                return;
            }
        }

        // do the actual call.
        this_call.pfn();
    }, timeout);
}

// other components.
/**
 * jquery/bootstrap pager.
 * depends: jquery1.10, boostrap2
 * https://code.csdn.net/snippets/146160
 * @see: http://blog.csdn.net/win_lin/article/details/17628631
 */