aboutsummaryrefslogtreecommitdiff
path: root/bridges/PatreonBridge.php
blob: a15d0378a005343378db34f2aefec91e971d5ed0 (plain) (blame)
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
<?php

class PatreonBridge extends BridgeAbstract
{
    const NAME = 'Patreon Bridge';
    const URI = 'https://www.patreon.com/';
    const CACHE_TIMEOUT = 300; // 5min
    const DESCRIPTION = 'Returns posts by creators on Patreon';
    const MAINTAINER = 'Roliga';
    const PARAMETERS = [ [
        'creator' => [
            'name' => 'Creator',
            'type' => 'text',
            'required' => true,
            'exampleValue' => 'sanityinc',
            'title' => 'Creator name as seen in their page URL'
        ]
    ]];

    public function collectData()
    {
        $html = getSimpleHTMLDOMCached($this->getURI(), 86400);
        $regex = '#/api/campaigns/([0-9]+)#';
        if (preg_match($regex, $html->save(), $matches) > 0) {
            $campaign_id = $matches[1];
        } else {
            returnServerError('Could not find campaign ID');
        }

        $query = [
            'include' => implode(',', [
                'user',
                'attachments',
                'user_defined_tags',
                //'campaign',
                //'poll.choices',
                //'poll.current_user_responses.user',
                //'poll.current_user_responses.choice',
                //'poll.current_user_responses.poll',
                //'access_rules.tier.null',
                //'images.null',
                //'audio.null'
            ]),
            'fields' => [
                'post' => implode(',', [
                    //'change_visibility_at',
                    //'comment_count',
                    'content',
                    //'current_user_can_delete',
                    //'current_user_can_view',
                    //'current_user_has_liked',
                    //'embed',
                    'image',
                    //'is_paid',
                    //'like_count',
                    //'min_cents_pledged_to_view',
                    //'patreon_url',
                    //'patron_count',
                    //'pledge_url',
                    //'post_file',
                    //'post_metadata',
                    //'post_type',
                    'published_at',
                    'teaser_text',
                    //'thumbnail_url',
                    'title',
                    //'upgrade_url',
                    'url',
                    //'was_posted_by_campaign_owner'
                ]),
                'user' => implode(',', [
                    //'image_url',
                    'full_name',
                    //'url'
                ])
            ],
            'filter' => [
                'contains_exclusive_posts' => true,
                'is_draft' => false,
                'campaign_id' => $campaign_id
            ],
            'sort' => '-published_at'
        ];
        $posts = $this->apiGet('posts', $query);

        foreach ($posts->data as $post) {
            $item = [
                'uri' => $post->attributes->url,
                'title' => $post->attributes->title,
                'timestamp' => $post->attributes->published_at,
                'content' => '',
                'uid' => 'patreon.com/' . $post->id
            ];

            $user = $this->findInclude(
                $posts,
                'user',
                $post->relationships->user->data->id
            );
            $item['author'] = $user->full_name;

            if (isset($post->attributes->image)) {
                $item['content'] .= '<p><a href="'
                    . $post->attributes->url
                    . '"><img src="'
                    . $post->attributes->image->thumb_url
                    . '" /></a></p>';
            }

            if (isset($post->attributes->content)) {
                $item['content'] .= $post->attributes->content;
            } elseif (isset($post->attributes->teaser_text)) {
                $item['content'] .= '<p>'
                    . $post->attributes->teaser_text
                    . '</p>';
            }

            if (isset($post->relationships->user_defined_tags)) {
                $item['categories'] = [];
                foreach ($post->relationships->user_defined_tags->data as $tag) {
                    $attrs = $this->findInclude($posts, 'post_tag', $tag->id);
                    $item['categories'][] = $attrs->value;
                }
            }

            if (isset($post->relationships->attachments)) {
                $item['enclosures'] = [];
                foreach ($post->relationships->attachments->data as $attachment) {
                    $attrs = $this->findInclude($posts, 'attachment', $attachment->id);
                    $item['enclosures'][] = $attrs->url;
                }
            }

            $this->items[] = $item;
        }
    }

    /*
     * Searches the "included" array in an API response and returns attributes
     * for the first match.
     */
    private function findInclude($data, $type, $id)
    {
        foreach ($data->included as $include) {
            if ($include->type === $type && $include->id === $id) {
                return $include->attributes;
            }
        }
    }

    private function apiGet($endpoint, $query_data = [])
    {
        $query_data['json-api-version'] = 1.0;
        $query_data['json-api-use-default-includes'] = 0;

        $url = 'https://www.patreon.com/api/'
            . $endpoint
            . '?'
            . http_build_query($query_data);

        /*
         * Accept-Language header and the CURL cipher list are for bypassing the
         * Cloudflare anti-bot protection on the Patreon API. If this ever breaks,
         * here are some other project that also deal with this:
         * https://github.com/mikf/gallery-dl/issues/342
         * https://github.com/daemionfox/patreon-feed/issues/7
         * https://www.patreondevelopers.com/t/api-returning-cloudflare-challenge/2025
         * https://github.com/splitbrain/patreon-rss/issues/4
         */
        $header = [
            'Accept-Language: en-US',
            'Content-Type: application/json'
        ];
        $opts = [
            CURLOPT_SSL_CIPHER_LIST => implode(':', [
                'DEFAULT',
                '!DHE-RSA-CHACHA20-POLY1305'
            ])
        ];

        $data = json_decode(getContents($url, $header, $opts));

        return $data;
    }

    public function getName()
    {
        if (!is_null($this->getInput('creator'))) {
            return $this->getInput('creator') . ' posts';
        }

        return parent::getName();
    }

    public function getURI()
    {
        if (!is_null($this->getInput('creator'))) {
            return self::URI . $this->getInput('creator');
        }

        return parent::getURI();
    }

    public function detectParameters($url)
    {
        $params = [];

        // Matches e.g. https://www.patreon.com/SomeCreator
        $regex = '/^(https?:\/\/)?(www\.)?patreon\.com\/([^\/&?\n]+)/';
        if (preg_match($regex, $url, $matches) > 0) {
            $params['creator'] = urldecode($matches[3]);
            return $params;
        }

        return null;
    }
}