@@ -55,18 +55,36 @@ export const shortcodeToDateString = (shortcode: string): string =>
55
55
shortcodeToInstaID ( shortcode ) ,
56
56
) ;
57
57
58
- export const shortcodeToInstaID = ( shortcode : string ) : number => {
58
+ export const shortcodeToInstaID = ( shortcode : string ) : string => {
59
+ /* Instagram changed the shortcode generation method at 2012-02-07
60
+ 2012-02-07T02:01:16.000Z --> o5H__ (old: sequential)
61
+ 2012-02-07T02:35:23.000Z --> GsBiMipBgr (new: timestamp derived)
62
+ 2290-05-20T12:17:23.928Z --> ___________ (last possible shortcode with 11 characters)
63
+ */
64
+
65
+ if ( shortcode . length > 28 ) shortcode = shortcode . slice ( 0 , - 28 ) ; // handle private account shortcodes
66
+
67
+ if ( shortcode . length < 10 || shortcode . length > 11 ) return '' ; // support new shortcode method only
68
+
59
69
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' ;
60
- let id = 0 ;
61
- for ( const char of shortcode ) {
62
- id = ( id * 64 ) + alphabet . indexOf ( char ) ;
70
+ const cMil = 1000000 ; // add 6 digits of precision to the Number max limit (safe at least until year 2290)
71
+ let idMil = 0 ; // store numbers above 999999
72
+ let idNum = 0 ; // store numbers below 1000000
73
+ for ( const char of shortcode ) { // base64 to base10
74
+ idMil *= 64 ;
75
+ idNum = ( idNum * 64 ) + alphabet . indexOf ( char ) ;
76
+ if ( idNum >= cMil ) {
77
+ let quot = Math . floor ( idNum / cMil ) ;
78
+ idMil += quot ;
79
+ idNum -= quot * cMil ;
80
+ }
63
81
}
64
82
65
- return id ;
83
+ return ( idMil . toString ( ) + idNum . toString ( ) . padStart ( cMil . toString ( ) . length - 1 , '0' ) ) . replace ( / ^ 0 + / , '' ) ;
66
84
} ;
67
85
68
- export const instaIDToTimestamp = ( id : number ) => {
69
- const timestamp = ( id / Math . pow ( 2 , 23 ) ) + 1314220021721 ;
86
+ export const instaIDToTimestamp = ( id : string ) => {
87
+ const timestamp = ( Number ( id ) / Math . pow ( 2 , 23 ) ) + 1314220021721 ;
70
88
71
89
return new Date ( timestamp ) . toLocaleString ( ) ;
72
90
} ;
0 commit comments