summaryrefslogtreecommitdiff
path: root/providers/Instagram.php
blob: 1fc9c53f7233d1e5af33d0ce31075fffc50fd707 (plain)
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
<?php

namespace Providers;

require_once('HtmlFeed.php');
require_once('Item.php');

class Instagram extends \Providers\HtmlFeed {

    protected function _getCachePath() {
        return '../cache/instagram.%s';
    }

    const JS_VAR = 'window._sharedData = ';

    protected function _getFeedUrl($feed) {
        return sprintf('https://instagram.com/%s', $feed);
    }

    protected function _parseFeedContent($tree) {
        $items = [];
        foreach ($tree->find('script') as $script) {
            $scriptContent = $script->text();
            if (strpos($scriptContent, self::JS_VAR) !== FALSE) {
                $data = json_decode(trim(str_replace(self::JS_VAR, '', $scriptContent), ';'), TRUE);
                $edges = $data['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'];
                foreach ($edges as $edge) {
                    $items[] = $edge['node'];
                }
            }
        }
        return $items;
    }

    protected function _mapItems($content) {
        return array_map(
            function ($obj) {
                $item = new Item();
                $item->ID = $obj['id'];
                $item->Link = sprintf(
                    'https://instagram.com/p/%s',
                    $obj['shortcode']
                );
                $texts = array_filter(
                    explode(PHP_EOL, $obj['edge_media_to_caption']['edges'][0]['node']['text']),
                    function($t) { return $t != '.'; }
                );
                $thumbs = $obj['thumbnail_resources'];
                if (count($thumbs)) {
                    $texts[] = sprintf('<img src="%s" />', end($obj['thumbnail_resources'])['src']);
                }
                $item->Title = $texts[0];
                $item->Text = implode('<br />', $texts);
                $item->Time = $obj['taken_at_timestamp'];
                return $item;
            },
            $content
        );
    }

    public function title() {
        return sprintf("%s's instagram posts", $this->_feed);
    }

}

?>