hello.js
138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
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
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
/*! hellojs v1.19.5 - (c) 2012-2021 Andrew Dodson - MIT https://adodson.com/hello.js/LICENSE */
// ES5 Object.create
if (!Object.create) {
// Shim, Object create
// A shim for Object.create(), it adds a prototype to a new object
Object.create = (function() {
function F() {}
return function(o) {
if (arguments.length != 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
}
// ES5 Object.keys
if (!Object.keys) {
Object.keys = function(o, k, r) {
r = [];
for (k in o) {
if (r.hasOwnProperty.call(o, k))
r.push(k);
}
return r;
};
}
/* eslint-disable no-extend-native */
// ES5 [].indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(s) {
for (var j = 0; j < this.length; j++) {
if (this[j] === s) {
return j;
}
}
return -1;
};
}
// ES5 [].forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
fun.call(thisArg, t[i], i, t);
}
}
return this;
};
}
// ES5 [].filter
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun, thisArg) {
var a = [];
this.forEach(function(val, i, t) {
if (fun.call(thisArg || void 0, val, i, t)) {
a.push(val);
}
});
return a;
};
}
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {
Array.prototype.map = function(fun, thisArg) {
var a = [];
this.forEach(function(val, i, t) {
a.push(fun.call(thisArg || void 0, val, i, t));
});
return a;
};
}
// ES5 isArray
if (!Array.isArray) {
// Function Array.isArray
Array.isArray = function(o) {
return Object.prototype.toString.call(o) === '[object Array]';
};
}
// Test for location.assign
if (typeof window === 'object' && typeof window.location === 'object' && !window.location.assign) {
window.location.assign = function(url) {
window.location = url;
};
}
// Test for Function.bind
if (!Function.prototype.bind) {
// MDN
// Polyfill IE8, does not support native Function.bind
Function.prototype.bind = function(b) {
if (typeof this !== 'function') {
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
function C() {}
var a = [].slice;
var f = a.call(arguments, 1);
var _this = this;
var D = function() {
return _this.apply(this instanceof C ? this : b || window, f.concat(a.call(arguments)));
};
C.prototype = this.prototype;
D.prototype = new C();
return D;
};
}
/* eslint-enable no-extend-native */
/**
* @hello.js
*
* HelloJS is a client side Javascript SDK for making OAuth2 logins and subsequent REST calls.
*
* @author Andrew Dodson
* @website https://adodson.com/hello.js/
*
* @copyright Andrew Dodson, 2012 - 2015
* @license MIT: You are free to use and modify this code for any use, on the condition that this copyright notice remains.
*/
var hello = function(name) {
return hello.use(name);
};
hello.utils = {
// Extend the first object with the properties and methods of the second
extend: function(r /*, a[, b[, ...]] */) {
// Get the arguments as an array but ommit the initial item
Array.prototype.slice.call(arguments, 1).forEach(function(a) {
if (Array.isArray(r) && Array.isArray(a)) {
Array.prototype.push.apply(r, a);
}
else if (r && (r instanceof Object || typeof r === 'object') && a && (a instanceof Object || typeof a === 'object') && r !== a) {
for (var x in a) {
// Prevent prototype pollution
if (x === '__proto__' || x === 'constructor') {
continue;
}
r[x] = hello.utils.extend(r[x], a[x]);
}
}
else {
if (Array.isArray(a)) {
// Clone it
a = a.slice(0);
}
r = a;
}
});
return r;
}
};
// Core library
hello.utils.extend(hello, {
settings: {
// OAuth2 authentication defaults
redirect_uri: window.location.href.split('#')[0],
response_type: 'token',
display: 'popup',
state: '',
// OAuth1 shim
// The path to the OAuth1 server for signing user requests
// Want to recreate your own? Checkout https://github.com/MrSwitch/node-oauth-shim
oauth_proxy: 'https://auth-server.herokuapp.com/proxy',
// API timeout in milliseconds
timeout: 20000,
// Popup Options
popup: {
resizable: 1,
scrollbars: 1,
width: 500,
height: 550
},
// Default scope
// Many services require atleast a profile scope,
// HelloJS automatially includes the value of provider.scope_map.basic
// If that's not required it can be removed via hello.settings.scope.length = 0;
scope: ['basic'],
// Scope Maps
// This is the default module scope, these are the defaults which each service is mapped too.
// By including them here it prevents the scope from being applied accidentally
scope_map: {
basic: ''
},
// Default service / network
default_service: null,
// Force authentication
// When hello.login is fired.
// (null): ignore current session expiry and continue with login
// (true): ignore current session expiry and continue with login, ask for user to reauthenticate
// (false): if the current session looks good for the request scopes return the current session.
force: null,
// Page URL
// When 'display=page' this property defines where the users page should end up after redirect_uri
// Ths could be problematic if the redirect_uri is indeed the final place,
// Typically this circumvents the problem of the redirect_url being a dumb relay page.
page_uri: window.location.href
},
// Service configuration objects
services: {},
// Use
// Define a new instance of the HelloJS library with a default service
use: function(service) {
// Create self, which inherits from its parent
var self = Object.create(this);
// Inherit the prototype from its parent
self.settings = Object.create(this.settings);
// Define the default service
if (service) {
self.settings.default_service = service;
}
// Create an instance of Events
self.utils.Event.call(self);
return self;
},
// Initialize
// Define the client_ids for the endpoint services
// @param object o, contains a key value pair, service => clientId
// @param object opts, contains a key value pair of options used for defining the authentication defaults
// @param number timeout, timeout in seconds
init: function(services, options) {
var utils = this.utils;
if (!services) {
return this.services;
}
// Define provider credentials
// Reformat the ID field
for (var x in services) {if (services.hasOwnProperty(x)) {
if (typeof (services[x]) !== 'object') {
services[x] = {id: services[x]};
}
}}
// Merge services if there already exists some
utils.extend(this.services, services);
// Update the default settings with this one.
if (options) {
utils.extend(this.settings, options);
// Do this immediatly incase the browser changes the current path.
if ('redirect_uri' in options) {
this.settings.redirect_uri = utils.url(options.redirect_uri).href;
}
}
return this;
},
// Login
// Using the endpoint
// @param network stringify name to connect to
// @param options object (optional) {display mode, is either none|popup(default)|page, scope: email,birthday,publish, .. }
// @param callback function (optional) fired on signin
login: function() {
// Create an object which inherits its parent as the prototype and constructs a new event chain.
var _this = this;
var utils = _this.utils;
var error = utils.error;
var promise = utils.Promise();
// Get parameters
var p = utils.args({network: 's', options: 'o', callback: 'f'}, arguments);
// Local vars
var url;
// Get all the custom options and store to be appended to the querystring
var qs = utils.diffKey(p.options, _this.settings);
// Merge/override options with app defaults
var opts = p.options = utils.merge(_this.settings, p.options || {});
// Merge/override options with app defaults
opts.popup = utils.merge(_this.settings.popup, p.options.popup || {});
// Network
p.network = p.network || _this.settings.default_service;
// Bind callback to both reject and fulfill states
promise.proxy.then(p.callback, p.callback);
// Trigger an event on the global listener
function emit(s, value) {
hello.emit(s, value);
}
promise.proxy.then(emit.bind(this, 'auth.login auth'), emit.bind(this, 'auth.failed auth'));
// Is our service valid?
if (typeof (p.network) !== 'string' || !(p.network in _this.services)) {
// Trigger the default login.
// Ahh we dont have one.
return promise.reject(error('invalid_network', 'The provided network was not recognized'));
}
var provider = _this.services[p.network];
// Create a global listener to capture events triggered out of scope
var callbackId = utils.globalEvent(function(obj) {
// The responseHandler returns a string, lets save this locally
if (obj) {
if (typeof (obj) == 'string') {
obj = JSON.parse(obj);
}
}
else {
obj = error('cancelled', 'The authentication was not completed');
}
// Handle these response using the local
// Trigger on the parent
if (!obj.error) {
// Save on the parent window the new credentials
// This fixes an IE10 bug i think... atleast it does for me.
utils.store(obj.network, obj);
// Fulfill a successful login
promise.fulfill({
network: obj.network,
authResponse: obj
});
}
else {
// Reject a successful login
promise.reject(obj);
}
});
var redirectUri = utils.url(opts.redirect_uri).href;
// May be a space-delimited list of multiple, complementary types
var responseType = provider.oauth.response_type || opts.response_type;
// Fallback to token if the module hasn't defined a grant url
if (/\bcode\b/.test(responseType) && !provider.oauth.grant) {
responseType = responseType.replace(/\bcode\b/, 'token');
}
// Query string parameters, we may pass our own arguments to form the querystring
p.qs = utils.merge(qs, {
client_id: encodeURIComponent(provider.id),
response_type: encodeURIComponent(responseType),
redirect_uri: encodeURIComponent(redirectUri),
state: {
client_id: provider.id,
network: p.network,
display: opts.display,
callback: callbackId,
state: opts.state,
redirect_uri: redirectUri
}
});
// Get current session for merging scopes, and for quick auth response
var session = utils.store(p.network);
// Scopes (authentication permisions)
// Ensure this is a string - IE has a problem moving Arrays between windows
// Append the setup scope
var SCOPE_SPLIT = /[,\s]+/;
// Include default scope settings (cloned).
var scope = _this.settings.scope ? [_this.settings.scope.toString()] : [];
// Extend the providers scope list with the default
var scopeMap = utils.merge(_this.settings.scope_map, provider.scope || {});
// Add user defined scopes...
if (opts.scope) {
scope.push(opts.scope.toString());
}
// Append scopes from a previous session.
// This helps keep app credentials constant,
// Avoiding having to keep tabs on what scopes are authorized
if (session && 'scope' in session && session.scope instanceof String) {
scope.push(session.scope);
}
// Join and Split again
scope = scope.join(',').split(SCOPE_SPLIT);
// Format remove duplicates and empty values
scope = utils.unique(scope).filter(filterEmpty);
// Save the the scopes to the state with the names that they were requested with.
p.qs.state.scope = scope.join(',');
// Map scopes to the providers naming convention
scope = scope.map(function(item) {
// Does this have a mapping?
return (item in scopeMap) ? scopeMap[item] : item;
});
// Stringify and Arrayify so that double mapped scopes are given the chance to be formatted
scope = scope.join(',').split(SCOPE_SPLIT);
// Again...
// Format remove duplicates and empty values
scope = utils.unique(scope).filter(filterEmpty);
// Join with the expected scope delimiter into a string
p.qs.scope = scope.join(provider.scope_delim || ',');
// Is the user already signed in with the appropriate scopes, valid access_token?
if (opts.force === false) {
if (session && 'access_token' in session && session.access_token && 'expires' in session && session.expires > ((new Date()).getTime() / 1e3)) {
// What is different about the scopes in the session vs the scopes in the new login?
var diff = utils.diff((session.scope || '').split(SCOPE_SPLIT), (p.qs.state.scope || '').split(SCOPE_SPLIT));
if (diff.length === 0) {
// OK trigger the callback
promise.fulfill({
unchanged: true,
network: p.network,
authResponse: session
});
// Nothing has changed
return promise;
}
}
}
// Page URL
if (opts.display === 'page' && opts.page_uri) {
// Add a page location, place to endup after session has authenticated
p.qs.state.page_uri = utils.url(opts.page_uri).href;
}
// Bespoke
// Override login querystrings from auth_options
if ('login' in provider && typeof (provider.login) === 'function') {
// Format the paramaters according to the providers formatting function
provider.login(p);
}
// Add OAuth to state
// Where the service is going to take advantage of the oauth_proxy
if (!/\btoken\b/.test(responseType) ||
parseInt(provider.oauth.version, 10) < 2 ||
(opts.display === 'none' && provider.oauth.grant && session && session.refresh_token)) {
// Add the oauth endpoints
p.qs.state.oauth = provider.oauth;
// Add the proxy url
p.qs.state.oauth_proxy = opts.oauth_proxy;
}
// Convert state to a string
p.qs.state = encodeURIComponent(JSON.stringify(p.qs.state));
// URL
if (parseInt(provider.oauth.version, 10) === 1) {
// Turn the request to the OAuth Proxy for 3-legged auth
url = utils.qs(opts.oauth_proxy, p.qs, encodeFunction);
}
// Refresh token
else if (opts.display === 'none' && provider.oauth.grant && session && session.refresh_token) {
// Add the refresh_token to the request
p.qs.refresh_token = session.refresh_token;
// Define the request path
url = utils.qs(opts.oauth_proxy, p.qs, encodeFunction);
}
else {
url = utils.qs(provider.oauth.auth, p.qs, encodeFunction);
}
// Broadcast this event as an auth:init
emit('auth.init', p);
// Execute
// Trigger how we want self displayed
if (opts.display === 'none') {
// Sign-in in the background, iframe
utils.iframe(url, redirectUri);
}
// Triggering popup?
else if (opts.display === 'popup') {
var popup = utils.popup(url, redirectUri, opts.popup);
var timer = setInterval(function() {
if (!popup || popup.closed) {
clearInterval(timer);
if (!promise.state) {
var response = error('cancelled', 'Login has been cancelled');
if (!popup) {
response = error('blocked', 'Popup was blocked');
}
response.network = p.network;
promise.reject(response);
}
}
}, 100);
}
else {
window.location = url;
}
return promise.proxy;
function encodeFunction(s) {return s;}
function filterEmpty(s) {return !!s;}
},
// Remove any data associated with a given service
// @param string name of the service
// @param function callback
logout: function() {
var _this = this;
var utils = _this.utils;
var error = utils.error;
// Create a new promise
var promise = utils.Promise();
var p = utils.args({name: 's', options: 'o', callback: 'f'}, arguments);
p.options = p.options || {};
// Add callback to events
promise.proxy.then(p.callback, p.callback);
// Trigger an event on the global listener
function emit(s, value) {
hello.emit(s, value);
}
promise.proxy.then(emit.bind(this, 'auth.logout auth'), emit.bind(this, 'error'));
// Network
p.name = p.name || this.settings.default_service;
p.authResponse = utils.store(p.name);
if (p.name && !(p.name in _this.services)) {
promise.reject(error('invalid_network', 'The network was unrecognized'));
}
else if (p.name && p.authResponse) {
// Define the callback
var callback = function(opts) {
// Remove from the store
utils.store(p.name, null);
// Emit events by default
promise.fulfill(hello.utils.merge({network: p.name}, opts || {}));
};
// Run an async operation to remove the users session
var _opts = {};
if (p.options.force) {
var logout = _this.services[p.name].logout;
if (logout) {
// Convert logout to URL string,
// If no string is returned, then this function will handle the logout async style
if (typeof (logout) === 'function') {
logout = logout(callback, p);
}
// If logout is a string then assume URL and open in iframe.
if (typeof (logout) === 'string') {
utils.iframe(logout);
_opts.force = null;
_opts.message = 'Logout success on providers site was indeterminate';
}
else if (logout === undefined) {
// The callback function will handle the response.
return promise.proxy;
}
}
}
// Remove local credentials
callback(_opts);
}
else {
promise.reject(error('invalid_session', 'There was no session to remove'));
}
return promise.proxy;
},
// Returns all the sessions that are subscribed too
// @param string optional, name of the service to get information about.
getAuthResponse: function(service) {
// If the service doesn't exist
service = service || this.settings.default_service;
if (!service || !(service in this.services)) {
return null;
}
return this.utils.store(service) || null;
},
// Events: placeholder for the events
events: {}
});
// Core utilities
hello.utils.extend(hello.utils, {
// Error
error: function(code, message) {
return {
error: {
code: code,
message: message
}
};
},
// Append the querystring to a url
// @param string url
// @param object parameters
qs: function(url, params, formatFunction) {
if (params) {
// Set default formatting function
formatFunction = formatFunction || encodeURIComponent;
// Override the items in the URL which already exist
for (var x in params) {
var str = '([\\?\\&])' + x + '=[^\\&]*';
var reg = new RegExp(str);
if (url.match(reg)) {
url = url.replace(reg, '$1' + x + '=' + formatFunction(params[x]));
delete params[x];
}
}
}
if (!this.isEmpty(params)) {
return url + (url.indexOf('?') > -1 ? '&' : '?') + this.param(params, formatFunction);
}
return url;
},
// Param
// Explode/encode the parameters of an URL string/object
// @param string s, string to decode
param: function(s, formatFunction) {
var b;
var a = {};
var m;
if (typeof (s) === 'string') {
formatFunction = formatFunction || decodeURIComponent;
m = s.replace(/^[\#\?]/, '').match(/([^=\/\&]+)=([^\&]+)/g);
if (m) {
for (var i = 0; i < m.length; i++) {
b = m[i].match(/([^=]+)=(.*)/);
a[b[1]] = formatFunction(b[2]);
}
}
return a;
}
else {
formatFunction = formatFunction || encodeURIComponent;
var o = s;
a = [];
for (var x in o) {if (o.hasOwnProperty(x)) {
if (o.hasOwnProperty(x)) {
a.push([x, o[x] === '?' ? '?' : formatFunction(o[x])].join('='));
}
}}
return a.join('&');
}
},
// Local storage facade
store: (function() {
var a = ['localStorage', 'sessionStorage'];
var i = -1;
var prefix = 'test';
// Set LocalStorage
var localStorage;
while (a[++i]) {
try {
// In Chrome with cookies blocked, calling localStorage throws an error
localStorage = window[a[i]];
localStorage.setItem(prefix + i, i);
localStorage.removeItem(prefix + i);
break;
}
catch (e) {
localStorage = null;
}
}
if (!localStorage) {
var cache = null;
localStorage = {
getItem: function(prop) {
prop = prop + '=';
var m = document.cookie.split(';');
for (var i = 0; i < m.length; i++) {
var _m = m[i].replace(/(^\s+|\s+$)/, '');
if (_m && _m.indexOf(prop) === 0) {
return _m.substr(prop.length);
}
}
return cache;
},
setItem: function(prop, value) {
cache = value;
document.cookie = prop + '=' + value;
}
};
// Fill the cache up
cache = localStorage.getItem('hello');
}
function get() {
var json = {};
try {
json = JSON.parse(localStorage.getItem('hello')) || {};
}
catch (e) {}
return json;
}
function set(json) {
localStorage.setItem('hello', JSON.stringify(json));
}
// Check if the browser support local storage
return function(name, value, days) {
// Local storage
var json = get();
if (name && value === undefined) {
return json[name] || null;
}
else if (name && value === null) {
try {
delete json[name];
}
catch (e) {
json[name] = null;
}
}
else if (name) {
json[name] = value;
}
else {
return json;
}
set(json);
return json || null;
};
})(),
// Create and Append new DOM elements
// @param node string
// @param attr object literal
// @param dom/string
append: function(node, attr, target) {
var n = typeof (node) === 'string' ? document.createElement(node) : node;
if (typeof (attr) === 'object') {
if ('tagName' in attr) {
target = attr;
}
else {
for (var x in attr) {if (attr.hasOwnProperty(x)) {
if (typeof (attr[x]) === 'object') {
for (var y in attr[x]) {if (attr[x].hasOwnProperty(y)) {
n[x][y] = attr[x][y];
}}
}
else if (x === 'html') {
n.innerHTML = attr[x];
}
// IE doesn't like us setting methods with setAttribute
else if (!/^on/.test(x)) {
n.setAttribute(x, attr[x]);
}
else {
n[x] = attr[x];
}
}}
}
}
if (target === 'body') {
(function self() {
if (document.body) {
document.body.appendChild(n);
}
else {
setTimeout(self, 16);
}
})();
}
else if (typeof (target) === 'object') {
target.appendChild(n);
}
else if (typeof (target) === 'string') {
document.getElementsByTagName(target)[0].appendChild(n);
}
return n;
},
// An easy way to create a hidden iframe
// @param string src
iframe: function(src) {
this.append('iframe', {src: src, style: {position: 'absolute', left: '-1000px', bottom: 0, height: '1px', width: '1px'}}, 'body');
},
// Recursive merge two objects into one, second parameter overides the first
// @param a array
merge: function(/* Args: a, b, c, .. n */) {
var args = Array.prototype.slice.call(arguments);
args.unshift({});
return this.extend.apply(null, args);
},
// Makes it easier to assign parameters, where some are optional
// @param o object
// @param a arguments
args: function(o, args) {
var p = {};
var i = 0;
var t = null;
var x = null;
// 'x' is the first key in the list of object parameters
for (x in o) {if (o.hasOwnProperty(x)) {
break;
}}
// Passing in hash object of arguments?
// Where the first argument can't be an object
if ((args.length === 1) && (typeof (args[0]) === 'object') && o[x] != 'o!') {
// Could this object still belong to a property?
// Check the object keys if they match any of the property keys
for (x in args[0]) {if (o.hasOwnProperty(x)) {
// Does this key exist in the property list?
if (x in o) {
// Yes this key does exist so its most likely this function has been invoked with an object parameter
// Return first argument as the hash of all arguments
return args[0];
}
}}
}
// Else loop through and account for the missing ones.
for (x in o) {if (o.hasOwnProperty(x)) {
t = typeof (args[i]);
if ((typeof (o[x]) === 'function' && o[x].test(args[i])) || (typeof (o[x]) === 'string' && (
(o[x].indexOf('s') > -1 && t === 'string') ||
(o[x].indexOf('o') > -1 && t === 'object') ||
(o[x].indexOf('i') > -1 && t === 'number') ||
(o[x].indexOf('a') > -1 && t === 'object') ||
(o[x].indexOf('f') > -1 && t === 'function')
))
) {
p[x] = args[i++];
}
else if (typeof (o[x]) === 'string' && o[x].indexOf('!') > -1) {
return false;
}
}}
return p;
},
// Returns a URL instance
url: function(path) {
// If the path is empty
if (!path) {
return window.location;
}
// Chrome and FireFox support new URL() to extract URL objects
else if (window.URL && URL instanceof Function && URL.length !== 0) {
return new URL(path, window.location);
}
// Ugly shim, it works!
else {
var a = document.createElement('a');
a.href = path;
return a.cloneNode(false);
}
},
diff: function(a, b) {
return b.filter(function(item) {
return a.indexOf(item) === -1;
});
},
// Get the different hash of properties unique to `a`, and not in `b`
diffKey: function(a, b) {
if (a || !b) {
var r = {};
for (var x in a) {
// Does the property not exist?
if (!(x in b)) {
r[x] = a[x];
}
}
return r;
}
return a;
},
// Unique
// Remove duplicate and null values from an array
// @param a array
unique: function(a) {
if (!Array.isArray(a)) { return []; }
return a.filter(function(item, index) {
// Is this the first location of item
return a.indexOf(item) === index;
});
},
isEmpty: function(obj) {
// Scalar
if (!obj)
return true;
// Array
if (Array.isArray(obj)) {
return !obj.length;
}
else if (typeof (obj) === 'object') {
// Object
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
}
return true;
},
/* eslint-disable */
/*!
** Thenable -- Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
** Copyright (c) 2013-2014 Ralf S. Engelschall <http://engelschall.com>
** Licensed under The MIT License <http://opensource.org/licenses/MIT>
** Source-Code distributed on <http://github.com/rse/thenable>
*/
Promise: (function() {
/* promise states [Promises/A+ 2.1] */
var STATE_PENDING = 0; /* [Promises/A+ 2.1.1] */
var STATE_FULFILLED = 1; /* [Promises/A+ 2.1.2] */
var STATE_REJECTED = 2; /* [Promises/A+ 2.1.3] */
/* promise object constructor */
var api = function(executor) {
/* optionally support non-constructor/plain-function call */
if (!(this instanceof api))
return new api(executor);
/* initialize object */
this.id = "Thenable/1.0.6";
this.state = STATE_PENDING; /* initial state */
this.fulfillValue = undefined; /* initial value */ /* [Promises/A+ 1.3, 2.1.2.2] */
this.rejectReason = undefined; /* initial reason */ /* [Promises/A+ 1.5, 2.1.3.2] */
this.onFulfilled = []; /* initial handlers */
this.onRejected = []; /* initial handlers */
/* provide optional information-hiding proxy */
this.proxy = {
then: this.then.bind(this)
};
/* support optional executor function */
if (typeof executor === "function")
executor.call(this, this.fulfill.bind(this), this.reject.bind(this));
};
/* promise API methods */
api.prototype = {
/* promise resolving methods */
fulfill: function(value) { return deliver(this, STATE_FULFILLED, "fulfillValue", value); },
reject: function(value) { return deliver(this, STATE_REJECTED, "rejectReason", value); },
/* "The then Method" [Promises/A+ 1.1, 1.2, 2.2] */
then: function(onFulfilled, onRejected) {
var curr = this;
var next = new api(); /* [Promises/A+ 2.2.7] */
curr.onFulfilled.push(
resolver(onFulfilled, next, "fulfill")); /* [Promises/A+ 2.2.2/2.2.6] */
curr.onRejected.push(
resolver(onRejected, next, "reject")); /* [Promises/A+ 2.2.3/2.2.6] */
execute(curr);
return next.proxy; /* [Promises/A+ 2.2.7, 3.3] */
}
};
/* deliver an action */
var deliver = function(curr, state, name, value) {
if (curr.state === STATE_PENDING) {
curr.state = state; /* [Promises/A+ 2.1.2.1, 2.1.3.1] */
curr[name] = value; /* [Promises/A+ 2.1.2.2, 2.1.3.2] */
execute(curr);
}
return curr;
};
/* execute all handlers */
var execute = function(curr) {
if (curr.state === STATE_FULFILLED)
execute_handlers(curr, "onFulfilled", curr.fulfillValue);
else if (curr.state === STATE_REJECTED)
execute_handlers(curr, "onRejected", curr.rejectReason);
};
/* execute particular set of handlers */
var execute_handlers = function(curr, name, value) {
/* global process: true */
/* global setImmediate: true */
/* global setTimeout: true */
/* short-circuit processing */
if (curr[name].length === 0)
return;
/* iterate over all handlers, exactly once */
var handlers = curr[name];
curr[name] = []; /* [Promises/A+ 2.2.2.3, 2.2.3.3] */
var func = function() {
for (var i = 0; i < handlers.length; i++)
handlers[i](value); /* [Promises/A+ 2.2.5] */
};
/* execute procedure asynchronously */ /* [Promises/A+ 2.2.4, 3.1] */
if (typeof process === "object" && typeof process.nextTick === "function")
process.nextTick(func);
else if (typeof setImmediate === "function")
setImmediate(func);
else
setTimeout(func, 0);
};
/* generate a resolver function */
var resolver = function(cb, next, method) {
return function(value) {
if (typeof cb !== "function") /* [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4] */
next[method].call(next, value); /* [Promises/A+ 2.2.7.3, 2.2.7.4] */
else {
var result;
try { result = cb(value); } /* [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2] */
catch (e) {
next.reject(e); /* [Promises/A+ 2.2.7.2] */
return;
}
resolve(next, result); /* [Promises/A+ 2.2.7.1] */
}
};
};
/* "Promise Resolution Procedure" */ /* [Promises/A+ 2.3] */
var resolve = function(promise, x) {
/* sanity check arguments */ /* [Promises/A+ 2.3.1] */
if (promise === x || promise.proxy === x) {
promise.reject(new TypeError("cannot resolve promise with itself"));
return;
}
/* surgically check for a "then" method
(mainly to just call the "getter" of "then" only once) */
var then;
if ((typeof x === "object" && x !== null) || typeof x === "function") {
try { then = x.then; } /* [Promises/A+ 2.3.3.1, 3.5] */
catch (e) {
promise.reject(e); /* [Promises/A+ 2.3.3.2] */
return;
}
}
/* handle own Thenables [Promises/A+ 2.3.2]
and similar "thenables" [Promises/A+ 2.3.3] */
if (typeof then === "function") {
var resolved = false;
try {
/* call retrieved "then" method */ /* [Promises/A+ 2.3.3.3] */
then.call(x,
/* resolvePromise */ /* [Promises/A+ 2.3.3.3.1] */
function(y) {
if (resolved) return; resolved = true; /* [Promises/A+ 2.3.3.3.3] */
if (y === x) /* [Promises/A+ 3.6] */
promise.reject(new TypeError("circular thenable chain"));
else
resolve(promise, y);
},
/* rejectPromise */ /* [Promises/A+ 2.3.3.3.2] */
function(r) {
if (resolved) return; resolved = true; /* [Promises/A+ 2.3.3.3.3] */
promise.reject(r);
}
);
}
catch (e) {
if (!resolved) /* [Promises/A+ 2.3.3.3.3] */
promise.reject(e); /* [Promises/A+ 2.3.3.3.4] */
}
return;
}
/* handle other values */
promise.fulfill(x); /* [Promises/A+ 2.3.4, 2.3.3.4] */
};
/* export API */
return api;
})(),
/* eslint-enable */
// Event
// A contructor superclass for adding event menthods, on, off, emit.
Event: function() {
var separator = /[\s\,]+/;
// If this doesn't support getPrototype then we can't get prototype.events of the parent
// So lets get the current instance events, and add those to a parent property
this.parent = {
events: this.events,
findEvents: this.findEvents,
parent: this.parent,
utils: this.utils
};
this.events = {};
// On, subscribe to events
// @param evt string
// @param callback function
this.on = function(evt, callback) {
if (callback && typeof (callback) === 'function') {
var a = evt.split(separator);
for (var i = 0; i < a.length; i++) {
// Has this event already been fired on this instance?
this.events[a[i]] = [callback].concat(this.events[a[i]] || []);
}
}
return this;
};
// Off, unsubscribe to events
// @param evt string
// @param callback function
this.off = function(evt, callback) {
this.findEvents(evt, function(name, index) {
if (!callback || this.events[name][index] === callback) {
this.events[name][index] = null;
}
});
return this;
};
// Emit
// Triggers any subscribed events
this.emit = function(evt /*, data, ... */) {
// Get arguments as an Array, knock off the first one
var args = Array.prototype.slice.call(arguments, 1);
args.push(evt);
// Handler
var handler = function(name, index) {
// Replace the last property with the event name
args[args.length - 1] = (name === '*' ? evt : name);
// Trigger
this.events[name][index].apply(this, args);
};
// Find the callbacks which match the condition and call
var _this = this;
while (_this && _this.findEvents) {
// Find events which match
_this.findEvents(evt + ',*', handler);
_this = _this.parent;
}
return this;
};
//
// Easy functions
this.emitAfter = function() {
var _this = this;
var args = arguments;
setTimeout(function() {
_this.emit.apply(_this, args);
}, 0);
return this;
};
this.findEvents = function(evt, callback) {
var a = evt.split(separator);
for (var name in this.events) {if (this.events.hasOwnProperty(name)) {
if (a.indexOf(name) > -1) {
for (var i = 0; i < this.events[name].length; i++) {
// Does the event handler exist?
if (this.events[name][i]) {
// Emit on the local instance of this
callback.call(this, name, i);
}
}
}
}}
};
return this;
},
// Global Events
// Attach the callback to the window object
// Return its unique reference
globalEvent: function(callback, guid) {
// If the guid has not been supplied then create a new one.
guid = guid || '_hellojs_' + parseInt(Math.random() * 1e12, 10).toString(36);
// Define the callback function
window[guid] = function() {
// Trigger the callback
try {
if (callback.apply(this, arguments)) {
delete window[guid];
}
}
catch (e) {
console.error(e);
}
};
return guid;
},
// Trigger a clientside popup
// This has been augmented to support PhoneGap
popup: function(url, redirectUri, options) {
var documentElement = document.documentElement;
// Multi Screen Popup Positioning (http://stackoverflow.com/a/16861050)
// Credit: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html
// Fixes dual-screen position Most browsers Firefox
if (options.height && options.top === undefined) {
var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;
var height = screen.height || window.innerHeight || documentElement.clientHeight;
options.top = parseInt((height - options.height) / 2, 10) + dualScreenTop;
}
if (options.width && options.left === undefined) {
var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
var width = screen.width || window.innerWidth || documentElement.clientWidth;
options.left = parseInt((width - options.width) / 2, 10) + dualScreenLeft;
}
// Convert options into an array
var optionsArray = [];
Object.keys(options).forEach(function(name) {
var value = options[name];
optionsArray.push(name + (value !== null ? '=' + value : ''));
});
// Call the open() function with the initial path
//
// OAuth redirect, fixes URI fragments from being lost in Safari
// (URI Fragments within 302 Location URI are lost over HTTPS)
// Loading the redirect.html before triggering the OAuth Flow seems to fix it.
//
// Firefox decodes URL fragments when calling location.hash.
// - This is bad if the value contains break points which are escaped
// - Hence the url must be encoded twice as it contains breakpoints.
if (navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1) {
url = redirectUri + '#oauth_redirect=' + encodeURIComponent(encodeURIComponent(url));
}
var popup = window.open(
url,
'_blank',
optionsArray.join(',')
);
if (popup && popup.focus) {
popup.focus();
}
return popup;
},
// OAuth and API response handler
responseHandler: function(window, parent) {
var _this = this;
var p;
var location = window.location;
// Is this an auth relay message which needs to call the proxy?
p = _this.param(location.search);
// OAuth2 or OAuth1 server response?
if (p && p.state && (p.code || p.oauth_token)) {
try {
var state = JSON.parse(p.state);
// Add this path as the redirect_uri
p.redirect_uri = state.redirect_uri || location.href.replace(/[\?\#].*$/, '');
// Redirect to the host
var path = _this.qs(state.oauth_proxy, p);
if (isValidUrl(path)) {
location.assign(path);
}
return;
}
catch (e) {
console.error('Could not decode state parameter', e);
return;
}
}
// Save session, from redirected authentication
// #access_token has come in?
//
// FACEBOOK is returning auth errors within as a query_string... thats a stickler for consistency.
// SoundCloud is the state in the querystring and the token in the hashtag, so we'll mix the two together
p = _this.merge(_this.param(location.search || ''), _this.param(location.hash || ''));
// If p.state
if (p && 'state' in p) {
// Remove any addition information
// E.g. p.state = 'facebook.page';
try {
var a = JSON.parse(p.state);
_this.extend(p, a);
}
catch (e) {
var stateDecoded = decodeURIComponent(p.state);
try {
var b = JSON.parse(stateDecoded);
_this.extend(p, b);
}
catch (e) {
console.error('Could not decode state parameter');
}
}
// Access_token?
if (('access_token' in p && p.access_token) && p.network) {
if (!p.expires_in || parseInt(p.expires_in, 10) === 0) {
// If p.expires_in is unset, set to 0
p.expires_in = 0;
}
p.expires_in = parseInt(p.expires_in, 10);
p.expires = ((new Date()).getTime() / 1e3) + (p.expires_in || (60 * 60 * 24 * 365));
// Lets use the "state" to assign it to one of our networks
authCallback(p, window, parent);
}
// Error=?
// &error_description=?
// &state=?
else if (('error' in p && p.error) && p.network) {
p.error = {
code: p.error,
message: p.error_message || p.error_description
};
// Let the state handler handle it
authCallback(p, window, parent);
}
// API call, or a cancelled login
// Result is serialized JSON string
else if (p.callback && p.callback in parent) {
// Trigger a function in the parent
var res = 'result' in p && p.result ? JSON.parse(p.result) : false;
// Trigger the callback on the parent
callback(parent, p.callback)(res);
closeWindow();
}
// If this page is still open
if (p.page_uri && isValidUrl(p.page_uri)) {
location.assign(p.page_uri);
}
}
// OAuth redirect, fixes URI fragments from being lost in Safari
// (URI Fragments within 302 Location URI are lost over HTTPS)
// Loading the redirect.html before triggering the OAuth Flow seems to fix it.
else if ('oauth_redirect' in p) {
var url = decodeURIComponent(p.oauth_redirect);
if (isValidUrl(url)) {
location.assign(url);
}
return;
}
function isValidUrl(url) {
var regexp = /^https?:/;
return regexp.test(url)
// If `HELLOJS_REDIRECT_URL` is defined in the window context, validate that the URL matches it.
&& (
!Object.prototype.hasOwnProperty.call(window, 'HELLOJS_REDIRECT_URL')
||
url.match(window.HELLOJS_REDIRECT_URL)
);
}
// Trigger a callback to authenticate
function authCallback(obj, window, parent) {
var cb = obj.callback;
var network = obj.network;
// Trigger the callback on the parent
_this.store(network, obj);
// If this is a page request it has no parent or opener window to handle callbacks
if (('display' in obj) && obj.display === 'page') {
return;
}
// Remove from session object
if (parent && cb && cb in parent) {
try {
delete obj.callback;
}
catch (e) {}
// Update store
_this.store(network, obj);
// Call the globalEvent function on the parent
// It's safer to pass back a string to the parent,
// Rather than an object/array (better for IE8)
var str = JSON.stringify(obj);
try {
callback(parent, cb)(str);
}
catch (e) {
// Error thrown whilst executing parent callback
}
}
closeWindow();
}
function callback(parent, callbackID) {
if (callbackID.indexOf('_hellojs_') !== 0) {
return function() {
throw 'Could not execute callback ' + callbackID;
};
}
return parent[callbackID];
}
function closeWindow() {
if (window.frameElement) {
// Inside an iframe, remove from parent
parent.document.body.removeChild(window.frameElement);
}
else {
// Close this current window
try {
window.close();
}
catch (e) {}
// IOS bug wont let us close a popup if still loading
if (window.addEventListener) {
window.addEventListener('load', function() {
window.close();
});
}
}
}
}
});
// Events
// Extend the hello object with its own event instance
hello.utils.Event.call(hello);
///////////////////////////////////
// Monitoring session state
// Check for session changes
///////////////////////////////////
(function(hello) {
// Monitor for a change in state and fire
var oldSessions = {};
// Hash of expired tokens
var expired = {};
// Listen to other triggers to Auth events, use these to update this
hello.on('auth.login, auth.logout', function(auth) {
if (auth && typeof (auth) === 'object' && auth.network) {
oldSessions[auth.network] = hello.utils.store(auth.network) || {};
}
});
(function self() {
var CURRENT_TIME = ((new Date()).getTime() / 1e3);
var emit = function(eventName) {
hello.emit('auth.' + eventName, {
network: name,
authResponse: session
});
};
// Loop through the services
for (var name in hello.services) {if (hello.services.hasOwnProperty(name)) {
if (!hello.services[name].id) {
// We haven't attached an ID so dont listen.
continue;
}
// Get session
var session = hello.utils.store(name) || {};
var provider = hello.services[name];
var oldSess = oldSessions[name] || {};
// Listen for globalEvents that did not get triggered from the child
if (session && 'callback' in session) {
// To do remove from session object...
var cb = session.callback;
try {
delete session.callback;
}
catch (e) {}
// Update store
// Removing the callback
hello.utils.store(name, session);
// Emit global events
try {
window[cb](session);
}
catch (e) {}
}
// Refresh token
if (session && ('expires' in session) && session.expires < CURRENT_TIME) {
// If auto refresh is possible
// Either the browser supports
var refresh = provider.refresh || session.refresh_token;
// Has the refresh been run recently?
if (refresh && (!(name in expired) || expired[name] < CURRENT_TIME)) {
// Try to resignin
hello.emit('notice', name + ' has expired trying to resignin');
hello.login(name, {display: 'none', force: false});
// Update expired, every 10 minutes
expired[name] = CURRENT_TIME + 600;
}
// Does this provider not support refresh
else if (!refresh && !(name in expired)) {
// Label the event
emit('expired');
expired[name] = true;
}
// If session has expired then we dont want to store its value until it can be established that its been updated
continue;
}
// Has session changed?
else if (oldSess.access_token === session.access_token &&
oldSess.expires === session.expires) {
continue;
}
// Access_token has been removed
else if (!session.access_token && oldSess.access_token) {
emit('logout');
}
// Access_token has been created
else if (session.access_token && !oldSess.access_token) {
emit('login');
}
// Access_token has been updated
else if (session.expires !== oldSess.expires) {
emit('update');
}
// Updated stored session
oldSessions[name] = session;
// Remove the expired flags
if (name in expired) {
delete expired[name];
}
}}
// Check error events
setTimeout(self, 1000);
})();
})(hello);
// EOF CORE lib
//////////////////////////////////
/////////////////////////////////////////
// API
// @param path string
// @param query object (optional)
// @param method string (optional)
// @param data object (optional)
// @param timeout integer (optional)
// @param callback function (optional)
hello.api = function() {
// Shorthand
var _this = this;
var utils = _this.utils;
var error = utils.error;
// Construct a new Promise object
var promise = utils.Promise();
// Arguments
var p = utils.args({path: 's!', query: 'o', method: 's', data: 'o', timeout: 'i', callback: 'f'}, arguments);
// Method
p.method = (p.method || 'get').toLowerCase();
// Headers
p.headers = p.headers || {};
// Query
p.query = p.query || {};
// If get, put all parameters into query
if (p.method === 'get' || p.method === 'delete') {
utils.extend(p.query, p.data);
p.data = {};
}
var data = p.data = p.data || {};
// Completed event callback
promise.then(p.callback, p.callback);
// Remove the network from path, e.g. facebook:/me/friends
// Results in { network : facebook, path : me/friends }
if (!p.path) {
return promise.reject(error('invalid_path', 'Missing the path parameter from the request'));
}
p.path = p.path.replace(/^\/+/, '');
var a = (p.path.split(/[\/\:]/, 2) || [])[0].toLowerCase();
if (a in _this.services) {
p.network = a;
var reg = new RegExp('^' + a + ':?\/?');
p.path = p.path.replace(reg, '');
}
// Network & Provider
// Define the network that this request is made for
p.network = _this.settings.default_service = p.network || _this.settings.default_service;
var o = _this.services[p.network];
// INVALID
// Is there no service by the given network name?
if (!o) {
return promise.reject(error('invalid_network', 'Could not match the service requested: ' + p.network));
}
// PATH
// As long as the path isn't flagged as unavaiable, e.g. path == false
if (!(!(p.method in o) || !(p.path in o[p.method]) || o[p.method][p.path] !== false)) {
return promise.reject(error('invalid_path', 'The provided path is not available on the selected network'));
}
// PROXY
// OAuth1 calls always need a proxy
if (!p.oauth_proxy) {
p.oauth_proxy = _this.settings.oauth_proxy;
}
if (!('proxy' in p)) {
p.proxy = p.oauth_proxy && o.oauth && parseInt(o.oauth.version, 10) === 1;
}
// TIMEOUT
// Adopt timeout from global settings by default
if (!('timeout' in p)) {
p.timeout = _this.settings.timeout;
}
// Format response
// Whether to run the raw response through post processing.
if (!('formatResponse' in p)) {
p.formatResponse = true;
}
// Get the current session
// Append the access_token to the query
p.authResponse = _this.getAuthResponse(p.network);
if (p.authResponse && p.authResponse.access_token) {
p.query.access_token = p.authResponse.access_token;
}
var url = p.path;
var m;
// Store the query as options
// This is used to populate the request object before the data is augmented by the prewrap handlers.
p.options = utils.clone(p.query);
// Clone the data object
// Prevent this script overwriting the data of the incoming object.
// Ensure that everytime we run an iteration the callbacks haven't removed some data
p.data = utils.clone(data);
// URL Mapping
// Is there a map for the given URL?
var actions = o[{'delete': 'del'}[p.method] || p.method] || {};
// Extrapolate the QueryString
// Provide a clean path
// Move the querystring into the data
if (p.method === 'get') {
var query = url.split(/[\?#]/)[1];
if (query) {
utils.extend(p.query, utils.param(query));
// Remove the query part from the URL
url = url.replace(/\?.*?(#|$)/, '$1');
}
}
// Is the hash fragment defined
if ((m = url.match(/#(.+)/, ''))) {
url = url.split('#')[0];
p.path = m[1];
}
else if (url in actions) {
p.path = url;
url = actions[url];
}
else if ('default' in actions) {
url = actions['default'];
}
// Redirect Handler
// This defines for the Form+Iframe+Hash hack where to return the results too.
p.redirect_uri = _this.settings.redirect_uri;
// Define FormatHandler
// The request can be procesed in a multitude of ways
// Here's the options - depending on the browser and endpoint
p.xhr = o.xhr;
p.jsonp = o.jsonp;
p.form = o.form;
// Make request
if (typeof (url) === 'function') {
// Does self have its own callback?
url(p, getPath);
}
else {
// Else the URL is a string
getPath(url);
}
return promise.proxy;
// If url needs a base
// Wrap everything in
function getPath(url) {
// Format the string if it needs it
url = url.replace(/\@\{([a-z\_\-]+)(\|.*?)?\}/gi, function(m, key, defaults) {
var val = defaults ? defaults.replace(/^\|/, '') : '';
if (key in p.query) {
val = p.query[key];
delete p.query[key];
}
else if (p.data && key in p.data) {
val = p.data[key];
delete p.data[key];
}
else if (!defaults) {
promise.reject(error('missing_attribute', 'The attribute ' + key + ' is missing from the request'));
}
return val;
});
// Add base
if (!url.match(/^https?:\/\//)) {
url = o.base + url;
}
// Define the request URL
p.url = url;
// Make the HTTP request with the curated request object
// CALLBACK HANDLER
// @ response object
// @ statusCode integer if available
utils.request(p, function(r, headers) {
// Is this a raw response?
if (!p.formatResponse) {
// Bad request? error statusCode or otherwise contains an error response vis JSONP?
if (typeof headers === 'object' ? (headers.statusCode >= 400) : (typeof r === 'object' && 'error' in r)) {
promise.reject(r);
}
else {
promise.fulfill(r);
}
return;
}
// Should this be an object
if (r === true) {
r = {success: true};
}
else if (!r) {
r = {};
}
// The delete callback needs a better response
if (p.method === 'delete') {
r = (!r || utils.isEmpty(r)) ? {success: true} : r;
}
// FORMAT RESPONSE?
// Does self request have a corresponding formatter
if (o.wrap && ((p.path in o.wrap) || ('default' in o.wrap))) {
var wrap = (p.path in o.wrap ? p.path : 'default');
var time = (new Date()).getTime();
// FORMAT RESPONSE
var b = o.wrap[wrap](r, headers, p);
// Has the response been utterly overwritten?
// Typically self augments the existing object.. but for those rare occassions
if (b) {
r = b;
}
}
// Is there a next_page defined in the response?
if (r && 'paging' in r && r.paging.next) {
// Add the relative path if it is missing from the paging/next path
if (r.paging.next[0] === '?') {
r.paging.next = p.path + r.paging.next;
}
// The relative path has been defined, lets markup the handler in the HashFragment
else {
r.paging.next += '#' + p.path;
}
}
// Dispatch to listeners
// Emit events which pertain to the formatted response
if (!r || 'error' in r) {
promise.reject(r);
}
else {
promise.fulfill(r);
}
});
}
};
// API utilities
hello.utils.extend(hello.utils, {
// Make an HTTP request
request: function(p, callback) {
var _this = this;
var error = _this.error;
// This has to go through a POST request
if (!_this.isEmpty(p.data) && !('FileList' in window) && _this.hasBinary(p.data)) {
// Disable XHR and JSONP
p.xhr = false;
p.jsonp = false;
}
// Check if the browser and service support CORS
var cors = this.request_cors(function() {
// If it does then run this...
return ((p.xhr === undefined) || (p.xhr && (typeof (p.xhr) !== 'function' || p.xhr(p, p.query))));
});
if (cors) {
formatUrl(p, function(url) {
var x = _this.xhr(p.method, url, p.headers, p.data, callback);
x.onprogress = p.onprogress || null;
// Windows Phone does not support xhr.upload, see #74
// Feature detect
if (x.upload && p.onuploadprogress) {
x.upload.onprogress = p.onuploadprogress;
}
});
return;
}
// Clone the query object
// Each request modifies the query object and needs to be tared after each one.
var _query = p.query;
p.query = _this.clone(p.query);
// Assign a new callbackID
p.callbackID = _this.globalEvent();
// JSONP
if (p.jsonp !== false) {
// Clone the query object
p.query.callback = p.callbackID;
// If the JSONP is a function then run it
if (typeof (p.jsonp) === 'function') {
p.jsonp(p, p.query);
}
// Lets use JSONP if the method is 'get'
if (p.method === 'get') {
formatUrl(p, function(url) {
_this.jsonp(url, callback, p.callbackID, p.timeout);
});
return;
}
else {
// It's not compatible reset query
p.query = _query;
}
}
// Otherwise we're on to the old school, iframe hacks and JSONP
if (p.form !== false) {
// Add some additional query parameters to the URL
// We're pretty stuffed if the endpoint doesn't like these
p.query.redirect_uri = p.redirect_uri;
p.query.state = JSON.stringify({callback: p.callbackID});
var opts;
if (typeof (p.form) === 'function') {
// Format the request
opts = p.form(p, p.query);
}
if (p.method === 'post' && opts !== false) {
formatUrl(p, function(url) {
_this.post(url, p.data, opts, callback, p.callbackID, p.timeout);
});
return;
}
}
// None of the methods were successful throw an error
callback(error('invalid_request', 'There was no mechanism for handling this request'));
return;
// Format URL
// Constructs the request URL, optionally wraps the URL through a call to a proxy server
// Returns the formatted URL
function formatUrl(p, callback) {
// Are we signing the request?
var sign;
// OAuth1
// Remove the token from the query before signing
if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) {
// OAUTH SIGNING PROXY
sign = p.query.access_token;
// Remove the access_token
delete p.query.access_token;
// Enfore use of Proxy
p.proxy = true;
}
// POST body to querystring
if (p.data && (p.method === 'get' || p.method === 'delete')) {
// Attach the p.data to the querystring.
_this.extend(p.query, p.data);
p.data = null;
}
// Construct the path
var path = _this.qs(p.url, p.query);
// Proxy the request through a server
// Used for signing OAuth1
// And circumventing services without Access-Control Headers
if (p.proxy) {
// Use the proxy as a path
path = _this.qs(p.oauth_proxy, {
path: path,
access_token: sign || '',
// This will prompt the request to be signed as though it is OAuth1
then: p.proxy_response_type || (p.method.toLowerCase() === 'get' ? 'redirect' : 'proxy'),
method: p.method.toLowerCase(),
suppress_response_codes: p.suppress_response_codes || true
});
}
callback(path);
}
},
// Test whether the browser supports the CORS response
request_cors: function(callback) {
return 'withCredentials' in new XMLHttpRequest() && callback();
},
// Return the type of DOM object
domInstance: function(type, data) {
var test = 'HTML' + (type || '').replace(
/^[a-z]/,
function(m) {
return m.toUpperCase();
}
) + 'Element';
if (!data) {
return false;
}
if (window[test]) {
return data instanceof window[test];
}
else if (window.Element) {
return data instanceof window.Element && (!type || (data.tagName && data.tagName.toLowerCase() === type));
}
else {
return (!(data instanceof Object || data instanceof Array || data instanceof String || data instanceof Number) && data.tagName && data.tagName.toLowerCase() === type);
}
},
// Create a clone of an object
clone: function(obj) {
// Does not clone DOM elements, nor Binary data, e.g. Blobs, Filelists
if (obj === null || typeof (obj) !== 'object' || obj instanceof Date || 'nodeName' in obj || this.isBinary(obj) || (typeof FormData === 'function' && obj instanceof FormData)) {
return obj;
}
if (Array.isArray(obj)) {
// Clone each item in the array
return obj.map(this.clone.bind(this));
}
// But does clone everything else.
var clone = {};
for (var x in obj) {
clone[x] = this.clone(obj[x]);
}
return clone;
},
// XHR: uses CORS to make requests
xhr: function(method, url, headers, data, callback) {
var r = new XMLHttpRequest();
var error = this.error;
// Binary?
var binary = false;
if (method === 'blob') {
binary = method;
method = 'GET';
}
method = method.toUpperCase();
// Xhr.responseType 'json' is not supported in any of the vendors yet.
r.onload = function(e) {
var json = r.response;
try {
json = JSON.parse(r.responseText);
}
catch (_e) {
if (r.status === 401) {
json = error('access_denied', r.statusText);
}
}
var headers = headersToJSON(r.getAllResponseHeaders());
headers.statusCode = r.status;
callback(json || (method === 'GET' ? error('empty_response', 'Could not get resource') : {}), headers);
};
r.onerror = function(e) {
var json = r.responseText;
try {
json = JSON.parse(r.responseText);
}
catch (_e) {}
callback(json || error('access_denied', 'Could not get resource'));
};
var x;
// Should we add the query to the URL?
if (method === 'GET' || method === 'DELETE') {
data = null;
}
else if (data && typeof (data) !== 'string' && !(data instanceof FormData) && !(data instanceof File) && !(data instanceof Blob)) {
// Loop through and add formData
var f = new FormData();
for (x in data) if (data.hasOwnProperty(x)) {
if (data[x] instanceof HTMLInputElement) {
if ('files' in data[x] && data[x].files.length > 0) {
f.append(x, data[x].files[0]);
}
}
else if (data[x] instanceof Blob) {
f.append(x, data[x], data.name);
}
else {
f.append(x, data[x]);
}
}
data = f;
}
// Open the path, async
r.open(method, url, true);
if (binary) {
if ('responseType' in r) {
r.responseType = binary;
}
else {
r.overrideMimeType('text/plain; charset=x-user-defined');
}
}
// Set any bespoke headers
if (headers) {
for (x in headers) {
r.setRequestHeader(x, headers[x]);
}
}
r.send(data);
return r;
// Headers are returned as a string
function headersToJSON(s) {
var r = {};
var reg = /([a-z\-]+):\s?(.*);?/gi;
var m;
while ((m = reg.exec(s))) {
r[m[1]] = m[2];
}
return r;
}
},
// JSONP
// Injects a script tag into the DOM to be executed and appends a callback function to the window object
// @param string/function pathFunc either a string of the URL or a callback function pathFunc(querystringhash, continueFunc);
// @param function callback a function to call on completion;
jsonp: function(url, callback, callbackID, timeout) {
var _this = this;
var error = _this.error;
// Change the name of the callback
var bool = 0;
var head = document.getElementsByTagName('head')[0];
var operaFix;
var result = error('server_error', 'server_error');
var cb = function() {
if (!(bool++)) {
window.setTimeout(function() {
callback(result);
head.removeChild(script);
}, 0);
}
};
// Add callback to the window object
callbackID = _this.globalEvent(function(json) {
result = json;
return true;
// Mark callback as done
}, callbackID);
// The URL is a function for some cases and as such
// Determine its value with a callback containing the new parameters of this function.
url = url.replace(new RegExp('=\\?(&|$)'), '=' + callbackID + '$1');
// Build script tag
var script = _this.append('script', {
id: callbackID,
name: callbackID,
src: url,
async: true,
onload: cb,
onerror: cb,
onreadystatechange: function() {
if (/loaded|complete/i.test(this.readyState)) {
cb();
}
}
});
// Opera fix error
// Problem: If an error occurs with script loading Opera fails to trigger the script.onerror handler we specified
//
// Fix:
// By setting the request to synchronous we can trigger the error handler when all else fails.
// This action will be ignored if we've already called the callback handler "cb" with a successful onload event
if (window.navigator.userAgent.toLowerCase().indexOf('opera') > -1) {
operaFix = _this.append('script', {
text: 'document.getElementById(\'' + callbackID + '\').onerror();'
});
script.async = false;
}
// Add timeout
if (timeout) {
window.setTimeout(function() {
result = error('timeout', 'timeout');
cb();
}, timeout);
}
// TODO: add fix for IE,
// However: unable recreate the bug of firing off the onreadystatechange before the script content has been executed and the value of "result" has been defined.
// Inject script tag into the head element
head.appendChild(script);
// Append Opera Fix to run after our script
if (operaFix) {
head.appendChild(operaFix);
}
},
// Post
// Send information to a remote location using the post mechanism
// @param string uri path
// @param object data, key value data to send
// @param function callback, function to execute in response
post: function(url, data, options, callback, callbackID, timeout) {
var _this = this;
var error = _this.error;
var doc = document;
// This hack needs a form
var form = null;
var reenableAfterSubmit = [];
var newform;
var i = 0;
var x = null;
var bool = 0;
var cb = function(r) {
if (!(bool++)) {
callback(r);
}
};
// What is the name of the callback to contain
// We'll also use this to name the iframe
_this.globalEvent(cb, callbackID);
// Build the iframe window
var win;
try {
// IE7 hack, only lets us define the name here, not later.
win = doc.createElement('<iframe name="' + callbackID + '">');
}
catch (e) {
win = doc.createElement('iframe');
}
win.name = callbackID;
win.id = callbackID;
win.style.display = 'none';
// Override callback mechanism. Triggger a response onload/onerror
if (options && options.callbackonload) {
// Onload is being fired twice
win.onload = function() {
cb({
response: 'posted',
message: 'Content was posted'
});
};
}
if (timeout) {
setTimeout(function() {
cb(error('timeout', 'The post operation timed out'));
}, timeout);
}
doc.body.appendChild(win);
// If we are just posting a single item
if (_this.domInstance('form', data)) {
// Get the parent form
form = data.form;
// Loop through and disable all of its siblings
for (i = 0; i < form.elements.length; i++) {
if (form.elements[i] !== data) {
form.elements[i].setAttribute('disabled', true);
}
}
// Move the focus to the form
data = form;
}
// Posting a form
if (_this.domInstance('form', data)) {
// This is a form element
form = data;
// Does this form need to be a multipart form?
for (i = 0; i < form.elements.length; i++) {
if (!form.elements[i].disabled && form.elements[i].type === 'file') {
form.encoding = form.enctype = 'multipart/form-data';
form.elements[i].setAttribute('name', 'file');
}
}
}
else {
// Its not a form element,
// Therefore it must be a JSON object of Key=>Value or Key=>Element
// If anyone of those values are a input type=file we shall shall insert its siblings into the form for which it belongs.
for (x in data) if (data.hasOwnProperty(x)) {
// Is this an input Element?
if (_this.domInstance('input', data[x]) && data[x].type === 'file') {
form = data[x].form;
form.encoding = form.enctype = 'multipart/form-data';
}
}
// Do If there is no defined form element, lets create one.
if (!form) {
// Build form
form = doc.createElement('form');
doc.body.appendChild(form);
newform = form;
}
var input;
// Add elements to the form if they dont exist
for (x in data) if (data.hasOwnProperty(x)) {
// Is this an element?
var el = (_this.domInstance('input', data[x]) || _this.domInstance('textArea', data[x]) || _this.domInstance('select', data[x]));
// Is this not an input element, or one that exists outside the form.
if (!el || data[x].form !== form) {
// Does an element have the same name?
var inputs = form.elements[x];
if (input) {
// Remove it.
if (!(inputs instanceof NodeList)) {
inputs = [inputs];
}
for (i = 0; i < inputs.length; i++) {
inputs[i].parentNode.removeChild(inputs[i]);
}
}
// Create an input element
input = doc.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', x);
// Does it have a value attribute?
if (el) {
input.value = data[x].value;
}
else if (_this.domInstance(null, data[x])) {
input.value = data[x].innerHTML || data[x].innerText;
}
else {
input.value = data[x];
}
form.appendChild(input);
}
// It is an element, which exists within the form, but the name is wrong
else if (el && data[x].name !== x) {
data[x].setAttribute('name', x);
data[x].name = x;
}
}
// Disable elements from within the form if they weren't specified
for (i = 0; i < form.elements.length; i++) {
input = form.elements[i];
// Does the same name and value exist in the parent
if (!(input.name in data) && input.getAttribute('disabled') !== true) {
// Disable
input.setAttribute('disabled', true);
// Add re-enable to callback
reenableAfterSubmit.push(input);
}
}
}
// Set the target of the form
form.setAttribute('method', 'POST');
form.setAttribute('target', callbackID);
form.target = callbackID;
// Update the form URL
form.setAttribute('action', url);
// Submit the form
// Some reason this needs to be offset from the current window execution
setTimeout(function() {
form.submit();
setTimeout(function() {
try {
// Remove the iframe from the page.
//win.parentNode.removeChild(win);
// Remove the form
if (newform) {
newform.parentNode.removeChild(newform);
}
}
catch (e) {
try {
console.error('HelloJS: could not remove iframe');
}
catch (ee) {}
}
// Reenable the disabled form
for (var i = 0; i < reenableAfterSubmit.length; i++) {
if (reenableAfterSubmit[i]) {
reenableAfterSubmit[i].setAttribute('disabled', false);
reenableAfterSubmit[i].disabled = false;
}
}
}, 0);
}, 100);
},
// Some of the providers require that only multipart is used with non-binary forms.
// This function checks whether the form contains binary data
hasBinary: function(data) {
for (var x in data) if (data.hasOwnProperty(x)) {
if (this.isBinary(data[x])) {
return true;
}
}
return false;
},
// Determines if a variable Either Is or like a FormInput has the value of a Blob
isBinary: function(data) {
return data instanceof Object && (
(this.domInstance('input', data) && data.type === 'file') ||
('FileList' in window && data instanceof window.FileList) ||
('File' in window && data instanceof window.File) ||
('Blob' in window && data instanceof window.Blob));
},
// Convert Data-URI to Blob string
toBlob: function(dataURI) {
var reg = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i;
var m = dataURI.match(reg);
if (!m) {
return dataURI;
}
var binary = atob(dataURI.replace(reg, ''));
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: m[1]});
}
});
// EXTRA: Convert FormElement to JSON for POSTing
// Wrappers to add additional functionality to existing functions
(function(hello) {
// Copy original function
var api = hello.api;
var utils = hello.utils;
utils.extend(utils, {
// DataToJSON
// This takes a FormElement|NodeList|InputElement|MixedObjects and convers the data object to JSON.
dataToJSON: function(p) {
var _this = this;
var w = window;
var data = p.data;
// Is data a form object
if (_this.domInstance('form', data)) {
data = _this.nodeListToJSON(data.elements);
}
else if ('NodeList' in w && data instanceof NodeList) {
data = _this.nodeListToJSON(data);
}
else if (_this.domInstance('input', data)) {
data = _this.nodeListToJSON([data]);
}
// Is data a blob, File, FileList?
if (('File' in w && data instanceof w.File) ||
('Blob' in w && data instanceof w.Blob) ||
('FileList' in w && data instanceof w.FileList)) {
data = {file: data};
}
// Loop through data if it's not form data it must now be a JSON object
if (!('FormData' in w && data instanceof w.FormData)) {
for (var x in data) if (data.hasOwnProperty(x)) {
if ('FileList' in w && data[x] instanceof w.FileList) {
if (data[x].length === 1) {
data[x] = data[x][0];
}
}
else if (_this.domInstance('input', data[x]) && data[x].type === 'file') {
continue;
}
else if (_this.domInstance('input', data[x]) ||
_this.domInstance('select', data[x]) ||
_this.domInstance('textArea', data[x])) {
data[x] = data[x].value;
}
else if (_this.domInstance(null, data[x])) {
data[x] = data[x].innerHTML || data[x].innerText;
}
}
}
p.data = data;
return data;
},
// NodeListToJSON
// Given a list of elements extrapolate their values and return as a json object
nodeListToJSON: function(nodelist) {
var json = {};
// Create a data string
for (var i = 0; i < nodelist.length; i++) {
var input = nodelist[i];
// If the name of the input is empty or diabled, dont add it.
if (input.disabled || !input.name) {
continue;
}
// Is this a file, does the browser not support 'files' and 'FormData'?
if (input.type === 'file') {
json[input.name] = input;
}
else {
json[input.name] = input.value || input.innerHTML;
}
}
return json;
}
});
// Replace it
hello.api = function() {
// Get arguments
var p = utils.args({path: 's!', method: 's', data: 'o', timeout: 'i', callback: 'f'}, arguments);
// Change for into a data object
if (p.data) {
utils.dataToJSON(p);
}
return api.call(this, p);
};
})(hello);
/////////////////////////////////////
//
// Save any access token that is in the current page URL
// Handle any response solicited through iframe hash tag following an API request
//
/////////////////////////////////////
hello.utils.responseHandler(window, window.opener || window.parent);
// Script to support ChromeApps
// This overides the hello.utils.popup method to support chrome.identity.launchWebAuthFlow
// See https://developer.chrome.com/apps/app_identity#non
// Is this a chrome app?
if (typeof chrome === 'object' && typeof chrome.identity === 'object' && chrome.identity.launchWebAuthFlow) {
(function() {
// Swap the popup method
hello.utils.popup = function(url) {
return _open(url, true);
};
// Swap the hidden iframe method
hello.utils.iframe = function(url) {
_open(url, false);
};
// Swap the request_cors method
hello.utils.request_cors = function(callback) {
callback();
// Always run as CORS
return true;
};
// Swap the storage method
var _cache = {};
chrome.storage.local.get('hello', function(r) {
// Update the cache
_cache = r.hello || {};
});
hello.utils.store = function(name, value) {
// Get all
if (arguments.length === 0) {
return _cache;
}
// Get
if (arguments.length === 1) {
return _cache[name] || null;
}
// Set
if (value) {
_cache[name] = value;
chrome.storage.local.set({hello: _cache});
return value;
}
// Delete
if (value === null) {
delete _cache[name];
chrome.storage.local.set({hello: _cache});
return null;
}
};
// Open function
function _open(url, interactive) {
// Launch
var ref = {
closed: false
};
// Launch the webAuthFlow
chrome.identity.launchWebAuthFlow({
url: url,
interactive: interactive
}, function(responseUrl) {
// Did the user cancel this prematurely
if (responseUrl === undefined) {
ref.closed = true;
return;
}
// Split appart the URL
var a = hello.utils.url(responseUrl);
// The location can be augmented in to a location object like so...
// We dont have window operations on the popup so lets create some
var _popup = {
location: {
// Change the location of the popup
assign: function(url) {
// If there is a secondary reassign
// In the case of OAuth1
// Trigger this in non-interactive mode.
_open(url, false);
},
search: a.search,
hash: a.hash,
href: a.href
},
close: function() {}
};
// Then this URL contains information which HelloJS must process
// URL string
// Window - any action such as window relocation goes here
// Opener - the parent window which opened this, aka this script
hello.utils.responseHandler(_popup, window);
});
// Return the reference
return ref;
}
})();
}
// Phonegap override for hello.phonegap.js
(function() {
// Is this a phonegap implementation?
if (!(/^file:\/{3}[^\/]/.test(window.location.href) && window.cordova)) {
// Cordova is not included.
return;
}
// Augment the hidden iframe method
hello.utils.iframe = function(url, redirectUri) {
hello.utils.popup(url, redirectUri, {hidden: 'yes'});
};
// Augment the popup
var utilPopup = hello.utils.popup;
// Replace popup
hello.utils.popup = function(url, redirectUri, options) {
// Run the standard
var popup = utilPopup.call(this, url, redirectUri, options);
// Create a function for reopening the popup, and assigning events to the new popup object
// PhoneGap support
// Add an event listener to listen to the change in the popup windows URL
// This must appear before popup.focus();
try {
if (popup && popup.addEventListener) {
// Get the origin of the redirect URI
var a = hello.utils.url(redirectUri);
var redirectUriOrigin = a.origin || (a.protocol + '//' + a.hostname);
// Listen to changes in the InAppBrowser window
popup.addEventListener('loadstart', function(e) {
var url = e.url;
// Is this the path, as given by the redirectUri?
// Check the new URL agains the redirectUriOrigin.
// According to #63 a user could click 'cancel' in some dialog boxes ....
// The popup redirects to another page with the same origin, yet we still wish it to close.
if (url.indexOf(redirectUriOrigin) !== 0) {
return;
}
// Split appart the URL
var a = hello.utils.url(url);
// We dont have window operations on the popup so lets create some
// The location can be augmented in to a location object like so...
var _popup = {
location: {
// Change the location of the popup
assign: function(location) {
// Unfourtunatly an app is may not change the location of a InAppBrowser window.
// So to shim this, just open a new one.
popup.executeScript({code: 'window.location.href = "' + location + ';"'});
},
search: a.search,
hash: a.hash,
href: a.href
},
close: function() {
if (popup.close) {
popup.close();
try {
popup.closed = true;
}
catch (_e) {}
}
}
};
// Then this URL contains information which HelloJS must process
// URL string
// Window - any action such as window relocation goes here
// Opener - the parent window which opened this, aka this script
hello.utils.responseHandler(_popup, window);
});
}
}
catch (e) {}
return popup;
};
})();
(function(hello) {
// OAuth1
var OAuth1Settings = {
version: '1.0',
auth: 'https://www.dropbox.com/1/oauth/authorize',
request: 'https://api.dropbox.com/1/oauth/request_token',
token: 'https://api.dropbox.com/1/oauth/access_token'
};
// OAuth2 Settings
var OAuth2Settings = {
version: 2,
auth: 'https://www.dropbox.com/1/oauth2/authorize',
grant: 'https://api.dropbox.com/1/oauth2/token'
};
// Initiate the Dropbox module
hello.init({
dropbox: {
name: 'Dropbox',
oauth: OAuth2Settings,
login: function(p) {
// OAuth2 non-standard adjustments
p.qs.scope = '';
// Should this be run as OAuth1?
// If the redirect_uri is is HTTP (non-secure) then its required to revert to the OAuth1 endpoints
var redirect = decodeURIComponent(p.qs.redirect_uri);
if (redirect.indexOf('http:') === 0 && redirect.indexOf('http://localhost/') !== 0) {
// Override the dropbox OAuth settings.
hello.services.dropbox.oauth = OAuth1Settings;
}
else {
// Override the dropbox OAuth settings.
hello.services.dropbox.oauth = OAuth2Settings;
}
// The dropbox login window is a different size
p.options.popup.width = 1000;
p.options.popup.height = 1000;
},
/*
Dropbox does not allow insecure HTTP URI's in the redirect_uri field
...otherwise I'd love to use OAuth2
Follow request https://forums.dropbox.com/topic.php?id=106505
p.qs.response_type = 'code';
oauth: {
version: 2,
auth: 'https://www.dropbox.com/1/oauth2/authorize',
grant: 'https://api.dropbox.com/1/oauth2/token'
}
*/
// API Base URL
base: 'https://api.dropbox.com/1/',
// Bespoke setting: this is states whether to use the custom environment of Dropbox or to use their own environment
// Because it's notoriously difficult for Dropbox too provide access from other webservices, this defaults to Sandbox
root: 'sandbox',
// Map GET requests
get: {
me: 'account/info',
// Https://www.dropbox.com/developers/core/docs#metadata
'me/files': req('metadata/auto/@{parent|}'),
'me/folder': req('metadata/auto/@{id}'),
'me/folders': req('metadata/auto/'),
'default': function(p, callback) {
if (p.path.match('https://api-content.dropbox.com/1/files/')) {
// This is a file, return binary data
p.method = 'blob';
}
callback(p.path);
}
},
post: {
'me/files': function(p, callback) {
var path = p.data.parent;
var fileName = p.data.name;
p.data = {
file: p.data.file
};
// Does this have a data-uri to upload as a file?
if (typeof (p.data.file) === 'string') {
p.data.file = hello.utils.toBlob(p.data.file);
}
callback('https://api-content.dropbox.com/1/files_put/auto/' + path + '/' + fileName);
},
'me/folders': function(p, callback) {
var name = p.data.name;
p.data = {};
callback('fileops/create_folder?root=@{root|sandbox}&' + hello.utils.param({
path: name
}));
}
},
// Map DELETE requests
del: {
'me/files': 'fileops/delete?root=@{root|sandbox}&path=@{id}',
'me/folder': 'fileops/delete?root=@{root|sandbox}&path=@{id}'
},
wrap: {
me: function(o) {
formatError(o);
if (!o.uid) {
return o;
}
o.name = o.display_name;
var m = o.name.split(' ');
o.first_name = m.shift();
o.last_name = m.join(' ');
o.id = o.uid;
delete o.uid;
delete o.display_name;
return o;
},
'default': function(o, headers, req) {
formatError(o);
if (o.is_dir && o.contents) {
o.data = o.contents;
delete o.contents;
o.data.forEach(function(item) {
item.root = o.root;
formatFile(item, headers, req);
});
}
formatFile(o, headers, req);
if (o.is_deleted) {
o.success = true;
}
return o;
}
},
// Doesn't return the CORS headers
xhr: function(p) {
// The proxy supports allow-cross-origin-resource
// Alas that's the only thing we're using.
if (p.data && p.data.file) {
var file = p.data.file;
if (file) {
if (file.files) {
p.data = file.files[0];
}
else {
p.data = file;
}
}
}
if (p.method === 'delete') {
p.method = 'post';
}
return true;
},
form: function(p, qs) {
delete qs.state;
delete qs.redirect_uri;
}
}
});
function formatError(o) {
if (o && 'error' in o) {
o.error = {
code: 'server_error',
message: o.error.message || o.error
};
}
}
function formatFile(o, headers, req) {
if (typeof o !== 'object' ||
(typeof Blob !== 'undefined' && o instanceof Blob) ||
(typeof ArrayBuffer !== 'undefined' && o instanceof ArrayBuffer)) {
// This is a file, let it through unformatted
return;
}
if ('error' in o) {
return;
}
var path = (o.root !== 'app_folder' ? o.root : '') + o.path.replace(/\&/g, '%26');
path = path.replace(/^\//, '');
if (o.thumb_exists) {
o.thumbnail = req.oauth_proxy + '?path=' +
encodeURIComponent('https://api-content.dropbox.com/1/thumbnails/auto/' + path + '?format=jpeg&size=m') + '&access_token=' + req.options.access_token;
}
o.type = (o.is_dir ? 'folder' : o.mime_type);
o.name = o.path.replace(/.*\//g, '');
if (o.is_dir) {
o.files = path.replace(/^\//, '');
}
else {
o.downloadLink = hello.settings.oauth_proxy + '?path=' +
encodeURIComponent('https://api-content.dropbox.com/1/files/auto/' + path) + '&access_token=' + req.options.access_token;
o.file = 'https://api-content.dropbox.com/1/files/auto/' + path;
}
if (!o.id) {
o.id = o.path.replace(/^\//, '');
}
// O.media = 'https://api-content.dropbox.com/1/files/' + path;
}
function req(str) {
return function(p, cb) {
delete p.query.limit;
cb(str);
};
}
})(hello);
(function(hello) {
// For APIs, once a version is no longer usable, any calls made to it will be defaulted to the next oldest usable version.
// So we explicitly state it.
var version = 'v2.9';
hello.init({
facebook: {
name: 'Facebook',
// SEE https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
oauth: {
version: 2,
auth: 'https://www.facebook.com/' + version + '/dialog/oauth/',
grant: 'https://graph.facebook.com/oauth/access_token'
},
// Authorization scopes
scope: {
basic: 'public_profile',
email: 'email',
share: 'user_posts',
birthday: 'user_birthday',
events: 'user_events',
photos: 'user_photos',
videos: 'user_videos',
friends: 'user_friends',
files: 'user_photos,user_videos',
publish_files: 'user_photos,user_videos,publish_actions',
publish: 'publish_actions',
// Deprecated in v2.0
// Create_event: 'create_event',
offline_access: ''
},
// Refresh the access_token
refresh: false,
login: function(p) {
// Reauthenticate
// https://developers.facebook.com/docs/facebook-login/reauthentication
if (p.options.force) {
p.qs.auth_type = 'reauthenticate';
}
// Set the display value
p.qs.display = p.options.display || 'popup';
},
logout: function(callback, options) {
// Assign callback to a global handler
var callbackID = hello.utils.globalEvent(callback);
var redirect = encodeURIComponent(hello.settings.redirect_uri + '?' + hello.utils.param({callback: callbackID, result: JSON.stringify({force: true}), state: '{}'}));
var token = (options.authResponse || {}).access_token;
hello.utils.iframe('https://www.facebook.com/logout.php?next=' + redirect + '&access_token=' + token);
// Possible responses:
// String URL - hello.logout should handle the logout
// Undefined - this function will handle the callback
// True - throw a success, this callback isn't handling the callback
// False - throw a error
if (!token) {
// If there isn't a token, the above wont return a response, so lets trigger a response
return false;
}
},
// API Base URL
base: 'https://graph.facebook.com/' + version + '/',
// Map GET requests
get: {
me: 'me?fields=email,first_name,last_name,name,timezone,verified',
'me/friends': 'me/friends',
'me/following': 'me/friends',
'me/followers': 'me/friends',
'me/share': 'me/feed',
'me/like': 'me/likes',
'me/files': 'me/albums',
'me/albums': 'me/albums?fields=cover_photo,name',
'me/album': '@{id}/photos?fields=picture',
'me/photos': 'me/photos',
'me/photo': '@{id}',
'friend/albums': '@{id}/albums',
'friend/photos': '@{id}/photos'
// Pagination
// Https://developers.facebook.com/docs/reference/api/pagination/
},
// Map POST requests
post: {
'me/share': 'me/feed',
'me/photo': '@{id}'
// Https://developers.facebook.com/docs/graph-api/reference/v2.2/object/likes/
},
wrap: {
me: formatUser,
'me/friends': formatFriends,
'me/following': formatFriends,
'me/followers': formatFriends,
'me/albums': format,
'me/photos': format,
'me/files': format,
'default': format
},
// Special requirements for handling XHR
xhr: function(p, qs) {
if (p.method === 'get' || p.method === 'post') {
qs.suppress_response_codes = true;
}
// Is this a post with a data-uri?
if (p.method === 'post' && p.data && typeof (p.data.file) === 'string') {
// Convert the Data-URI to a Blob
p.data.file = hello.utils.toBlob(p.data.file);
}
return true;
},
// Special requirements for handling JSONP fallback
jsonp: function(p, qs) {
var m = p.method;
if (m !== 'get' && !hello.utils.hasBinary(p.data)) {
p.data.method = m;
p.method = 'get';
}
else if (p.method === 'delete') {
qs.method = 'delete';
p.method = 'post';
}
},
// Special requirements for iframe form hack
form: function(p) {
return {
// Fire the callback onload
callbackonload: true
};
}
}
});
var base = 'https://graph.facebook.com/';
function formatUser(o) {
if (o.id) {
o.thumbnail = o.picture = 'https://graph.facebook.com/' + o.id + '/picture';
}
return o;
}
function formatFriends(o) {
if ('data' in o) {
o.data.forEach(formatUser);
}
return o;
}
function format(o, headers, req) {
if (typeof o === 'boolean') {
o = {success: o};
}
if (o && 'data' in o) {
var token = req.query.access_token;
if (!(o.data instanceof Array)) {
var data = o.data;
delete o.data;
o.data = [data];
}
o.data.forEach(function(d) {
if (d.picture) {
d.thumbnail = d.picture;
}
d.pictures = (d.images || [])
.sort(function(a, b) {
return a.width - b.width;
});
if (d.cover_photo && d.cover_photo.id) {
d.thumbnail = base + d.cover_photo.id + '/picture?access_token=' + token;
}
if (d.type === 'album') {
d.files = d.photos = base + d.id + '/photos';
}
if (d.can_upload) {
d.upload_location = base + d.id + '/photos';
}
});
}
return o;
}
})(hello);
(function(hello) {
hello.init({
flickr: {
name: 'Flickr',
// Ensure that you define an oauth_proxy
oauth: {
version: '1.0a',
auth: 'https://www.flickr.com/services/oauth/authorize?perms=read',
request: 'https://www.flickr.com/services/oauth/request_token',
token: 'https://www.flickr.com/services/oauth/access_token'
},
// API base URL
base: 'https://api.flickr.com/services/rest',
// Map GET resquests
get: {
me: sign('flickr.people.getInfo'),
'me/friends': sign('flickr.contacts.getList', {per_page: '@{limit|50}'}),
'me/following': sign('flickr.contacts.getList', {per_page: '@{limit|50}'}),
'me/followers': sign('flickr.contacts.getList', {per_page: '@{limit|50}'}),
'me/albums': sign('flickr.photosets.getList', {per_page: '@{limit|50}'}),
'me/album': sign('flickr.photosets.getPhotos', {photoset_id: '@{id}'}),
'me/photos': sign('flickr.people.getPhotos', {per_page: '@{limit|50}'})
},
wrap: {
me: function(o) {
formatError(o);
o = checkResponse(o, 'person');
if (o.id) {
if (o.realname) {
o.name = o.realname._content;
var m = o.name.split(' ');
o.first_name = m.shift();
o.last_name = m.join(' ');
}
o.thumbnail = getBuddyIcon(o, 'l');
o.picture = getBuddyIcon(o, 'l');
}
return o;
},
'me/friends': formatFriends,
'me/followers': formatFriends,
'me/following': formatFriends,
'me/albums': function(o) {
formatError(o);
o = checkResponse(o, 'photosets');
paging(o);
if (o.photoset) {
o.data = o.photoset;
o.data.forEach(function(item) {
item.name = item.title._content;
item.photos = 'https://api.flickr.com/services/rest' + getApiUrl('flickr.photosets.getPhotos', {photoset_id: item.id}, true);
});
delete o.photoset;
}
return o;
},
'me/photos': function(o) {
formatError(o);
return formatPhotos(o);
},
'default': function(o) {
formatError(o);
return formatPhotos(o);
}
},
xhr: false,
jsonp: function(p, qs) {
if (p.method == 'get') {
delete qs.callback;
qs.jsoncallback = p.callbackID;
}
}
}
});
function getApiUrl(method, extraParams, skipNetwork) {
var url = ((skipNetwork) ? '' : 'flickr:') +
'?method=' + method +
'&api_key=' + hello.services.flickr.id +
'&format=json';
for (var param in extraParams) {
if (extraParams.hasOwnProperty(param)) {
url += '&' + param + '=' + extraParams[param];
}
}
return url;
}
// This is not exactly neat but avoid to call
// The method 'flickr.test.login' for each api call
function withUser(cb) {
var auth = hello.getAuthResponse('flickr');
cb(auth && auth.user_nsid ? auth.user_nsid : null);
}
function sign(url, params) {
if (!params) {
params = {};
}
return function(p, callback) {
withUser(function(userId) {
params.user_id = userId;
callback(getApiUrl(url, params, true));
});
};
}
function getBuddyIcon(profile, size) {
var url = 'https://www.flickr.com/images/buddyicon.gif';
if (profile.nsid && profile.iconserver && profile.iconfarm) {
url = 'https://farm' + profile.iconfarm + '.staticflickr.com/' +
profile.iconserver + '/' +
'buddyicons/' + profile.nsid +
((size) ? '_' + size : '') + '.jpg';
}
return url;
}
// See: https://www.flickr.com/services/api/misc.urls.html
function createPhotoUrl(id, farm, server, secret, size) {
size = (size) ? '_' + size : '';
return 'https://farm' + farm + '.staticflickr.com/' + server + '/' + id + '_' + secret + size + '.jpg';
}
function formatUser(o) {
}
function formatError(o) {
if (o && o.stat && o.stat.toLowerCase() != 'ok') {
o.error = {
code: 'invalid_request',
message: o.message
};
}
}
function formatPhotos(o) {
if (o.photoset || o.photos) {
var set = ('photoset' in o) ? 'photoset' : 'photos';
o = checkResponse(o, set);
paging(o);
o.data = o.photo;
delete o.photo;
for (var i = 0; i < o.data.length; i++) {
var photo = o.data[i];
photo.name = photo.title;
photo.picture = createPhotoUrl(photo.id, photo.farm, photo.server, photo.secret, '');
photo.pictures = createPictures(photo.id, photo.farm, photo.server, photo.secret);
photo.source = createPhotoUrl(photo.id, photo.farm, photo.server, photo.secret, 'b');
photo.thumbnail = createPhotoUrl(photo.id, photo.farm, photo.server, photo.secret, 'm');
}
}
return o;
}
// See: https://www.flickr.com/services/api/misc.urls.html
function createPictures(id, farm, server, secret) {
var NO_LIMIT = 2048;
var sizes = [
{id: 't', max: 100},
{id: 'm', max: 240},
{id: 'n', max: 320},
{id: '', max: 500},
{id: 'z', max: 640},
{id: 'c', max: 800},
{id: 'b', max: 1024},
{id: 'h', max: 1600},
{id: 'k', max: 2048},
{id: 'o', max: NO_LIMIT}
];
return sizes.map(function(size) {
return {
source: createPhotoUrl(id, farm, server, secret, size.id),
// Note: this is a guess that's almost certain to be wrong (unless square source)
width: size.max,
height: size.max
};
});
}
function checkResponse(o, key) {
if (key in o) {
o = o[key];
}
else if (!('error' in o)) {
o.error = {
code: 'invalid_request',
message: o.message || 'Failed to get data from Flickr'
};
}
return o;
}
function formatFriends(o) {
formatError(o);
if (o.contacts) {
o = checkResponse(o, 'contacts');
paging(o);
o.data = o.contact;
delete o.contact;
for (var i = 0; i < o.data.length; i++) {
var item = o.data[i];
item.id = item.nsid;
item.name = item.realname || item.username;
item.thumbnail = getBuddyIcon(item, 'm');
}
}
return o;
}
function paging(res) {
if (res.page && res.pages && res.page !== res.pages) {
res.paging = {
next: '?page=' + (++res.page)
};
}
}
})(hello);
(function(hello) {
hello.init({
foursquare: {
name: 'Foursquare',
oauth: {
// See: https://developer.foursquare.com/overview/auth
version: 2,
auth: 'https://foursquare.com/oauth2/authenticate',
grant: 'https://foursquare.com/oauth2/access_token'
},
// Refresh the access_token once expired
refresh: true,
base: 'https://api.foursquare.com/v2/',
get: {
me: 'users/self',
'me/friends': 'users/self/friends',
'me/followers': 'users/self/friends',
'me/following': 'users/self/friends'
},
wrap: {
me: function(o) {
formatError(o);
if (o && o.response) {
o = o.response.user;
formatUser(o);
}
return o;
},
'default': function(o) {
formatError(o);
// Format friends
if (o && 'response' in o && 'friends' in o.response && 'items' in o.response.friends) {
o.data = o.response.friends.items;
o.data.forEach(formatUser);
delete o.response;
}
return o;
}
},
xhr: formatRequest,
jsonp: formatRequest
}
});
function formatError(o) {
if (o.meta && (o.meta.code === 400 || o.meta.code === 401)) {
o.error = {
code: 'access_denied',
message: o.meta.errorDetail
};
}
}
function formatUser(o) {
if (o && o.id) {
o.thumbnail = o.photo.prefix + '100x100' + o.photo.suffix;
o.name = o.firstName + ' ' + o.lastName;
o.first_name = o.firstName;
o.last_name = o.lastName;
if (o.contact) {
if (o.contact.email) {
o.email = o.contact.email;
}
}
}
}
function formatRequest(p, qs) {
var token = qs.access_token;
delete qs.access_token;
qs.oauth_token = token;
qs.v = 20121125;
return true;
}
})(hello);
(function(hello) {
hello.init({
github: {
name: 'GitHub',
oauth: {
version: 2,
auth: 'https://github.com/login/oauth/authorize',
grant: 'https://github.com/login/oauth/access_token',
response_type: 'code'
},
scope: {
email: 'user:email'
},
base: 'https://api.github.com/',
get: {
me: 'user',
'me/friends': 'user/following?per_page=@{limit|100}',
'me/following': 'user/following?per_page=@{limit|100}',
'me/followers': 'user/followers?per_page=@{limit|100}',
'me/like': 'user/starred?per_page=@{limit|100}'
},
wrap: {
me: function(o, headers) {
formatError(o, headers);
formatUser(o);
return o;
},
'default': function(o, headers, req) {
formatError(o, headers);
if (Array.isArray(o)) {
o = {data: o};
}
if (o.data) {
paging(o, headers, req);
o.data.forEach(formatUser);
}
return o;
}
},
xhr: function(p) {
if (p.method !== 'get' && p.data) {
// Serialize payload as JSON
p.headers = p.headers || {};
p.headers['Content-Type'] = 'application/json';
if (typeof (p.data) === 'object') {
p.data = JSON.stringify(p.data);
}
}
return true;
}
}
});
function formatError(o, headers) {
var code = headers ? headers.statusCode : (o && 'meta' in o && 'status' in o.meta && o.meta.status);
if ((code === 401 || code === 403)) {
o.error = {
code: 'access_denied',
message: o.message || (o.data ? o.data.message : 'Could not get response')
};
delete o.message;
}
}
function formatUser(o) {
if (o.id) {
o.thumbnail = o.picture = o.avatar_url;
o.name = o.login;
}
}
function paging(res, headers, req) {
if (res.data && res.data.length && headers && headers.Link) {
var next = headers.Link.match(/<(.*?)>;\s*rel=\"next\"/);
if (next) {
res.paging = {
next: next[1]
};
}
}
}
})(hello);
(function(hello) {
var contactsUrl = 'https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json&max-results=@{limit|1000}&start-index=@{start|1}';
hello.init({
google: {
name: 'Google Sign-In',
// See: http://code.google.com/apis/accounts/docs/OAuth2UserAgent.html
oauth: {
version: 2,
auth: 'https://accounts.google.com/o/oauth2/v2/auth',
grant: 'https://www.googleapis.com/oauth2/v4/token'
},
// Authorization scopes
scope: {
basic: 'openid profile',
email: 'email',
birthday: '',
events: '',
photos: 'https://picasaweb.google.com/data/',
videos: 'http://gdata.youtube.com',
files: 'https://www.googleapis.com/auth/drive.readonly',
publish: '',
publish_files: 'https://www.googleapis.com/auth/drive',
share: '',
create_event: '',
offline_access: ''
},
scope_delim: ' ',
login: function(p) {
if (p.qs.response_type === 'code') {
// Let's set this to an offline access to return a refresh_token
p.qs.access_type = 'offline';
}
else if (p.qs.response_type.indexOf('id_token') > -1) {
p.qs.nonce = parseInt(Math.random() * 1e12, 10).toString(36);
}
// Reauthenticate
// https://developers.google.com/identity/protocols/
if (p.options.force) {
p.qs.prompt = 'consent';
}
},
// API base URI
base: 'https://www.googleapis.com/',
// Map GET requests
get: {
me: 'oauth2/v3/userinfo?alt=json',
// Deprecated Sept 1, 2014
//'me': 'oauth2/v1/userinfo?alt=json',
// See: https://developers.google.com/+/api/latest/people/list
'me/following': contactsUrl,
'me/followers': contactsUrl,
'me/contacts': contactsUrl,
'me/albums': 'https://picasaweb.google.com/data/feed/api/user/default?alt=json&max-results=@{limit|100}&start-index=@{start|1}',
'me/album': function(p, callback) {
var key = p.query.id;
delete p.query.id;
callback(key.replace('/entry/', '/feed/'));
},
'me/photos': 'https://picasaweb.google.com/data/feed/api/user/default?alt=json&kind=photo&max-results=@{limit|100}&start-index=@{start|1}',
// See: https://developers.google.com/drive/v2/reference/files/list
'me/file': 'drive/v2/files/@{id}',
'me/files': 'drive/v2/files?q=%22@{parent|root}%22+in+parents+and+trashed=false&maxResults=@{limit|100}',
// See: https://developers.google.com/drive/v2/reference/files/list
'me/folders': 'drive/v2/files?q=%22@{id|root}%22+in+parents+and+mimeType+=+%22application/vnd.google-apps.folder%22+and+trashed=false&maxResults=@{limit|100}',
// See: https://developers.google.com/drive/v2/reference/files/list
'me/folder': 'drive/v2/files?q=%22@{id|root}%22+in+parents+and+trashed=false&maxResults=@{limit|100}'
},
// Map POST requests
post: {
// Google Drive
'me/files': uploadDrive,
'me/folders': function(p, callback) {
p.data = {
title: p.data.name,
parents: [{id: p.data.parent || 'root'}],
mimeType: 'application/vnd.google-apps.folder'
};
callback('drive/v2/files');
}
},
// Map PUT requests
put: {
'me/files': uploadDrive
},
// Map DELETE requests
del: {
'me/files': 'drive/v2/files/@{id}',
'me/folder': 'drive/v2/files/@{id}'
},
// Map PATCH requests
patch: {
'me/file': 'drive/v2/files/@{id}'
},
wrap: {
me: function(o) {
if (o.sub) {
o.id = o.sub;
}
if (o.id) {
o.last_name = o.family_name || (o.name ? o.name.familyName : null);
o.first_name = o.given_name || (o.name ? o.name.givenName : null);
if (o.emails && o.emails.length) {
o.email = o.emails[0].value;
}
formatPerson(o);
}
return o;
},
'me/friends': function(o) {
if (o.items) {
paging(o);
o.data = o.items;
o.data.forEach(formatPerson);
delete o.items;
}
return o;
},
'me/contacts': formatFriends,
'me/followers': formatFriends,
'me/following': formatFriends,
'me/share': formatFeed,
'me/feed': formatFeed,
'me/albums': gEntry,
'me/photos': formatPhotos,
'default': gEntry
},
xhr: function(p) {
if (p.method === 'post' || p.method === 'put') {
toJSON(p);
}
else if (p.method === 'patch') {
hello.utils.extend(p.query, p.data);
p.data = null;
}
return true;
},
// Don't even try submitting via form.
// This means no POST operations in <=IE9
form: false
}
});
function toInt(s) {
return parseInt(s, 10);
}
function formatFeed(o) {
paging(o);
o.data = o.items;
delete o.items;
return o;
}
// Format: ensure each record contains a name, id etc.
function formatItem(o) {
if (o.error) {
return;
}
if (!o.name) {
o.name = o.title || o.message;
}
if (!o.picture) {
o.picture = o.thumbnailLink;
}
if (!o.thumbnail) {
o.thumbnail = o.thumbnailLink;
}
if (o.mimeType === 'application/vnd.google-apps.folder') {
o.type = 'folder';
o.files = 'https://www.googleapis.com/drive/v2/files?q=%22' + o.id + '%22+in+parents';
}
return o;
}
function formatImage(image) {
return {
source: image.url,
width: image.width,
height: image.height
};
}
function formatPhotos(o) {
if ('feed' in o) {
o.data = 'entry' in o.feed ? o.feed.entry.map(formatEntry) : [];
delete o.feed;
}
return o;
}
// Google has a horrible JSON API
function gEntry(o) {
paging(o);
if ('feed' in o && 'entry' in o.feed) {
o.data = o.feed.entry.map(formatEntry);
delete o.feed;
}
// Old style: Picasa, etc.
else if ('entry' in o) {
return formatEntry(o.entry);
}
// New style: Google Drive
else if ('items' in o) {
o.data = o.items.map(formatItem);
delete o.items;
}
else {
formatItem(o);
}
return o;
}
function formatPerson(o) {
o.name = o.displayName || o.name;
o.picture = o.picture || (o.image ? o.image.url : null);
o.thumbnail = o.picture;
}
function formatFriends(o, headers, req) {
paging(o);
var r = [];
if ('feed' in o && 'entry' in o.feed) {
var token = req.query.access_token;
for (var i = 0; i < o.feed.entry.length; i++) {
var a = o.feed.entry[i];
a.id = a.id.$t;
a.name = a.title.$t;
delete a.title;
if (a.gd$email) {
a.email = (a.gd$email && a.gd$email.length > 0) ? a.gd$email[0].address : null;
a.emails = a.gd$email;
delete a.gd$email;
}
if (a.updated) {
a.updated = a.updated.$t;
}
if (a.link) {
var pic = (a.link.length > 0) ? a.link[0].href : null;
if (pic && a.link[0].gd$etag) {
pic += (pic.indexOf('?') > -1 ? '&' : '?') + 'access_token=' + token;
a.picture = pic;
a.thumbnail = pic;
}
delete a.link;
}
if (a.category) {
delete a.category;
}
}
o.data = o.feed.entry;
delete o.feed;
}
return o;
}
function formatEntry(a) {
var group = a.media$group;
var photo = group.media$content.length ? group.media$content[0] : {};
var mediaContent = group.media$content || [];
var mediaThumbnail = group.media$thumbnail || [];
var pictures = mediaContent
.concat(mediaThumbnail)
.map(formatImage)
.sort(function(a, b) {
return a.width - b.width;
});
var i = 0;
var _a;
var p = {
id: a.id.$t,
name: a.title.$t,
description: a.summary.$t,
updated_time: a.updated.$t,
created_time: a.published.$t,
picture: photo ? photo.url : null,
pictures: pictures,
images: [],
thumbnail: photo ? photo.url : null,
width: photo.width,
height: photo.height
};
// Get feed/children
if ('link' in a) {
for (i = 0; i < a.link.length; i++) {
var d = a.link[i];
if (d.rel.match(/\#feed$/)) {
p.upload_location = p.files = p.photos = d.href;
break;
}
}
}
// Get images of different scales
if ('category' in a && a.category.length) {
_a = a.category;
for (i = 0; i < _a.length; i++) {
if (_a[i].scheme && _a[i].scheme.match(/\#kind$/)) {
p.type = _a[i].term.replace(/^.*?\#/, '');
}
}
}
// Get images of different scales
if ('media$thumbnail' in group && group.media$thumbnail.length) {
_a = group.media$thumbnail;
p.thumbnail = _a[0].url;
p.images = _a.map(formatImage);
}
_a = group.media$content;
if (_a && _a.length) {
p.images.push(formatImage(_a[0]));
}
return p;
}
function paging(res) {
// Contacts V2
if ('feed' in res && res.feed.openSearch$itemsPerPage) {
var limit = toInt(res.feed.openSearch$itemsPerPage.$t);
var start = toInt(res.feed.openSearch$startIndex.$t);
var total = toInt(res.feed.openSearch$totalResults.$t);
if ((start + limit) < total) {
res.paging = {
next: '?start=' + (start + limit)
};
}
}
else if ('nextPageToken' in res) {
res.paging = {
next: '?pageToken=' + res.nextPageToken
};
}
}
// Construct a multipart message
function Multipart() {
// Internal body
var body = [];
var boundary = (Math.random() * 1e10).toString(32);
var counter = 0;
var lineBreak = '\r\n';
var delim = lineBreak + '--' + boundary;
var ready = function() {};
var dataUri = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i;
// Add file
function addFile(item) {
var fr = new FileReader();
fr.onload = function(e) {
addContent(btoa(e.target.result), item.type + lineBreak + 'Content-Transfer-Encoding: base64');
};
fr.readAsBinaryString(item);
}
// Add content
function addContent(content, type) {
body.push(lineBreak + 'Content-Type: ' + type + lineBreak + lineBreak + content);
counter--;
ready();
}
// Add new things to the object
this.append = function(content, type) {
// Does the content have an array
if (typeof (content) === 'string' || !('length' in Object(content))) {
// Converti to multiples
content = [content];
}
for (var i = 0; i < content.length; i++) {
counter++;
var item = content[i];
// Is this a file?
// Files can be either Blobs or File types
if (
(typeof (File) !== 'undefined' && item instanceof File) ||
(typeof (Blob) !== 'undefined' && item instanceof Blob)
) {
// Read the file in
addFile(item);
}
// Data-URI?
// Data:[<mime type>][;charset=<charset>][;base64],<encoded data>
// /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i
else if (typeof (item) === 'string' && item.match(dataUri)) {
var m = item.match(dataUri);
addContent(item.replace(dataUri, ''), m[1] + lineBreak + 'Content-Transfer-Encoding: base64');
}
// Regular string
else {
addContent(item, type);
}
}
};
this.onready = function(fn) {
ready = function() {
if (counter === 0) {
// Trigger ready
body.unshift('');
body.push('--');
fn(body.join(delim), boundary);
body = [];
}
};
ready();
};
}
// Upload to Drive
// If this is PUT then only augment the file uploaded
// PUT https://developers.google.com/drive/v2/reference/files/update
// POST https://developers.google.com/drive/manage-uploads
function uploadDrive(p, callback) {
var data = {};
// Test for DOM element
if (p.data &&
(typeof (HTMLInputElement) !== 'undefined' && p.data instanceof HTMLInputElement)
) {
p.data = {file: p.data};
}
if (!p.data.name && Object(Object(p.data.file).files).length && p.method === 'post') {
p.data.name = p.data.file.files[0].name;
}
if (p.method === 'post') {
p.data = {
title: p.data.name,
parents: [{id: p.data.parent || 'root'}],
file: p.data.file
};
}
else {
// Make a reference
data = p.data;
p.data = {};
// Add the parts to change as required
if (data.parent) {
p.data.parents = [{id: p.data.parent || 'root'}];
}
if (data.file) {
p.data.file = data.file;
}
if (data.name) {
p.data.title = data.name;
}
}
// Extract the file, if it exists from the data object
// If the File is an INPUT element lets just concern ourselves with the NodeList
var file;
if ('file' in p.data) {
file = p.data.file;
delete p.data.file;
if (typeof (file) === 'object' && 'files' in file) {
// Assign the NodeList
file = file.files;
}
if (!file || !file.length) {
callback({
error: {
code: 'request_invalid',
message: 'There were no files attached with this request to upload'
}
});
return;
}
}
// Set type p.data.mimeType = Object(file[0]).type || 'application/octet-stream';
// Construct a multipart message
var parts = new Multipart();
parts.append(JSON.stringify(p.data), 'application/json');
// Read the file into a base64 string... yep a hassle, i know
// FormData doesn't let us assign our own Multipart headers and HTTP Content-Type
// Alas GoogleApi need these in a particular format
if (file) {
parts.append(file);
}
parts.onready(function(body, boundary) {
p.headers['content-type'] = 'multipart/related; boundary="' + boundary + '"';
p.data = body;
callback('upload/drive/v2/files' + (data.id ? '/' + data.id : '') + '?uploadType=multipart');
});
}
function toJSON(p) {
if (typeof (p.data) === 'object') {
// Convert the POST into a javascript object
try {
p.data = JSON.stringify(p.data);
p.headers['content-type'] = 'application/json';
}
catch (e) {}
}
}
})(hello);
(function(hello) {
hello.init({
instagram: {
name: 'Instagram',
oauth: {
// See: http://instagram.com/developer/authentication/
version: 2,
auth: 'https://instagram.com/oauth/authorize/',
grant: 'https://api.instagram.com/oauth/access_token'
},
// Refresh the access_token once expired
refresh: true,
scope: {
basic: 'basic',
photos: '',
friends: 'relationships',
publish: 'likes comments',
email: '',
share: '',
publish_files: '',
files: '',
videos: '',
offline_access: ''
},
scope_delim: ' ',
base: 'https://api.instagram.com/v1/',
get: {
me: 'users/self',
'me/feed': 'users/self/feed?count=@{limit|100}',
'me/photos': 'users/self/media/recent?min_id=0&count=@{limit|100}',
'me/friends': 'users/self/follows?count=@{limit|100}',
'me/following': 'users/self/follows?count=@{limit|100}',
'me/followers': 'users/self/followed-by?count=@{limit|100}',
'friend/photos': 'users/@{id}/media/recent?min_id=0&count=@{limit|100}'
},
post: {
'me/like': function(p, callback) {
var id = p.data.id;
p.data = {};
callback('media/' + id + '/likes');
}
},
del: {
'me/like': 'media/@{id}/likes'
},
wrap: {
me: function(o) {
formatError(o);
if ('data' in o) {
o.id = o.data.id;
o.thumbnail = o.data.profile_picture;
o.name = o.data.full_name || o.data.username;
}
return o;
},
'me/friends': formatFriends,
'me/following': formatFriends,
'me/followers': formatFriends,
'me/photos': function(o) {
formatError(o);
paging(o);
if ('data' in o) {
o.data = o.data.filter(function(d) {
return d.type === 'image';
});
o.data.forEach(function(d) {
d.name = d.caption ? d.caption.text : null;
d.thumbnail = d.images.thumbnail.url;
d.picture = d.images.standard_resolution.url;
d.pictures = Object.keys(d.images)
.map(function(key) {
var image = d.images[key];
return formatImage(image);
})
.sort(function(a, b) {
return a.width - b.width;
});
});
}
return o;
},
'default': function(o) {
o = formatError(o);
paging(o);
return o;
}
},
// Instagram does not return any CORS Headers
// So besides JSONP we're stuck with proxy
xhr: function(p, qs) {
var method = p.method;
var proxy = method !== 'get';
if (proxy) {
if ((method === 'post' || method === 'put') && p.query.access_token) {
p.data.access_token = p.query.access_token;
delete p.query.access_token;
}
// No access control headers
// Use the proxy instead
p.proxy = proxy;
}
return proxy;
},
// No form
form: false
}
});
function formatImage(image) {
return {
source: image.url,
width: image.width,
height: image.height
};
}
function formatError(o) {
if (typeof o === 'string') {
return {
error: {
code: 'invalid_request',
message: o
}
};
}
if (o && 'meta' in o && 'error_type' in o.meta) {
o.error = {
code: o.meta.error_type,
message: o.meta.error_message
};
}
return o;
}
function formatFriends(o) {
paging(o);
if (o && 'data' in o) {
o.data.forEach(formatFriend);
}
return o;
}
function formatFriend(o) {
if (o.id) {
o.thumbnail = o.profile_picture;
o.name = o.full_name || o.username;
}
}
// See: http://instagram.com/developer/endpoints/
function paging(res) {
if ('pagination' in res) {
res.paging = {
next: res.pagination.next_url
};
delete res.pagination;
}
}
})(hello);
(function(hello) {
hello.init({
joinme: {
name: 'join.me',
oauth: {
version: 2,
auth: 'https://secure.join.me/api/public/v1/auth/oauth2',
grant: 'https://secure.join.me/api/public/v1/auth/oauth2'
},
refresh: false,
scope: {
basic: 'user_info',
user: 'user_info',
scheduler: 'scheduler',
start: 'start_meeting',
email: '',
friends: '',
share: '',
publish: '',
photos: '',
publish_files: '',
files: '',
videos: '',
offline_access: ''
},
scope_delim: ' ',
login: function(p) {
p.options.popup.width = 400;
p.options.popup.height = 700;
},
base: 'https://api.join.me/v1/',
get: {
me: 'user',
meetings: 'meetings',
'meetings/info': 'meetings/@{id}'
},
post: {
'meetings/start/adhoc': function(p, callback) {
callback('meetings/start');
},
'meetings/start/scheduled': function(p, callback) {
var meetingId = p.data.meetingId;
p.data = {};
callback('meetings/' + meetingId + '/start');
},
'meetings/schedule': function(p, callback) {
callback('meetings');
}
},
patch: {
'meetings/update': function(p, callback) {
callback('meetings/' + p.data.meetingId);
}
},
del: {
'meetings/delete': 'meetings/@{id}'
},
wrap: {
me: function(o, headers) {
formatError(o, headers);
if (!o.email) {
return o;
}
o.name = o.fullName;
o.first_name = o.name.split(' ')[0];
o.last_name = o.name.split(' ')[1];
o.id = o.email;
return o;
},
'default': function(o, headers) {
formatError(o, headers);
return o;
}
},
xhr: formatRequest
}
});
function formatError(o, headers) {
var errorCode;
var message;
var details;
if (o && ('Message' in o)) {
message = o.Message;
delete o.Message;
if ('ErrorCode' in o) {
errorCode = o.ErrorCode;
delete o.ErrorCode;
}
else {
errorCode = getErrorCode(headers);
}
o.error = {
code: errorCode,
message: message,
details: o
};
}
return o;
}
function formatRequest(p, qs) {
// Move the access token from the request body to the request header
var token = qs.access_token;
delete qs.access_token;
p.headers.Authorization = 'Bearer ' + token;
// Format non-get requests to indicate json body
if (p.method !== 'get' && p.data) {
p.headers['Content-Type'] = 'application/json';
if (typeof (p.data) === 'object') {
p.data = JSON.stringify(p.data);
}
}
if (p.method === 'put') {
p.method = 'patch';
}
return true;
}
function getErrorCode(headers) {
switch (headers.statusCode) {
case 400:
return 'invalid_request';
case 403:
return 'stale_token';
case 401:
return 'invalid_token';
case 500:
return 'server_error';
default:
return 'server_error';
}
}
}(hello));
(function(hello) {
hello.init({
linkedin: {
oauth: {
version: 2,
response_type: 'code',
auth: 'https://www.linkedin.com/uas/oauth2/authorization',
grant: 'https://www.linkedin.com/uas/oauth2/accessToken'
},
// Refresh the access_token once expired
refresh: true,
scope: {
basic: 'r_basicprofile',
email: 'r_emailaddress',
files: '',
friends: '',
photos: '',
publish: 'w_share',
publish_files: 'w_share',
share: '',
videos: '',
offline_access: ''
},
scope_delim: ' ',
base: 'https://api.linkedin.com/v1/',
get: {
me: 'people/~:(picture-url,first-name,last-name,id,formatted-name,email-address)',
// See: http://developer.linkedin.com/documents/get-network-updates-and-statistics-api
'me/share': 'people/~/network/updates?count=@{limit|250}'
},
post: {
// See: https://developer.linkedin.com/documents/api-requests-json
'me/share': function(p, callback) {
var data = {
visibility: {
code: 'anyone'
}
};
if (p.data.id) {
data.attribution = {
share: {
id: p.data.id
}
};
}
else {
data.comment = p.data.message;
if (p.data.picture && p.data.link) {
data.content = {
'submitted-url': p.data.link,
'submitted-image-url': p.data.picture
};
}
}
p.data = JSON.stringify(data);
callback('people/~/shares?format=json');
},
'me/like': like
},
del: {
'me/like': like
},
wrap: {
me: function(o) {
formatError(o);
formatUser(o);
return o;
},
'me/friends': formatFriends,
'me/following': formatFriends,
'me/followers': formatFriends,
'me/share': function(o) {
formatError(o);
paging(o);
if (o.values) {
o.data = o.values.map(formatUser);
o.data.forEach(function(item) {
item.message = item.headline;
});
delete o.values;
}
return o;
},
'default': function(o, headers) {
formatError(o);
empty(o, headers);
paging(o);
}
},
jsonp: function(p, qs) {
formatQuery(qs);
if (p.method === 'get') {
qs.format = 'jsonp';
qs['error-callback'] = p.callbackID;
}
},
xhr: function(p, qs) {
if (p.method !== 'get') {
formatQuery(qs);
p.headers['Content-Type'] = 'application/json';
// Note: x-li-format ensures error responses are not returned in XML
p.headers['x-li-format'] = 'json';
p.proxy = true;
return true;
}
return false;
}
}
});
function formatError(o) {
if (o && 'errorCode' in o) {
o.error = {
code: o.status,
message: o.message
};
}
}
function formatUser(o) {
if (o.error) {
return;
}
o.first_name = o.firstName;
o.last_name = o.lastName;
o.name = o.formattedName || (o.first_name + ' ' + o.last_name);
o.thumbnail = o.pictureUrl;
o.email = o.emailAddress;
return o;
}
function formatFriends(o) {
formatError(o);
paging(o);
if (o.values) {
o.data = o.values.map(formatUser);
delete o.values;
}
return o;
}
function paging(res) {
if ('_count' in res && '_start' in res && (res._count + res._start) < res._total) {
res.paging = {
next: '?start=' + (res._start + res._count) + '&count=' + res._count
};
}
}
function empty(o, headers) {
if (JSON.stringify(o) === '{}' && headers.statusCode === 200) {
o.success = true;
}
}
function formatQuery(qs) {
// LinkedIn signs requests with the parameter 'oauth2_access_token'
// ... yeah another one who thinks they should be different!
if (qs.access_token) {
qs.oauth2_access_token = qs.access_token;
delete qs.access_token;
}
}
function like(p, callback) {
p.headers['x-li-format'] = 'json';
var id = p.data.id;
p.data = (p.method !== 'delete').toString();
p.method = 'put';
callback('people/~/network/updates/key=' + id + '/is-liked');
}
})(hello);
// See: https://developers.soundcloud.com/docs/api/reference
(function(hello) {
hello.init({
soundcloud: {
name: 'SoundCloud',
oauth: {
version: 2,
auth: 'https://soundcloud.com/connect',
grant: 'https://soundcloud.com/oauth2/token'
},
// Request path translated
base: 'https://api.soundcloud.com/',
get: {
me: 'me.json',
// Http://developers.soundcloud.com/docs/api/reference#me
'me/friends': 'me/followings.json',
'me/followers': 'me/followers.json',
'me/following': 'me/followings.json',
// See: http://developers.soundcloud.com/docs/api/reference#activities
'default': function(p, callback) {
// Include '.json at the end of each request'
callback(p.path + '.json');
}
},
// Response handlers
wrap: {
me: function(o) {
formatUser(o);
return o;
},
'default': function(o) {
if (Array.isArray(o)) {
o = {
data: o.map(formatUser)
};
}
paging(o);
return o;
}
},
xhr: formatRequest,
jsonp: formatRequest
}
});
function formatRequest(p, qs) {
// Alter the querystring
var token = qs.access_token;
delete qs.access_token;
qs.oauth_token = token;
qs['_status_code_map[302]'] = 200;
return true;
}
function formatUser(o) {
if (o.id) {
o.picture = o.avatar_url;
o.thumbnail = o.avatar_url;
o.name = o.username || o.full_name;
}
return o;
}
// See: http://developers.soundcloud.com/docs/api/reference#activities
function paging(res) {
if ('next_href' in res) {
res.paging = {
next: res.next_href
};
}
}
})(hello);
// See: https://developer.spotify.com/web-api/
(function(hello) {
hello.init({
spotify: {
name: 'Spotify',
oauth: {
version: 2,
auth: 'https://accounts.spotify.com/authorize',
grant: 'https://accounts.spotify.com/api/token'
},
// See: https://developer.spotify.com/web-api/using-scopes/
scope_delim: ' ',
scope: {
basic: '',
photos: '',
friends: 'user-follow-read',
publish: 'user-library-read',
email: 'user-read-email',
share: '',
publish_files: '',
files: '',
videos: '',
offline_access: ''
},
// Request path translated
base: 'https://api.spotify.com',
// See: https://developer.spotify.com/web-api/endpoint-reference/
get: {
me: '/v1/me',
'me/following': '/v1/me/following?type=artist', // Only 'artist' is supported
// Because tracks, albums and playlist exist on spotify, the tracks are considered
// the resource for the 'me/likes' endpoint
'me/like': '/v1/me/tracks'
},
// Response handlers
wrap: {
me: formatUser,
'me/following': formatFollowees,
'me/like': formatTracks
},
xhr: formatRequest,
jsonp: false
}
});
// Move the access token from the request body to the request header
function formatRequest(p, qs) {
var token = qs.access_token;
delete qs.access_token;
p.headers.Authorization = 'Bearer ' + token;
return true;
}
function formatUser(o) {
if (o.id) {
o.name = o.display_name;
o.thumbnail = o.images.length ? o.images[0].url : null;
o.picture = o.thumbnail;
}
return o;
}
function formatFollowees(o) {
paging(o);
if (o && 'artists' in o) {
o.data = o.artists.items.forEach(formatUser);
}
return o;
}
function formatTracks(o) {
paging(o);
o.data = o.items;
return o;
}
function paging(res) {
if (res && 'next' in res) {
res.paging = {
next: res.next
};
delete res.next;
}
}
})(hello);
(function(hello) {
var base = 'https://api.twitter.com/';
hello.init({
twitter: {
// Ensure that you define an oauth_proxy
oauth: {
version: '1.0a',
auth: base + 'oauth/authenticate',
request: base + 'oauth/request_token',
token: base + 'oauth/access_token'
},
login: function(p) {
// Reauthenticate
// https://dev.twitter.com/oauth/reference/get/oauth/authenticate
var prefix = '?force_login=true';
this.oauth.auth = this.oauth.auth.replace(prefix, '') + (p.options.force ? prefix : '');
},
base: base + '1.1/',
get: {
me: 'account/verify_credentials.json',
'me/friends': 'friends/list.json?count=@{limit|200}',
'me/following': 'friends/list.json?count=@{limit|200}',
'me/followers': 'followers/list.json?count=@{limit|200}',
// Https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
'me/share': 'statuses/user_timeline.json?count=@{limit|200}',
// Https://dev.twitter.com/rest/reference/get/favorites/list
'me/like': 'favorites/list.json?count=@{limit|200}'
},
post: {
'me/share': function(p, callback) {
var data = p.data;
p.data = null;
var status = [];
// Change message to status
if (data.message) {
status.push(data.message);
delete data.message;
}
// If link is given
if (data.link) {
status.push(data.link);
delete data.link;
}
if (data.picture) {
status.push(data.picture);
delete data.picture;
}
// Compound all the components
if (status.length) {
data.status = status.join(' ');
}
// Tweet media
if (data.file) {
data['media[]'] = data.file;
delete data.file;
p.data = data;
callback('statuses/update_with_media.json');
}
// Retweet?
else if ('id' in data) {
callback('statuses/retweet/' + data.id + '.json');
}
// Tweet
else {
// Assign the post body to the query parameters
hello.utils.extend(p.query, data);
callback('statuses/update.json?include_entities=1');
}
},
// See: https://dev.twitter.com/rest/reference/post/favorites/create
'me/like': function(p, callback) {
var id = p.data.id;
p.data = null;
callback('favorites/create.json?id=' + id);
}
},
del: {
// See: https://dev.twitter.com/rest/reference/post/favorites/destroy
'me/like': function(p, callback) {
p.method = 'post';
var id = p.data.id;
p.data = null;
callback('favorites/destroy.json?id=' + id);
}
},
wrap: {
me: function(res) {
formatError(res);
formatUser(res);
return res;
},
'me/friends': formatFriends,
'me/followers': formatFriends,
'me/following': formatFriends,
'me/share': function(res) {
formatError(res);
paging(res);
if (!res.error && 'length' in res) {
return {data: res};
}
return res;
},
'default': function(res) {
res = arrayToDataResponse(res);
paging(res);
return res;
}
},
xhr: function(p) {
// Rely on the proxy for non-GET requests.
return (p.method !== 'get');
}
}
});
function formatUser(o) {
if (o.id) {
if (o.name) {
var m = o.name.split(' ');
o.first_name = m.shift();
o.last_name = m.join(' ');
}
// See: https://dev.twitter.com/overview/general/user-profile-images-and-banners
o.thumbnail = o.profile_image_url_https || o.profile_image_url;
}
return o;
}
function formatFriends(o) {
formatError(o);
paging(o);
if (o.users) {
o.data = o.users.map(formatUser);
delete o.users;
}
return o;
}
function formatError(o) {
if (o.errors) {
var e = o.errors[0];
o.error = {
code: 'request_failed',
message: e.message
};
}
}
// Take a cursor and add it to the path
function paging(res) {
// Does the response include a 'next_cursor_string'
if ('next_cursor_str' in res) {
// See: https://dev.twitter.com/docs/misc/cursoring
res.paging = {
next: '?cursor=' + res.next_cursor_str
};
}
}
function arrayToDataResponse(res) {
return Array.isArray(res) ? {data: res} : res;
}
/**
// The documentation says to define user in the request
// Although its not actually required.
var user_id;
function withUserId(callback){
if(user_id){
callback(user_id);
}
else{
hello.api('twitter:/me', function(o){
user_id = o.id;
callback(o.id);
});
}
}
function sign(url){
return function(p, callback){
withUserId(function(user_id){
callback(url+'?user_id='+user_id);
});
};
}
*/
})(hello);
// Vkontakte (vk.com)
(function(hello) {
hello.init({
vk: {
name: 'Vk',
// See https://vk.com/dev/oauth_dialog
oauth: {
version: 2,
auth: 'https://oauth.vk.com/authorize',
grant: 'https://oauth.vk.com/access_token'
},
// Authorization scopes
// See https://vk.com/dev/permissions
scope: {
email: 'email',
friends: 'friends',
photos: 'photos',
videos: 'video',
share: 'share',
offline_access: 'offline'
},
// Refresh the access_token
refresh: true,
login: function(p) {
p.qs.display = window.navigator &&
window.navigator.userAgent &&
/ipad|phone|phone|android/.test(window.navigator.userAgent.toLowerCase()) ? 'mobile' : 'popup';
},
// API Base URL
base: 'https://api.vk.com/method/',
// Map GET requests
get: {
me: function(p, callback) {
p.query.fields = 'id,first_name,last_name,photo_max';
callback('users.get');
}
},
wrap: {
me: function(res, headers, req) {
formatError(res);
return formatUser(res, req);
}
},
// No XHR
xhr: false,
// All requests should be JSONP as of missing CORS headers in https://api.vk.com/method/*
jsonp: true,
// No form
form: false
}
});
function formatUser(o, req) {
if (o !== null && 'response' in o && o.response !== null && o.response.length) {
o = o.response[0];
o.id = o.uid;
o.thumbnail = o.picture = o.photo_max;
o.name = o.first_name + ' ' + o.last_name;
if (req.authResponse && req.authResponse.email !== null)
o.email = req.authResponse.email;
}
return o;
}
function formatError(o) {
if (o.error) {
var e = o.error;
o.error = {
code: e.error_code,
message: e.error_msg
};
}
}
})(hello);
(function(hello) {
hello.init({
windows: {
name: 'Windows live',
// REF: http://msdn.microsoft.com/en-us/library/hh243641.aspx
oauth: {
version: 2,
auth: 'https://login.live.com/oauth20_authorize.srf',
grant: 'https://login.live.com/oauth20_token.srf'
},
// Refresh the access_token once expired
refresh: true,
logout: function() {
return 'http://login.live.com/oauth20_logout.srf?ts=' + (new Date()).getTime();
},
// Authorization scopes
scope: {
basic: 'wl.signin,wl.basic',
email: 'wl.emails',
birthday: 'wl.birthday',
events: 'wl.calendars',
photos: 'wl.photos',
videos: 'wl.photos',
friends: 'wl.contacts_emails',
files: 'wl.skydrive',
publish: 'wl.share',
publish_files: 'wl.skydrive_update',
share: 'wl.share',
create_event: 'wl.calendars_update,wl.events_create',
offline_access: 'wl.offline_access'
},
// API base URL
base: 'https://apis.live.net/v5.0/',
// Map GET requests
get: {
// Friends
me: 'me',
'me/friends': 'me/friends',
'me/following': 'me/contacts',
'me/followers': 'me/friends',
'me/contacts': 'me/contacts',
'me/albums': 'me/albums',
// Include the data[id] in the path
'me/album': '@{id}/files',
'me/photo': '@{id}',
// Files
'me/files': '@{parent|me/skydrive}/files',
'me/folders': '@{id|me/skydrive}/files',
'me/folder': '@{id|me/skydrive}/files'
},
// Map POST requests
post: {
'me/albums': 'me/albums',
'me/album': '@{id}/files/',
'me/folders': '@{id|me/skydrive/}',
'me/files': '@{parent|me/skydrive}/files'
},
// Map DELETE requests
del: {
// Include the data[id] in the path
'me/album': '@{id}',
'me/photo': '@{id}',
'me/folder': '@{id}',
'me/files': '@{id}'
},
wrap: {
me: formatUser,
'me/friends': formatFriends,
'me/contacts': formatFriends,
'me/followers': formatFriends,
'me/following': formatFriends,
'me/albums': formatAlbums,
'me/photos': formatDefault,
'default': formatDefault
},
xhr: function(p) {
if (p.method !== 'get' && p.method !== 'delete' && !hello.utils.hasBinary(p.data)) {
// Does this have a data-uri to upload as a file?
if (typeof (p.data.file) === 'string') {
p.data.file = hello.utils.toBlob(p.data.file);
}
else {
p.data = JSON.stringify(p.data);
p.headers = {
'Content-Type': 'application/json'
};
}
}
return true;
},
jsonp: function(p) {
if (p.method !== 'get' && !hello.utils.hasBinary(p.data)) {
p.data.method = p.method;
p.method = 'get';
}
}
}
});
function formatDefault(o) {
if ('data' in o) {
o.data.forEach(function(d) {
if (d.picture) {
d.thumbnail = d.picture;
}
if (d.images) {
d.pictures = d.images
.map(formatImage)
.sort(function(a, b) {
return a.width - b.width;
});
}
});
}
return o;
}
function formatImage(image) {
return {
width: image.width,
height: image.height,
source: image.source
};
}
function formatAlbums(o) {
if ('data' in o) {
o.data.forEach(function(d) {
d.photos = d.files = 'https://apis.live.net/v5.0/' + d.id + '/photos';
});
}
return o;
}
function formatUser(o, headers, req) {
if (o.id) {
var token = req.query.access_token;
if (o.emails) {
o.email = o.emails.preferred;
}
// If this is not an non-network friend
if (o.is_friend !== false) {
// Use the id of the user_id if available
var id = (o.user_id || o.id);
o.thumbnail = o.picture = 'https://apis.live.net/v5.0/' + id + '/picture?access_token=' + token;
}
}
return o;
}
function formatFriends(o, headers, req) {
if ('data' in o) {
o.data.forEach(function(d) {
formatUser(d, headers, req);
});
}
return o;
}
})(hello);
(function(hello) {
hello.init({
yahoo: {
// Ensure that you define an oauth_proxy
oauth: {
version: '1.0a',
auth: 'https://api.login.yahoo.com/oauth/v2/request_auth',
request: 'https://api.login.yahoo.com/oauth/v2/get_request_token',
token: 'https://api.login.yahoo.com/oauth/v2/get_token'
},
// Login handler
login: function(p) {
// Change the default popup window to be at least 560
// Yahoo does dynamically change it on the fly for the signin screen (only, what if your already signed in)
p.options.popup.width = 560;
// Yahoo throws an parameter error if for whatever reason the state.scope contains a comma, so lets remove scope
try {delete p.qs.state.scope;}
catch (e) {}
},
base: 'https://social.yahooapis.com/v1/',
get: {
me: yql('select * from social.profile(0) where guid=me'),
'me/friends': yql('select * from social.contacts(0) where guid=me'),
'me/following': yql('select * from social.contacts(0) where guid=me')
},
wrap: {
me: formatUser,
// Can't get IDs
// It might be better to loop through the social.relationship table with has unique IDs of users.
'me/friends': formatFriends,
'me/following': formatFriends,
'default': paging
}
}
});
/*
// Auto-refresh fix: bug in Yahoo can't get this to work with node-oauth-shim
login : function(o){
// Is the user already logged in
var auth = hello('yahoo').getAuthResponse();
// Is this a refresh token?
if(o.options.display==='none'&&auth&&auth.access_token&&auth.refresh_token){
// Add the old token and the refresh token, including path to the query
// See http://developer.yahoo.com/oauth/guide/oauth-refreshaccesstoken.html
o.qs.access_token = auth.access_token;
o.qs.refresh_token = auth.refresh_token;
o.qs.token_url = 'https://api.login.yahoo.com/oauth/v2/get_token';
}
},
*/
function formatError(o) {
if (o && 'meta' in o && 'error_type' in o.meta) {
o.error = {
code: o.meta.error_type,
message: o.meta.error_message
};
}
}
function formatUser(o) {
formatError(o);
if (o.query && o.query.results && o.query.results.profile) {
o = o.query.results.profile;
o.id = o.guid;
o.last_name = o.familyName;
o.first_name = o.givenName || o.nickname;
var a = [];
if (o.first_name) {
a.push(o.first_name);
}
if (o.last_name) {
a.push(o.last_name);
}
o.name = a.join(' ');
o.email = (o.emails && o.emails[0]) ? o.emails[0].handle : null;
o.thumbnail = o.image ? o.image.imageUrl : null;
}
return o;
}
function formatFriends(o, headers, request) {
formatError(o);
paging(o, headers, request);
var contact;
var field;
if (o.query && o.query.results && o.query.results.contact) {
o.data = o.query.results.contact;
delete o.query;
if (!Array.isArray(o.data)) {
o.data = [o.data];
}
o.data.forEach(formatFriend);
}
return o;
}
function formatFriend(contact) {
contact.id = null;
// #362: Reports of responses returning a single item, rather than an Array of items.
// Format the contact.fields to be an array.
if (contact.fields && !(contact.fields instanceof Array)) {
contact.fields = [contact.fields];
}
(contact.fields || []).forEach(function(field) {
if (field.type === 'email') {
contact.email = field.value;
}
if (field.type === 'name') {
contact.first_name = field.value.givenName;
contact.last_name = field.value.familyName;
contact.name = field.value.givenName + ' ' + field.value.familyName;
}
if (field.type === 'yahooid') {
contact.id = field.value;
}
});
}
function paging(res, headers, request) {
// See: http://developer.yahoo.com/yql/guide/paging.html#local_limits
if (res.query && res.query.count && request.options) {
res.paging = {
next: '?start=' + (res.query.count + (+request.options.start || 1))
};
}
return res;
}
function yql(q) {
return 'https://query.yahooapis.com/v1/yql?q=' + (q + ' limit @{limit|100} offset @{start|0}').replace(/\s/g, '%20') + '&format=json';
}
})(hello);
// Register as anonymous AMD module
if (typeof define === 'function' && define.amd) {
define(function() {
return hello;
});
}
// CommonJS module for browserify
if (typeof module === 'object' && module.exports) {
module.exports = hello;
}