1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
|
/* jshint -W041 */
/* jslint browser: true*/
/* global cordova,StatusBar,angular,console, URI, moment, localforage, CryptoJS, Connection, LZString */
// This is my central data respository and common functions
// that many other controllers use
// It's grown over time. I guess I may have to split this into multiple services in the future
angular.module('zmApp.controllers')
.service('NVR', ['$ionicPlatform', '$http', '$q', '$ionicLoading', '$ionicBackdrop', '$fileLogger', 'zm', '$rootScope', '$ionicContentBanner', '$timeout', '$cordovaPinDialog', '$ionicPopup', '$localstorage', '$state', '$translate', '$cordovaSQLite',
function ($ionicPlatform, $http, $q, $ionicLoading, $ionicBackdrop, $fileLogger,
zm, $rootScope, $ionicContentBanner, $timeout, $cordovaPinDialog,
$ionicPopup, $localstorage, $state, $translate, $cordovaSQLite ) {
var currentServerMultiPortSupported = false;
var tokenExpiryTimer = null;
/*
DO NOT TOUCH zmAppVersion
It is changed by sync_version.sh
*/
var zmAppVersion = "1.4.009";
var isBackground = false;
var justResumed = false;
var timeSinceResumed = -1;
var monitorsLoaded = 0;
var snapshotFrame = 1; // will be 'snapshot'
// if ZM >= 1.31
var monitors = [];
var zmgroups = [];
var multiservers = [];
var migrationComplete = false;
$rootScope.initComplete = false; // will be true when init is fully done to take care of spurious state changes at times
var tz = "";
var isTzSupported = false;
var languages = [{
text: 'English',
value: 'en'
},
{
text: 'العربية',
value: 'ar'
},
{
text: 'Bosnian',
value: 'ba'
},
{
text: '简体中文',
value: 'zh_CN'
},
{
text: 'Deutsch',
value: 'de'
},
{
text: 'Español',
value: 'es'
},
{
text: 'Français',
value: 'fr'
},
{
text: 'Italiano',
value: 'it'
},
{
text: 'Magyar',
value: 'hu'
},
{
text: 'Nederlands',
value: 'nl'
},
{
text: 'Polski',
value: 'pl'
},
{
text: 'Portugese',
value: 'pt'
},
{
text: 'Русский',
value: 'ru'
},
{
text: 'Swedish',
value: 'se'
},
];
var serverGroupList = {};
var defaultLang = 'en';
var isFirstUse = true;
var lastUpdateCheck = null;
var latestBlogPostChecked = null;
var loginData = {
'serverName': '',
'username': '',
'password': '',
'fallbackConfiguration': '',
'url': '', // This is the ZM portal path
'apiurl': '', // This is the API path
'eventServer': '', //experimental Event server address
'maxMontage': "100", //total # of monitors to display in montage
'streamingurl': "",
'maxFPS': "3", // image streaming FPS
'montageQuality': "50", // montage streaming quality in %
'singleImageQuality': "100", // event single streaming quality in %
'monSingleImageQuality': "100", // live view quality
'montageHistoryQuality': "50",
'useSSL': false, // "1" if HTTPS --> not used #589
'keepAwake': true, // don't dim/dim during live view
'isUseAuth': true, // true if user wants ZM auth
'isUseBasicAuth': false,
'basicAuthUser': '',
'basicAuthPassword': '',
'isUseEventServer': false, // true if you configure the websocket event server
'disablePush': false, // true if only websocket mode is desired
'eventServerMonitors': '', // list of monitors to notify from ES
'eventServerInterval': '', // list of intervals for all monitors
'refreshSec': '2', // timer value for frame change in sec
'refreshSecLowBW': 8,
'singleliveFPS':'',
'montageliveFPS':'',
'enableLogs': true,
'enableDebug': true, // if enabled with log messages with "debug"
'usePin': false,
'pinCode': '',
'canSwipeMonitors': true,
'persistMontageOrder': false,
'onTapScreen': "",
'enableh264': true,
'gapless': false,
'montageOrder': '',
'montageHiddenOrder': '',
'montageArraySize': '0',
'showMontageSubMenu': false,
'graphSize': 2000,
'enableAlarmCount': true,
'minAlarmCount': 1,
'montageSize': '3',
'useNphZms': true,
'useNphZmsForEvents': true,
'packMontage': false,
'exitOnSleep': false,
'forceNetworkStop': false,
'defaultPushSound': false,
'enableBlog': true,
'use24hr': false,
'packeryPositions': '',
'currentMontageProfile': '',
'packeryPositionsArray': {},
'EHpackeryPositions': '',
'packerySizes': '',
'timelineModalGraphType': 'all',
'resumeDelay': 0,
'language': 'en',
'reachability': true,
'forceImageModePath': false,
'vibrateOnPush': true,
'soundOnPush': true,
'cycleMonitors': false,
'cycleMontage': false,
'cycleMontageInterval': 10, // 10sec
'cycleMonitorsInterval': 10, // 10sec
'enableLowBandwidth': false,
'autoSwitchBandwidth': false,
'disableAlarmCheckMontage': false,
'useLocalTimeZone': true,
'fastLogin': true,
'followTimeLine': false,
'timelineScale': -1,
'hideArchived': false,
'videoPlaybackSpeed': 2,
'enableThumbs': true,
'enableStrictSSL': false,
'enableSlowLoading': false,
'isFullScreen': false,
'reloadInMontage': false,
'momentGridSize': 40,
'momentMonitorFilter': [],
'enableMomentSubMenu': true,
'momentShowIcons':false,
'momentArrangeBy': 'StartTime',
'showLiveForInProgressEvents': true,
'disableSimulStreaming': false,
'insertBasicAuthToken': false,
'loginAPISupported': false,
'montageResizeSteps': 0.2,
'currentServerVersion': '',
'saveToCloud': true,
'montageReviewCollapse': true,
'objectDetectionFilter': false,
'enableEventRefresh': true,
'lastEventCheckTimes': {},
'enableMontageOverlays': true,
'showMontageSidebars': false,
'isTokenSupported': false,
'accessTokenExpires': '',
'refreshTokenExpires': '',
'accessToken': '',
'refreshToken': '',
'isKiosk': false,
'kioskPassword': '',
'useAPICaching': true,
'pauseStreams': false,
'liveStreamBuffer': 10,
'zmNinjaCustomId':undefined, // filled in init. custom header
'obfuscationScheme': 'lzs', // or 'aes'
'showAnimation': true,
'montageHideFooter': false,
'httpCordovaNoEncode': false,
'currentZMGroupNames': [],
'unsupported': {},
'monitorSpecific': {}
};
var defaultLoginData = angular.copy(loginData);
var configParams = {
'ZM_EVENT_IMAGE_DIGITS': '-1',
'ZM_PATH_ZMS': '',
'ZM_MIN_STREAMING_PORT': '-1'
};
/**
* Allows/Disallows self signed certs
*
* @returns
*/
function setCordovaHttpOptions() {
/*debug ("Cordova HTTP: Setting JSON serializer");
cordova.plugin.http.setDataSerializer('utf8');*/
if (loginData.isUseBasicAuth) {
debug("Cordova HTTP: configuring basic auth");
cordova.plugin.http.useBasicAuth(loginData.basicAuthUser, loginData.basicAuthPassword);
}
var cid = loginData.zmNinjaCustomId.replace('%APPVER%',zmAppVersion);
debug ("Setting cordova header X-ZmNinja to "+cid);
// setup custom header
cordova.plugin.http.setHeader('*', 'X-ZmNinja', cid);
if (!loginData.enableStrictSSL) {
//alert("Enabling insecure SSL");
log(">>>> Disabling strict SSL checking (turn off in Dev Options if you can't connect)");
cordova.plugin.http.setSSLCertMode('nocheck', function () {
debug('--> SSL is permissive, will allow any certs. Use at your own risk.');
}, function () {
NVR.log('-->Error setting SSL permissive');
});
if ($rootScope.platformOS == 'android') {
log(">>> Android: enabling inline image view for self signed certs");
cordova.plugins.certificates.trustUnsecureCerts(true);
}
} else {
log(">>>> Enabling strict SSL checking (turn off in Dev Options if you can't connect)");
}
}
/**
* Checks if a complex object is empty
*
* @param {any} obj
* @returns
*/
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
function clear_unsupported() {
loginData.unsupported = {};
setLogin(loginData);
}
function set_unsupported(p) {
loginData.unsupported[p] = true;
debug ('Setting '+p+' to unsupported');
setLogin(loginData);
}
function get_unsupported(p) {
return p? loginData.unsupported[p]:loginData.unsupported;
}
function getBandwidth() {
// if mode is not on always return high
if (loginData.enableLowBandwidth == false) {
return "highbw";
}
// if mode is force on, return low
if (loginData.enableLowBandwidth == true && loginData.autoSwitchBandwidth != true) {
return "lowbw";
}
if (loginData.enableLowBandwidth == true && loginData.autoSwitchBandwidth == true && $rootScope.platformOS == 'desktop') {
return "highbw";
}
// else return real state
var networkState = navigator.connection.type;
var strState;
switch (networkState) {
case Connection.WIFI:
strState = "highbw";
break;
case Connection.ETHERNET:
strState = "highbw";
break;
default:
strState = "lowbw";
break;
}
return strState;
}
//--------------------------------------------------------------------------
// uses fileLogger to write logs to file for later investigation
//--------------------------------------------------------------------------
// separate out a debug so we don't do this if comparison for normal logs
function debug(val) {
if (loginData.enableDebug && loginData.enableLogs) {
if (val !== undefined) {
var regex1 = /"password":".*?"/g;
var regex2 = /&pass=.*?(?=["&]|$)/g;
var regex3 = /&token=([^&]*)/g;
var regex4 = /&auth=([^&]*)/g;
//console.log ("VAL IS " + val);
val = val.replace(regex1, "<password removed>");
val = val.replace(regex2, "<password removed>");
val = val.replace (regex3, "&token=<removed>");
val = val.replace (regex4, "&auth=<removed>");
}
$ionicPlatform.ready(function () {
$fileLogger.debug(val);
});
//console.log (val);
}
}
// custom caching function
// as native http doesn't cache
function delete_cache (key) {
return localforage.removeItem(key);
}
function delete_all_caches() {
debug ('Clearing all unsupported flags');
clear_unsupported();
debug ('CACHE: Flushing all network API caches...');
return localforage.removeItem('cached_monitors')
.then ( function () {return localforage.removeItem('cached_api_version');})
.then ( function () {return localforage.removeItem('cached_multi_servers');})
.then ( function () {return localforage.removeItem('cached_multi_port');})
.then ( function () {return localforage.removeItem('cached_timezone');})
.then ( function () {return localforage.removeItem('cached_zmgroups');})
.catch ( function (err) {debug ('Error removing all caches: '+JSON.stringify(err));});
}
function cache_or_http(url,key,doCrypt, expiry) {
if (!loginData.useAPICaching) {
debug ('CACHE: Not being used, as it is disabled');
return $http.get(url);
}
// debug ('Inside cache_or_http with key:'+key+' crypt:'+doCrypt+' exp:'+expiry);
var d = $q.defer();
if (!expiry) expiry = 3600;
if (!doCrypt) doCrypt = false;
localforage.getItem(key)
.then (function (cache_data) {
if (cache_data) {
debug ('CACHE: found for key: '+key+' with expiry of:'+cache_data.expiry+'s');
data = cache_data.data;
t = moment(cache_data.time);
diff = moment().diff(t,'seconds');
if (diff >=cache_data.expiry) {
debug ('CACHE: cached value for key:'+key+' has expired as '+diff+' >='+cache_data.expiry);
localforage.removeItem (key)
.then (function() {return cache_or_http(url, key, doCrypt, expiry);})
.catch (function(err) {
debug ('CACHE: error deleting key, err:'+JSON.stringify(err)+' but still proceeding with another call to cache_or_http');
return cache_or_http(url, key, doCrypt, expiry);
});
}
else {
debug ('CACHE: cached value for key:'+key+' is good as '+diff+' <'+cache_data.expiry);
}
//data = JSON.parse(data);
if (doCrypt) {
debug ('CACHE: decryption requested');
data = decrypt(data);
}
else
data = JSON.parse(data);
d.resolve(data);
return (d.promise);
} else {
debug ('CACHE: NOT found for:'+key+ ' reverting to HTTP');
return $http.get(url)
.then ( function (data) {
cache_entry = {
'data': null,
'time': null,
'expiry': expiry
};
debug ('CACHE: storing key data in cache now, with expiry of '+expiry);
if (doCrypt) {
debug ('CACHE: encrypting request');
var ct = encrypt(data);
cache_entry.data = ct;
}
else {
cache_entry.data = JSON.stringify(data);
}
cache_entry.time = moment().toString();
//debug ('Setting key:'+key+' data value to:'+cache_entry.data);
localforage.setItem(key, cache_entry);
d.resolve(data);
return d.promise;
})
.catch ( function (err) {
log ('CACHE: error with http get '+JSON.stringify(err));
d.reject(err);
return d.promise;
});
}
})
.catch ( function (err) {
//debug ('cache_or_http error:'+JSON.stringify(err));
d.reject(err);
return d.promise;
//return $http.get(url);
}) ;
//debug ('returning promise');
return d.promise;
}
function getZMGroups() {
//{"groups":[{"Group":{"Id":"1","Name":"test","ParentId":null}},{"Group":{"Id":"2","Name":"test2","ParentId":null}}]}
var d = $q.defer();
zmgroups = [];
if (get_unsupported('groups_associations')) {
debug ('Groups Association API is marked as unsupported, not invoking');
d.resolve(true);
return d.promise;
}
var apiurl = loginData.apiurl+'/groups/associations.json?'+$rootScope.authSession;
for (var m=0; m < monitors.length; m++ ) {
if (!monitors[m].Monitor.Group) monitors[m].Monitor.Group=[];
}
cache_or_http(apiurl, 'cached_zmgroups')
.then (function (data) {
data = data.data;
// console.log (JSON.stringify(data));
//debug ('Groups are:'+JSON.stringify(data));
if (data && data.groups) {
zmgroups = [];
for (var i=0; i< data.groups.length; i++) {
zmgroups.push(data.groups[i].Group.Name);
//console.log( "Checking Group "+data.groups[i].Group.Name);
for (var j=0; j < data.groups[i].Monitor.length; j++) {
for (var k = 0; k < monitors.length; k++) {
// console.log(k);
if (monitors[k].Monitor.Id == data.groups[i].Monitor[j].Id) {
monitors[k].Monitor.Group.push({'id':data.groups[i].Group.Id, 'name':data.groups[i].Group.Name});
var parent = data.groups[i].Group.ParentId;
while (parent) {
var parentFound = false;
var x;
for (x = 0; x < data.groups.length; x++) {
if (data.groups[x].Group.Id == parent) {
parentFound = true;
break;
}
}
if (parentFound) {
monitors[k].Monitor.Group.push({'id':data.groups[x].Group.Id, 'name':data.groups[x].Group.Name});
// console.log (data.groups[x].Group.Id+ " is parent of "+data.groups[i].Group.Id);
parent = data.groups[x].Group.ParentId;
}
}
// console.log ('DONE HIERARCHY');
// console.log ('Monitor: '+ monitors[k].Monitor.Name+" belongs to Group:"+data.groups[i].Group.Name);
}
} // monitors
} // groups monitors
} // groups
d.resolve(true);
return (d.promise);
} else {
debug ('No groups found');
d.resolve(true);
return (d.promise);
}
}, function (err) {
debug('Error retrieving groups:'+JSON.stringify(err));
set_unsupported('groups_associations');
d.resolve(true);
return (d.promise);
});
return (d.promise);
}
function getZmsMultiPortSupport(forceReload) {
var d = $q.defer();
if (configParams.ZM_MIN_STREAMING_PORT == -1 || forceReload) {
log("Checking value of ZM_MIN_STREAMING_PORT for the first time");
var apiurl = loginData.apiurl;
var myurl = apiurl + '/configs/viewByName/ZM_MIN_STREAMING_PORT.json?' + $rootScope.authSession;
cache_or_http(myurl,'cached_multi_port', false, 3600*24)
.then(function (data) {
data = data.data;
//console.log ("GOT " + JSON.stringify(data));
if (data.config && data.config.Value) {
configParams.ZM_MIN_STREAMING_PORT = data.config.Value;
setCurrentServerMultiPortSupported(true);
log("Got min streaming port value of: " + configParams.ZM_MIN_STREAMING_PORT);
} else {
setCurrentServerMultiPortSupported(false);
log("ZM_MIN_STREAMING_PORT not configured, disabling");
configParams.ZM_MIN_STREAMING_PORT = 0;
}
d.resolve(configParams.ZM_MIN_STREAMING_PORT);
return (d.promise);
},
function (err) {
configParams.ZM_MIN_STREAMING_PORT = 0;
log("ZM_MIN_STREAMING_PORT not supported");
setCurrentServerMultiPortSupported(false);
d.resolve(configParams.ZM_MIN_STREAMING_PORT);
return (d.promise);
});
} else {
log("sending stored ZM_MIN_STREAMING_PORT " +
configParams.ZM_MIN_STREAMING_PORT);
d.resolve(configParams.ZM_MIN_STREAMING_PORT);
return (d.promise);
}
return (d.promise);
}
function proceedWithFreshLogin(noBroadcast) {
// recompute rand anyway so even if you don't have auth
// your stream should not get frozen
$rootScope.rand = Math.floor((Math.random() * 100000) + 1);
$rootScope.modalRand = Math.floor((Math.random() * 100000) + 1);
// console.log ("***** STATENAME IS " + statename);
var d = $q.defer();
log("Doing fresh login to ZM");
var httpDelay = loginData.enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout;
str = "<a style='color:white; text-decoration:none' href='#' ng-click='$root.cancelAuth()' <i class='ion-close-circled'></i> " + $translate.instant('kAuthenticating')+"</a>";
if (str) {
$ionicLoading.show({
template: str,
noBackdrop: true,
duration: httpDelay
});
}
//first login using new API
$rootScope.authSession = '';
var loginAPI = loginData.apiurl + '/host/login.json';
$http({
method: 'post',
url: loginAPI,
timeout: httpDelay,
skipIntercept: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
responseType: 'text',
transformResponse: undefined,
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
user: loginData.username,
pass: loginData.password
}
})
//$http.get(loginAPI)
.then(function (textsucc) {
$ionicLoading.hide();
var succ;
try {
succ = JSON.parse(textsucc.data);
if (!succ.version) {
debug("API login returned fake success, going back to webscrape");
loginData.loginAPISupported = false;
setLogin(loginData);
loginWebScrape()
.then(function () {
d.resolve("Login Success");
return d.promise;
},
function () {
$ionicLoading.hide();
d.reject("Login Error");
return (d.promise);
});
return d.promise;
}
debug("API based login returned. ");
console.log (JSON.stringify(succ));
setCurrentServerVersion(succ.version);
$ionicLoading.hide();
//$rootScope.loggedIntoZm = 1;
//console.log ("***** CLEARING AUTHSESSION IN LINE 466");
$rootScope.authSession = '';
if (succ.refresh_token) {
$rootScope.authSession = '&token='+succ.access_token;
log ("New refresh token retrieved: ..."+succ.refresh_token.substr(-5));
loginData.isTokenSupported = true;
loginData.accessToken = succ.access_token;
loginData.accessTokenExpires = moment.utc().add(succ.access_token_expires, 'seconds');
loginData.refreshToken = succ.refresh_token;
$rootScope.tokenExpires = succ.access_token_expires;
log ('----> Setting token re-login after '+succ.access_token_expires+' seconds');
if (tokenExpiryTimer) $timeout.cancel(tokenExpiryTimer);
//succ.access_token_expires = 30;
tokenExpiryTimer = $timeout ( function () {
$rootScope.$broadcast('token-expiry');
}, succ.access_token_expires * 1000);
loginData.refreshTokenExpires = moment.utc().add(succ.refresh_token_expires, 'seconds');
log ("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss"));
log ("New refresh token expires on: UTC "+loginData.refreshTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
log ("New access token expires on: UTC "+loginData.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
setLogin(loginData);
}
else {
if (succ.credentials != undefined) {
if (succ.credentials != '') {
log ("Could not recover token details, trying old auth credentials");
loginData.isTokenSupported = false;
setLogin(loginData);
$rootScope.authSession = "&" + succ.credentials;
if (succ.append_password == '1') {
$rootScope.authSession = $rootScope.authSession +
loginData.password;
}
} else {
// incase auth is turned off, but user said
// its on.
$rootScope.authSession="&nonauth=none";
debug ('Your auth seems to be turned off, but you said yes');
}
}
else {
log ("Neither token nor old cred worked. Seems like an error");
}
}
loginData.loginAPISupported = true;
setLogin(loginData);
log("Stream authentication construction: " +
$rootScope.authSession);
log("Successfully logged into Zoneminder via API");
d.resolve("Login Success");
if (!noBroadcast) $rootScope.$broadcast('auth-success', succ);
return d.promise;
} catch (e) {
debug("Login API approach did not work...");
loginData.loginAPISupported = false;
loginData.isTokenSupported = false;
setLogin(loginData);
loginWebScrape()
.then(function () {
d.resolve("Login Success");
return d.promise;
},
function (err) {
$ionicLoading.hide();
d.reject("Login Error");
return (d.promise);
});
return d.promise;
}
},
function (err) {
//console.log("******************* API login error " + JSON.stringify(err));
$ionicLoading.hide();
//if (err && err.data && 'success' in err.data) {
log("API based login not supported, need to use web scraping...");
// login using old web scraping
loginData.loginAPISupported = false;
setLogin(loginData);
loginWebScrape()
.then(function () {
d.resolve("Login Success");
return d.promise;
},
function (err) {
d.reject("Login Error");
return (d.promise);
});
}
); // post .then
return d.promise;
}
function loginWebScrape(noBroadcast) {
var d = $q.defer();
if ($rootScope.userCancelledAuth) {
debug ('NVR loginWebScrape: User cancelled auth, not proceeding');
d.reject(true);
return d.promise;
}
debug("Logging in using old web-scrape method");
$ionicLoading.show({
template: "<a style='color:white; text-decoration:none' href='#' ng-click='$root.cancelAuth()' <i class='ion-close-circled'></i> " + $translate.instant('kAuthenticatingWebScrape')+"</a>",
noBackdrop: true,
duration: httpDelay
});
var httpDelay = loginData.enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout;
//NVR.debug ("*** AUTH LOGIN URL IS " + loginData.url);
$http({
method: 'post',
timeout: httpDelay,
//withCredentials: true,
url: loginData.url + '/index.php?view=console',
skipIntercept:true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" +
encodeURIComponent(obj[p]));
var params = str.join("&");
return params;
},
data: {
username: loginData.username,
password: loginData.password,
action: "login",
view: "console"
}
})
.then(function (data, status, headers) {
// console.log(">>>>>>>>>>>>>> PARALLEL POST SUCCESS");
data = data.data;
$ionicLoading.hide();
// Coming here does not mean success
// it could also be a bad login, but
// ZM returns you to login.php and returns 200 OK
// so we will check if the data has
// <title>ZM - Login</title> -- it it does then its the login page
if (data.indexOf(zm.loginScreenString1) >=0) {
//eventServer.start();
//$rootScope.loggedIntoZm = 1;
log("zmAutologin successfully logged into Zoneminder");
$rootScope.apiValid = true;
// now go to authKey part, so don't return yet...
} else // this means login error
{
// $rootScope.loggedIntoZm = -1;
//console.log("**** ZM Login FAILED");
log("zmAutologin Error: Bad Credentials ", "error");
if (!noBroadcast) $rootScope.$broadcast('auth-error', "incorrect credentials");
d.reject("Login Error");
return (d.promise);
// no need to go to next code, so return above
}
// Now go ahead and re-get auth key
// if login was a success
// console.log ("***** CLEARING AUTHSESSION IN AUTHKEY");
$rootScope.authSession = '';
getAuthKey($rootScope.validMonitorId)
.then(function (success) {
//console.log(success);
//console.log ("***** SETTING AUTHSESSION IN AUTHKEY"+success);
$rootScope.authSession = success;
log("Stream authentication construction: " +
$rootScope.authSession);
d.resolve("Login Success");
$rootScope.$broadcast('auth-success', data);
return d.promise;
},
function (error) {
//console.log(error);
log("Modal: Error returned Stream authentication construction. Retaining old value of: " + $rootScope.authSession);
debug("Error was: " + JSON.stringify(error));
d.resolve("Login Success");
if (!noBroadcast) $rootScope.$broadcast('auth-success', data);
});
return (d.promise);
},
function (error, status) {
// console.log(">>>>>>>>>>>>>> PARALLEL POST ERROR");
$ionicLoading.hide();
//console.log("**** ZM Login FAILED");
// FIXME: Is this sometimes results in null
log("zmAutologin Error " + JSON.stringify(error) + " and status " + status);
// bad urls etc come here
//$rootScope.loggedIntoZm = -1;
if (!noBroadcast) $rootScope.$broadcast('auth-error', error);
d.reject("Login Error");
return d.promise;
});
return d.promise;
}
function getAuthKey(mid, ck) {
var d = $q.defer();
var myurl;
if (!loginData.isUseAuth) {
$rootScope.authSession = "";
d.resolve($rootScope.authSession);
return d.promise;
}
if ($rootScope.authSession != '' && $rootScope.authSession != 'undefined') {
log("We already have an auth key of:" + $rootScope.authSession);
d.resolve($rootScope.authSession);
return d.promise;
}
if (loginData.currentServerVersion && (versionCompare(loginData.currentServerVersion, zm.versionWithLoginAPI) != -1 || loginData.loginAPISupported)) {
myurl = loginData.apiurl + '/host/login.json';
debug("Server version " + loginData.currentServerVersion + " > 1.31.41, so using login API:" + myurl);
$http.get(myurl)
.then(function (s) {
debug("Credentials API returned: " + JSON.stringify(s));
if (!s.data || s.data.credentials == undefined) {
$rootScope.authSession = "";
d.resolve($rootScope.authSession);
debug("login() API Succeded, but did NOT return credentials key: " + JSON.stringify(s));
return d.promise;
} else {
if (s.data.credentials != '') {
$rootScope.authSession = "&" + s.data.credentials;
if (s.data.append_password == '1') {
$rootScope.authSession = $rootScope.authSession +
loginData.password;
}
}
else {
// incase auth is turned off, but user said
// its on.
$rootScope.authSession="&nonauth=none";
debug ('Your auth seems to be turned off, but you said yes');
}
d.resolve($rootScope.authSession);
return d.promise;
}
},
function (e) {
//console.log ("***** CLEARING AUTHSESSION IN GETCREDENTIALS");
$rootScope.authSession = "";
d.resolve($rootScope.authSession);
debug("AuthHash API Error: " + JSON.stringify(e));
return d.promise;
}
);
return d.promise;
}
//old way without login API
var as = 'undefined';
if (!mid && monitors && monitors.length > 0) {
mid = monitors[0].Monitor.Id;
}
if (!mid) {
log("Deferring auth key, as monitorId unknown");
d.resolve("");
$rootScope.authSession = as;
return (d.promise);
}
// Skipping monitor number as I only need an auth key
// so no need to generate an image
myurl = loginData.url + "/index.php?view=watch&mid=" + mid;
debug("NVR: Getting auth from " + myurl + " with mid=" + mid);
$http.get(myurl)
.then(function (success) {
//console.log ("**** RESULT IS " + JSON.stringify(success));
// Look for auth=
var auth = success.data.match("auth=(.*?)&");
if (auth && (auth[1] != null)) {
log("NVR: Extracted a stream authentication key of: " + auth[1]);
as = "&auth=" + auth[1];
$rootScope.authSession = as;
d.resolve(as);
} else {
log("NVR: Did not find a stream auth key, looking for user=");
auth = success.data.match("user=(.*?)&");
if (auth && (auth[1] != null)) {
log("NVR: Found simple stream auth mode (user=)");
as = "&user=" + loginData.username + "&pass=" + encodeURIComponent(loginData.password);
$rootScope.authSession = as;
d.resolve(as);
} else {
log("Data Model: Did not find any stream mode of auth");
as = "";
$rootScope.authSession = "";
d.resolve(as);
return d.promise;
}
return (d.promise);
}
},
function (error) {
log("NVR: Error resolving auth key " + JSON.stringify(error));
d.resolve("");
return (d.promise);
});
return (d.promise);
}
function log(val, logtype) {
if (loginData.enableLogs) {
if (val !== undefined) {
var regex1 = /"password":".*?"/g;
var regex2 = /&pass=.*?(?=["&]|$)/g;
var regex3 = /&token=([^&]*)/g;
var regex4 = /&auth=([^&]*)/g;
//console.log ("VAL IS " + val);
val = val.replace(regex1, "<password removed>");
val = val.replace(regex2, "<password removed>");
val = val.replace (regex3, "&token=<removed>");
val = val.replace (regex4, "&auth=<removed>");
}
// make sure password is removed
//"username":"zmninja","password":"xyz",
//val = val.replace(/\"password:\",
$ionicPlatform.ready(function () {
$fileLogger.log(logtype, val);
});
// console.log (val);
}
}
function reloadMonitorDisplayStatus() {
debug("Loading hidden/unhidden status for profile:" + loginData.currentMontageProfile);
var positionsStr = loginData.packeryPositions;
//console.log ("positionStr="+positionsStr);
var positions = {};
if (loginData.packeryPositions != '' && loginData.packeryPositions != undefined) {
// console.log("positions=" + loginData.packeryPositions);
try {
positions = JSON.parse(positionsStr);
} catch (e) {
debug("error parsing positions");
}
for (var m = 0; m < monitors.length; m++) {
var positionFound = false;
for (var p = 0; p < positions.length; p++) {
if (monitors[m].Monitor.Id == positions[p].attr) {
monitors[m].Monitor.listDisplay = positions[p].display;
positionFound = true;
//debug("NVR: Setting MID:" + monitors[m].Monitor.Id + " to " + monitors[m].Monitor.listDisplay);
}
}
if (!positionFound) {
if (loginData.currentMontageProfile != $translate.instant('kMontageDefaultProfile')) {
monitors[m].Monitor.listDisplay = 'noshow';
//console.log("*************DISABLE NEW MONITOR");
} else // make sure we add it because its show all view
{
monitors[m].Monitor.listDisplay = 'show';
//console.log("*************ENABLE NEW MONITOR");
}
}
}
} else // if there are no packery positions, make sure all are displayed!
{
debug("no packery profile, making sure monitors are show");
for (var m1 = 0; m1 < monitors.length; m1++) {
monitors[m1].Monitor.listDisplay = 'show';
}
}
}
function setLogin(newLogin) {
//var d = $q.defer();
// if we are here, we should remove cache
loginData = angular.copy(newLogin);
//console.log ('****** SET LOGIN:'+JSON.stringify(loginData));
$rootScope.LoginData = loginData;
serverGroupList[loginData.serverName] = angular.copy(loginData);
var ct = encrypt(serverGroupList);
//debug ("Crypto is: " + ct);
return localforage.setItem("serverGroupList", ct)
.then(function () {
return localforage.setItem("defaultServerName", loginData.serverName);
})
.then(function () {
//debug("saving defaultServerName worked");
return localforage.removeItem("settings-temp-data");
})
.catch(function (err) {
log("SetLogin localforage store error " + JSON.stringify(err));
});
}
//credit: https://gist.github.com/alexey-bass/1115557
function versionCompare(left, right) {
if (typeof left + typeof right != 'stringstring')
return false;
var a = left.split('.');
var b = right.split('.');
var i = 0;
var len = Math.max(a.length, b.length);
for (; i < len; i++) {
if ((a[i] && !b[i] && parseInt(a[i]) > 0) || (parseInt(a[i]) > parseInt(b[i]))) {
return 1;
} else if ((b[i] && !a[i] && parseInt(b[i]) > 0) || (parseInt(a[i]) < parseInt(b[i]))) {
return -1;
}
}
return 0;
}
function _checkInitSanity(loginData) {
// old version hacks for new variables
// always true Oct 27 2016
loginData.persistMontageOrder = true;
loginData.enableh264 = true;
if (typeof loginData.isUseBasicAuth === 'undefined') {
loginData.isUseBasicAuth = false;
loginData.basicAuthUser = '';
loginData.basicAuthPassword = '';
$rootScope.basicAuthHeader = '';
$rootScope.basicAuthToken = '';
}
if (loginData.url.indexOf('@') != -1) {
log(">> " + loginData.url);
log(">>User/Password detected in URL, changing to new auth handling...");
loginData.isUseBasicAuth = true;
var components = URI.parse(loginData.url);
loginData.url = components.scheme + "://" + components.host;
if (components.port) loginData.url = loginData.url + ":" + components.port;
if (components.path) loginData.url = loginData.url + components.path;
components = URI.parse(loginData.streamingurl);
loginData.streamingurl = components.scheme + "://" + components.host;
if (components.port) loginData.streamingurl = loginData.streamingurl + ":" + components.port;
if (components.path) loginData.streamingurl = loginData.streamingurl + components.path;
components = URI.parse(loginData.apiurl);
loginData.apiurl = components.scheme + "://" + components.host;
if (components.port) loginData.apiurl = loginData.apiurl + ":" + components.port;
if (components.path) loginData.apiurl = loginData.apiurl + components.path;
$rootScope.basicAuthToken = btoa(components.userinfo);
$rootScope.basicAuthHeader = 'Basic ' + $rootScope.basicAuthToken;
//console.log (">>>> SET BASIC AUTH TO " + $rootScope.basicAuthHeader);
var up = components.userinfo.split(':');
loginData.basicAuthPassword = up[1];
loginData.basicAuthUser = up[0];
//console.log ("SETTING "+loginData.basicAuthUser+" "+loginData.basicAuthPassword);
}
if (loginData.isUseBasicAuth) {
$rootScope.basicAuthToken = btoa(loginData.basicAuthUser + ':' + loginData.basicAuthPassword);
$rootScope.basicAuthHeader = 'Basic ' + $rootScope.basicAuthToken;
debug("Basic authentication detected, constructing Authorization Header");
// console.log ("BASIC AUTH SET TO:"+$rootScope.basicAuthHeader);
}
if (typeof loginData.enableAlarmCount === 'undefined') {
debug("enableAlarmCount does not exist, setting to true");
loginData.enableAlarmCount = true;
}
if (typeof loginData.onTapScreen == 'undefined') {
loginData.onTapScreen = $translate.instant('kTapMontage');
}
if (loginData.onTapScreen != $translate.instant('kTapMontage') &&
loginData.onTapScreen != $translate.instant('kTapEvents') &&
loginData.onTapScreen != $translate.instant('kTapLiveMonitor')) {
log("Invalid onTap setting found, resetting. I got " + loginData.onTapScreen);
loginData.onTapScreen = $translate.instant('kMontage');
}
if (typeof loginData.minAlarmCount === 'undefined') {
debug("minAlarmCount does not exist, setting to true");
loginData.minAlarmCount = 1;
}
if (typeof loginData.montageSize == 'undefined') {
debug("montageSize does not exist, setting to 2 (2 per col)");
loginData.montageSize = 2;
}
if (typeof loginData.useNphZms == 'undefined') {
debug("useNphZms does not exist. Setting to true");
loginData.useNphZms = true;
}
if (typeof loginData.useNphZmsForEvents == 'undefined') {
debug("useNphZmsForEvents does not exist. Setting to true");
loginData.useNphZmsForEvents = true;
}
if (typeof loginData.forceImageModePath == 'undefined') {
debug("forceImageModePath does not exist. Setting to false");
loginData.forceImageModePath = false;
}
if (typeof loginData.reachability == 'undefined') {
debug("reachability does not exist. Setting to true");
loginData.reachability = true;
}
// force it - this may not be the problem
loginData.reachability = true;
// and now, force enable it
loginData.useNphZms = true;
loginData.useNphZmsForEvents = true;
if (typeof loginData.packMontage == 'undefined') {
debug("packMontage does not exist. Setting to false");
loginData.packMontage = false;
}
if (typeof loginData.forceNetworkStop == 'undefined') {
debug("forceNetwork does not exist. Setting to false");
loginData.forceNetworkStop = false;
}
if (typeof loginData.enableLogs == 'undefined') {
debug("enableLogs does not exist. Setting to true");
loginData.enableLogs = true;
}
if (typeof loginData.defaultPushSound == 'undefined') {
debug("defaultPushSound does not exist. Setting to false");
loginData.defaultPushSound = false;
}
//console.log("INIT SIMUL=" + loginData.disableSimulStreaming);
//console.log("INIT PLATFORM IS=" + $rootScope.platformOS);
if (typeof loginData.disableSimulStreaming == 'undefined') {
loginData.disableSimulStreaming = false;
//console.log("INIT DISABLING SIMUL:" + loginData.disableSimulStreaming);
}
if (typeof loginData.exitOnSleep == 'undefined') {
debug("exitOnSleep does not exist. Setting to false");
loginData.exitOnSleep = false;
}
if (typeof loginData.enableBlog == 'undefined') {
debug("enableBlog does not exist. Setting to true");
loginData.enableBlog = true;
}
if (typeof loginData.packeryPositionsArray == 'undefined') {
debug("packeryPositionsArray does not exist. Setting to empty");
loginData.packeryPositionsArray = {};
}
if (typeof loginData.packeryPositions == 'undefined') {
debug("packeryPositions does not exist. Setting to empty");
loginData.packeryPositions = "";
}
if (typeof loginData.EHpackeryPositions == 'undefined') {
//debug("EHpackeryPositions does not exist. Setting to empty");
loginData.EHpackeryPositions = "";
}
if (typeof loginData.packerySizes == 'undefined') {
//debug("packerySizes does not exist. Setting to empty");
loginData.packerySizes = "";
}
if (typeof loginData.use24hr == 'undefined') {
//debug("use24hr does not exist. Setting to false");
loginData.use24hr = false;
}
if (typeof timelineModalGraphType == 'undefined') {
//debug("timeline graph type not set. Setting to all");
loginData.timelineModalGraphType = $translate.instant('kGraphAll');
//console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + loginData.timelineModalGraphType);
}
if (typeof loginData.resumeDelay == 'undefined') {
//debug("resumeDelay does not exist. Setting to 0");
loginData.resumeDelay = 0;
}
// override resumeDelay - it was developed on a wrong assumption
loginData.resumeDelay = 0;
if (typeof loginData.montageHistoryQuality == 'undefined') {
debug("montageHistoryQuality does not exist. Setting to 50");
loginData.montageHistoryQuality = "50";
}
if (typeof loginData.vibrateOnPush == 'undefined') {
debug("vibrate on push not found, setting to true");
loginData.vibrateOnPush = true;
}
if (typeof loginData.isFullScreen == 'undefined') {
loginData.isFullScreen = false;
}
if (typeof loginData.reloadInMontage == 'undefined') {
loginData.reloadInMontage = false;
}
if (typeof loginData.soundOnPush == 'undefined') {
debug("sound on push not found, setting to true");
loginData.soundOnPush = true;
}
if (typeof loginData.cycleMonitors == 'undefined') {
loginData.cycleMonitors = false;
}
if (typeof loginData.cycleMonitorsInterval == 'undefined') {
loginData.cycleMonitorsInterval = 10;
}
if (typeof loginData.cycleMontage == 'undefined') {
loginData.cycleMontage = false;
}
if (typeof loginData.cycleMontageInterval == 'undefined') {
loginData.cycleMontageInterval = 10;
}
if (typeof loginData.enableLowBandwidth == 'undefined') {
loginData.enableLowBandwidth = false;
}
if (typeof loginData.autoSwitchBandwidth == 'undefined') {
loginData.autoSwitchBandwidth = false;
}
$rootScope.runMode = getBandwidth();
log("Setting NVR init bandwidth to: " + $rootScope.runMode);
if (typeof loginData.refreshSecLowBW == 'undefined') {
loginData.refreshSecLowBW = 8;
}
if (typeof loginData.singleliveFPS == 'undefined') {
loginData.singleliveFPS = '';
}
if (typeof loginData.montageliveFPS == 'undefined') {
loginData.montageLiveFPS = '';
}
if (typeof loginData.disableAlarmCheckMontage == 'undefined') {
loginData.disableAlarmCheckMontage = false;
}
if (typeof loginData.useLocalTimeZone == 'undefined') {
loginData.useLocalTimeZone = true;
}
if (typeof loginData.fastLogin == 'undefined') {
loginData.fastLogin = true;
}
if (typeof loginData.currentMontageProfile == 'undefined') {
loginData.currentMontageProfile = '';
}
if (typeof loginData.followTimeLine == 'undefined') {
loginData.followTimeLine = false;
}
if (typeof loginData.timelineScale == 'undefined') {
loginData.timelineScale = -1;
}
if (typeof loginData.showMontageSubMenu == 'undefined') {
loginData.showMontageSubMenu = false;
}
if (typeof loginData.monSingleImageQuality == 'undefined') {
loginData.monSingleImageQuality = 100;
}
if (typeof loginData.hideArchived == 'undefined') {
loginData.hideArchived = false;
}
if (typeof loginData.videoPlaybackSpeed == 'undefined') {
loginData.videoPlaybackSpeed = 1;
}
if (typeof loginData.enableThumbs == 'undefined') {
loginData.enableThumbs = true;
}
if (typeof loginData.enableSlowLoading == 'undefined') {
loginData.enableSlowLoading = false;
}
if (typeof loginData.enableStrictSSL == 'undefined') {
loginData.enableStrictSSL = false;
}
if (typeof loginData.momentGridSize == 'undefined') {
loginData.momentGridSize = 40;
}
if (typeof loginData.enableMomentSubMenu == 'undefined') {
loginData.enableMomentSubMenu = true;
}
if (typeof loginData.momentShowIcons == 'undefined') {
loginData.momentShowIcons = false;
}
if (typeof loginData.momentMonitorFilter == 'undefined') {
loginData.momentMonitorFilter = JSON.stringify([]);
}
if (typeof loginData.momentArrangeBy == 'undefined') {
loginData.momentArrangeBy = "StartTime";
}
if (typeof loginData.insertBasicAuthToken == 'undefined') {
loginData.insertBasicAuthToken = false;
}
if (typeof loginData.showLiveForInProgressEvents == 'undefined') {
loginData.showLiveForInProgressEvents = true;
}
if (typeof loginData.loginAPISupported == 'undefined') {
loginData.loginAPISupported = false;
}
if (typeof loginData.montageResizeSteps == 'undefined') {
loginData.montageResizeSteps = 0.2;
}
if (typeof loginData.saveToCloud == 'undefined') {
loginData.saveToCloud = true;
}
if (typeof loginData.montageReviewCollapse == 'undefined') {
loginData.montageReviewCollapse = true;
}
if (typeof loginData.objectDetectionFilter == 'undefined') {
loginData.objectDetectionFilter = false;
}
if (typeof loginData.enableEventRefresh == 'undefined') {
loginData.enableEventRefresh = true;
}
if (typeof loginData.lastEventCheckTimes == 'undefined') {
loginData.lastEventCheckTimes = {};
}
if (typeof loginData.enableMontageOverlays == 'undefined') {
loginData.enableMontageOverlays = true;
}
if (typeof loginData.showMontageSidebars == 'undefined') {
loginData.showMontageSidebars = false;
}
if (typeof loginData.isTokenSupported == 'undefined') {
loginData.isTokenSupported = false;
}
if (typeof loginData.accessTokenExpires == 'undefined') {
loginData.accessTokenExpires = '';
}
if (typeof loginData.refreshTokenExpires == 'undefined') {
loginData.refreshTokenExpires = '';
}
if (typeof loginData.refreshToken == 'undefined') {
loginData.refreshToken = '';
}
if (typeof loginData.accessToken == 'undefined') {
loginData.accessToken = '';
}
if (typeof loginData.isKiosk == 'undefined') {
loginData.isKiosk = false;
}
if (typeof loginData.useAPICaching == 'undefined') {
loginData.useAPICaching = true;
}
if (typeof loginData.pauseStreams == 'undefined') {
loginData.pauseStreams = false;
}
if (typeof loginData.liveStreamBuffer == 'undefined') {
loginData.liveStreamBuffer = 10;
}
if ((typeof loginData.zmNinjaCustomId == 'undefined') || (loginData.zmNinjaCustomId == '')) {
loginData.zmNinjaCustomId = 'zmNinja_%APPVER%';
}
// Silly error to hardcode the version when I released
// 1.3.x. Let's fix it
if (loginData.zmNinjaCustomId.indexOf('zmNinja_1.3')!=-1) {
loginData.zmNinjaCustomId = 'zmNinja_%APPVER%';
}
if (typeof loginData.obfuscationScheme == 'undefined') {
loginData.obfuscationScheme = 'lzs';
}
if (typeof loginData.showAnimation == 'undefined') {
loginData.showAnimation = true;
}
if (typeof loginData.montageHideFooter == 'undefined') {
loginData.montageHideFooter = false;
}
if (typeof loginData.httpCordovaNoEncode == 'undefined') {
loginData.httpCordovaNoEncode = false;
}
if (typeof loginData.currentZMGroupNames == 'undefined') {
loginData.currentZMGroupNames = [];
}
if (typeof loginData.unsupported == 'undefined') {
loginData.unsupported = {};
}
if (typeof loginData.monitorSpecific == 'undefined') {
loginData.monitorSpecific = {};
}
loginData.canSwipeMonitors = true;
loginData.forceImageModePath = false;
loginData.enableBlog = true;
loginData.pauseStreams = true;
}
function regenConnKeys (mon) {
var nowt = moment();
if (mon) {
debug ("NVR: Regnerating connkey for Monitor:"+mon.Monitor.Id + " at "+nowt);
mon.Monitor.connKey = (Math.floor((Math.random() * 999999) + 1)).toString();
mon.Monitor.regenTime = nowt;
if (mon.Monitor.regenHandle) {
//debug ("cancelling regen timer for Monitor:"+mon.Monitor.Id);
$timeout.cancel(mon.Monitor.regenHandle);
mon.Monitor.regenHandle = null;
}
} else {
debug("NVR: Regenerating connkeys for all monitors at "+nowt);
for (var i = 0; i < monitors.length; i++) {
monitors[i].Monitor.connKey = (Math.floor((Math.random() * 999999) + 1)).toString();
monitors[i].Monitor.rndKey = (Math.floor((Math.random() * 999999) + 1)).toString();
monitors[i].Monitor.regenTime = nowt;
if (monitors[i].Monitor.regenHandle) {
$timeout.cancel(monitors[i].Monitor.regenHandle);
monitors[i].Monitor.regenHandle = null;
}
}
}
}
//--------------------------------------------------------------------------
// Banner display of messages
//--------------------------------------------------------------------------
function displayBanner(mytype, mytext, myinterval, mytimer) {
var contentBannerInstance =
$ionicContentBanner.show({
text: mytext || 'no text',
interval: myinterval || 2000,
//autoClose: mytimer || 6000,
type: mytype || 'info',
transition: 'vertical',
//cancelOnStateChange: false
});
$timeout(function () {
contentBannerInstance();
}, mytimer || 6000);
}
function setCurrentServerMultiPortSupported(val) {
debug("Setting multi-port to:" + val);
currentServerMultiPortSupported = val;
}
function setCurrentServerVersion(val) {
loginData.currentServerVersion = val;
setLogin(loginData);
debug("Setting server version to:" + val);
}
function encrypt(data) {
var jsdata = JSON.stringify(data);
var compress;
if (loginData.obfuscationScheme == 'lzs') {
compress = '--Z--'+LZString.compressToUTF16(jsdata);
}
else if (loginData.obfuscationScheme == 'aes') {
compress = CryptoJS.AES.encrypt(jsdata, zm.cipherKey).toString();
} else {
log ('ERROR: obfuscation scheme:'+loginData.obfuscationScheme+' not recognized');
return undefined;
}
debug ('obfuscate: original:'+jsdata.length+' obfuscated:'+compress.length+' scheme:'+loginData.obfuscationScheme);
return compress;
}
function decrypt(data) {
//debug ('-->deobfuscating '+data.length+' bytes using scheme:'+loginData.obfuscationScheme);
var decodedVal;
var scheme;
if (data.substr(0,5) == '--Z--') {
//debug ('unpacking');
scheme = 'lzs';
decodedVal = LZString.decompressFromUTF16(data.substr(5));
} else {
var bytes = CryptoJS.AES.decrypt(data.toString(), zm.cipherKey);
decodedVal = bytes.toString(CryptoJS.enc.Utf8);
scheme = 'aes';
}
//console.log ('-->decrypted ' + decodedVal);
debug ('deobfuscate: before:'+data.length+' after:'+decodedVal.length+' scheme:'+scheme);
var decodedJSON = JSON.parse(decodedVal);
return (decodedJSON);
}
return {
clear_unsupported: function () {
return clear_unsupported();
},
set_unsupported: function (data) {
return set_unsupported(data);
},
get_unsupported: function (data) {
return get_unsupported(data);
},
encrypt: function(data) {
return encrypt(data);
},
decrypt: function(data) {
return decrypt(data);
},
insertSpecialTokens: function () {
var tokens = '';
if (loginData.zmNinjaCustomId) {
var cid = loginData.zmNinjaCustomId.replace('%APPVER%', zmAppVersion);
tokens+='&id='+cid;
}
if (loginData.insertBasicAuthToken && $rootScope.basicAuthToken) {
tokens += "&basicauth=" + $rootScope.basicAuthToken;
}
return tokens;
},
setCurrentServerMultiPortSupported: function (val) {
setCurrentServerMultiPortSupported(val);
},
setCurrentServerVersion: function (val) {
setCurrentServerVersion(val);
},
getCurrentServerMultiPortSupported: function () {
return (currentServerMultiPortSupported);
},
isMultiPortDisabled: function () {
return loginData.disableSimulStreaming;
},
getCurrentServerVersion: function () {
return (loginData.currentServerVersion);
},
//-------------------------------------------------------------
// used by various controllers to log messages to file
//-------------------------------------------------------------
migrationComplete: function () {
migrationComplete = true;
},
isEmpty: function (obj) {
return isEmpty(obj);
},
log: function (val, type) {
var logtype = 'info';
if (type != undefined)
logtype = type;
log(val, logtype);
},
debug: function (val) {
debug(val);
},
evaluateTappedNotification: function () {
var state = "";
var stateParams1 = {};
var stateParams2 = {};
debug("Inside evaluateNotifications");
if ($rootScope.LoginData.isKiosk) {
NVR.log ('>>> evaluation: You are in kiosk mode, forcing transition to montage');
state = "app.montage";
$rootScope.tappedNotification = 0;
return [state, stateParams1, stateParams2];
}
if ($rootScope.tappedNotification == 2) { // url launch
debug("Came via app url launch with mid=" + $rootScope.tappedMid);
debug("Came via app url launch with eid=" + $rootScope.tappedEid);
if (parseInt($rootScope.tappedMid) > 0) {
debug("Going to live view ");
state = "app.monitors";
} else if (parseInt($rootScope.tappedEid) > 0) {
debug("Going to events with EID=" + $rootScope.tappedEid);
state = "app.events";
stateParams1 = {
"id": 0,
"playEvent": true
};
stateParams2 = {
reload: true
};
}
} // 2
else if ($rootScope.tappedNotification == 1) // push
{
debug("Came via push tap. onTapScreen=" + loginData.onTapScreen);
if (loginData.onTapScreen == $translate.instant('kTapMontage')) {
debug("Going to montage");
state = "app.montage";
} else if (loginData.onTapScreen == $translate.instant('kTapEvents')) {
debug("Going to events");
state = "app.events";
stateParams1 = {
"id": 0,
"playEvent": true
};
} else // we go to live
{
debug("Going to live view ");
state = "app.monitors";
}
}
$rootScope.tappedNotification = 0;
return [state, stateParams1, stateParams2];
},
setLastUpdateCheck: function (val) {
lastUpdateCheck = val;
localforage.setItem("lastUpdateCheck", lastUpdateCheck);
},
getLastUpdateCheck: function () {
return lastUpdateCheck;
},
setLatestBlogPostChecked: function (val) {
//console.log(">>>>>>>>>>>> Setting blog date: " + val);
latestBlogPostChecked = val;
localforage.setItem("latestBlogPostChecked", latestBlogPostChecked);
},
getLatestBlogPostChecked: function () {
return latestBlogPostChecked;
},
// This function is called when the app is ready to run
// sets up various variables
// including persistent login data for the ZM apis and portal
// The reason I need both is because as of today, there is no way
// to access images using the API and they are authenticated via
// the ZM portal authentication, which is pretty messy. But unless
// the ZM authors fix this and streamline the access of images
// from APIs, I don't have an option
// used when an empty server profile is created
getDefaultLoginObject: function () {
return angular.copy(defaultLoginData);
},
getReachableConfig: function (skipFirst) {
var d = $q.defer();
if (loginData.serverName == "") {
log("Reachable: No server name configured, likely first use?");
d.reject("No servers");
return d.promise;
}
var chainURLs = [];
var savedLoginData = angular.copy(loginData);
//log ("Making sure " + loginData.serverName + " is reachable...");
var tLd = serverGroupList[loginData.serverName];
if (skipFirst && tLd.fallbackConfiguration) {
tLd = serverGroupList[tLd.fallbackConfiguration];
if (!tLd) {
d.reject("No available severs");
loginData = savedLoginData;
return d.promise;
}
}
var keepBuilding = true;
while (keepBuilding == true && tLd) {
if (arrayObjectIndexOf(chainURLs, tLd.url + "/index.php?view=console", "url") == -1 && tLd.url !== undefined && tLd.url != '') // no loop
{
log("Adding to chain stack: " + tLd.serverName + ">" + tLd.url);
chainURLs.push({
url: tLd.url + "/index.php?view=console",
server: tLd.serverName
});
log("Fallback of " + tLd.serverName + " is " + tLd.fallbackConfiguration);
if (tLd.fallbackConfiguration) {
tLd = serverGroupList[tLd.fallbackConfiguration];
if (tLd === undefined) {
// This can happen if the fallback profile was deleted
log("Looks like a server object was deleted, but is still in fallback");
keepBuilding = false;
}
} else {
log("reached end of chain loop");
}
} else {
if (tLd.fallbackConfiguration) {
log("detected loop when " + tLd.serverName + " fallsback to " + tLd.fallbackConfiguration);
}
keepBuilding = false;
}
}
if (chainURLs.length == 1) {
log ('No need to do a reachability test, as there are no fallbacks');
d.resolve("done");
return d.promise;
}
console.log ('chainURLS:'+ chainURLs.length);
//contactedServers.push(loginData.serverName);
findFirstReachableUrl(chainURLs).then(function (firstReachableUrl) {
d.resolve(firstReachableUrl);
// also make sure loginData points to this now
loginData = angular.copy(serverGroupList[firstReachableUrl.server]);
setLogin(loginData);
//$localstorage.set("defaultServerName",firstReachableUrl.server);
log("Based on reachability, first serverName will be " + firstReachableUrl.server);
//console.log("set login Data to " + JSON.stringify(loginData));
return d.promise;
// OK: do something with firstReachableUrl
}, function () {
d.reject("No servers reachable");
loginData = savedLoginData;
return d.promise;
// KO: no url could be reached
});
function arrayObjectIndexOf(myArray, searchTerm, property) {
for (var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i][property] === searchTerm)
return i;
}
return -1;
}
function findFirstReachableUrl(urls) {
if (urls.length > 0 && $rootScope.userCancelledAuth != true) {
$ionicLoading.show({
template: "<a style='color:white; text-decoration:none' href='#' ng-click='$root.cancelAuth()' <i class='ion-close-circled'></i> " + $translate.instant('kTrying')+ ' ' + urls[0].server+"</a>",
noBackdrop: true,
});
log("Reachability test.." + urls[0].url);
if (loginData.reachability) {
//console.log ("************* AUGH");
var hDelay = loginData.enableSlowLoading ? zm.largeHttpTimeout : zm.httpTimeout;
return $http({
method: 'GET',
timeout: hDelay,
url: urls[0].url
}).then(function () {
log("Success: reachability on " + urls[0].url);
$ionicLoading.hide();
return urls[0];
}, function (err) {
log("Failed reachability on " + urls[0].url + " with error " + JSON.stringify(err));
return findFirstReachableUrl(urls.slice(1));
});
} else {
log("Reachability is disabled in config, faking this test and returning success on " + urls[0]);
return urls[0];
}
} else {
$ionicLoading.hide();
return $q.reject("No reachable URL");
}
}
return d.promise;
},
cloudSync: function () {
var d = $q.defer();
if (!window.cordova) {
log("Cloud settings plugin not found, skipping cloud sync...");
d.resolve(true);
return d.promise;
}
/* window.cordova.plugin.cloudsettings.enableDebug(function(){
console.log("Debug mode enabled");
});*/
log("CloudSync: Syncing with cloud if enabled...");
var sgl = "";
var decodedSgl = "";
var dsn = "";
localforage.getItem("serverGroupList")
.then(function (_sgl) {
sgl = _sgl;
return localforage.getItem("defaultServerName");
})
.then(function (_dsn) {
dsn = _dsn;
return true;
})
.then(function () {
if (sgl && dsn) {
if (typeof sgl == 'string') {
log("user profile encrypted, decoding...");
decodedSgl = decrypt(sgl);
} else {
decodedSgl = sgl;
}
var loadedData = decodedSgl[dsn];
if (!isEmpty(loadedData)) {
if (!loadedData.saveToCloud) {
log("Cloud sync is disabled, exiting...");
d.resolve(true);
return d.promise;
}
}
log("Found valid local configuration, overwriting cloud settings...");
//console.log (">>>>>>>>>>>>>>SAVING: " + sgl + dsn);
window.cordova.plugin.cloudsettings.save({
'serverGroupList': sgl,
'defaultServerName': dsn
},
function () {
log("local data synced with cloud...");
d.resolve(true);
return d.promise;
},
function (err) {
log("error syncing cloud data..." + err);
d.resolve(true);
return d.promise;
}, true);
}
// bad or missing local config
else {
log("Did not find a valid local configuration, trying cloud...");
window.cordova.plugin.cloudsettings.exists(function (exists) {
if (exists) {
log("A cloud configuration has been found");
window.cordova.plugin.cloudsettings.load(function (cloudData) {
//console.log("CLOUD DATA FOUND" + JSON.stringify(cloudData));
// debug("Cloud data retrieved is:" + JSON.stringify(cloudData));
if (cloudData && cloudData.defaultServerName && cloudData.serverGroupList) {
log("retrieved a valid cloud config with a defaultServerName of:" + cloudData.defaultServerName);
log("replacing local DB with cloud...");
localforage.setItem('isFirstUse', false)
.then(function () {
log("cleared first use");
return localforage.setItem("defaultServerName", cloudData.defaultServerName);
})
.then(function () {
log("saved defaultServerName");
return localforage.setItem("serverGroupList", cloudData.serverGroupList);
})
.then(function () {
log("saved serverGroupList, returning from cloudSync()");
d.resolve(true);
return d.promise;
});
}
// cloud did not have (useable)data
else {
log("Did not find a valid cloud config");
d.resolve(true);
return d.promise;
}
});
} else {
log("Cloud data does not exist");
d.resolve(true);
return d.promise;
}
});
}
});
return d.promise;
},
checkInitSanity: function (l) {
_checkInitSanity(l);
},
init: function () {
log("ZMData init: checking for stored variables & setting up log file");
localforage.getItem("latestBlogPostChecked")
.then(function (val) {
latestBlogPostChecked = val;
},
function (err) {
latestBlogPostChecked = null;
});
$ionicLoading.show({
template: $translate.instant('kRetrievingProfileData'),
});
localforage.getItem("serverGroupList").then(function (val) {
// decrypt it now
var decodedVal;
if (typeof val == 'string') {
log("user profile encrypted, decoding...");
decodedVal = decrypt(val);
} else {
log("user profile not encrypted");
decodedVal = val;
}
//decodedVal = val;
// debug("user profile retrieved:" + JSON.stringify(decodedVal));
$ionicLoading.hide();
serverGroupList = decodedVal;
var sname;
$ionicLoading.show({
template: $translate.instant('kRetrievingProfileData'),
});
localforage.getItem("defaultServerName")
.then(function (val) {
$ionicLoading.hide();
//console.log ("!!!!!!!!!!!!!!!!!!default server name is " + sname);
sname = val;
// console.log("!!!!!!!!!!!!!!!!!!!Got VAL " + sname);
var loadedData = serverGroupList[sname];
// console.log(">>>>>>>>>>> loadedData is: " + JSON.stringify(loadedData));
if (!isEmpty(loadedData)) {
loginData = loadedData;
_checkInitSanity(loginData);
log("NVR init retrieved store loginData, marking init as complete");
$rootScope.initComplete = true;
} else {
log("defaultServer configuration NOT found. Keeping login at defaults. Marking init as complete.");
}
// from local forage
if (window.cordova) setCordovaHttpOptions();
$rootScope.LoginData = loginData;
$rootScope.$broadcast('init-complete');
});
monitorsLoaded = 0;
//console.log("Getting out of NVR init");
$rootScope.showBlog = loginData.enableBlog;
//debug("loginData structure values: " + JSON.stringify(loginData));
});
},
isForceNetworkStop: function () {
return loginData.forceNetworkStop;
},
setJustResumed: function (val) {
justResumed = val;
if (val) {
timeSinceResumed = moment();
}
},
getTimeSinceResumed: function () {
// will be -1 if never resumed
return timeSinceResumed;
},
stopNetwork: function (str, dontDoIt) {
var d = $q.defer();
var s = "";
if (str) s = str + ":";
if (justResumed || dontDoIt) {
// we don't call stop as we did stop on pause
log(s + " Not calling window stop ");
d.resolve(true);
return (d.promise);
} else {
log(s + " stopNework: Calling window.stop()");
$timeout(function () {
window.stop();
d.resolve(true);
return (d.promise);
});
}
return d.promise;
},
hasLoginInfo: function () {
if ((loginData.username != "" && loginData.password != "" && loginData.url != "" &&
loginData.apiurl != "") || (loginData.isUseAuth != '1')) {
return 1;
} else {
return 0;
}
},
getLanguages: function () {
return languages;
},
setDefaultLanguage: function (l, permanent) {
if (!l) l = 'en';
defaultLang = l;
var d = $q.defer();
if (permanent) {
//window.localStorage.setItem("defaultLang", l);
//console.log("setting default lang");
localforage.setItem("defaultLang", l)
.then(function (val) {
log("Set language in localforage to: " + val);
});
}
//console.log("invoking translate use with " + l);
$translate.use(l).then(function (data) {
log("Device Language is:" + data);
moment.locale(data);
$translate.fallbackLanguage('en');
d.resolve(data);
return d.promise;
}, function (error) {
log("Device Language error: " + error);
$translate.use('en');
moment.locale('en');
d.resolve('en');
return d.promise;
});
return d.promise;
},
getDefaultLanguage: function () {
return defaultLang;
//return window.localStorage.getItem("defaultLang");
},
reloadMonitorDisplayStatus: function () {
return reloadMonitorDisplayStatus();
},
getLogin: function () {
return angular.copy(loginData);
},
getServerGroups: function () {
return angular.copy(serverGroupList);
},
setServerGroups: function (sg) {
serverGroupList = angular.copy(sg);
},
getKeepAwake: function () {
return (loginData.keepAwake == '1') ? true : false;
},
setAppVersion: function (ver) {
zmAppVersion = ver;
$rootScope.appVersion = ver; // for custom header
//console.log ('****** VER:'+$rootScope.appVersion);
},
getCustomHeader: function () {
return loginData.zmNinjaCustomId;
},
getAppVersion: function () {
return (zmAppVersion);
},
setBackground: function (val) {
isBackground = val;
},
isBackground: function () {
return isBackground;
},
isFirstUse: function () {
// console.log("isFirstUse is " + isFirstUse);
return isFirstUse;
// return ((window.localStorage.getItem("isFirstUse") == undefined) ? true : false);
},
updateHrsSinceChecked: function (key) {
var tnow = moment();
debug("Updating " + key + " to " + JSON.stringify(tnow));
localforage.setItem(key, JSON.stringify(tnow));
},
hrsSinceChecked: function (key) {
var tnow = moment();
var d = $q.defer();
localforage.getItem(key)
.then(function (val) {
if (val == null) {
// doesn't exist
localforage.setItem(key, JSON.stringify(tnow));
debug(key + " doesn't exist, storing it as:" + tnow);
d.resolve(365 * 12 * 24);
return (d.promise);
} else {
val = JSON.parse(val);
var duration = moment.duration(tnow.diff(val)).asHours().toFixed(1);
debug("It has been " + duration + " hours since " + key + " was checked");
d.resolve(duration);
return (d.promise);
}
return (d.promise);
},
function (err) {
debug("Hmm? hrsSinceCheck failed");
d.resolve(365 * 12 * 24);
return d.promise;
}
);
return d.promise;
},
versionCompare: function (l, r) {
return versionCompare(l, r);
},
//-----------------------------------------------------------------
// Allow the option to reset first use if I need it in future
//-----------------------------------------------------------------
setFirstUse: function (val) {
//window.localStorage.setItem("isFirstUse", val ? "1" : "0");
//localforage.setItem("isFirstUse", val,
// function(err) {if (err) log ("localforage error, //storing isFirstUse: " + JSON.stringify(err));});
isFirstUse = val;
debug("Setting isFirstUse to:" + val);
localforage.setItem("isFirstUse", val)
.then(function (succ) {
debug("Saved isFirstUse ok");
})
.catch(function (err) {
debug("Error Saving isFirstUse:" + JSON.stringify(err));
});
//console.log (">>>>>>setting isFirstUse to " + val);
},
getTimeFormat: function () {
return (loginData.use24hr ? "HH:mm" : "hh:mm a");
},
getTimeFormatSec: function () {
return (loginData.use24hr ? "HH:mm:ss" : "hh:mm:ss a");
},
//------------------------------------------------------------------
// switches screen to 'always on' or 'auto'
//------------------------------------------------------------------
setAwake: function (val) {
//console.log ("**** setAwake called with:" + val);
// log("Switching screen always on to " + val);
if (val) {
if (window.cordova != undefined) {
window.plugins.insomnia.keepAwake();
} else {
//console.log ("Skipping insomnia, cordova does not exist");
}
} else {
if (window.cordova != undefined) {
window.plugins.insomnia.allowSleepAgain();
} else {
//console.log ("Skipping insomnia, cordova does not exist");
}
}
},
//--------------------------------------------------------------------------
// writes all params to local storage. FIXME: Move all of this into a JSON
// object
//--------------------------------------------------------------------------
setLogin: function (newLogin) {
$rootScope.showBlog = newLogin.enableBlog;
return setLogin(newLogin);
},
//-------------------------------------------------------
// returns API version or none
//-------------------------------------------------------
getAPIversion: function () {
var d = $q.defer();
var apiurl = loginData.apiurl + '/host/getVersion.json?' + $rootScope.authSession;
debug("getAPIversion called with " + apiurl);
cache_or_http(apiurl,'cached_api_version',false, 3600*24)
.then(function (success) {
if (success.data.version) {
//console.log("API VERSION RETURNED: " + JSON.stringify(success));
$rootScope.apiValid = true;
if (versionCompare(success.data.version, '1.32.0') != -1) {
debug("snapshot supported in image.php");
snapshotFrame = 'snapshot';
} else {
debug("snapshot NOT supported in image.php");
snapshotFrame = 1;
}
setCurrentServerVersion(success.data.version);
debug("getAPI version succeeded with " + success.data.version);
d.resolve(success.data.version);
}
return (d.promise);
},
function (error) {
debug("getAPIversion error handler " + JSON.stringify(error));
d.reject("-1.-1.-1");
setCurrentServerVersion("");
$rootScope.apiValid = false;
return (d.promise);
});
return (d.promise);
},
displayBanner: function (mytype, mytext, myinterval, mytimer) {
displayBanner(mytype, mytext, myinterval, mytimer);
},
isReCaptcha: function () {
// always resolves
var d = $q.defer();
if (loginData.isTokenSupported) {
debug ('No need for re-captcha checks with tokens');
d.resolve(false);
return (d.promise);
}
var myurl = loginData.url;
log("Checking if reCaptcha is enabled in ZM...");
// console.log ("Recaptcha: "+myurl);
$http.get(myurl)
.then(function (success) {
// console.log ("Inside recaptcha success");
if (success.data.search("g-recaptcha") != -1) {
// recaptcha enable. zmNinja won't work
log("ZM has recaptcha enabled", "error");
displayBanner('error', ['Recaptcha must be disabled in Zoneminder', $rootScope.appName + ' will not work with recaptcha'], "", 8000);
d.resolve(true);
return (d.promise);
} else {
d.resolve(false);
log("ZM has recaptcha disabled - good");
return (d.promise);
}
},
function (err) {
// for whatever reason recaptcha check failed
// console.log ("Inside recaptcha fail");
d.resolve(false);
log("Recaptcha failed, but assuming ZM has recaptcha disabled");
return (d.promise);
});
return (d.promise);
},
//-----------------------------------------------------------------------------
// Grabs the computed auth key for streaming
// FIXME: Currently a hack - does a screen parse - convert to API based support
//-----------------------------------------------------------------------------
// need a mid as restricted users won't be able to get
// auth with just &watch
getAuthKey: function (mid, ck) {
return getAuthKey(mid, ck);
},
//-----------------------------------------------------------------------------
// This function tells is if this ZM version has ZMS multiport support
//-----------------------------------------------------------------------------
clearZmsMultiPortSupport: function () {
debug("Clearing Multiport...");
configParams.ZM_MIN_STREAMING_PORT = -1;
},
getZmsMultiPortSupport: function () {
// 0 => not supported
// >=1 => supported
// -1 => haven't checked - should never be returned
return getZmsMultiPortSupport();
},
getZMGroups: function () {
return getZMGroups();
},
//-----------------------------------------------------------------------------
// This function returns the numdigits for padding capture images
//-----------------------------------------------------------------------------
getAuthHashLogin: function () {
return $http.get(loginData.apiurl + '/configs/viewByName/ZM_AUTH_HASH_LOGINS.json?' + $rootScope.authSession);
},
getKeyConfigParams: function (forceReload) {
var d = $q.defer();
configParams.ZM_EVENT_IMAGE_DIGITS = 5;
d.resolve(configParams.ZM_EVENT_IMAGE_DIGITS);
return (d.promise);
/*
if (forceReload == 1 || configParams.ZM_EVENT_IMAGE_DIGITS == '-1') {
var apiurl = loginData.apiurl;
var myurl = apiurl + '/configs/viewByName/ZM_EVENT_IMAGE_DIGITS.json?' + $rootScope.authSession;
//debug("Config URL for digits is:" + myurl);
$http.get(myurl)
.then(function (data) {
data = data.data;
log("ZM_EVENT_IMAGE_DIGITS is " + data.config.Value);
configParams.ZM_EVENT_IMAGE_DIGITS = data.config.Value;
d.resolve(configParams.ZM_EVENT_IMAGE_DIGITS);
return (d.promise);
}, function (err) {
log("Error retrieving ZM_EVENT_IMAGE_DIGITS" + JSON.stringify(err), "error");
log("Taking a guess, setting ZM_EVENT_IMAGE_DIGITS to 5");
// FIXME: take a plunge and keep it at 5?
configParams.ZM_EVENT_IMAGE_DIGITS = 5;
d.resolve(configParams.ZM_EVENT_IMAGE_DIGITS);
return (d.promise);
});
} else {
// log("ZM_EVENT_IMAGE_DIGITS is already configured for " +
// configParams.ZM_EVENT_IMAGE_DIGITS);
d.resolve(configParams.ZM_EVENT_IMAGE_DIGITS);
return (d.promise);
}
return (d.promise);
*/
},
//--------------------------------------------------------------------------
// Useful to know what ZMS is using as its cgi-bin. If people misconfigure
// the setting in the app, they can check their logs
//--------------------------------------------------------------------------
getPathZms: function () {
var d = $q.defer();
var apiurl = loginData.apiurl;
var myurl = apiurl + '/configs/viewByName/ZM_PATH_ZMS.json?' + $rootScope.authSession;
debug("Config URL for ZMS PATH is:" + myurl);
$http.get(myurl)
.then(function (data) {
data = data.data;
//console.log (">>>> GOT: "+JSON.stringify(data));
configParams.ZM_PATH_ZMS = data.config.Value;
d.resolve(configParams.ZM_PATH_ZMS);
return (d.promise);
},
function (error) {
log("Can't retrieving ZM_PATH_ZMS: " + JSON.stringify(error));
d.resolve("");
return (d.promise);
});
return (d.promise);
},
//--------------------------------------------------------------------------
// returns high or low BW mode
//--------------------------------------------------------------------------
getBandwidth: function () {
return getBandwidth();
},
getSnapshotFrame: function () {
return snapshotFrame;
},
//-----------------------------------------------------------------------------
// This function returns a list of monitors
// if forceReload == 1 then it will force an HTTP API request to get a list of monitors
// if 0. then it will return back the previously loaded monitor list if one exists, else
// will issue a new HTTP API to get it
// I've wrapped this function in my own promise even though http returns a promise.
//-----------------------------------------------------------------------------
//
// returns a non promise version
// so if monitors is null, it will return null
// As of now, this is only used by EventServer.js to
// send the right list of monitors after registration
// token
getMonitorsNow: function () {
debug ('getMonitorsNow: returning '+monitors.length+' monitors');
return monitors;
},
listOfZMGroups: function () {
return zmgroups;
},
pauseLiveStream: function (ck, url, name) {
if (!url) url = loginData.url;
var myauthtoken = $rootScope.authSession.replace("&auth=", "");
var req = url + '/index.php';
req = req + "?view=request&request=stream";
req = req + "&connkey=" + ck;
req = req + "&auth=" + myauthtoken;
// req = req + "&command=17";
debug("NVR: Pausing live stream ck:" + ck + " for " + name + " url:" + url);
return $http.get(req + "&command=1")
.then(
function (s) {
// debug("pause success for ck:" + ck );
},
function (e) {
// debug("pause error for ck:" + ck + " with:" + JSON.stringify(e));
}
);
},
resumeLiveStream: function (ck, url, name) {
if (!url) url = loginData.url;
var myauthtoken = $rootScope.authSession.replace("&auth=", "");
var req = url + '/index.php';
req = req + "?view=request&request=stream";
req = req + "&connkey=" + ck;
req = req + "&auth=" + myauthtoken;
// req = req + "&command=17";
debug("NVR: Resuming live stream ck:" + ck + " for " + name);
return $http.get(req + "&command=2")
.then(
function (s) {
// debug("play success for ck:" + ck + " with:" + JSON.stringify(s));
},
function (e) {
// debug("play error for ck:" + ck + " with:" + JSON.stringify(e));
}
);
},
killLiveStream: function (ck, url, name) {
if (!url) url = loginData.url;
var myauthtoken = $rootScope.authSession.replace("&auth=", "");
var req = url + '/index.php';
req = req + "?view=request&request=stream";
req = req + "&connkey=" + ck;
req = req + "&auth=" + myauthtoken;
// req = req + "&command=17";
if (name == undefined) name = "";
debug("NVR: killing " + name + " live stream ck:" + ck);
return $http.get(req + "&command=17")
.then(
function (s) {
// debug ("kill success for ck:"+ck+" with:"+JSON.stringify(s));
},
function (e) { //debug ("kill success for ck:"+ck+" with:"+JSON.stringify(e));
}
);
},
regenConnKeys: function (mon) {
return regenConnKeys (mon);
},
getMonitors: function (forceReload) {
//console.log("** Inside ZMData getMonitors with forceReload=" + forceReload);
$ionicLoading.show({
template: $translate.instant('kLoadingMonitors'),
animation: 'fade-in',
showBackdrop: false,
duration: zm.loadingTimeout,
maxWidth: 200,
showDelay: 0
});
var d = $q.defer();
if ((monitorsLoaded == 0) || (forceReload == 1)) // monitors are empty or force reload
{
//console.log("NVR: Invoking HTTP get to load monitors");
log((forceReload == 1) ? "getMonitors:Force reloading all monitors" : "getMonitors:Loading all monitors");
var apiurl = loginData.apiurl;
var myurl = apiurl + "/monitors";
myurl += "/index/"+"Type !=:WebSite.json" + "?"+$rootScope.authSession;
getZmsMultiPortSupport()
.then(function (zmsPort) {
var controlURL = "";
debug("ZMS Multiport reported: " + zmsPort);
debug("Monitor URL to fetch is:" + myurl);
cache_or_http(myurl,'cached_monitors', true,3600*24)
//$http.get(myurl /*,{timeout:15000}*/ )
.then(function (data) {
// console.log("HTTP success got " + JSON.stringify(data.monitors));
data = data.data;
if (data.monitors) monitors = data.monitors;
// Now let's make sure we remove repeating monitors
// may happen in groups case
debug ("Before duplicate processing, we have: "+monitors.length+" monitors");
//console.log (JSON.stringify(monitors));
var monitorHash = {};
for (var mo in monitors) {
monitorHash[monitors[mo].Monitor.Id] = monitors[mo];
}
monitors = [];
for (mo in monitorHash) {
monitors.push(monitorHash[mo]);
}
debug ("After duplicate processing, we have: "+monitors.length+" monitors");
//console.log (JSON.stringify(monitors));
if ($rootScope.authSession == '') {
log("Now that we have monitors, lets get AuthKey...");
getAuthKey(monitors[0].Monitor.Id, (Math.floor((Math.random() * 999999) + 1)).toString());
}
monitors.sort(function (a, b) {
return parseInt(a.Monitor.Sequence) - parseInt(b.Monitor.Sequence);
});
//console.log("promise resolved inside HTTP success");
monitorsLoaded = 1;
reloadMonitorDisplayStatus();
debug("Inside getMonitors, will also regen connkeys");
debug("Now trying to get multi-server data, if present");
cache_or_http(apiurl + "/servers.json?" + $rootScope.authSession, 'cached_multi_servers', true, 3600*24)
.then(function (data) {
data = data.data;
// We found a server list API, so lets make sure
// we get the hostname as it will be needed for playback
log("multi server list loaded");
multiservers = data.servers;
var multiserver_scheme = "http://";
//console.log ("PORTAL URL IS:"+loginData.url);
if (loginData.url && (loginData.url.toLowerCase().indexOf("https://") != -1)) {
debug("Portal scheme is https, will use https for any multi-server without a protocol");
multiserver_scheme = "https://";
}
debug("default multi-server protocol will be:" + multiserver_scheme);
for (var i = 0; i < monitors.length; i++) {
// zm 1.33.15 prefixes 'ROTATE_' to orientation
monitors[i].Monitor.Orientation = monitors[i].Monitor.Orientation.replace('ROTATE_','');
var recordingType = '';
if (monitors[i].Monitor.SaveJPEGs > 0) {
recordingType = $translate.instant('kImages');
}
if (monitors[i].Monitor.VideoWriter > 0) {
if (recordingType.length) recordingType += " + ";
recordingType = recordingType + $translate.instant('kVideo') + " (";
recordingType = recordingType + (monitors[i].Monitor.VideoWriter == 1 ? $translate.instant('kMonitorVideoEncode') : $translate.instant('kMonitorVideoPassThru')) + ")";
}
// in 1.30.4 these fields did not exist
monitors[i].Monitor.recordingType = recordingType ? recordingType : $translate.instant('kImages');
monitors[i].Monitor.listDisplay = 'show';
monitors[i].Monitor.isAlarmed = false;
monitors[i].Monitor.connKey = (Math.floor((Math.random() * 999999) + 1)).toString();
monitors[i].Monitor.rndKey = (Math.floor((Math.random() * 999999) + 1)).toString();
var serverFound = false;
for (var j = 0; j < multiservers.length; j++) {
//console.log ("Comparing " + multiservers[j].Server.Id + " AND " + monitors[i].Monitor.ServerId);
if (multiservers[j].Server.Id == monitors[i].Monitor.ServerId) {
//console.log ("Found match");
serverFound = true;
break;
}
}
if (serverFound) {
// we found a monitor using a multi-server
if (!/^https?:\/\//i.test(multiservers[j].Server.Hostname)) {
if (multiservers[j].Server.Protocol) {
multiservers[j].Server.Hostname = multiservers[j].Server.Protocol +
"://" + multiservers[j].Server.Hostname;
} else {
multiservers[j].Server.Hostname = multiserver_scheme + multiservers[j].Server.Hostname;
}
}
// debug("Monitor " + monitors[i].Monitor.Id + " has a recording server hostname of " + multiservers[j].Server.Hostname);
// Now here is the logic, I need to retrieve serverhostname,
// and slap on the host protocol and path. Meh.
var s = URI.parse(loginData.streamingurl);
var m = URI.parse(multiservers[j].Server.Hostname);
var p = URI.parse(loginData.url);
debug("recording server reported is " + JSON.stringify(m));
//debug("portal parsed is " + JSON.stringify(p));
//debug("streaming url parsed is " + JSON.stringify(s));
debug("multi-port is:" + zmsPort);
var st = "";
var baseurl = "";
var streamingurl = "";
st += (m.scheme ? m.scheme : p.scheme) + "://"; // server scheme overrides
// if server doesn't have a protocol, what we want is in path
if (!m.host) {
m.host = m.path;
m.path = undefined;
}
st += m.host;
//console.log ("STEP 1: ST="+st);
// now lets do port magic
if (multiservers[j].Server.Port) {
debug("Found port inside multiserver: " + multiservers[j].Server.Id + ", using: " + multiservers[j].Server.Port);
st += ":" + multiservers[j].Server.Port;
} else {
debug("No port in serverId:" + multiservers[j].Server.Id);
if (zmsPort <= 0 || loginData.disableSimulStreaming) {
// no multiport so take from portal or multiserver if there
if (p.port || m.port) {
st += (m.port ? ":" + m.port : ":" + p.port);
streamingurl = st;
//console.log ("STEP 2 no ZMS: ST="+st);
}
} else {
// we have multiserver
var sport = parseInt(zmsPort) + parseInt(monitors[i].Monitor.Id);
st = st + ':' + sport;
}
}
baseurl = st;
controlURL = st;
controlURL += (p.path ? p.path : '');
st += (s.path ? s.path : p.path);
streamingurl += (s.path ? s.path : p.path);
//console.log ("STEP 3: ST="+st);
//console.log ("----------STREAMING URL PARSED AS " + st);
monitors[i].Monitor.streamingURL = st;
monitors[i].Monitor.baseURL = baseurl;
monitors[i].Monitor.controlURL = controlURL;
monitors[i].Monitor.recordingURL = controlURL;
debug("Storing baseurl=" + baseurl + " streamingURL=" + st + " recordingURL=" + controlURL);
//console.log ("** Streaming="+st+" **base="+baseurl);
// starting 1.30 we have fid=xxx mode to return images
monitors[i].Monitor.imageMode = (versionCompare($rootScope.apiVersion, "1.30") == -1) ? "path" : "fid";
// debug("API " + $rootScope.apiVersion + ": Monitor " + monitors[i].Monitor.Id + " will use " + monitors[i].Monitor.imageMode + " for direct image access");
//debug ("Streaming URL for Monitor " + monitors[i].Monitor.Id + " is " + monitors[i].Monitor.streamingURL );
//debug ("Base URL for Monitor " + monitors[i].Monitor.Id + " is " + monitors[i].Monitor.baseURL );
} else {
// Non multiserver case
//monitors[i].Monitor.listDisplay = 'show';
debug("No servers matched, filling defaults...");
monitors[i].Monitor.isAlarmed = false;
monitors[i].Monitor.connKey = (Math.floor((Math.random() * 999999) + 1)).toString();
monitors[i].Monitor.rndKey = (Math.floor((Math.random() * 999999) + 1)).toString();
var st2 = loginData.streamingurl;
controlURL = loginData.url;
if (zmsPort > 0 && !loginData.disableSimulStreaming) {
// we need to insert minport
st2 = "";
var p2 = URI.parse(loginData.streamingurl);
var p3 = URI.parse(loginData.url);
st2 += p2.scheme + "://";
if (!p2.host) {
p2.host = p2.path;
p2.path = undefined;
}
st2 += p2.host;
var sport2 = parseInt(zmsPort) + parseInt(monitors[i].Monitor.Id);
st2 = st2 + ':' + sport2;
controlURL = st2;
if (p2.path) st2 += p2.path;
if (p3.path) controlURL += p3.path;
}
debug("Storing streaming=" + st2 + " recording=" + controlURL);
monitors[i].Monitor.streamingURL = st2;
monitors[i].Monitor.controlURL = controlURL;
monitors[i].Monitor.recordingURL = controlURL;
//debug ("Streaming URL for Monitor " + monitors[i].Monitor.Id + " is " + monitors[i].Monitor.streamingURL );
//console.log ("NO SERVER MATCH CONSTRUCTED STREAMING PATH="+st2);
monitors[i].Monitor.baseURL = loginData.url;
monitors[i].Monitor.imageMode = (versionCompare($rootScope.apiVersion, "1.30") == -1) ? "path" : "fid";
} // non multiserver end
}
// now get packery hide if applicable
reloadMonitorDisplayStatus();
getZMGroups().then ( function (succ) {
d.resolve(monitors);
return d.promise;
});
return d.promise;
},
function (err) {
log("multi server list loading error");
multiservers = [];
for (var i = 0; i < monitors.length; i++) {
//monitors[i].Monitor.listDisplay = 'show';
// zm 1.33.15 prefixes 'ROTATE_' to orientation
monitors[i].Monitor.Orientation = monitors[i].Monitor.Orientation.replace('ROTATE_','');
monitors[i].Monitor.isAlarmed = false;
monitors[i].Monitor.connKey = (Math.floor((Math.random() * 999999) + 1)).toString();
monitors[i].Monitor.rndKey = (Math.floor((Math.random() * 999999) + 1)).toString();
var st = loginData.streamingurl;
if (zmsPort > 0) {
// we need to insert minport
st = "";
var p = URI.parse(loginData.streamingurl);
st += p.scheme + "://";
if (!p.host) {
p.host = p.path;
p.path = undefined;
}
st += p.host;
var sport = parseInt(zmsPort) + parseInt(monitors[i].Monitor.Id);
st = st + ':' + sport;
if (p.path) st += p.path;
}
monitors[i].Monitor.streamingURL = st;
// console.log ("CONSTRUCTED STREAMING PATH="+st);
monitors[i].Monitor.baseURL = loginData.url;
monitors[i].Monitor.imageMode = (versionCompare($rootScope.apiVersion, "1.30") == -1) ? "path" : "fid";
//debug("API " + $rootScope.apiVersion + ": Monitor " + monitors[i].Monitor.Id + " will use " + monitors[i].Monitor.imageMode + " for direct image access");
}
getZMGroups().then ( function (succ) {
d.resolve(monitors);
return d.promise;
});
return d.promise;
});
$ionicLoading.hide();
log("Monitor load was successful, loaded " + monitors.length + " monitors");
},
function (err) {
//console.log("HTTP Error " + err);
log("Monitor load failed " + JSON.stringify(err), "error");
// To keep it simple for now, I'm translating an error
// to imply no monitors could be loaded. FIXME: conver to proper error
monitors = [];
//console.log("promise resolved inside HTTP fail");
displayBanner('error', ['error retrieving monitor list', 'please try again']);
d.resolve(monitors);
$ionicLoading.hide();
monitorsLoaded = 0;
return d.promise;
});
});
return d.promise;
} else // monitors are loaded
{
//console.log("Returning pre-loaded list of " + monitors.length + " monitors");
log("Returning pre-loaded list of " + monitors.length + " monitors");
d.resolve(monitors);
//console.log ("Returning"+JSON.stringify(monitors));
$ionicLoading.hide();
return d.promise;
}
},
proceedWithLogin: function (obj) {
var noBroadcast = false;
var tryAccess = true;
var tryRefresh = true;
if (obj) {
noBroadcast = obj.nobroadcast;
tryAccess = obj.access;
tryRefresh = obj.refresh;
}
var d = $q.defer();
// This is a good time to check if auth is used :-p
if (!loginData.isUseAuth) {
log("Auth is disabled, setting authSession to empty");
$rootScope.apiValid = true;
$rootScope.authSession = '';
d.resolve("Login Success");
if (!noBroadcast) $rootScope.$broadcast('auth-success', 'no auth');
return (d.promise);
}
// lets first try tokens and stored tokens
if (loginData.isTokenSupported)
{
log ("Detected token login supported");
var now = moment.utc();
var diff_access = moment.utc(loginData.accessTokenExpires).diff(now, 'minutes');
var diff_refresh = moment.utc(loginData.refreshTokenExpires).diff(now, 'minutes');
// first see if we can work with access token
if (moment.utc(loginData.accessTokenExpires).isAfter(now) && diff_access >=zm.accessTokenLeewayMin && tryAccess) {
log ("Access token still has "+diff_access+" minutes left, using it");
log ('----> Setting token re-login after '+diff_access*60+' seconds');
if (tokenExpiryTimer) $timeout.cancel(tokenExpiryTimer);
tokenExpiryTimer = $timeout ( function () {
$rootScope.$broadcast('token-expiry');
}, diff_access * 60 * 1000);
$rootScope.authSession = '&token='+loginData.accessToken;
d.resolve("Login success via access token");
// console.log ("**************** TOKEN SET="+$rootScope.authSession);
if (!noBroadcast) $rootScope.$broadcast('auth-success', '' );
return d.promise;
}
// then see if we have at least 30 mins left for refresh token
else if (moment.utc(loginData.refreshTokenExpires).isAfter(now) && diff_refresh >=zm.refreshTokenLeewayMin && tryRefresh) {
log ("Refresh token still has "+diff_refresh+" minutes left, using it");
var loginAPI = loginData.apiurl + '/host/login.json?token='+loginData.refreshToken;
$http({
method:'GET',
url: loginAPI,
skipIntercept:true,
})
.then (function (succ) {
succ = succ.data;
if (succ.access_token) {
// console.log ("**************** TOKEN SET="+succ.access_token);
$rootScope.authSession = '&token='+succ.access_token;
log ("New access token retrieved: ..."+succ.access_token.substr(-5));
loginData.accessToken = succ.access_token;
loginData.accessTokenExpires = moment.utc().add(succ.access_token_expires,'seconds');
//succ.access_token_expires = 30;
$rootScope.tokenExpires = succ.access_token_expires;
log ('----> Setting token re-login after '+succ.access_token_expires+' seconds');
if (tokenExpiryTimer) $timeout.cancel(tokenExpiryTimer);
tokenExpiryTimer = $timeout ( function () {
$rootScope.$broadcast('token-expiry');
}, succ.access_token_expires * 1000);
log ("Current time is: UTC "+moment.utc().format("YYYY-MM-DD hh:mm:ss"));
log ("New access token expires on: UTC "+loginData.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
log ("New access token expires on:"+loginData.accessTokenExpires.format("YYYY-MM-DD hh:mm:ss"));
loginData.isTokenSupported = true;
setLogin(loginData);
d.resolve("Login success via refresh token");
if (!noBroadcast) $rootScope.$broadcast('auth-success', '' );
return d.promise;
}
else {
log ('ERROR:Trying to refresh with refresh token:'+JSON.stringify(succ));
return proceedWithFreshLogin(noBroadcast)
.then (function (succ) {
d.resolve(succ);
return (d.promise);
},
function(err) {
d.resolve(err);
return (d.promise);
});
}
},
function (err) {
log ('access token login HTTP failed with: '+JSON.stringify(err));
return proceedWithFreshLogin(noBroadcast)
.then (function (succ) {
d.resolve(succ);
return (d.promise);
},
function(err) {
d.resolve(err);
return (d.promise);});
});
} // valid refresh
else {
log ('both access and refresh tokens are expired, using a fresh login');
return proceedWithFreshLogin(noBroadcast)
.then (function (succ) {
d.resolve(succ);
return (d.promise);
},
function(err) {
d.resolve(err);
return (d.promise);
});
}
} // is token supported
else {
log ("Token login not being used");
// coming here means token reloads fell through
return proceedWithFreshLogin(noBroadcast)
.then (function (succ) {
d.resolve(succ);
return (d.promise);
},
function(err) {
d.resolve(err);
return (d.promise);
});
}
return (d.promise);
},
zmPrivacyProcessed: function () {
var apiurl = loginData.apiurl;
var myurl = apiurl + '/configs/viewByName/ZM_SHOW_PRIVACY.json?' + $rootScope.authSession;
var d = $q.defer();
$http({
url: myurl,
method: 'GET',
transformResponse: undefined,
responseType: 'text',
})
// $http.get(myurl)
.then(function (textsucc) {
var succ;
try {
//console.log(textsucc);
succ = JSON.parse(textsucc.data);
if (succ.data) succ = succ.data;
if (succ.config) {
if (succ.config.Value == '1') {
debug("Real value of PRIVACY is:" + succ.config.Value);
d.resolve(false);
} else {
debug("Real value of PRIVACY is:" + succ.config.Value);
d.resolve(true);
}
return d.promise;
} else {
debug("ZM_SHOW_PRIVACY likely does not exist");
d.resolve(true);
return d.promise;
}
} catch (e) {
debug("ZM_SHOW_PRIVACY parsing error, assuming it doesn't exist");
d.resolve(true);
return d.promise;
}
},
function (err) {
debug("ZM_SHOW_PRIVACY returned an error, it likely doesn't exist");
d.resolve(true);
return d.promise;
});
return d.promise;
},
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
setMonitors: function (mon) {
//console.log("ZMData setMonitors called with " + mon.length + " monitors");
monitors = mon;
},
processFastLogin: function () {
var d = $q.defer();
if (1) {
d.reject("not implemented");
return d.promise;
}
// console.log("inside processFastLogin");
if (!loginData.fastLogin) {
//console.log("Fast login not set");
d.reject("fast login not enabled");
debug("fast login not enabled");
return d.promise;
} else //fastlogin is on
{
localforage.getItem("lastLogin")
.then(function (succ) {
//console.log("fast login DB found");
var dt = moment(succ);
if (dt.isValid()) {
debug("Got last login as " + dt.toString());
if (moment.duration(moment().diff(dt)).asHours() >= 2) {
d.reject("duration since last login >=2hrs, need to relogin");
return d.promise;
} else {
d.resolve("fast login is valid, less then 2 hrs");
return d.promise;
}
} else {
//console.log("Invalid date found");
d.reject("last-login invalid");
return d.promise;
}
},
function (e) {
//console.log("fastlogin DB not found");
d.reject("last-login not found, fastlogin rejected");
return d.promise;
});
}
return d.promise;
},
// returns if this mid is hidden or not
isNotHidden: function (mid) {
var notHidden = true;
for (var i = 0; i < monitors.length; i++) {
if (monitors[i].Monitor.Id == mid) {
notHidden = (monitors[i].Monitor.listDisplay == 'show') ? true : false;
break;
}
}
return notHidden;
},
getLocalTimeZoneNow: function () {
return moment.tz.guess();
},
//returns TZ value immediately (sync)
getTimeZoneNow: function () {
// console.log ("getTimeZoneNow: " + tz ? tz : moment.tz.guess());
return tz ? tz : moment.tz.guess();
},
// returns server timezone, failing which local timezone
// always resolves true
isTzSupported: function () {
return isTzSupported;
},
flushAPICache: function () {
return delete_all_caches();
},
getTimeZone: function (isForce) {
var d = $q.defer();
if (!tz || isForce) {
log("First invocation of TimeZone, asking server");
var apiurl = loginData.apiurl + '/host/getTimeZone.json?' + $rootScope.authSession;
cache_or_http(apiurl, "cached_timezone", false, 3600*24)
.then(function (success) {
tz = success.data.tz;
d.resolve(tz);
debug("Timezone API response is:" + success.data.tz);
if (success.data.tz !== undefined)
isTzSupported = true;
else
isTzSupported = false;
$rootScope.$broadcast('tz-updated');
return (d.promise);
},
function (error) {
tz = moment.tz.guess();
debug("Timezone API error handler, guessing local:" + tz);
d.resolve(tz);
isTzSupported = false;
return (d.promise);
});
} else {
d.resolve(tz);
return d.promise;
}
return d.promise;
},
//-----------------------------------------------------------------------------
// When I display events in the event controller, this is the first function I call
// This returns the total number of pages
// I then proceed to display pages in reverse order to display the latest events first
// I also reverse sort them in NVR to sort by date
// All this effort because the ZM APIs return events in sorted order, oldest first. Yeesh.
//-----------------------------------------------------------------------------
getEventsPages: function (monitorId, startTime, endTime, noObjectFilter) {
//console.log("********** INSIDE EVENTS PAGES ");
var d = $q.defer();
var apiurl = loginData.apiurl;
var myurl = apiurl + "/events/index";
if (monitorId != 0)
myurl = myurl + "/"+"MonitorId:" + monitorId;
if (startTime)
myurl = myurl + "/"+"StartTime <=:" + endTime;
if (endTime)
myurl = myurl + "/"+"EndTime >=:" + startTime;
myurl = myurl + "/"+"AlarmFrames >=:" + (loginData.enableAlarmCount ? loginData.minAlarmCount : 0);
//https:///zm/api/events/index/Notes%20REGEXP:detected%3A.json
if (loginData.objectDetectionFilter && !noObjectFilter) {
myurl = myurl +'/'+ 'Notes REGEXP:detected:';
}
myurl = myurl + ".json?" + $rootScope.authSession;
//console.log (">>>>>Constructed URL " + myurl);
$ionicLoading.show({
template: $translate.instant('kCalcEventSize') + '...',
animation: 'fade-in',
showBackdrop: false,
duration: zm.loadingTimeout,
maxWidth: 200,
showDelay: 0
});
//var myurl = (monitorId == 0) ? apiurl + "/events.json?page=1" : apiurl + "/events/index/MonitorId:" + monitorId + ".json?page=1";
$http.get(myurl)
.then(function (data) {
data = data.data;
$ionicLoading.hide();
//console.log ("**** EVENTS PAGES I GOT "+JSON.stringify(data));
//console.log("**** PAGE COUNT IS " + data.pagination.pageCount);
d.resolve(data.pagination);
return d.promise;
},
function (error) {
$ionicLoading.hide();
// console.log("*** ERROR GETTING TOTAL PAGES ***");
log("Error retrieving page count of events " + JSON.stringify(error), "error");
displayBanner('error', ['error retrieving event page count', 'please try again']);
d.reject(error);
return d.promise;
});
return d.promise;
},
//-----------------------------------------------------------------------------
// This function returns events for specific monitor or all monitors
// You get here by tapping on events in the monitor screen or from
// the menu events option
// monitorId == 0 means all monitors (ZM starts from 1)
//-----------------------------------------------------------------------------
// new reminder
//
//https:///zm/api/events.json?&sort=StartTime&direction=desc&page=1
getEvents: function (monitorId, pageId, loadingStr, startTime, endTime, noObjectFilter, monListFilter) {
if (!pageId) pageId = 1;
//console.log("ZMData getEvents called with ID=" + monitorId + "and Page=" + pageId);
if (!loadingStr) {
loadingStr="<button class='button button-clear' style='line-height: normal; min-height: 0; min-width: 0; color:#fff;' ng-click='$root.cancelAuth()'><i class='ion-close-circled'></i> " + $translate.instant('kLoadingEvents') + "...</button>";
//loadingStr = $translate.instant('kLoadingEvents') + "...";
}
//if (loadingStr) loa
if (loadingStr != 'none') {
$ionicLoading.show({
template: loadingStr,
animation: 'fade-in',
showBackdrop: false,
maxWidth: 200,
showDelay: 0,
duration: zm.loadingTimeout, //specifically for Android - http seems to get stuck at times
});
}
var d = $q.defer();
var myevents = [];
var apiurl = loginData.apiurl;
var myurl = apiurl + "/events/index";
if (monitorId != 0)
myurl = myurl + "/"+"MonitorId:" + monitorId;
if (startTime)
myurl = myurl + "/"+"StartTime <=:" + endTime;
if (endTime)
myurl = myurl + "/"+"EndTime >=:" + startTime;
myurl = myurl + "/"+"AlarmFrames >=:" + (loginData.enableAlarmCount ? loginData.minAlarmCount : 0);
//console.log ('********* MON FILTER '+monListFilter);
if (monListFilter)
myurl = myurl + monListFilter;
// don't know why but adding page messes up Notes
//https:///zm/api/events/index/Notes%20REGEXP: detected%3A.json
if (loginData.objectDetectionFilter && !noObjectFilter) {
myurl = myurl + '/'+'Notes REGEXP:detected:';
}
myurl = myurl + ".json?&sort=StartTime&direction=desc&page=" + pageId + $rootScope.authSession;
debug("getEvents:" + myurl);
//console.log ("LOG: "+myurl);
// Simulated data
// myurl = "https://api.myjson.com/bins/4jx44.json";
//console.log (">>>>>Constructed URL " + myurl);
$http.get(myurl /*,{timeout:15000}*/ )
.then(function (data) {
data = data.data;
if (loadingStr != 'none') $ionicLoading.hide();
//myevents = data.events;
myevents = data;
//console.log (myevents);
d.resolve(myevents);
return d.promise;
},
function (err) {
if (loadingStr != 'none') $ionicLoading.hide();
displayBanner('error', ['error retrieving event list', 'please try again']);
//console.log("HTTP Events error " + err);
log("Error fetching events for page " + pageId + " Err: " + JSON.stringify(err), "error");
// I need to reject this as I have infinite scrolling
// implemented in EventCtrl.js --> and if it does not know
// it got an error going to the next page, it will get into
// an infinite loop as we are at the bottom of the list always
d.reject(myevents);
return d.promise;
});
return d.promise;
},
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
getMontageSize: function () {
return loginData.montageSize;
},
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
setMontageSize: function (montage) {
loginData.montageSize = montage;
},
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
getMonitorsLoaded: function () {
// console.log("**** Inside promise function ");
var deferred = $q.defer();
if (monitorsLoaded != 0) {
deferred.resolve(monitorsLoaded);
}
return deferred.promise;
},
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
setMonitorsLoaded: function (loaded) {
// console.log("ZMData.setMonitorsLoaded=" + loaded);
monitorsLoaded = loaded;
},
//-----------------------------------------------------------------------------
// returns the next monitor ID in the list
// used for swipe next
//-----------------------------------------------------------------------------
getNextMonitor: function (monitorId, direction) {
var id = parseInt(monitorId);
var foundIndex = -1;
for (var i = 0; i < monitors.length; i++) {
if (parseInt(monitors[i].Monitor.Id) == id) {
foundIndex = i;
break;
}
}
if (foundIndex != -1) {
foundIndex = foundIndex + direction;
// wrap around if needed
if (foundIndex < 0) foundIndex = monitors.length - 1;
if (foundIndex >= monitors.length) foundIndex = 0;
return (monitors[foundIndex].Monitor.Id);
} else {
log("getNextMonitor could not find monitor " + monitorId);
return (monitorId);
}
},
//-----------------------------------------------------------------------------
// Given a monitor Id it returns the monitor name
// FIXME: Can I do a better job with associative arrays?
//-----------------------------------------------------------------------------
getMonitorName: function (id) {
var idnum = parseInt(id);
for (var i = 0; i < monitors.length; i++) {
if (parseInt(monitors[i].Monitor.Id) == idnum) {
// console.log ("Matched, exiting getMonitorname");
return monitors[i].Monitor.Name;
}
}
return "(Unknown)";
},
getMonitorObject: function (id) {
var idnum = parseInt(id);
for (var i = 0; i < monitors.length; i++) {
if (parseInt(monitors[i].Monitor.Id) == idnum) {
// console.log ("Matched, exiting getMonitorname");
return monitors[i];
}
}
return undefined;
},
getImageMode: function (id) {
var idnum = parseInt(id);
for (var i = 0; i < monitors.length; i++) {
if (parseInt(monitors[i].Monitor.Id) == idnum) {
// console.log ("Matched, exiting getMonitorname");
return monitors[i].Monitor.imageMode;
}
}
return "(Unknown)";
},
getStreamingURL: function (id) {
var idnum = parseInt(id);
for (var i = 0; i < monitors.length; i++) {
// console.log ("Matched, exiting getMonitorname");
if (parseInt(monitors[i].Monitor.Id) == idnum) {
return monitors[i].Monitor.streamingURL;
}
}
return "(Unknown)";
},
// tries to set up a DB
// set/get a value and if it fails
// goes back to localstorage
// needed for some old Android phones where index setting works, but actually fails
configureStorageDB: function () {
debug("Inside configureStorageDB");
var d = $q.defer();
localforage.config({
name: zm.dbName
});
if ($rootScope.platformOS == 'ios') {
order = [window.cordovaSQLiteDriver._driver,
localforage.INDEXEDDB,
localforage.LOCALSTORAGE
];
} else {
// don't do SQL for Android
// large keys hang on some devices
// see https://github.com/litehelpers/Cordova-sqlite-storage/issues/533
order = [
localforage.INDEXEDDB,
localforage.LOCALSTORAGE,
];
}
debug("configureStorageDB: trying order:" + JSON.stringify(order));
localforage.defineDriver(window.cordovaSQLiteDriver).then(function () {
return localforage.setDriver(
// Try setting cordovaSQLiteDriver if available,
// for desktops, it will pick the next one
order
);
})
.then(function (succ) {
log("configureStorageDB:localforage driver for storage:" + localforage.driver());
debug("configureStorageDB:Making sure this storage driver works...");
return localforage.setItem('testPromiseKey', 'testPromiseValue');
})
.then(function (succ) {
return localforage.getItem('testPromiseKey');
})
.then(function (succ) {
if (succ != 'testPromiseValue') {
log("configureStorageDB:this driver could not restore a test val, reverting to localstorage and hoping for the best...");
return forceLocalStorage();
} else {
debug("configureStorageDB:test get/set worked, this driver is ok...");
d.resolve(true);
return d.promise;
}
})
.catch(function (err) {
log("configureStorageDB:this driver errored, reverting to localstorage and hoping for the best...: " + JSON.stringify(err));
return forceLocalStorage();
});
return d.promise;
function forceLocalStorage() {
// var d = $q.defer();
localforage.setDriver(localforage.LOCALSTORAGE)
.then(function (succ) {
log("configureStorageDB:localforage forced setting to localstorage returned a driver of: " + localforage.driver());
d.resolve(true);
return d.promise;
},
function (err) {
log("*** configureStorageDB: Error setting localStorage too, zmNinja WILL NOT SAVE ***");
log("*** configureStorageDB: Dance, rejoice, keep re-configuring everytime you run ***");
d.resolve(true);
return d.promise;
});
return d.promise;
}
},
getRecordingURL: function (id) {
var idnum = parseInt(id);
for (var i = 0; i < monitors.length; i++) {
if (parseInt(monitors[i].Monitor.Id) == idnum) {
// console.log ("Matched, exiting getMonitorname");
//console.log ("!!!"+monitors[i].Monitor.controlURL);
return monitors[i].Monitor.controlURL;
}
}
return "(Unknown)";
},
getBaseURL: function (id) {
var idnum = parseInt(id);
for (var i = 0; i < monitors.length; i++) {
if (parseInt(monitors[i].Monitor.Id) == idnum) {
// console.log ("Matched, exiting getMonitorname");
return monitors[i].Monitor.baseURL;
}
}
return "(Unknown)";
},
logout: function () {
var d = $q.defer();
if ($rootScope.userCancelledAuth) {
debug ('NVR logout: User cancelled auth, not proceeding');
d.reject(true);
return d.promise;
}
// always resolves
if (!loginData.isUseAuth || loginData.isTokenSupported) {
log("No need for logout!");
d.resolve(true);
return d.promise;
}
// $ionicLoading.show({ template: '<button class="button button-clear" style="line-height: normal; min-height: 0; min-width: 0;" ng-click="$root.cancel()"></button><i class="icon ion-chevron-up"></i> Loading...' });
$ionicLoading.show({
//template:$translate.instant('kCleaningUp'),
template: "<a style='color:white; text-decoration:none' href='#' ng-click='$root.cancelAuth()' <i class='ion-close-circled'></i> " + $translate.instant('kCleaningUp')+"</a>",
noBackdrop: true,
});
log(loginData.url + "=>Logging out of any existing ZM sessions...");
$rootScope.authSession = "";
// console.log("CURRENT SERVER: " + loginData.currentServerVersion);
if (loginData.currentServerVersion && (versionCompare(loginData.currentServerVersion, zm.versionWithLoginAPI) != -1 || loginData.loginAPISupported)) {
debug("Logging out using API method");
$http.get(loginData.apiurl + '/host/logout.json', {
timeout: 7000,
transformResponse: undefined,
// responseType:'text',
})
.then(function (s) {
debug("Logout returned... ");
d.resolve(true);
$ionicLoading.hide();
return d.promise;
},
function (e) {
debug("Logout errored but really don't worry, your ZM version may not support it");
$ionicLoading.hide();
d.resolve(true);
return d.promise;
}
);
return d.promise;
}
// old logout mode
debug("Logging out using Web method");
$http({
method: 'POST',
timeout: 7000,
//withCredentials: true,
url: loginData.url + '/index.php?view=console',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" +
encodeURIComponent(obj[p]));
var params = str.join("&");
return params;
},
data: {
action: "logout",
view: "login"
}
})
.then(function (succ) {
$ionicLoading.hide();
d.resolve(true);
return d.promise;
},
function (err) {
$ionicLoading.hide();
d.resolve(true);
return d.promise;
});
return d.promise;
}
};
}
]);
|