anncic-api 3.4.5 → 3.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/apitest.js CHANGED
@@ -1,946 +1,946 @@
1
- var currentUrl;
2
- var xhrTestingApi = null;
3
- var todayPassedTime = null;
4
- var _keyTypes = {};
5
- var _sortType = null;
6
- var descriptionsList = {};
7
-
8
-
9
- Date.prototype.format = function (format) {
10
- var o =
11
- {
12
- "M+": this.getMonth() + 1,
13
- //month
14
- "d+": this.getDate(),
15
- //day
16
- "h+": this.getHours(),
17
- //hour
18
- "m+": this.getMinutes(),
19
- //minute
20
- "s+": this.getSeconds(),
21
- //second
22
- "q+": Math.floor((this.getMonth() + 3) / 3),
23
- //quarter
24
- "S": this.getMilliseconds()
25
- //millisecond
26
-
27
- }
28
-
29
- if (/(y+)/.test(format)) {
30
- format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
31
-
32
- }
33
-
34
- for (var k in o) {
35
- if (new RegExp("(" + k + ")").test(format)) {
36
- format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
37
-
38
- }
39
-
40
- }
41
- return format;
42
-
43
- }
44
-
45
- //'2012-11-16 10:36:50';
46
- function datetime_to_unix(datetime) {
47
- if (datetime == '') {
48
- return 0;
49
-
50
- }
51
- else if (parseInt(datetime) == datetime) {
52
- return parseInt(datetime);
53
-
54
- }
55
- var tmp_datetime = datetime.replace(/:/g, '-');
56
- tmp_datetime = tmp_datetime.replace(/ /g, '-');
57
- var arr = tmp_datetime.split("-");
58
- var now = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
59
- return parseInt(now.getTime() / 1000);
60
-
61
- }
62
-
63
- //'2012-11-16 10:36:50';
64
- function unix_to_datetime(unix) {
65
- var now = new Date(parseInt(unix) * 1000);
66
- return now.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
67
-
68
- }
69
-
70
-
71
- function JSON_stringify(s, emit_unicode) {
72
- var json = JSON.stringify(s);
73
- return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
74
- function (c) {
75
- return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(- 4);
76
-
77
- }
78
- );
79
-
80
- }
81
-
82
-
83
-
84
- function range_to_badge(range) {
85
- var s = '';
86
- if (range < 0) {
87
- }
88
- else if (range < 60 * 60) {
89
- s = '<span class="badge badge-soon">刚才</span>';
90
-
91
- }
92
- else {
93
- if (!todayPassedTime) {
94
- todayPassedTime = (new Date()).getTime() / 1000 - datetime_to_unix((new Date().format('yyyy-MM-dd 00:00:00')));
95
-
96
- }
97
-
98
- range = range + 60 * 60 * 24 - todayPassedTime;
99
-
100
- if (range < 60 * 60 * 24) {
101
- s = '<span class="badge badge-today">今天</span>';
102
-
103
- }
104
- else if (range < 60 * 60 * 24 * 2) {
105
- s = '<span class="badge badge-yesterday">昨天</span>';
106
-
107
- }
108
- else if (range < 60 * 60 * 24 * 3) {
109
- s = '<span class="badge badge-beforeyester">前天</span>';
110
-
111
- }
112
- else if (range < 60 * 60 * 24 * 365) {
113
- s = '<span class="badge">' + (parseInt(range / 60 / 60 / 24)) + '天前</span>';
114
-
115
- }
116
- else if (range< 60*60*24*7)
117
- {
118
- s = '<span class="badge">本周</span>';
119
- }
120
- else if (range< 60*60*24*15)
121
- {
122
- s = '<span class="badge">半月内</span>';
123
- }
124
- else if (range< 60*60*24*2)
125
- {
126
- s = '<span class="badge">今天</span>';
127
- }
128
- else if (range< 60*60*24*2)
129
- {
130
- s = '<span class="badge">今天</span>';
131
- }
132
- else if (range< 60*60*24*2)
133
- {
134
- s = '<span class="badge">今天</span>';
135
- }
136
-
137
- }
138
- return s;
139
-
140
- }
141
-
142
- /**
143
- * 自定义pretty-json展开方案,Local结尾的key不展开
144
- */
145
- function expandAll(node) {
146
- // console.log(node);
147
- for (var i in node.childs) {
148
- var child = node.childs[i];
149
- if (child instanceof PrettyJSON.view.Node) {
150
- if (!child.path.match(/.*Local$/)) {
151
- child.show();
152
- expandAll(child);
153
-
154
- }
155
-
156
- }
157
-
158
- }
159
-
160
- }
161
-
162
- function searchApiKey(_this, _isSelect) {
163
- if (_isSelect) {
164
- _this.select();
165
-
166
- }
167
- var _keyType = $(_this).val();
168
- if (_keyType == '') {
169
- return;
170
-
171
- }
172
- $(_this).addClass("btn-primary").siblings().removeClass("btn-primary");
173
- $(this).attr('keytype', _keyType);
174
- setTimeout(function () {
175
- if ($(this).attr('keytype') == $(_this).val()) {
176
- filterApiList($(_this).val());
177
-
178
- }
179
-
180
- },
181
- 500);
182
-
183
- }
184
-
185
- function changeKeyType(_this) {
186
- $(_this).addClass("btn-primary").siblings().removeClass("btn-primary");
187
- var _keyType = $(_this).attr('keytype');
188
- filterApiList(_keyType);
189
-
190
- }
191
-
192
- function filterApiList(_keyType) {
193
- _keyType = _keyType.toLowerCase();
194
- if (_keyType == '所有') {
195
- $('#list_api_btns').children().show();
196
-
197
- }
198
- else {
199
- $('#list_api_btns').children().each(function () {
200
- var htmlText = $(this).html().replace(/<.*?>/g, '').toLowerCase();
201
- if (htmlText.indexOf(_keyType) >= 0) {
202
- $(this).show(0);
203
-
204
- }
205
- else {
206
- $(this).hide(0);
207
-
208
- }
209
-
210
- });
211
-
212
- }
213
-
214
- }
215
-
216
- function getHeaders() {
217
- var _headers = {
218
- "Content-Type":"application/x-www-form-urlencoded"
219
- };
220
- $('form').find('[form-type=header]').each(function () {
221
- var _key = $(this).val();
222
- if (_key != '') {
223
- if (_headers == null) {
224
- _headers = {};
225
- }
226
- _headers[_key] = $(this).parent().siblings().find("input,textarea").val();
227
- }
228
-
229
- });
230
- return _headers;
231
-
232
- }
233
- function getValues() {
234
- var _getValues = [];
235
- $('form').find('[form-type=field]').each(function () {
236
- var _key = $(this).val();
237
- var _input = $(this).parent().siblings().find("input,textarea");
238
- if (_key != '' && _input.attr('type') != 'file') {
239
- var _val = $(this).parent().siblings().find("input,textarea").val();
240
- _getValues.push(_key + '=' + encodeURIComponent(_val));
241
- }
242
-
243
- });
244
- return _getValues;
245
-
246
- }
247
- function getPosts() {
248
- var _data = [],_formdata = new FormData(),hasfile = false;
249
- $('form').find('[form-type=field]').each(function () {
250
- var _key = $(this).val(),_input = $(this).parent().siblings().find("input,textarea");
251
- if ( _key ) {
252
- if( _input.attr('type') == 'file' ){
253
- if( _input[0] && _input[0].files && _input[0].files.length > 0 ){
254
- for(var file of _input[0].files){
255
- _formdata.append(_key,file);
256
- }
257
- }
258
- hasfile = true;
259
- }else{
260
- _formdata.append(_key,_input.val());
261
- _data.push(_key + '=' + encodeURIComponent(_input.val()));
262
- }
263
- }
264
- });
265
- return hasfile?_formdata:_data.join('&');
266
- }
267
-
268
- function reFormGroup(_formType, _formRequest,_formDevice) {
269
- var _formGroup = null;
270
- $('form').find('[form-type=' + _formType + ']').each(function () {
271
- if ($(this).val() == _formRequest['key']) {
272
- _formGroup = $(this).closest(".form-group");
273
- }
274
- });
275
- if (_formGroup == null) {
276
- var _firstNode = $('form').find('[form-type=' + _formType + ']').first().closest(".form-group");
277
- $('form').find('[form-type=' + _formType + ']').last().closest(".form-group").after(_firstNode.clone(true));
278
- _formGroup = $('form').find('[form-type=' + _formType + ']').last().closest(".form-group");
279
-
280
- }
281
-
282
- if( typeof(_formDevice) == 'string' ){
283
- _formGroup.attr('form-'+ _formType +'-devices',_formDevice)
284
- }
285
- _formGroup.attr('is-required', _formRequest['required'] ? 'true' : 'false').trigger('mouseenter').trigger('mouseleave').attr('title', (_formRequest['title'] || _formRequest['key'] || _formType) + "<br/>" + (_formRequest['description'] || '')).attr('data-html', "true").tooltip().show();
286
- var _inputs = _formGroup.find('input,textarea');
287
- _inputs.eq(0).val(_formRequest['key'])
288
- .attr('field-type', _formRequest['type'])
289
- .attr('field-required', _formRequest['required'])
290
- .attr('field-title', (_formRequest['title'] || _formRequest['key'] || _formType))
291
- .attr('field-desc', _formRequest['description']);
292
-
293
- if (_formRequest['type'] == 'file') {
294
- _inputs.eq(1).replaceWith('<input type="file"' + (_formType == 'field' ? ' name="' + _formRequest['key'] + '"' : '') + (_formRequest['key'].indexOf('[]') > 0 ? ' multiple="multiple"' : '') + '/>')
295
-
296
- }
297
- else if (_formRequest['type'] == 'text') {
298
- _inputs.eq(1).replaceWith('<textarea name="' + _formRequest['key'] + '">' + _formRequest['default'] + '</textarea>');
299
- } else if (_formRequest['type'] == 'select' && _formRequest['key'] == "Device") {
300
- var dropdown = _inputs.eq(1).siblings('.input-group-btn').find('ul.dropdown-menu');
301
- dropdown.html('');
302
- for (let label in devices) {
303
-
304
- dropdown.append('<li data-label="' + label + '" data-value="' + label + '" ><a href="javascript:void(0)">' + label + '</a></li>')
305
- }
306
- dropdown.children('li').bind('click', function () {
307
- let this_device = $(this).data('label');
308
- for (let label in devices) {
309
- $('form').find('[form-type="header"]').closest('.form-group[form-header-devices="'+label+'"]').remove();
310
- if( label == this_device && Array.isArray(devices[label].headers) ){
311
- for (var j in devices[label].headers) {
312
- reFormGroup('header', devices[label].headers[j],label);
313
- }
314
- }
315
- }
316
- $(_inputs.eq(1)).val(this_device);
317
- })
318
- setTimeout(function(){
319
- dropdown.children('li').eq(0).trigger('click');
320
- _inputs.eq(1).siblings('.input-group-btn').unbind().show().parent().addClass('input-group')
321
- },10)
322
- }
323
- else if (_formRequest['type'] == 'md5') {
324
- _inputs.eq(1).val(hex_md5(_formRequest['default'])).unbind().change(function () {
325
- $(this).val(hex_md5($(this).val()));
326
- });
327
-
328
- }
329
- else {
330
- if (_formRequest['default'] == '') {
331
- if (_formRequest['type'] == 'datetime') {
332
- _formRequest['default'] = (new Date().format('yyyy-MM-dd hh:mm:ss'));
333
-
334
- }
335
- else if (_formRequest['type'] == 'date') {
336
- _formRequest['default'] = (new Date().format('yyyy-MM-dd'));
337
-
338
- }
339
-
340
- }
341
- _inputs.eq(1).val(_formRequest['default']);
342
-
343
- }
344
- if (_formType == 'field') {
345
- _inputs.eq(1).attr('name', _formRequest['key']);
346
-
347
- }
348
- if (_formRequest['click']) {
349
- _inputs.eq(1).siblings('.input-group-addon').show().unbind().bind('click', _formRequest['click']).parent().addClass('input-group');
350
-
351
- }
352
- else {
353
- // _inputs.eq(1).closest('.input-group').removeClass('input-group');
354
- }
355
- $('#div_headerfield').scrollTop(99999);
356
-
357
- }
358
-
359
- function changePlan(p_plan) {
360
- var planList = p_plan.split('|');
361
- switch (planList[0]) {
362
- case '#api':
363
- var i = parseInt(planList[1]);
364
- if (i >= 0) {
365
- if (apiList[i]) {
366
- $('#btn_api_title_' + i).trigger('click');
367
-
368
- }
369
-
370
- }
371
- break;
372
- case '#request':
373
- if (planList.length >= 3) {
374
- if (planList.length == 6 && planList[5] != '') {
375
- _prefixUnSelected = JSON.parse(planList[5]);
376
- for (var i in _prefixUnSelected) {
377
- $('#prefixs_list .input_api_prefix[prefix=' + _prefixUnSelected[i] + ']').attr('checked', false);
378
- }
379
- if (_prefixUnSelected.length > 0) {
380
- apiListInit();
381
- }
382
- }
383
- setTimeout(function () {
384
- if (planList[1] != 'undefined') {
385
- $('#div_switchgroup button[unique-id=' + planList[1] + ']').trigger('click');
386
- }
387
- if (planList[2] != 'undefined') {
388
- $('#div_apilist .panel[unique-id=' + planList[2] + '] h4 a').trigger('click');
389
- }
390
- setTimeout(function () {
391
- if (planList.length >= 4) {
392
- json = JSON.parse(planList[3]);
393
- for (var i in json) {
394
- reFormGroup('field', json[i]);
395
-
396
- }
397
- }
398
- if (planList.length == 5) {
399
- json = JSON.parse(planList[4]);
400
- for (var i in json) {
401
- reFormGroup('header', json[i]);
402
-
403
- }
404
- }
405
- }, 50);
406
- }, 50);
407
-
408
-
409
- }
410
-
411
- break;
412
-
413
- case 'help':
414
- break;
415
-
416
- }
417
-
418
- }
419
-
420
- function updatePlan() {
421
- var buttonUniqueId = $('#div_switchgroup .btn-primary').attr('unique-id');
422
- var apiUniqueId = $('.panel-collapse.in').closest('.panel').attr('unique-id');
423
- var _posts = [];
424
- $('form').find('[form-type=field]').each(function () {
425
- var _key = $(this).val();
426
- var _input = $(this).parent().siblings().find("input,textarea");
427
- if (_key != '' && _input.attr('type') != 'file') {
428
- var _val = $(this).parent().siblings().find("input,textarea").val();
429
- _posts.push({
430
- 'key': _key,
431
- 'type': $(this).attr('field-type'),
432
- 'required': $(this).attr('field-required'),
433
- 'default': _val,
434
- 'title': $(this).attr('field-title'),
435
- 'description': $(this).attr('field-desc')
436
- });
437
-
438
- }
439
-
440
- });
441
- var _headers = [];
442
- $('form').find('[form-type=header]').each(function () {
443
- var _key = $(this).val();
444
- if (_key != '') {
445
- var _val = $(this).parent().siblings().find("input,textarea").val();
446
- _headers.push({
447
- 'key': _key,
448
- 'type': $(this).attr('field-type'),
449
- 'required': $(this).attr('field-required'),
450
- 'default': _val,
451
- 'title': $(this).attr('field-title'),
452
- 'description': $(this).attr('field-desc')
453
- });
454
-
455
- }
456
-
457
- });
458
-
459
- var _prefixUnSelected = $('#prefixs_list .input_api_prefix').not(':checked').map(function () {
460
- return $(this).attr('prefix');
461
- }).get();
462
-
463
- _href = '#request' + '|' + buttonUniqueId + '|' + apiUniqueId + '|' + JSON_stringify(_posts, false) + '|' + JSON_stringify(_headers, false) + '|' + JSON_stringify(_prefixUnSelected, false);
464
- // setCurrentUrl(_href);
465
-
466
- }
467
-
468
- function setCurrentUrl(_href) {
469
- self.location = _href;
470
- currentUrl = self.location.href;
471
-
472
- }
473
-
474
- function reFormApi(i) {
475
- var _api = apiList[i];
476
- document.getElementsByTagName('title')[0].innerHTML = _api['title'] + '/API:测试工具';
477
- // setCurrentUrl('#api'+'|'+i+'|'+apiList[i]['title']);
478
- if (_api['router'].indexOf('http') < 0) {
479
- _api['router'] = window.location.protocol + '//' + window.location.host + (_api['router'].indexOf('/') == 0 ? '' : '/') + _api['router'];
480
- _api['router'] = _api['router'].replace(/\/[^\/]+\/\.\.\//g, '/');
481
-
482
- }
483
- $('#link_api_url').val(_api['router']);
484
-
485
- if (_api['method'] == 'get') {
486
- $('#switch_method button').eq(0).trigger('click');
487
-
488
- }else if (_api['method'] == 'post') {
489
- $('#switch_method button').eq(1).trigger('click');
490
-
491
- }
492
-
493
- $('form').find('[form-type=field]').each(function (i) {
494
- if (i > 0) {
495
- $(this).closest(".form-group").remove();
496
-
497
- }
498
-
499
- });
500
-
501
- for (var j in _api['request']) {
502
- _api['request'][j]['default'] = _api['request'][j]['default'] || _api['request'][j]['default'] || '';
503
- if (_api['request'][j]['required'] || _api['request'][j]['default'] != '') {
504
- reFormGroup('field', _api['request'][j]);
505
-
506
- }
507
-
508
- }
509
- // $('form').find('.input-group-addon').trigger('click');
510
- // setTimeout(function() {updatePlan();}, 1000);
511
-
512
- }
513
-
514
- function reFormGroupApi(i, j) {
515
- reFormGroup('field', apiList[i]['request'][j]);
516
-
517
- }
518
-
519
- function reFormHeader() {
520
- for (var j in headerList) {
521
- reFormGroup('header', headerList[j]);
522
-
523
- }
524
-
525
- }
526
-
527
- function sortKeyBar(_newSortType) {
528
- if (_newSortType) {
529
- _sortType = _newSortType;
530
-
531
- }
532
- else {
533
- switch (_sortType) {
534
- case 'name':
535
- _sortType = 'time';
536
- break;
537
-
538
- case 'time':
539
- _sortType = 'name';
540
- break;
541
-
542
- }
543
-
544
- }
545
- apiKeyBarInit();
546
- return false;
547
-
548
- }
549
-
550
- function apiKeyBarInit() {
551
- var _now = (new Date()).getTime() / 1000;
552
- var _keyTypeArray = [];
553
- var _timeLast = 0;
554
- for (var _keyType in _keyTypes) {
555
- _keyTypeArray.push({
556
- 'keyType': _keyType,
557
- 'keyPY': makeFirstPy(_keyType),
558
- 'timeunix': _keyTypes[_keyType]
559
- });
560
- _timeLast = Math.max(_timeLast, _keyTypes[_keyType]);
561
-
562
- }
563
- if (_sortType == 'name' || (_sortType == null && (_now - _timeLast > 60 * 60 * 24 * 3))) {
564
- if (!_sortType) {
565
- sortKeyBar('name');
566
- return false;
567
- }
568
- console.log('按名称排序');
569
- _keyTypeArray.sort(function compare(a, b) {
570
- // return a['keyPY'].localeCompare(b['keyPY']);
571
- return (a['keyPY'] + a['keyType']).localeCompare(b['keyPY'] + b['keyType'], 'zh');
572
- });
573
- }
574
- else {
575
- if (!_sortType) {
576
- sortKeyBar('time');
577
- return false;
578
- }
579
- console.log('按时间排序');
580
- _keyTypeArray.sort(function compare(a, b) {
581
- return a['timeunix'] <= b['timeunix'] ? 1 : -1;
582
-
583
- });
584
- }
585
-
586
- $('#switch_examples').empty();
587
- var _lastKeyPY = null;
588
- for (var i in _keyTypeArray) {
589
- var _keyType = _keyTypeArray[i]['keyType'];
590
- var _keyPY = _keyTypeArray[i]['keyPY'];
591
- var _timeunix = _keyTypeArray[i]['timeunix'];
592
- $('#switch_examples').append('<button type="button" class="btn btn-default" onclick="changeKeyType(this);" keytype="' + _keyType + '" unique-id="' + hex_md5(_keyType) + '" >'
593
- + _keyType
594
- + (_sortType == 'time' ? range_to_badge(_now - _timeunix) : (_lastKeyPY != _keyPY ? '<span class="badge">' + _keyPY + '</span>' : ''))
595
- + '</button>');
596
- _lastKeyPY = _keyPY;
597
-
598
- }
599
-
600
- var _sortStr = '排序';
601
- switch (_sortType) {
602
- case 'name':
603
- _sortStr = '按名称排序';
604
- break;
605
-
606
- case 'time':
607
- _sortStr = '按时间排序';
608
- break;
609
-
610
- }
611
- $('<button type="button" class="btn btn-default" onclick="changeKeyType(this);" keytype="所有">所有<span class="badge key_bar_sort" onclick="return sortKeyBar();" >' + _sortStr + '</span></button>').insertBefore($('#switch_examples button').eq(0));
612
- $('<input id="input_search" type="text" class="btn btn-default" onkeyup="searchApiKey(this);" onclick="searchApiKey(this,1);" placeholder="search"/>').insertAfter($('#switch_examples button').eq(0));
613
-
614
-
615
- }
616
-
617
- function apiListInit() {
618
- if ($('#prefixs_list').html() == '') {
619
- var hasprefix = [];
620
- for (var _apiList of apiList) {
621
- if( _apiList.prefix && hasprefix.indexOf(_apiList.prefix) == -1 ){
622
- hasprefix.push(_apiList.prefix);
623
- $('#prefixs_list').append('<label><input type="checkbox" class="input_api_prefix" prefix="' + _apiList.prefix + '" onclick="apiListInit()"/>' + _apiList.prefix + '</label>');
624
- $('#prefixs_list').show();
625
- }
626
- }
627
- }
628
-
629
- var _prefixLength = $('#prefixs_list').children().length;
630
- var _prefixsSelected = $('#prefixs_list .input_api_prefix:checked').map(function () {
631
- return $(this).attr('prefix');
632
- }).get();
633
-
634
-
635
-
636
- var _listNode = $('#list_api_btns').empty();
637
- var _now = (new Date()).getTime() / 1000;
638
- _keyTypes = {};
639
-
640
- for (var i in apiList) {
641
- var _api = apiList[i];
642
-
643
- if (_api['time']) {
644
- _api['timeunix'] = datetime_to_unix(_api['time']);
645
-
646
- }
647
- else {
648
- _api['timeunix'] = 1;
649
- }
650
- for (var j in _api['request']) {
651
- var requestTime = 1;
652
- if (_api['request'][j]['time']) {
653
- _api['request'][j]['timeunix'] = datetime_to_unix(_api['request'][j]['time']);
654
- if (_api['request'][j]['timeunix'] > _api['timeunix']) {
655
- _api['timeunix'] = _api['request'][j]['timeunix'];
656
- }
657
- }
658
- }
659
-
660
- }
661
-
662
- apiList.sort(function compare(a, b) {
663
- return a['timeunix'] <= b['timeunix'] ? 1 : -1;
664
- });
665
-
666
- for (var i in apiList) {
667
- var _api = apiList[i];
668
-
669
- var _keyString = '';
670
- _keyString = '';
671
- if (_api['describe'] != '') {
672
- _keyString = _api['describe'].replace('\n', '<br/>').replace(/[\n\r]/g, '<br/>') + '<br/><br/>';
673
-
674
- }
675
- _keyString += 'url: ' + _api['router'];
676
- if (_api['time'] && _api['time'] != '') {
677
- _keyString += '<span class="span-time">' + _api['time'] + '</span>';
678
- }
679
- _keyString += '<br/>';
680
-
681
- if (_api['filepath'] && _api['filepath'] != '') {
682
- _keyString += 'filepath: ' + _api['filepath']+ '<br/>';
683
- }
684
-
685
- if (_api['request'].length > 0) {
686
- _keyString += '<table class="table table-striped">';
687
- _keyString += '<tr><th>字段名</th><th>必须</th><th>格式</th><th>字段描述</th><th>默认值</th><th>rules</th></tr>';
688
- for (var j in _api['request']) {
689
- var requestTime = 1;
690
- if (_api['request'][j]['timeunix']) {
691
- requestTime = _api['request'][j]['timeunix'];
692
-
693
- }
694
- _keyString += '<tr onclick="reFormGroupApi(' + i + ',' + j + ');"><td>' + _api['request'][j]['key'] + (range_to_badge(_now - requestTime)) + '</td><td>' + (_api['request'][j]['required'] ? '是' : '否') + '</td><td>' + _api['request'][j]['type'] + '</td><td><span>' + _api['request'][j]['title'] + '</span>&nbsp;&nbsp;<span style="color:red;">' + _api['request'][j]['description'] + '</span></td><td>' + (_api['request'][j]['default'] || '') + '</td><td>' + JSON.stringify(_api['request'][j]['rules']) + '</td></tr>'
695
-
696
- }
697
- _keyString += '</table>';
698
-
699
- }
700
-
701
- var _panelString = '<div class="panel panel-default" unique-id="' + hex_md5(apiList[i]['title']) + '" >\
702
- <div class="panel-heading">\
703
- <h4 class="panel-title">\
704
- <a id="btn_api_title_' + i + '" href="javascript:;" data-toggle="collapse" data-parent="#list_api_btns" data-target="#collapseDiv' + i + '" onclick="reFormApi(' + i + ');" style="width: 100%;display: inline-block;">'
705
- + (range_to_badge(_now - _api['timeunix']))
706
- + _api['title']
707
- + '<span class="span-method">' + _api['method'] + '</span>'
708
- + '</a>'
709
- + '\
710
- </h4>\
711
- </div>\
712
- <div id="collapseDiv' + i + '" class="panel-collapse collapse">\
713
- <div class="panel-body">' + _keyString + '</div>\
714
- </div>\
715
- </div>';
716
-
717
- if( _prefixLength > 0 ){
718
- if( _prefixsSelected && _prefixsSelected.length > 0 ){
719
- if( _prefixsSelected.indexOf(_api['prefix']) == -1 ){
720
- continue;
721
- }
722
- }else if( _api['prefix'] ){
723
- continue;
724
- }
725
- }
726
-
727
- if (_api['title'].match(/[::]/g)) {
728
- var _keyType = _api['title'].replace(/([::]).*/g, '$1');
729
- if (!_keyTypes[_keyType]) {
730
- _keyTypes[_keyType] = _api['timeunix'];
731
- }
732
- }
733
- _listNode.append(_panelString);
734
- }
735
- _listNode.collapse();
736
-
737
-
738
-
739
- reFormHeader();
740
-
741
- apiKeyBarInit();
742
-
743
- }
744
-
745
-
746
-
747
- $(function () {
748
- apiListInit();
749
-
750
-
751
- $('#switch_examples').children().eq(0).trigger('click');
752
-
753
- $('#btn_add_header').click(function () {
754
- var _firstNode = $('form').find('[form-type=header]').first().closest(".form-group");
755
- $('form').find('[form-type=header]').last().closest(".form-group").after(_firstNode.clone(true));
756
- $('form').find('[form-type=header]').last().closest(".form-group").show();
757
-
758
- });
759
- $('#btn_add_field').click(function () {
760
- var _firstNode = $('form').find('[form-type=field]').first().closest(".form-group");
761
- $('form').find('[form-type=field]').last().closest(".form-group").after(_firstNode.clone(true));
762
- $('form').find('[form-type=field]').last().closest(".form-group").show();
763
-
764
- });
765
- $('.form-group').bind({
766
- mouseenter: function () {
767
- if ($(this).attr('is-required') && $(this).attr('is-required') == 'true') {
768
-
769
- }
770
- else {
771
- if ($(this).find('.btn_del').length == 0) {
772
- $(this).find('[form-type]').before('<div class="btn_del" > x </div>').prev().click(function () {
773
- $(this).closest(".form-group").trigger('mouseleave').remove();
774
-
775
- });
776
-
777
- }
778
- $(this).find('.btn_del').show();
779
-
780
- }
781
-
782
- }
783
- ,
784
- mouseleave: function () {
785
- if ($(this).attr('is-required')) {
786
-
787
- }
788
- else {
789
- $(this).find('.btn_del').hide();
790
-
791
- }
792
-
793
- }
794
-
795
- });
796
- $('form').find('[form-type=field]').bind({
797
- change: function () {
798
- $(this).parent().siblings().find('input,textarea').attr('name', $(this).val());
799
-
800
- }
801
- });
802
-
803
- $('#switch_method button').click(function () {
804
- $(this).addClass("btn-primary").siblings().removeClass("btn-primary");
805
-
806
- });
807
-
808
- $('#div_frames>ul>li').eq(0).find('a').bind({
809
- click: function () {
810
- var json,
811
- data;
812
- data = $('#textarea_results').val();
813
- try {
814
- json = JSON.parse(data);
815
- }
816
- catch (e) {
817
- // console.log('json 解析失败');
818
- if (data.match(/^<.*?>[\s\S]*<.*?>$/g)) {
819
- $('#div_json_view').html(data);
820
- }
821
- else {
822
- setTimeout(function () {
823
- $('#div_frames>ul>li').eq(1).find('a').trigger("click");
824
- },
825
- 100);
826
- }
827
-
828
- return;
829
-
830
- }
831
-
832
- var node = new PrettyJSON.view.Node({
833
- el: $('#div_json_view'),
834
- data: json,
835
- dateFormat: "DD/MM/YYYY - HH24:MI:SS"
836
-
837
- });
838
- // console.log(node);
839
- // node.expandAll();
840
- expandAll(node);
841
-
842
- }
843
- });
844
-
845
- $('#textarea_results')[0].onchange = function () {
846
- var json, data;
847
- data = $(this).val();
848
- try {
849
- json = JSON.parse(data);
850
- } catch (e) {
851
- $('#div_json_view').html(data);
852
- $('#div_frames>ul>li').eq(1).trigger("click");
853
- return;
854
- }
855
-
856
- var node = new PrettyJSON.view.Node({
857
- el: $('#div_json_view'),
858
- data: json,
859
- dateFormat: "DD/MM/YYYY - HH24:MI:SS"
860
- });
861
- expandAll(node);
862
- }
863
- $('#btn_test_url').click(function(){
864
-
865
- if ($('#checkbox_is_autosign').prop('checked'))
866
- {
867
- $('form').find('.input-group-addon').trigger('click');//每次都自动重算
868
- }
869
-
870
- $('#textarea_results').val('waiting....');
871
- $('#div_json_view').html('waiting....');
872
-
873
- if (xhrTestingApi){xhrTestingApi.abort();}
874
-
875
- var _headers = getHeaders();
876
-
877
- var _link = $('#link_api_url').val();
878
- if (_link == '') {
879
- alert('API URL NO FOUND');
880
- $('#link_api_url').focus();
881
- return false;
882
- }
883
-
884
- var _method = $('#switch_method .btn-primary').html().toLowerCase();
885
-
886
- var _data=null;
887
- if (_method=='get' || _method == 'delete')
888
- {
889
- var _getValues = getValues();
890
- _link = _link + (_link.indexOf('?')>0?'&':'?') + _getValues.join('&');
891
- }else {
892
- _data = getPosts();
893
- }
894
-
895
- xhrTestingApi = $.ajax({
896
- url: _link,
897
- data:_data,
898
- type: _method,
899
- headers: _headers,
900
- dataType:"text",
901
- mimeType:"multipart/form-data",
902
- error: function(XHR,textStatus,errorThrown) {
903
- $('#textarea_results').val(XHR.responseText);
904
- alert ("XHR="+XHR+"\ntextStatus="+textStatus+"\nerrorThrown=" + errorThrown);
905
- },
906
-
907
- success: function(data,textStatus) {
908
- xhrTestingApi = null;
909
- $('#textarea_results').val(data);
910
- $('#textarea_results').trigger("change");
911
- $('#div_frames>ul>li').eq(0).trigger("click");
912
- },
913
- cache: (_method=='get'),
914
- contentType: false,
915
- processData: false
916
- });
917
-
918
- });
919
-
920
- //url 监控
921
- setInterval(function () {
922
- var _currentUrl = self.location.href;
923
- if (currentUrl != _currentUrl) {
924
- currentUrl = _currentUrl;
925
- changePlan(self.location.hash);
926
- };
927
- }, 300);
928
- });
929
-
930
- function isJSON(str) {
931
- if (typeof str == 'string') {
932
- try {
933
- var obj = JSON.parse(str);
934
- if (typeof obj == 'object' && obj) {
935
- return true;
936
- } else {
937
- return false;
938
- }
939
-
940
- } catch (e) {
941
- console.log('error:' + str + '!!!' + e);
942
- return false;
943
- }
944
- }
945
- console.log('It is not a string!')
1
+ var currentUrl;
2
+ var xhrTestingApi = null;
3
+ var todayPassedTime = null;
4
+ var _keyTypes = {};
5
+ var _sortType = null;
6
+ var descriptionsList = {};
7
+
8
+
9
+ Date.prototype.format = function (format) {
10
+ var o =
11
+ {
12
+ "M+": this.getMonth() + 1,
13
+ //month
14
+ "d+": this.getDate(),
15
+ //day
16
+ "h+": this.getHours(),
17
+ //hour
18
+ "m+": this.getMinutes(),
19
+ //minute
20
+ "s+": this.getSeconds(),
21
+ //second
22
+ "q+": Math.floor((this.getMonth() + 3) / 3),
23
+ //quarter
24
+ "S": this.getMilliseconds()
25
+ //millisecond
26
+
27
+ }
28
+
29
+ if (/(y+)/.test(format)) {
30
+ format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
31
+
32
+ }
33
+
34
+ for (var k in o) {
35
+ if (new RegExp("(" + k + ")").test(format)) {
36
+ format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
37
+
38
+ }
39
+
40
+ }
41
+ return format;
42
+
43
+ }
44
+
45
+ //'2012-11-16 10:36:50';
46
+ function datetime_to_unix(datetime) {
47
+ if (datetime == '') {
48
+ return 0;
49
+
50
+ }
51
+ else if (parseInt(datetime) == datetime) {
52
+ return parseInt(datetime);
53
+
54
+ }
55
+ var tmp_datetime = datetime.replace(/:/g, '-');
56
+ tmp_datetime = tmp_datetime.replace(/ /g, '-');
57
+ var arr = tmp_datetime.split("-");
58
+ var now = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
59
+ return parseInt(now.getTime() / 1000);
60
+
61
+ }
62
+
63
+ //'2012-11-16 10:36:50';
64
+ function unix_to_datetime(unix) {
65
+ var now = new Date(parseInt(unix) * 1000);
66
+ return now.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
67
+
68
+ }
69
+
70
+
71
+ function JSON_stringify(s, emit_unicode) {
72
+ var json = JSON.stringify(s);
73
+ return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
74
+ function (c) {
75
+ return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(- 4);
76
+
77
+ }
78
+ );
79
+
80
+ }
81
+
82
+
83
+
84
+ function range_to_badge(range) {
85
+ var s = '';
86
+ if (range < 0) {
87
+ }
88
+ else if (range < 60 * 60) {
89
+ s = '<span class="badge badge-soon">刚才</span>';
90
+
91
+ }
92
+ else {
93
+ if (!todayPassedTime) {
94
+ todayPassedTime = (new Date()).getTime() / 1000 - datetime_to_unix((new Date().format('yyyy-MM-dd 00:00:00')));
95
+
96
+ }
97
+
98
+ range = range + 60 * 60 * 24 - todayPassedTime;
99
+
100
+ if (range < 60 * 60 * 24) {
101
+ s = '<span class="badge badge-today">今天</span>';
102
+
103
+ }
104
+ else if (range < 60 * 60 * 24 * 2) {
105
+ s = '<span class="badge badge-yesterday">昨天</span>';
106
+
107
+ }
108
+ else if (range < 60 * 60 * 24 * 3) {
109
+ s = '<span class="badge badge-beforeyester">前天</span>';
110
+
111
+ }
112
+ else if (range < 60 * 60 * 24 * 365) {
113
+ s = '<span class="badge">' + (parseInt(range / 60 / 60 / 24)) + '天前</span>';
114
+
115
+ }
116
+ else if (range< 60*60*24*7)
117
+ {
118
+ s = '<span class="badge">本周</span>';
119
+ }
120
+ else if (range< 60*60*24*15)
121
+ {
122
+ s = '<span class="badge">半月内</span>';
123
+ }
124
+ else if (range< 60*60*24*2)
125
+ {
126
+ s = '<span class="badge">今天</span>';
127
+ }
128
+ else if (range< 60*60*24*2)
129
+ {
130
+ s = '<span class="badge">今天</span>';
131
+ }
132
+ else if (range< 60*60*24*2)
133
+ {
134
+ s = '<span class="badge">今天</span>';
135
+ }
136
+
137
+ }
138
+ return s;
139
+
140
+ }
141
+
142
+ /**
143
+ * 自定义pretty-json展开方案,Local结尾的key不展开
144
+ */
145
+ function expandAll(node) {
146
+ // console.log(node);
147
+ for (var i in node.childs) {
148
+ var child = node.childs[i];
149
+ if (child instanceof PrettyJSON.view.Node) {
150
+ if (!child.path.match(/.*Local$/)) {
151
+ child.show();
152
+ expandAll(child);
153
+
154
+ }
155
+
156
+ }
157
+
158
+ }
159
+
160
+ }
161
+
162
+ function searchApiKey(_this, _isSelect) {
163
+ if (_isSelect) {
164
+ _this.select();
165
+
166
+ }
167
+ var _keyType = $(_this).val();
168
+ if (_keyType == '') {
169
+ return;
170
+
171
+ }
172
+ $(_this).addClass("btn-primary").siblings().removeClass("btn-primary");
173
+ $(this).attr('keytype', _keyType);
174
+ setTimeout(function () {
175
+ if ($(this).attr('keytype') == $(_this).val()) {
176
+ filterApiList($(_this).val());
177
+
178
+ }
179
+
180
+ },
181
+ 500);
182
+
183
+ }
184
+
185
+ function changeKeyType(_this) {
186
+ $(_this).addClass("btn-primary").siblings().removeClass("btn-primary");
187
+ var _keyType = $(_this).attr('keytype');
188
+ filterApiList(_keyType);
189
+
190
+ }
191
+
192
+ function filterApiList(_keyType) {
193
+ _keyType = _keyType.toLowerCase();
194
+ if (_keyType == '所有') {
195
+ $('#list_api_btns').children().show();
196
+
197
+ }
198
+ else {
199
+ $('#list_api_btns').children().each(function () {
200
+ var htmlText = $(this).html().replace(/<.*?>/g, '').toLowerCase();
201
+ if (htmlText.indexOf(_keyType) >= 0) {
202
+ $(this).show(0);
203
+
204
+ }
205
+ else {
206
+ $(this).hide(0);
207
+
208
+ }
209
+
210
+ });
211
+
212
+ }
213
+
214
+ }
215
+
216
+ function getHeaders() {
217
+ var _headers = {
218
+ "Content-Type":"application/x-www-form-urlencoded"
219
+ };
220
+ $('form').find('[form-type=header]').each(function () {
221
+ var _key = $(this).val();
222
+ if (_key != '') {
223
+ if (_headers == null) {
224
+ _headers = {};
225
+ }
226
+ _headers[_key] = $(this).parent().siblings().find("input,textarea").val();
227
+ }
228
+
229
+ });
230
+ return _headers;
231
+
232
+ }
233
+ function getValues() {
234
+ var _getValues = [];
235
+ $('form').find('[form-type=field]').each(function () {
236
+ var _key = $(this).val();
237
+ var _input = $(this).parent().siblings().find("input,textarea");
238
+ if (_key != '' && _input.attr('type') != 'file') {
239
+ var _val = $(this).parent().siblings().find("input,textarea").val();
240
+ _getValues.push(_key + '=' + encodeURIComponent(_val));
241
+ }
242
+
243
+ });
244
+ return _getValues;
245
+
246
+ }
247
+ function getPosts() {
248
+ var _data = [],_formdata = new FormData(),hasfile = false;
249
+ $('form').find('[form-type=field]').each(function () {
250
+ var _key = $(this).val(),_input = $(this).parent().siblings().find("input,textarea");
251
+ if ( _key ) {
252
+ if( _input.attr('type') == 'file' ){
253
+ if( _input[0] && _input[0].files && _input[0].files.length > 0 ){
254
+ for(var file of _input[0].files){
255
+ _formdata.append(_key,file);
256
+ }
257
+ }
258
+ hasfile = true;
259
+ }else{
260
+ _formdata.append(_key,_input.val());
261
+ _data.push(_key + '=' + encodeURIComponent(_input.val()));
262
+ }
263
+ }
264
+ });
265
+ return hasfile?_formdata:_data.join('&');
266
+ }
267
+
268
+ function reFormGroup(_formType, _formRequest,_formDevice) {
269
+ var _formGroup = null;
270
+ $('form').find('[form-type=' + _formType + ']').each(function () {
271
+ if ($(this).val() == _formRequest['key']) {
272
+ _formGroup = $(this).closest(".form-group");
273
+ }
274
+ });
275
+ if (_formGroup == null) {
276
+ var _firstNode = $('form').find('[form-type=' + _formType + ']').first().closest(".form-group");
277
+ $('form').find('[form-type=' + _formType + ']').last().closest(".form-group").after(_firstNode.clone(true));
278
+ _formGroup = $('form').find('[form-type=' + _formType + ']').last().closest(".form-group");
279
+
280
+ }
281
+
282
+ if( typeof(_formDevice) == 'string' ){
283
+ _formGroup.attr('form-'+ _formType +'-devices',_formDevice)
284
+ }
285
+ _formGroup.attr('is-required', _formRequest['required'] ? 'true' : 'false').trigger('mouseenter').trigger('mouseleave').attr('title', (_formRequest['title'] || _formRequest['key'] || _formType) + "<br/>" + (_formRequest['description'] || '')).attr('data-html', "true").tooltip().show();
286
+ var _inputs = _formGroup.find('input,textarea');
287
+ _inputs.eq(0).val(_formRequest['key'])
288
+ .attr('field-type', _formRequest['type'])
289
+ .attr('field-required', _formRequest['required'])
290
+ .attr('field-title', (_formRequest['title'] || _formRequest['key'] || _formType))
291
+ .attr('field-desc', _formRequest['description']);
292
+
293
+ if (_formRequest['type'] == 'file') {
294
+ _inputs.eq(1).replaceWith('<input type="file"' + (_formType == 'field' ? ' name="' + _formRequest['key'] + '"' : '') + (_formRequest['key'].indexOf('[]') > 0 ? ' multiple="multiple"' : '') + '/>')
295
+
296
+ }
297
+ else if (_formRequest['type'] == 'text') {
298
+ _inputs.eq(1).replaceWith('<textarea name="' + _formRequest['key'] + '">' + _formRequest['default'] + '</textarea>');
299
+ } else if (_formRequest['type'] == 'select' && _formRequest['key'] == "Device") {
300
+ var dropdown = _inputs.eq(1).siblings('.input-group-btn').find('ul.dropdown-menu');
301
+ dropdown.html('');
302
+ for (let label in devices) {
303
+
304
+ dropdown.append('<li data-label="' + label + '" data-value="' + label + '" ><a href="javascript:void(0)">' + label + '</a></li>')
305
+ }
306
+ dropdown.children('li').bind('click', function () {
307
+ let this_device = $(this).data('label');
308
+ for (let label in devices) {
309
+ $('form').find('[form-type="header"]').closest('.form-group[form-header-devices="'+label+'"]').remove();
310
+ if( label == this_device && Array.isArray(devices[label].headers) ){
311
+ for (var j in devices[label].headers) {
312
+ reFormGroup('header', devices[label].headers[j],label);
313
+ }
314
+ }
315
+ }
316
+ $(_inputs.eq(1)).val(this_device);
317
+ })
318
+ setTimeout(function(){
319
+ dropdown.children('li').eq(0).trigger('click');
320
+ _inputs.eq(1).siblings('.input-group-btn').unbind().show().parent().addClass('input-group')
321
+ },10)
322
+ }
323
+ else if (_formRequest['type'] == 'md5') {
324
+ _inputs.eq(1).val(hex_md5(_formRequest['default'])).unbind().change(function () {
325
+ $(this).val(hex_md5($(this).val()));
326
+ });
327
+
328
+ }
329
+ else {
330
+ if (_formRequest['default'] == '') {
331
+ if (_formRequest['type'] == 'datetime') {
332
+ _formRequest['default'] = (new Date().format('yyyy-MM-dd hh:mm:ss'));
333
+
334
+ }
335
+ else if (_formRequest['type'] == 'date') {
336
+ _formRequest['default'] = (new Date().format('yyyy-MM-dd'));
337
+
338
+ }
339
+
340
+ }
341
+ _inputs.eq(1).val(_formRequest['default']);
342
+
343
+ }
344
+ if (_formType == 'field') {
345
+ _inputs.eq(1).attr('name', _formRequest['key']);
346
+
347
+ }
348
+ if (_formRequest['click']) {
349
+ _inputs.eq(1).siblings('.input-group-addon').show().unbind().bind('click', _formRequest['click']).parent().addClass('input-group');
350
+
351
+ }
352
+ else {
353
+ // _inputs.eq(1).closest('.input-group').removeClass('input-group');
354
+ }
355
+ $('#div_headerfield').scrollTop(99999);
356
+
357
+ }
358
+
359
+ function changePlan(p_plan) {
360
+ var planList = p_plan.split('|');
361
+ switch (planList[0]) {
362
+ case '#api':
363
+ var i = parseInt(planList[1]);
364
+ if (i >= 0) {
365
+ if (apiList[i]) {
366
+ $('#btn_api_title_' + i).trigger('click');
367
+
368
+ }
369
+
370
+ }
371
+ break;
372
+ case '#request':
373
+ if (planList.length >= 3) {
374
+ if (planList.length == 6 && planList[5] != '') {
375
+ _prefixUnSelected = JSON.parse(planList[5]);
376
+ for (var i in _prefixUnSelected) {
377
+ $('#prefixs_list .input_api_prefix[prefix=' + _prefixUnSelected[i] + ']').attr('checked', false);
378
+ }
379
+ if (_prefixUnSelected.length > 0) {
380
+ apiListInit();
381
+ }
382
+ }
383
+ setTimeout(function () {
384
+ if (planList[1] != 'undefined') {
385
+ $('#div_switchgroup button[unique-id=' + planList[1] + ']').trigger('click');
386
+ }
387
+ if (planList[2] != 'undefined') {
388
+ $('#div_apilist .panel[unique-id=' + planList[2] + '] h4 a').trigger('click');
389
+ }
390
+ setTimeout(function () {
391
+ if (planList.length >= 4) {
392
+ json = JSON.parse(planList[3]);
393
+ for (var i in json) {
394
+ reFormGroup('field', json[i]);
395
+
396
+ }
397
+ }
398
+ if (planList.length == 5) {
399
+ json = JSON.parse(planList[4]);
400
+ for (var i in json) {
401
+ reFormGroup('header', json[i]);
402
+
403
+ }
404
+ }
405
+ }, 50);
406
+ }, 50);
407
+
408
+
409
+ }
410
+
411
+ break;
412
+
413
+ case 'help':
414
+ break;
415
+
416
+ }
417
+
418
+ }
419
+
420
+ function updatePlan() {
421
+ var buttonUniqueId = $('#div_switchgroup .btn-primary').attr('unique-id');
422
+ var apiUniqueId = $('.panel-collapse.in').closest('.panel').attr('unique-id');
423
+ var _posts = [];
424
+ $('form').find('[form-type=field]').each(function () {
425
+ var _key = $(this).val();
426
+ var _input = $(this).parent().siblings().find("input,textarea");
427
+ if (_key != '' && _input.attr('type') != 'file') {
428
+ var _val = $(this).parent().siblings().find("input,textarea").val();
429
+ _posts.push({
430
+ 'key': _key,
431
+ 'type': $(this).attr('field-type'),
432
+ 'required': $(this).attr('field-required'),
433
+ 'default': _val,
434
+ 'title': $(this).attr('field-title'),
435
+ 'description': $(this).attr('field-desc')
436
+ });
437
+
438
+ }
439
+
440
+ });
441
+ var _headers = [];
442
+ $('form').find('[form-type=header]').each(function () {
443
+ var _key = $(this).val();
444
+ if (_key != '') {
445
+ var _val = $(this).parent().siblings().find("input,textarea").val();
446
+ _headers.push({
447
+ 'key': _key,
448
+ 'type': $(this).attr('field-type'),
449
+ 'required': $(this).attr('field-required'),
450
+ 'default': _val,
451
+ 'title': $(this).attr('field-title'),
452
+ 'description': $(this).attr('field-desc')
453
+ });
454
+
455
+ }
456
+
457
+ });
458
+
459
+ var _prefixUnSelected = $('#prefixs_list .input_api_prefix').not(':checked').map(function () {
460
+ return $(this).attr('prefix');
461
+ }).get();
462
+
463
+ _href = '#request' + '|' + buttonUniqueId + '|' + apiUniqueId + '|' + JSON_stringify(_posts, false) + '|' + JSON_stringify(_headers, false) + '|' + JSON_stringify(_prefixUnSelected, false);
464
+ // setCurrentUrl(_href);
465
+
466
+ }
467
+
468
+ function setCurrentUrl(_href) {
469
+ self.location = _href;
470
+ currentUrl = self.location.href;
471
+
472
+ }
473
+
474
+ function reFormApi(i) {
475
+ var _api = apiList[i];
476
+ document.getElementsByTagName('title')[0].innerHTML = _api['title'] + '/API:测试工具';
477
+ // setCurrentUrl('#api'+'|'+i+'|'+apiList[i]['title']);
478
+ if (_api['router'].indexOf('http') < 0) {
479
+ _api['router'] = window.location.protocol + '//' + window.location.host + (_api['router'].indexOf('/') == 0 ? '' : '/') + _api['router'];
480
+ _api['router'] = _api['router'].replace(/\/[^\/]+\/\.\.\//g, '/');
481
+
482
+ }
483
+ $('#link_api_url').val(_api['router']);
484
+
485
+ if (_api['method'] == 'get') {
486
+ $('#switch_method button').eq(0).trigger('click');
487
+
488
+ }else if (_api['method'] == 'post') {
489
+ $('#switch_method button').eq(1).trigger('click');
490
+
491
+ }
492
+
493
+ $('form').find('[form-type=field]').each(function (i) {
494
+ if (i > 0) {
495
+ $(this).closest(".form-group").remove();
496
+
497
+ }
498
+
499
+ });
500
+
501
+ for (var j in _api['request']) {
502
+ _api['request'][j]['default'] = _api['request'][j]['default'] || _api['request'][j]['default'] || '';
503
+ if (_api['request'][j]['required'] || _api['request'][j]['default'] != '') {
504
+ reFormGroup('field', _api['request'][j]);
505
+
506
+ }
507
+
508
+ }
509
+ // $('form').find('.input-group-addon').trigger('click');
510
+ // setTimeout(function() {updatePlan();}, 1000);
511
+
512
+ }
513
+
514
+ function reFormGroupApi(i, j) {
515
+ reFormGroup('field', apiList[i]['request'][j]);
516
+
517
+ }
518
+
519
+ function reFormHeader() {
520
+ for (var j in headerList) {
521
+ reFormGroup('header', headerList[j]);
522
+
523
+ }
524
+
525
+ }
526
+
527
+ function sortKeyBar(_newSortType) {
528
+ if (_newSortType) {
529
+ _sortType = _newSortType;
530
+
531
+ }
532
+ else {
533
+ switch (_sortType) {
534
+ case 'name':
535
+ _sortType = 'time';
536
+ break;
537
+
538
+ case 'time':
539
+ _sortType = 'name';
540
+ break;
541
+
542
+ }
543
+
544
+ }
545
+ apiKeyBarInit();
546
+ return false;
547
+
548
+ }
549
+
550
+ function apiKeyBarInit() {
551
+ var _now = (new Date()).getTime() / 1000;
552
+ var _keyTypeArray = [];
553
+ var _timeLast = 0;
554
+ for (var _keyType in _keyTypes) {
555
+ _keyTypeArray.push({
556
+ 'keyType': _keyType,
557
+ 'keyPY': makeFirstPy(_keyType),
558
+ 'timeunix': _keyTypes[_keyType]
559
+ });
560
+ _timeLast = Math.max(_timeLast, _keyTypes[_keyType]);
561
+
562
+ }
563
+ if (_sortType == 'name' || (_sortType == null && (_now - _timeLast > 60 * 60 * 24 * 3))) {
564
+ if (!_sortType) {
565
+ sortKeyBar('name');
566
+ return false;
567
+ }
568
+ console.log('按名称排序');
569
+ _keyTypeArray.sort(function compare(a, b) {
570
+ // return a['keyPY'].localeCompare(b['keyPY']);
571
+ return (a['keyPY'] + a['keyType']).localeCompare(b['keyPY'] + b['keyType'], 'zh');
572
+ });
573
+ }
574
+ else {
575
+ if (!_sortType) {
576
+ sortKeyBar('time');
577
+ return false;
578
+ }
579
+ console.log('按时间排序');
580
+ _keyTypeArray.sort(function compare(a, b) {
581
+ return a['timeunix'] <= b['timeunix'] ? 1 : -1;
582
+
583
+ });
584
+ }
585
+
586
+ $('#switch_examples').empty();
587
+ var _lastKeyPY = null;
588
+ for (var i in _keyTypeArray) {
589
+ var _keyType = _keyTypeArray[i]['keyType'];
590
+ var _keyPY = _keyTypeArray[i]['keyPY'];
591
+ var _timeunix = _keyTypeArray[i]['timeunix'];
592
+ $('#switch_examples').append('<button type="button" class="btn btn-default" onclick="changeKeyType(this);" keytype="' + _keyType + '" unique-id="' + hex_md5(_keyType) + '" >'
593
+ + _keyType
594
+ + (_sortType == 'time' ? range_to_badge(_now - _timeunix) : (_lastKeyPY != _keyPY ? '<span class="badge">' + _keyPY + '</span>' : ''))
595
+ + '</button>');
596
+ _lastKeyPY = _keyPY;
597
+
598
+ }
599
+
600
+ var _sortStr = '排序';
601
+ switch (_sortType) {
602
+ case 'name':
603
+ _sortStr = '按名称排序';
604
+ break;
605
+
606
+ case 'time':
607
+ _sortStr = '按时间排序';
608
+ break;
609
+
610
+ }
611
+ $('<button type="button" class="btn btn-default" onclick="changeKeyType(this);" keytype="所有">所有<span class="badge key_bar_sort" onclick="return sortKeyBar();" >' + _sortStr + '</span></button>').insertBefore($('#switch_examples button').eq(0));
612
+ $('<input id="input_search" type="text" class="btn btn-default" onkeyup="searchApiKey(this);" onclick="searchApiKey(this,1);" placeholder="search"/>').insertAfter($('#switch_examples button').eq(0));
613
+
614
+
615
+ }
616
+
617
+ function apiListInit() {
618
+ if ($('#prefixs_list').html() == '') {
619
+ var hasprefix = [];
620
+ for (var _apiList of apiList) {
621
+ if( _apiList.prefix && hasprefix.indexOf(_apiList.prefix) == -1 ){
622
+ hasprefix.push(_apiList.prefix);
623
+ $('#prefixs_list').append('<label><input type="checkbox" class="input_api_prefix" prefix="' + _apiList.prefix + '" onclick="apiListInit()"/>' + _apiList.prefix + '</label>');
624
+ $('#prefixs_list').show();
625
+ }
626
+ }
627
+ }
628
+
629
+ var _prefixLength = $('#prefixs_list').children().length;
630
+ var _prefixsSelected = $('#prefixs_list .input_api_prefix:checked').map(function () {
631
+ return $(this).attr('prefix');
632
+ }).get();
633
+
634
+
635
+
636
+ var _listNode = $('#list_api_btns').empty();
637
+ var _now = (new Date()).getTime() / 1000;
638
+ _keyTypes = {};
639
+
640
+ for (var i in apiList) {
641
+ var _api = apiList[i];
642
+
643
+ if (_api['time']) {
644
+ _api['timeunix'] = datetime_to_unix(_api['time']);
645
+
646
+ }
647
+ else {
648
+ _api['timeunix'] = 1;
649
+ }
650
+ for (var j in _api['request']) {
651
+ var requestTime = 1;
652
+ if (_api['request'][j]['time']) {
653
+ _api['request'][j]['timeunix'] = datetime_to_unix(_api['request'][j]['time']);
654
+ if (_api['request'][j]['timeunix'] > _api['timeunix']) {
655
+ _api['timeunix'] = _api['request'][j]['timeunix'];
656
+ }
657
+ }
658
+ }
659
+
660
+ }
661
+
662
+ apiList.sort(function compare(a, b) {
663
+ return a['timeunix'] <= b['timeunix'] ? 1 : -1;
664
+ });
665
+
666
+ for (var i in apiList) {
667
+ var _api = apiList[i];
668
+
669
+ var _keyString = '';
670
+ _keyString = '';
671
+ if (_api['describe'] != '') {
672
+ _keyString = _api['describe'].replace('\n', '<br/>').replace(/[\n\r]/g, '<br/>') + '<br/><br/>';
673
+
674
+ }
675
+ _keyString += 'url: ' + _api['router'];
676
+ if (_api['time'] && _api['time'] != '') {
677
+ _keyString += '<span class="span-time">' + _api['time'] + '</span>';
678
+ }
679
+ _keyString += '<br/>';
680
+
681
+ if (_api['filepath'] && _api['filepath'] != '') {
682
+ _keyString += 'filepath: ' + _api['filepath']+ '<br/>';
683
+ }
684
+
685
+ if (_api['request'].length > 0) {
686
+ _keyString += '<table class="table table-striped">';
687
+ _keyString += '<tr><th>字段名</th><th>必须</th><th>格式</th><th>字段描述</th><th>默认值</th><th>rules</th></tr>';
688
+ for (var j in _api['request']) {
689
+ var requestTime = 1;
690
+ if (_api['request'][j]['timeunix']) {
691
+ requestTime = _api['request'][j]['timeunix'];
692
+
693
+ }
694
+ _keyString += '<tr onclick="reFormGroupApi(' + i + ',' + j + ');"><td>' + _api['request'][j]['key'] + (range_to_badge(_now - requestTime)) + '</td><td>' + (_api['request'][j]['required'] ? '是' : '否') + '</td><td>' + _api['request'][j]['type'] + '</td><td><span>' + _api['request'][j]['title'] + '</span>&nbsp;&nbsp;<span style="color:red;">' + _api['request'][j]['description'] + '</span></td><td>' + (_api['request'][j]['default'] || '') + '</td><td>' + JSON.stringify(_api['request'][j]['rules']) + '</td></tr>'
695
+
696
+ }
697
+ _keyString += '</table>';
698
+
699
+ }
700
+
701
+ var _panelString = '<div class="panel panel-default" unique-id="' + hex_md5(apiList[i]['title']) + '" >\
702
+ <div class="panel-heading">\
703
+ <h4 class="panel-title">\
704
+ <a id="btn_api_title_' + i + '" href="javascript:;" data-toggle="collapse" data-parent="#list_api_btns" data-target="#collapseDiv' + i + '" onclick="reFormApi(' + i + ');" style="width: 100%;display: inline-block;">'
705
+ + (range_to_badge(_now - _api['timeunix']))
706
+ + _api['title']
707
+ + '<span class="span-method">' + _api['method'] + '</span>'
708
+ + '</a>'
709
+ + '\
710
+ </h4>\
711
+ </div>\
712
+ <div id="collapseDiv' + i + '" class="panel-collapse collapse">\
713
+ <div class="panel-body">' + _keyString + '</div>\
714
+ </div>\
715
+ </div>';
716
+
717
+ if( _prefixLength > 0 ){
718
+ if( _prefixsSelected && _prefixsSelected.length > 0 ){
719
+ if( _prefixsSelected.indexOf(_api['prefix']) == -1 ){
720
+ continue;
721
+ }
722
+ }else if( _api['prefix'] ){
723
+ continue;
724
+ }
725
+ }
726
+
727
+ if (_api['title'].match(/[::]/g)) {
728
+ var _keyType = _api['title'].replace(/([::]).*/g, '$1');
729
+ if (!_keyTypes[_keyType]) {
730
+ _keyTypes[_keyType] = _api['timeunix'];
731
+ }
732
+ }
733
+ _listNode.append(_panelString);
734
+ }
735
+ _listNode.collapse();
736
+
737
+
738
+
739
+ reFormHeader();
740
+
741
+ apiKeyBarInit();
742
+
743
+ }
744
+
745
+
746
+
747
+ $(function () {
748
+ apiListInit();
749
+
750
+
751
+ $('#switch_examples').children().eq(0).trigger('click');
752
+
753
+ $('#btn_add_header').click(function () {
754
+ var _firstNode = $('form').find('[form-type=header]').first().closest(".form-group");
755
+ $('form').find('[form-type=header]').last().closest(".form-group").after(_firstNode.clone(true));
756
+ $('form').find('[form-type=header]').last().closest(".form-group").show();
757
+
758
+ });
759
+ $('#btn_add_field').click(function () {
760
+ var _firstNode = $('form').find('[form-type=field]').first().closest(".form-group");
761
+ $('form').find('[form-type=field]').last().closest(".form-group").after(_firstNode.clone(true));
762
+ $('form').find('[form-type=field]').last().closest(".form-group").show();
763
+
764
+ });
765
+ $('.form-group').bind({
766
+ mouseenter: function () {
767
+ if ($(this).attr('is-required') && $(this).attr('is-required') == 'true') {
768
+
769
+ }
770
+ else {
771
+ if ($(this).find('.btn_del').length == 0) {
772
+ $(this).find('[form-type]').before('<div class="btn_del" > x </div>').prev().click(function () {
773
+ $(this).closest(".form-group").trigger('mouseleave').remove();
774
+
775
+ });
776
+
777
+ }
778
+ $(this).find('.btn_del').show();
779
+
780
+ }
781
+
782
+ }
783
+ ,
784
+ mouseleave: function () {
785
+ if ($(this).attr('is-required')) {
786
+
787
+ }
788
+ else {
789
+ $(this).find('.btn_del').hide();
790
+
791
+ }
792
+
793
+ }
794
+
795
+ });
796
+ $('form').find('[form-type=field]').bind({
797
+ change: function () {
798
+ $(this).parent().siblings().find('input,textarea').attr('name', $(this).val());
799
+
800
+ }
801
+ });
802
+
803
+ $('#switch_method button').click(function () {
804
+ $(this).addClass("btn-primary").siblings().removeClass("btn-primary");
805
+
806
+ });
807
+
808
+ $('#div_frames>ul>li').eq(0).find('a').bind({
809
+ click: function () {
810
+ var json,
811
+ data;
812
+ data = $('#textarea_results').val();
813
+ try {
814
+ json = JSON.parse(data);
815
+ }
816
+ catch (e) {
817
+ // console.log('json 解析失败');
818
+ if (data.match(/^<.*?>[\s\S]*<.*?>$/g)) {
819
+ $('#div_json_view').html(data);
820
+ }
821
+ else {
822
+ setTimeout(function () {
823
+ $('#div_frames>ul>li').eq(1).find('a').trigger("click");
824
+ },
825
+ 100);
826
+ }
827
+
828
+ return;
829
+
830
+ }
831
+
832
+ var node = new PrettyJSON.view.Node({
833
+ el: $('#div_json_view'),
834
+ data: json,
835
+ dateFormat: "DD/MM/YYYY - HH24:MI:SS"
836
+
837
+ });
838
+ // console.log(node);
839
+ // node.expandAll();
840
+ expandAll(node);
841
+
842
+ }
843
+ });
844
+
845
+ $('#textarea_results')[0].onchange = function () {
846
+ var json, data;
847
+ data = $(this).val();
848
+ try {
849
+ json = JSON.parse(data);
850
+ } catch (e) {
851
+ $('#div_json_view').html(data);
852
+ $('#div_frames>ul>li').eq(1).trigger("click");
853
+ return;
854
+ }
855
+
856
+ var node = new PrettyJSON.view.Node({
857
+ el: $('#div_json_view'),
858
+ data: json,
859
+ dateFormat: "DD/MM/YYYY - HH24:MI:SS"
860
+ });
861
+ expandAll(node);
862
+ }
863
+ $('#btn_test_url').click(function(){
864
+
865
+ if ($('#checkbox_is_autosign').prop('checked'))
866
+ {
867
+ $('form').find('.input-group-addon').trigger('click');//每次都自动重算
868
+ }
869
+
870
+ $('#textarea_results').val('waiting....');
871
+ $('#div_json_view').html('waiting....');
872
+
873
+ if (xhrTestingApi){xhrTestingApi.abort();}
874
+
875
+ var _headers = getHeaders();
876
+
877
+ var _link = $('#link_api_url').val();
878
+ if (_link == '') {
879
+ alert('API URL NO FOUND');
880
+ $('#link_api_url').focus();
881
+ return false;
882
+ }
883
+
884
+ var _method = $('#switch_method .btn-primary').html().toLowerCase();
885
+
886
+ var _data=null;
887
+ if (_method=='get' || _method == 'delete')
888
+ {
889
+ var _getValues = getValues();
890
+ _link = _link + (_link.indexOf('?')>0?'&':'?') + _getValues.join('&');
891
+ }else {
892
+ _data = getPosts();
893
+ }
894
+
895
+ xhrTestingApi = $.ajax({
896
+ url: _link,
897
+ data:_data,
898
+ type: _method,
899
+ headers: _headers,
900
+ dataType:"text",
901
+ mimeType:"multipart/form-data",
902
+ error: function(XHR,textStatus,errorThrown) {
903
+ $('#textarea_results').val(XHR.responseText);
904
+ alert ("XHR="+XHR+"\ntextStatus="+textStatus+"\nerrorThrown=" + errorThrown);
905
+ },
906
+
907
+ success: function(data,textStatus) {
908
+ xhrTestingApi = null;
909
+ $('#textarea_results').val(data);
910
+ $('#textarea_results').trigger("change");
911
+ $('#div_frames>ul>li').eq(0).trigger("click");
912
+ },
913
+ cache: (_method=='get'),
914
+ contentType: false,
915
+ processData: false
916
+ });
917
+
918
+ });
919
+
920
+ //url 监控
921
+ setInterval(function () {
922
+ var _currentUrl = self.location.href;
923
+ if (currentUrl != _currentUrl) {
924
+ currentUrl = _currentUrl;
925
+ changePlan(self.location.hash);
926
+ };
927
+ }, 300);
928
+ });
929
+
930
+ function isJSON(str) {
931
+ if (typeof str == 'string') {
932
+ try {
933
+ var obj = JSON.parse(str);
934
+ if (typeof obj == 'object' && obj) {
935
+ return true;
936
+ } else {
937
+ return false;
938
+ }
939
+
940
+ } catch (e) {
941
+ console.log('error:' + str + '!!!' + e);
942
+ return false;
943
+ }
944
+ }
945
+ console.log('It is not a string!')
946
946
  }