Completed
Push — master ( d07d22...90f9d4 )
by Dimas
08:53
created

dimas.isURL   A

Complexity

Conditions 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 14
rs 9.95
c 0
b 0
f 0
cc 2
1
var ORIGIN = null as any;
2
if (isnode()) {
3
  const process = require("process");
4
  ORIGIN = process.cwd();
5
} else {
6
  ORIGIN = location.protocol + "//" + location.host + location.pathname;
7
}
8
var IP: string;
9
10
class dimas {
11
  /**
12
   * Disabling button
13
   * @param t element of button
14
   * @param V
15
   */
16
  disable_button(t: JQuery<any> | HTMLButtonElement, V: any = null) {
17
    var el: HTMLButtonElement;
18
    if (t instanceof jQuery) {
19
      el = t.get();
20
    } else if (t instanceof HTMLButtonElement) {
21
      el = t;
22
    }
23
    if (typeof el != "undefined") {
24
      el.setAttribute("disabled", "true");
25
    }
26
  }
27
  /**
28
   * Enabling button
29
   * @param t element of button
30
   * @param V
31
   */
32
  enable_button(t: JQuery<any> | HTMLButtonElement, V: any = null) {
33
    var el: HTMLButtonElement;
34
    if (t instanceof jQuery) {
35
      el = t.get();
36
    } else if (t instanceof HTMLButtonElement) {
37
      el = t;
38
    }
39
    if (typeof el != "undefined") {
40
      el.removeAttribute("disabled");
41
    }
42
  }
43
  /**
44
   * get current url without querystrings
45
   */
46
  static url = ORIGIN;
47
  static ip: any = null;
48
  static setIp(ip: any) {
49
    this.ip = ip;
50
    IP = ip;
51
  }
52
  static getIp() {
53
    return this.ip;
54
  }
55
56
  /**
57
   * framework captcha
58
   */
59
  static captcha = {
60
    /**
61
     * DO NOT ASSIGN THIS
62
     */
63
    check: null as NodeJS.Timer,
64
    /**
65
     * Get current captcha id
66
     */
67
    id(header_name: string | null): string {
68
      if (!this.captcha.check) {
69
        this.captcha.get(header_name);
70
      }
71
      return storage().get("captcha");
72
    },
73
    /**
74
     * Get current captcha from backend
75
     * And process it by jsonpCallback
76
     */
77
    get(header_name: null | string): void {
78
      if (!this.captcha.check) {
79
        this.captcha.check = setTimeout(() => {
80
          this.captcha.get(header_name);
81
        }, 60000);
82
      }
83
      var ua = md5(navigator.userAgent).rot13();
84
85
      $.ajax({
86
        url: this.url + "?login=" + guid(),
87
        method: "POST",
88
        headers: {
89
          Accept: "application/javascript",
90
          [header_name]: ua,
91
          [IP.rot13()]: ua,
92
        },
93
        dataType: "jsonp",
94
        jsonpCallback: "framework().captcha.jspCallback",
95
      });
96
    },
97
98
    callback(arg?: any) {},
99
100
    /**
101
     * Captcha JSONP callback
102
     */
103
    jspCallback(res: { captcha: string }) {
104
      if (res.hasOwnProperty("captcha")) {
105
        storage().set("captcha", res.captcha.rot13());
106
        this.captcha.callback(storage().get("captcha"));
107
        this.captcha.listen();
108
      }
109
    },
110
    listener_started: null as any | string,
111
    /**
112
     * Form Captcha listener
113
     */
114
    listen() {
115
      if (this.captcha.listener_started) {
116
        return null;
117
      }
118
      this.captcha.listener_started = new Date().toISOString();
119
      return $(document).on("focus", "form[captcha]", function (e) {
120
        var captcha = $(this).find('[name="captcha"]');
121
        if (!captcha.length) {
122
          $(this).append(
123
            '<input type="hidden" name="captcha" id="' + guid() + '" />'
124
          );
125
          captcha = $(this).find('[name="captcha"]');
126
        }
127
        if (captcha.length) {
128
          captcha.val(storage().get("captcha").rot13());
129
        }
130
        var form = captcha.parents("form");
131
        var button = form.find('[type="submit"]');
132
        form.one("submit", function (e) {
133
          e.preventDefault();
134
          console.log("submit with captcha");
135
          button.prop("disabled", true);
136
          this.captcha.callback = function () {
137
            button.prop("disabled", false);
138
          };
139
          this.captcha.get(null);
140
          form.off("submit");
141
        });
142
        //captcha.parents('form').find('[type="submit"]').one('click', function());
143
      });
144
    },
145
  };
146
147
  /**
148
   * Count Array/Object/String length
149
   * @param {any[]|string|object} data
150
   */
151
  count(data: any[] | string | object) {
152
    if (Array.isArray(data) || typeof data == "string") {
153
      return data.length;
154
    } else if (typeof data == "object") {
155
      return Object.keys(data).length;
156
    } else if (typeof data == "number") {
157
      return data;
158
    }
159
  }
160
161
  /**
162
   * Make async function
163
   * @param callback
164
   */
165
  async(callback: any) {
166
    return new Promise(function (resolve, reject) {
167
      if (typeof callback == "function") {
168
        callback();
169
      }
170
      resolve(true);
171
    });
172
  }
173
174
  /**
175
   * Rupiah currency auto format
176
   */
177
  rp(angka: number, prefix: string | any = null) {
178
    if (!prefix) {
179
      prefix = "Rp. ";
180
    }
181
    var number_string = angka.toString().replace(/[^,\d]/g, ""),
182
      split = number_string.split(","),
183
      sisa = split[0].length % 3,
184
      rupiah = split[0].substr(0, sisa),
185
      ribuan = split[0].substr(sisa).match(/\d{3}/gi);
186
    if (ribuan) {
187
      var separator = sisa ? "." : "";
188
189
      rupiah += separator + ribuan.join(".");
190
    }
191
192
    rupiah = split[1] != undefined ? rupiah + "," + split[1] : rupiah;
193
    return !prefix ? rupiah : prefix + " " + rupiah;
194
  }
195
196
  /**
197
   * Check if variable is number / numeric
198
   * @param {String|Number} v
199
   */
200
  isNumber(v: string | number) {
201
    return (
202
      !isNaN(parseInt(v.toString()) - parseFloat(v.toString())) &&
203
      /^\d+$/.test(v.toString())
204
    );
205
  }
206
207
  /**
208
   * Check if valid url
209
   * @param url url address
210
   */
211
  isURL(url: string) {
212
    let result: URL;
213
    try {
214
      result = new URL(url);
215
    } catch (_) {
216
      return false;
217
    }
218
219
    return result.protocol === "http:" || result.protocol === "https:";
220
  }
221
222
  /**
223
   * Check url is valid and reachable
224
   * @param url url address
225
   * @param callback callback function
226
   */
227
  isURLReachable(url: string, callback: (arg0: boolean, arg1: string) => any) {
228
    if (this.isURL(url)) {
229
      var myRequest = new Request(url);
230
231
      fetch(myRequest).then(function (response) {
232
        console.log(`${response.status} ${url}`);
233
        if (response.status == 200) {
234
          callback(true, url);
235
        }
236
      });
237
    }
238
  }
239
240
  /**
241
   * strpad / startwith zero [0]
242
   * @param {number} val
243
   */
244
  strpad(val: number) {
245
    if (val >= 10) {
246
      return val;
247
    } else {
248
      return "0" + val;
249
    }
250
  }
251
252
  /**
253
   * Autofill datetime-local value
254
   */
255
  datetimelocal(v?: string | number) {
256
    var d = !v ? new Date() : new Date(v);
257
    $("input[type=datetime-local]").val(
258
      d.getFullYear() +
259
        "-" +
260
        this.strpad(d.getMonth() + 1) +
261
        "-" +
262
        this.strpad(d.getDate()) +
263
        "T" +
264
        this.strpad(d.getHours()) +
265
        ":" +
266
        this.strpad(d.getMinutes())
267
    );
268
  }
269
270
  /**
271
   * Get cookie
272
   * @param string name cookie
273
   */
274
  gc(name: string) {
275
    var nameEQ = name + "=";
276
    var ca = document.cookie.split(";");
277
    for (var i = 0; i < ca.length; i++) {
278
      var c = ca[i];
279
      while (c.charAt(0) == " ") {
280
        c = c.substring(1, c.length);
281
        if (c.indexOf(nameEQ) == 0) {
282
          return c.substring(nameEQ.length, c.length);
283
        }
284
      }
285
    }
286
287
    return null;
288
  }
289
290
  /**
291
   * Odd or Even (Ganjil Genap);
292
   * @param type odd or even
293
   */
294
  oddoreven(n: string, type: string) {
295
    if (!type) {
296
      type = "odd";
297
    }
298
    var time = !n ? new Date().getDay() : Number(n);
299
300
    if (!/^-{0,1}\d+jQuery/.test(time.toString())) {
301
      alert("arguments is not number, please remove quote");
302
      return null;
303
    }
304
305
    var hasil = time % 2;
306
307
    var type = /^(odd|ganjil)$/.test(type) ? "1" : "0";
308
    //return hasil == (type == ('odd' || 'ganjil') ? 1 : 0);
309
310
    return hasil.toString() == type.toString();
311
  }
312
313
  /**
314
   * Set cookie
315
   * @param {String} name
316
   * @param {any} value
317
   * @param {number} hours
318
   */
319
  sc(name: string, value: any, hours: number) {
320
    var expires = "";
321
    if (hours) {
322
      var date = new Date();
323
      date.setTime(date.getTime() + hours * 3600 * 1000);
324
      expires = "; expires=" + date.toUTCString();
325
    }
326
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
327
  }
328
329
  allcookies() {
330
    var pairs = document.cookie.split(";");
331
    var cookies: { [key: string]: any } = {};
332
    for (var i = 0; i < pairs.length; i++) {
333
      var pair = pairs[i].split("=");
334
      var str: string = pair[0].trim();
335
      cookies[str] = unescape(pair.slice(1).join("="));
336
    }
337
    return cookies;
338
  }
339
340
  /**
341
   * Remove Cookie
342
   */
343
  rc(name: string): void {
344
    document.cookie = name + "=; Max-Age=-99999999;";
345
  }
346
347
  /**
348
   * Get Query name from current url
349
   */
350
  getquery(variable: any) {
351
    var query = window.location.search.substring(1);
352
    var vars = query.split("&");
353
    for (var i = 0; i < vars.length; i++) {
354
      var pair = vars[i].split("=");
355
      if (pair[0] == variable) {
356
        return pair[1];
357
      }
358
    }
359
    return false;
360
  }
361
362
  recode(content: string, passcode: string) {
363
    var result = [];
364
    var str = "";
365
    var codesArr = JSON.parse(content);
366
    var passLen = passcode.length;
367
    for (var i = 0; i < codesArr.length; i++) {
368
      var passOffset = i % passLen;
369
      var calAscii = codesArr[i] - passcode.charCodeAt(passOffset);
370
      result.push(calAscii);
371
    }
372
    for (var i = 0; i < result.length; i++) {
373
      var ch = String.fromCharCode(result[i]);
374
      str += ch;
375
    }
376
    return str;
377
  }
378
379
  /**
380
   * Get js file from url
381
   * @param {String} url
382
   * @param {Function} callback
383
   */
384
  js(url: string, callback: Function | any) {
385
    var pel = document.body || document.head;
386
    var script = document.createElement("script");
387
    script.type = "text/javascript";
388
    script.src = url;
389
    if (typeof callback == "function") script.onreadystatechange = callback;
390
391
    script.onload = callback;
392
    pel.appendChild(script);
393
  }
394
395
  /**
396
   * Countdown trigger
397
   * @param {JQuery} elm
398
   */
399
  pctdRUN(elm: JQuery) {
400
    var tl = parseInt(elm.attr("countdown")) > 0 ? elm.attr("countdown") : 5,
401
      bs = elm.data("base") ? elm.data("base") : "bg-info",
402
      bw = elm.data("warning") ? elm.data("warning") : "bg-danger",
403
      bc = elm.data("success") ? elm.data("success") : "bg-success",
404
      countdown = elm.progressBarTimer({
405
        warningThreshold: 5,
406
        timeLimit: tl,
407
408
        // base style
409
        baseStyle: bs,
410
411
        // warning style
412
        warningStyle: bw,
413
414
        // complete style
415
        completeStyle: bc,
416
417
        // should the timer be smooth or stepping
418
        smooth: true,
419
420
        // striped progress bar
421
        striped: true,
422
423
        // animated stripes
424
        animated: true,
425
426
        // height of progress bar
427
        // 0 = default height
428
        height: 0,
429
        onFinish() {
430
          var callback = elm.data("callback");
431
          if (callback) {
432
            var xn = window[callback];
433
            if (typeof xn == "function") {
434
              var x = eval(callback);
435
              x();
436
            } else {
437
              console.log(callback + " isn't function ");
438
            }
439
          }
440
        },
441
        label: {
442
          show: true,
443
          type: "percent", // or 'seconds' => 23/60
444
        },
445
        autoStart: true,
446
      });
447
    return countdown;
448
  }
449
450
  /**
451
   * Progress Countdown
452
   * @param {JQuery} elm
453
   */
454
  pctd(elm: JQuery) {
455
    var t = this;
456
457
    if (typeof progressBarTimer == "undefined") {
458
      this.js(
459
        "https://cdn.jsdelivr.net/gh/dimaslanjaka/Web-Manajemen@master/js/jquery.progressBarTimer.js",
460
        function () {
461
          t.pctdRUN(elm);
462
        }
463
      );
464
    } else {
465
      window.onload = function (params: any) {
466
        this.pctdRUN(elm);
467
      };
468
    }
469
  }
470
471
  /**
472
   * Parseurl just like as parse_url at php
473
   */
474
  parseurl(url: string) {
475
    var parser = document.createElement("a"),
476
      searchObject: { [key: string]: any } = {},
477
      queries: string[],
478
      split: any[],
479
      i: number;
480
    // Let the browser do the work
481
    parser.href = url;
482
    // Convert query string to object
483
    queries = parser.search.replace(/^\?/, "").split("&");
484
    for (i = 0; i < queries.length; i++) {
485
      split = queries[i].split("=");
486
      searchObject[split[0]] = split[1];
487
    }
488
    return {
489
      protocol: parser.protocol,
490
      host: parser.host,
491
      hostname: parser.hostname,
492
      port: parser.port,
493
      pathname: parser.pathname,
494
      search: parser.search,
495
      searchObject: searchObject,
496
      hash: parser.hash,
497
      protohost: parser.protocol + "//" + parser.host,
498
    };
499
  }
500
}
501
502
/**
503
 * Framework object initializer
504
 */
