~romuloalves/get-instagram-feed

ref: 1a074b212b8f7665f152cd0a861201748336ac64 get-instagram-feed/src/get-picture.ts -rw-r--r-- 1.8 KiB
1a074b21 — romuloalves Implements v1 1 year, 8 months ago
                                                                                
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
import { get } from 'https';

const startDataString = 'window._sharedData = ';
const getInstagramUrl = (id: string) => `https://www.instagram.com/${id}/`;

const getJsonData = (html:string): Object => {
  const startIndex = html.indexOf(startDataString) + startDataString.length
  const endIndex = html.indexOf(';</script>', startIndex)
  const substring = html.substring(startIndex, endIndex)
  const data = JSON.parse(substring)

  return getImages(data)
};

const getImages = (data: any): Array<Object> => {
  if (data == null || data.entry_data == null ||
    data.entry_data.ProfilePage == null || data.entry_data.ProfilePage.length === 0) {
    return [];
  }

  const [profilePage, ..._] = data.entry_data.ProfilePage;

  return profilePage.graphql.user.edge_owner_to_timeline_media.edges.map((edge: any) => {
    const { node: media } = edge;
    let caption = '';
    let likes = 0;

    if (media.edge_media_to_caption && media.edge_media_to_caption.edges && media.edge_media_to_caption.edges.length > 0) {
      caption = media.edge_media_to_caption.edges[0].node.text;
    }

    if (media.edge_media_preview_like && media.edge_media_preview_like.count) {
      likes = media.edge_media_preview_like.count;
    }

    return {
      id: media.id,
      thumbnail: media.thumbnail_src,
      isVideo: media.is_video,
      likes,
      mediaUrl: media.display_url,
      dimensions: media.dimensions,
      takenAt: media.taken_at_timestamp,
      owner: media.owner,
      caption
    };
  });
}

export default async user => {
  return new Promise((resolve, reject) => {
    const userUrl = getInstagramUrl(user);
    let html = '';

    get(userUrl, res => {
      res.on('data', chunk => {
        html += chunk;
      });

      res.on('end', () => {
        resolve(getJsonData(html));
      });
    }).on('error', err => reject(err));
  });
};