2
0

winlin.utility.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. // winlin.utility.js
  2. /**
  3. * common utilities
  4. * depends: jquery1.10
  5. * https://code.csdn.net/snippets/147103
  6. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  7. * v 1.0.11
  8. */
  9. /**
  10. * padding the output.
  11. * padding(3, 5, '0') is 00003
  12. * padding(3, 5, 'x') is xxxx3
  13. * @see http://blog.csdn.net/win_lin/article/details/12065413
  14. */
  15. function padding(number, length, prefix) {
  16. if(String(number).length >= length){
  17. return String(number);
  18. }
  19. return padding(prefix+number, length, prefix);
  20. }
  21. /**
  22. * extends system array, to remove all specified elem.
  23. * @param arr the array to remove elem from.
  24. * @param elem the elem to remove.
  25. * @remark all elem will be removed.
  26. * for example,
  27. * arr = [10, 15, 20, 30, 20, 40]
  28. * system_array_remove(arr, 10) // arr=[15, 20, 30, 20, 40]
  29. * system_array_remove(arr, 20) // arr=[15, 30, 40]
  30. */
  31. function system_array_remove(arr, elem) {
  32. if (!arr) {
  33. return;
  34. }
  35. var removed = true;
  36. var i = 0;
  37. while (removed) {
  38. removed = false;
  39. for (; i < arr.length; i++) {
  40. if (elem == arr[i]) {
  41. arr.splice(i, 1);
  42. removed = true;
  43. break;
  44. }
  45. }
  46. }
  47. }
  48. /**
  49. * whether the array contains specified element.
  50. * @param arr the array to find.
  51. * @param elem_or_function the element value or compare function.
  52. * @returns true contains elem; otherwise false.
  53. * for example,
  54. * arr = [10, 15, 20, 30, 20, 40]
  55. * system_array_contains(arr, 10) // true
  56. * system_array_contains(arr, 11) // false
  57. * system_array_contains(arr, function(elem){return elem == 30;}); // true
  58. * system_array_contains(arr, function(elem){return elem == 60;}); // false
  59. */
  60. function system_array_contains(arr, elem_or_function) {
  61. return system_array_get(arr, elem_or_function) != null;
  62. }
  63. /**
  64. * get the specified element from array
  65. * @param arr the array to find.
  66. * @param elem_or_function the element value or compare function.
  67. * @returns the matched elem; otherwise null.
  68. * for example,
  69. * arr = [10, 15, 20, 30, 20, 40]
  70. * system_array_get(arr, 10) // 10
  71. * system_array_get(arr, 11) // null
  72. * system_array_get(arr, function(elem){return elem == 30;}); // 30
  73. * system_array_get(arr, function(elem){return elem == 60;}); // null
  74. */
  75. function system_array_get(arr, elem_or_function) {
  76. for (var i = 0; i < arr.length; i++) {
  77. if (typeof elem_or_function == "function") {
  78. if (elem_or_function(arr[i])) {
  79. return arr[i];
  80. }
  81. } else {
  82. if (elem_or_function == arr[i]) {
  83. return arr[i];
  84. }
  85. }
  86. }
  87. return null;
  88. }
  89. /**
  90. * to iterate on array.
  91. * @param arr the array to iterate on.
  92. * @param pfn the function to apply on it
  93. * for example,
  94. * arr = [10, 15, 20, 30, 20, 40]
  95. * system_array_foreach(arr, function(elem, index){
  96. * console.log('index=' + index + ',elem=' + elem);
  97. * });
  98. */
  99. function system_array_foreach(arr, pfn) {
  100. for (var i = 0; i < arr.length; i++) {
  101. if (pfn) {
  102. pfn(arr[i], i)
  103. }
  104. }
  105. }
  106. /**
  107. * array sort asc, for example:
  108. * [a, b] in [10, 11, 9]
  109. * then sort to: [9, 10, 11]
  110. * Usage, for example:
  111. obj.data.data.sort(function(a, b){
  112. return array_sort_asc(a.metadata.meta_id, b.metadata.meta_id);
  113. });
  114. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  115. * @remark, if need desc, use -1*array_sort_asc(a,b)
  116. */
  117. function array_sort_asc(elem_a, elem_b) {
  118. if (elem_a > elem_b) {
  119. return 1;
  120. }
  121. return (elem_a < elem_b)? -1 : 0;
  122. }
  123. function array_sort_desc(elem_a, elem_b) {
  124. return -1 * array_sort_asc(elem_a, elem_b);
  125. }
  126. function system_array_sort_asc(elem_a, elem_b) {
  127. return array_sort_asc(elem_a, elem_b);
  128. }
  129. function system_array_sort_desc(elem_a, elem_b) {
  130. return -1 * array_sort_asc(elem_a, elem_b);
  131. }
  132. /**
  133. * parse the query string to object.
  134. * parse the url location object as: host(hostname:http_port), pathname(dir/filename)
  135. * for example, url http://192.168.1.168:1980/ui/players.html?vhost=player.vhost.com&app=test&stream=livestream
  136. * parsed to object:
  137. {
  138. host : "192.168.1.168:1980",
  139. hostname : "192.168.1.168",
  140. http_port : 1980,
  141. pathname : "/ui/players.html",
  142. dir : "/ui",
  143. filename : "/players.html",
  144. vhost : "player.vhost.com",
  145. app : "test",
  146. stream : "livestream"
  147. }
  148. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  149. */
  150. function parse_query_string(){
  151. var obj = {};
  152. // add the uri object.
  153. // parse the host(hostname:http_port), pathname(dir/filename)
  154. obj.host = window.location.host;
  155. obj.hostname = window.location.hostname;
  156. obj.http_port = (window.location.port == "")? 80:window.location.port;
  157. obj.pathname = window.location.pathname;
  158. if (obj.pathname.lastIndexOf("/") <= 0) {
  159. obj.dir = "/";
  160. obj.filename = "";
  161. } else {
  162. obj.dir = obj.pathname.substr(0, obj.pathname.lastIndexOf("/"));
  163. obj.filename = obj.pathname.substr(obj.pathname.lastIndexOf("/"));
  164. }
  165. // pure user query object.
  166. obj.user_query = {};
  167. // parse the query string.
  168. var query_string = String(window.location.search).replace(" ", "").split("?")[1];
  169. if(query_string == undefined){
  170. query_string = String(window.location.hash).replace(" ", "").split("#")[1];
  171. if(query_string == undefined){
  172. return obj;
  173. }
  174. }
  175. var queries = query_string.split("&");
  176. $(queries).each(function(){
  177. var query = this.split("=");
  178. obj[query[0]] = query[1];
  179. obj.user_query[query[0]] = query[1];
  180. });
  181. return obj;
  182. }
  183. /**
  184. * parse the rtmp url,
  185. * for example: rtmp://demo.srs.com:1935/live...vhost...players/livestream
  186. * @return object {server, port, vhost, app, stream}
  187. * for exmaple, rtmp_url is rtmp://demo.srs.com:1935/live...vhost...players/livestream
  188. * parsed to object:
  189. {
  190. server: "demo.srs.com",
  191. port: 1935,
  192. vhost: "players",
  193. app: "live",
  194. stream: "livestream"
  195. }
  196. */
  197. function parse_rtmp_url(rtmp_url) {
  198. // @see: http://stackoverflow.com/questions/10469575/how-to-use-location-object-to-parse-url-without-redirecting-the-page-in-javascri
  199. var a = document.createElement("a");
  200. a.href = rtmp_url.replace("rtmp://", "http://").replace("?", "...").replace("=", "...");
  201. var vhost = a.hostname;
  202. var port = (a.port == "")? "1935":a.port;
  203. var app = a.pathname.substr(1, a.pathname.lastIndexOf("/") - 1);
  204. var stream = a.pathname.substr(a.pathname.lastIndexOf("/") + 1);
  205. // parse the vhost in the params of app, that srs supports.
  206. app = app.replace("...vhost...", "?vhost=");
  207. if (app.indexOf("?") >= 0) {
  208. var params = app.substr(app.indexOf("?"));
  209. app = app.substr(0, app.indexOf("?"));
  210. if (params.indexOf("vhost=") > 0) {
  211. vhost = params.substr(params.indexOf("vhost=") + "vhost=".length);
  212. if (vhost.indexOf("&") > 0) {
  213. vhost = vhost.substr(0, vhost.indexOf("&"));
  214. }
  215. }
  216. }
  217. // when vhost equals to server, and server is ip,
  218. // the vhost is __defaultVhost__
  219. if (a.hostname == vhost) {
  220. var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
  221. if (re.test(a.hostname)) {
  222. vhost = "__defaultVhost__";
  223. }
  224. }
  225. var ret = {
  226. server: a.hostname, port: port,
  227. vhost: vhost, app: app, stream: stream
  228. };
  229. return ret;
  230. }
  231. /**
  232. * get the agent.
  233. * @return an object specifies some browser.
  234. * for example, get_browser_agents().MSIE
  235. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  236. */
  237. function get_browser_agents() {
  238. var agent = navigator.userAgent;
  239. /**
  240. WindowsPC platform, Win7:
  241. chrome 31.0.1650.63:
  242. Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
  243. (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
  244. firefox 23.0.1:
  245. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101
  246. Firefox/23.0
  247. safari 5.1.7(7534.57.2):
  248. Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2
  249. (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2
  250. opera 15.0.1147.153:
  251. Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
  252. (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
  253. OPR/15.0.1147.153
  254. 360 6.2.1.272:
  255. Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64;
  256. Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729;
  257. .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C;
  258. .NET4.0E)
  259. IE 10.0.9200.16750(update: 10.0.12):
  260. Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64;
  261. Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729;
  262. .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C;
  263. .NET4.0E)
  264. */
  265. return {
  266. // platform
  267. Android: agent.indexOf("Android") != -1,
  268. Windows: agent.indexOf("Windows") != -1,
  269. iPhone: agent.indexOf("iPhone") != -1,
  270. // Windows Browsers
  271. Chrome: agent.indexOf("Chrome") != -1,
  272. Firefox: agent.indexOf("Firefox") != -1,
  273. QQBrowser: agent.indexOf("QQBrowser") != -1,
  274. MSIE: agent.indexOf("MSIE") != -1,
  275. // Android Browsers
  276. Opera: agent.indexOf("Presto") != -1,
  277. MQQBrowser: agent.indexOf("MQQBrowser") != -1
  278. };
  279. }
  280. /**
  281. * format relative seconds to HH:MM:SS,
  282. * for example, 210s formated to 00:03:30
  283. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  284. * @usage relative_seconds_to_HHMMSS(210)
  285. */
  286. function relative_seconds_to_HHMMSS(seconds){
  287. var date = new Date();
  288. date.setTime(Number(seconds) * 1000);
  289. var ret = padding(date.getUTCHours(), 2, '0')
  290. + ":" + padding(date.getUTCMinutes(), 2, '0')
  291. + ":" + padding(date.getUTCSeconds(), 2, '0');
  292. return ret;
  293. }
  294. /**
  295. * format absolute seconds to HH:MM:SS,
  296. * for example, 1389146480s (2014-01-08 10:01:20 GMT+0800) formated to 10:01:20
  297. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  298. * @usage absolute_seconds_to_HHMMSS(new Date().getTime() / 1000)
  299. */
  300. function absolute_seconds_to_HHMMSS(seconds){
  301. var date = new Date();
  302. date.setTime(Number(seconds) * 1000);
  303. var ret = padding(date.getHours(), 2, '0')
  304. + ":" + padding(date.getMinutes(), 2, '0')
  305. + ":" + padding(date.getSeconds(), 2, '0');
  306. return ret;
  307. }
  308. /**
  309. * format absolute seconds to YYYY-mm-dd,
  310. * for example, 1389146480s (2014-01-08 10:01:20 GMT+0800) formated to 2014-01-08
  311. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  312. * @usage absolute_seconds_to_YYYYmmdd(new Date().getTime() / 1000)
  313. */
  314. function absolute_seconds_to_YYYYmmdd(seconds) {
  315. var date = new Date();
  316. date.setTime(Number(seconds) * 1000);
  317. var ret = date.getFullYear()
  318. + "-" + padding(date.getMonth() + 1, 2, '0')
  319. + "-" + padding(date.getDate(), 2, '0');
  320. return ret;
  321. }
  322. /**
  323. * parse the date in str to Date object.
  324. * @param str the date in str, format as "YYYY-mm-dd", for example, 2014-12-11
  325. * @returns a date object.
  326. * @usage YYYYmmdd_parse("2014-12-11")
  327. */
  328. function YYYYmmdd_parse(str) {
  329. var date = new Date();
  330. date.setTime(Date.parse(str));
  331. return date;
  332. }
  333. /**
  334. * async refresh function call. to avoid multiple call.
  335. * @remark AsyncRefresh is for jquery to refresh the speicified pfn in a page;
  336. * if angularjs, use AsyncRefresh2 to change pfn, cancel previous request for angularjs use singleton object.
  337. * @param refresh_interval the default refresh interval ms.
  338. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  339. * the pfn can be implements as following:
  340. var async_refresh = new AsyncRefresh(pfn, 3000);
  341. function pfn() {
  342. if (!async_refresh.refresh_is_enabled()) {
  343. async_refresh.request(100);
  344. return;
  345. }
  346. $.ajax({
  347. type: 'GET', async: true, url: 'xxxxx',
  348. complete: function(){
  349. if (!async_refresh.refresh_is_enabled()) {
  350. async_refresh.request(0);
  351. } else {
  352. async_refresh.request(async_refresh.refresh_interval);
  353. }
  354. },
  355. success: function(res){
  356. // if donot allow refresh, directly return.
  357. if (!async_refresh.refresh_is_enabled()) {
  358. return;
  359. }
  360. // render the res.
  361. }
  362. });
  363. }
  364. */
  365. function AsyncRefresh(pfn, refresh_interval) {
  366. this.refresh_interval = refresh_interval;
  367. this.__handler = null;
  368. this.__pfn = pfn;
  369. this.__enabled = true;
  370. }
  371. /**
  372. * disable the refresher, the pfn must check the refresh state.
  373. */
  374. AsyncRefresh.prototype.refresh_disable = function() {
  375. this.__enabled = false;
  376. }
  377. AsyncRefresh.prototype.refresh_enable = function() {
  378. this.__enabled = true;
  379. }
  380. AsyncRefresh.prototype.refresh_is_enabled = function() {
  381. return this.__enabled;
  382. }
  383. /**
  384. * start new async request
  385. * @param timeout the timeout in ms.
  386. * user can use the refresh_interval of the AsyncRefresh object,
  387. * which initialized in constructor.
  388. */
  389. AsyncRefresh.prototype.request = function(timeout) {
  390. if (this.__handler) {
  391. clearTimeout(this.__handler);
  392. }
  393. this.__handler = setTimeout(this.__pfn, timeout);
  394. }
  395. /**
  396. * async refresh v2, support cancellable refresh, and change the refresh pfn.
  397. * @remakr for angularjs. if user only need jquery, maybe AsyncRefresh is better.
  398. * @see: http://blog.csdn.net/win_lin/article/details/17994347
  399. * Usage:
  400. bsmControllers.controller('CServers', ['$scope', 'MServer', function($scope, MServer){
  401. async_refresh2.refresh_change(function(){
  402. // 获取服务器列表
  403. MServer.servers_load({}, function(data){
  404. $scope.servers = data.data.servers;
  405. async_refresh2.request();
  406. });
  407. }, 3000);
  408. async_refresh2.request(0);
  409. }]);
  410. bsmControllers.controller('CStreams', ['$scope', 'MStream', function($scope, MStream){
  411. async_refresh2.refresh_change(function(){
  412. // 获取流列表
  413. MStream.streams_load({}, function(data){
  414. $scope.streams = data.data.streams;
  415. async_refresh2.request();
  416. });
  417. }, 3000);
  418. async_refresh2.request(0);
  419. }]);
  420. */
  421. function AsyncRefresh2() {
  422. /**
  423. * the function callback before call the pfn.
  424. * the protype is function():bool, which return true to invoke, false to abort the call.
  425. * null to ignore this callback.
  426. *
  427. * for example, user can abort the refresh by find the class popover:
  428. * async_refresh2.on_before_call_pfn = function() {
  429. * if ($(".popover").length > 0) {
  430. * async_refresh2.request();
  431. * return false;
  432. * }
  433. * return true;
  434. * };
  435. */
  436. this.on_before_call_pfn = null;
  437. // use a anonymous function to call, and check the enabled when actually invoke.
  438. this.__call = {
  439. pfn: null,
  440. timeout: 0,
  441. __enabled: false,
  442. __handler: null
  443. };
  444. }
  445. // singleton
  446. var async_refresh2 = new AsyncRefresh2();
  447. /**
  448. * initialize or refresh change. cancel previous request, setup new request.
  449. * @param pfn a function():void to request after timeout. null to disable refresher.
  450. * @param timeout the timeout in ms, to call pfn. null to disable refresher.
  451. */
  452. AsyncRefresh2.prototype.initialize = function(pfn, timeout) {
  453. this.refresh_change(pfn, timeout);
  454. }
  455. /**
  456. * stop refresh, the refresh pfn is set to null.
  457. */
  458. AsyncRefresh2.prototype.stop = function() {
  459. this.refresh_change(null, null);
  460. }
  461. /**
  462. * change refresh pfn, the old pfn will set to disabled.
  463. */
  464. AsyncRefresh2.prototype.refresh_change = function(pfn, timeout) {
  465. // cancel the previous call.
  466. if (this.__call.__handler) {
  467. clearTimeout(this.__handler);
  468. }
  469. this.__call.__enabled = false;
  470. // setup new call.
  471. this.__call = {
  472. pfn: pfn,
  473. timeout: timeout,
  474. __enabled: true,
  475. __handler: null
  476. };
  477. }
  478. /**
  479. * start new request, we never auto start the request,
  480. * user must start new request when previous completed.
  481. * @param timeout [optional] if not specified, use the timeout in initialize or refresh_change.
  482. */
  483. AsyncRefresh2.prototype.request = function(timeout) {
  484. var self = this;
  485. var this_call = this.__call;
  486. // clear previous timeout.
  487. if (this_call.__handler) {
  488. clearTimeout(this_call.__handler);
  489. }
  490. // override the timeout
  491. if (timeout == undefined) {
  492. timeout = this_call.timeout;
  493. }
  494. // if user disabled refresher.
  495. if (this_call.pfn == null || timeout == null) {
  496. return;
  497. }
  498. this_call.__handler = setTimeout(function(){
  499. // cancelled by refresh_change, ignore.
  500. if (!this_call.__enabled) {
  501. return;
  502. }
  503. // callback if the handler installled.
  504. if (self.on_before_call_pfn) {
  505. if (!self.on_before_call_pfn()) {
  506. return;
  507. }
  508. }
  509. // do the actual call.
  510. this_call.pfn();
  511. }, timeout);
  512. }
  513. // other components.
  514. /**
  515. * jquery/bootstrap pager.
  516. * depends: jquery1.10, boostrap2
  517. * https://code.csdn.net/snippets/146160
  518. * @see: http://blog.csdn.net/win_lin/article/details/17628631
  519. */