505
function framework() {
506
  return new dimas();
507
}
508
509
class app {
510
  static base = "/src/MVC/themes/assets/js/";
511
  static setbase(path: string) {
512
    this.base = path;
513
  }
514
515
  static direct(...args: string[]) {
516
    var scripts = document.querySelectorAll("script[src]");
517
    var last = scripts[scripts.length - 1];
518
    var lastsrc = last.getAttribute("src");
519
    var parsed = framework().parseurl(lastsrc);
520
    args.forEach(function (src) {
521
      this.js(`${app.base}${src}${parsed.search}`, function () {
522
        console.log(`${src} engine inbound`);
523
      });
524
    });
525
  }
526
527
  static load(...args: any[]) {
528
    var scripts = document.querySelectorAll("script[src]");
529
    var last = scripts[scripts.length - 1];
530
    var lastsrc = last.getAttribute("src");
531
    var parsed = framework().parseurl(lastsrc);
532
    args.forEach(function (key, index) {
533
      console.log(key, app.base);
534
      let src: string = "";
535
      if (/^(ajx|ajaxjQuery|ajxjquery|ajquery)$/s.test(key)) {
536
        src = "ajaxJquery.js";
537
      } else if (/^(ajv|ajaxVanilla|ajaxv|avanilla)$/s.test(key)) {
538
        src = "ajaxVanilla.js";
539
      }
540
541
      if (src != "") {
542
        this.js(`${app.base}${src}${parsed.search}`, function () {
543
          console.log(`${src} engine inbound`);
544
        });
545
      }
546
    });
547
  }
548
}
549
550
if (typeof module !== "undefined" && module.exports) {
551
  module.exports.app = app;
552
  module.exports.dimas = dimas;
553
}
554
555
//app.direct('Array.js', 'Object.js', 'saver.js', 'user.js');
556