├── .editorconfig
├── .eslintrc
├── .gitignore
├── .prettierrc
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── package.json
├── webtask-mailchimp.js
├── webtask-medium.js
├── webtask-meetup.js
└── webtask-youtube.js
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | indent_size = 4
6 | end_of_line = lf
7 | indent_style = space
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [json]
12 | indent_size = 2
13 |
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "oceanprotocol"
3 | }
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | package-lock.json
3 | yarn.lock
4 | .env
5 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "semi": false,
3 | "singleQuote": true,
4 | "trailingComma": "none"
5 | }
6 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js: node
3 |
4 | # will run `npm install` automatically
5 |
6 | script:
7 | - npm test
8 |
9 | notifications:
10 | email: false
11 |
12 | cache:
13 | directories:
14 | - node_modules
15 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | See the page titled "[Ways to Contribute](https://docs.oceanprotocol.com/concepts/contributing/)" in the Ocean Protocol documentation.
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://oceanprotocol.com)
2 |
3 |
webtasks
4 |
5 | > 🐬 Ocean Protocol's webtasks doing automatic things for us via webtask.io
6 |
7 | 
8 |
9 | [](https://travis-ci.com/oceanprotocol/webtasks)
10 | [](https://github.com/oceanprotocol/eslint-config-oceanprotocol) [](https://greenkeeper.io/)
11 |
12 | - [Tasks](#tasks)
13 | - [Medium](#medium)
14 | - [Get Latest Posts](#get-latest-posts)
15 | - [Get Followers Count](#get-followers-count)
16 | - [Get Categories](#get-categories)
17 | - [YouTube](#youtube)
18 | - [MailChimp](#mailchimp)
19 | - [Meetup](#meetup)
20 | - [`GET /`](#get-)
21 | - [Development](#development)
22 | - [Deployment](#deployment)
23 | - [Authors](#authors)
24 | - [License](#license)
25 |
26 | ---
27 |
28 | ## Tasks
29 |
30 | ### Medium
31 |
32 | **`webtask-medium.js`**: Generic task to fetch and reconstruct items from any medium publication.
33 |
34 | #### Get Latest Posts
35 |
36 | Requires the Medium username appended at the end of the url:
37 |
38 | ```bash
39 | http://localhost:8080/:medium_username
40 |
41 | # when published on webtask.io
42 | https://TASK_URL/TASK_NAME/:medium_username
43 | ```
44 |
45 | #### Get Followers Count
46 |
47 | ```bash
48 | http://localhost:8080/:medium_username/followers
49 |
50 | # when published on webtask.io
51 | https://TASK_URL/TASK_NAME/:medium_username/followers
52 | ```
53 |
54 | **Response**
55 |
56 | ```json
57 | {
58 | "followers": 2528
59 | }
60 | ```
61 |
62 | #### Get Categories
63 |
64 | Reflecting the navigation categories used in the blog.
65 |
66 | ```bash
67 | http://localhost:8080/:medium_username/categories
68 |
69 | # when published on webtask.io
70 | https://TASK_URL/TASK_NAME/:medium_username/categories
71 | ```
72 |
73 | **Response**
74 |
75 | ```json
76 | [
77 | {
78 | "title": "Product",
79 | "url": "https://blog.oceanprotocol.com/product/home"
80 | }, {
81 | "title": "Community",
82 | "url": "https://blog.oceanprotocol.com/community/home"
83 | }, {
84 | "title": "Deep Tech",
85 | "url": "https://blog.oceanprotocol.com/deep-tech/home"
86 | }, {
87 | "title": "People",
88 | "url": "https://blog.oceanprotocol.com/people/home"
89 | }, {
90 | "title": "Token Launch",
91 | "url": "https://blog.oceanprotocol.com/token/home"
92 | }, {
93 | "title": "Use Cases",
94 | "url": "https://blog.oceanprotocol.com/usecases/home"
95 | }
96 | ]
97 | ```
98 |
99 | ### YouTube
100 |
101 | **`webtask-youtube.js`**: Generic task to fetch and reconstruct items from any YouTube account. YouTube API key is provided via [secret environment variable](https://webtask.io/docs/issue_parameters) `YOUTUBE_API_KEY` setup in web editor of webtask.io.
102 |
103 | * `/playlist/:playlistId`: returns all videos in the given playlist.
104 | * `/channel/:channelId`: returns latest 10 videos in the given channel, sorted by date.
105 |
106 | Construct your `GET` request urls like so:
107 |
108 | ```bash
109 | http://localhost:8080/playlist/:youtube_playlist_id
110 | http://localhost:8080/channel/:youtube_channel_id
111 |
112 | # when published on webtask.io
113 | https://TASK_URL/TASK_NAME/playlist/:youtube_playlist_id
114 | https://TASK_URL/TASK_NAME/channel/:youtube_channel_id
115 | ```
116 |
117 | **Response**
118 |
119 | For all endpoints, response is reconstructed in the same format:
120 |
121 | ```json
122 | [{
123 | "id": "8EMowpNlWPE",
124 | "title": "Fang Gong, Researcher - Bringing Privacy to Ocean Protocol",
125 | "description": "At Ocean Protocol, we unlock data for AI and use TCRs to maintain a registry of high-quality data sets through voting. Privacy is essential to protecting the ...",
126 | "imageUrl": "https://i.ytimg.com/vi/8EMowpNlWPE/mqdefault.jpg",
127 | "videoUrl": "https://www.youtube.com/watch?v=8EMowpNlWPE"
128 | },
129 | {
130 | ...
131 | }]
132 | ```
133 |
134 | If you want to get the original response returned from YouTube API, append `/raw` at the end of your request, e.g.:
135 |
136 | ```
137 | https://TASK_URL/TASK_NAME/playlist/:youtube_playlist_id/raw
138 | ```
139 |
140 | ### MailChimp
141 |
142 | **`webtask-mailchimp.js`**: Task to add a new newsletter subscriber.
143 |
144 | Construct your `POST /newsletter` request url like so, e.g. locally:
145 |
146 | ```bash
147 | http://localhost:8080/newsletter/jelly@mcjellyfish.com
148 |
149 | # when published on webtask.io
150 | https://TASK_URL/TASK_NAME/newsletter/jelly@mcjellyfish.com
151 | ```
152 |
153 | **Response**
154 |
155 | When subscription is successful:
156 |
157 | ```json
158 | { "status": "created" }
159 | ```
160 |
161 | When subscriber already exists:
162 |
163 | ```json
164 | { "status": "exists" }
165 | ```
166 |
167 | All errors from MailChimp (when `"status"` is a number) are simply passed through and follow the MailChimp API error responses, e.g.:
168 |
169 | ```json
170 | {
171 | "type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
172 | "title": "Forgotten Email Not Subscribed",
173 | "status": 400,
174 | "detail": "matthias@bigchaindb.com was permanently deleted and cannot be re-imported. The contact must re-subscribe to get back on the list.",
175 | "instance": "06171156-4bca-4b6c-a84f-aa3690a82798"
176 | }
177 | ```
178 |
179 | ### Meetup
180 |
181 | **`webtask-meetup.js`**: Task to get information from Meetup.
182 |
183 | #### `GET /`
184 |
185 | ```bash
186 | http://localhost:8080/meetup
187 |
188 | # when published on webtask.io
189 | https://TASK_URL/TASK_NAME/meetup
190 | ```
191 |
192 | **Response**
193 |
194 | Field `groups` holds passed through array of objects with all groups. See https://www.meetup.com/meetup_api/docs/pro/:urlname/groups/
195 |
196 | ```json
197 | {
198 | "groups": [{
199 | ...
200 | }],
201 | "members": 40238
202 | }
203 | ```
204 |
205 | ## Development
206 |
207 | ```bash
208 | npm install wt-cli -g
209 | npm start
210 | ```
211 |
212 | And go to [localhost:8080](http://localhost:8080)
213 |
214 | ## Deployment
215 |
216 | All tasks are running serverless on webtask.io where you can login with your GitHub account. Then interact with it locally with the `wt-cli`:
217 |
218 | ```bash
219 | npm install wt-cli -g
220 | wt init YOUR_GITHUB_EMAIL
221 |
222 | wt create webtask-medium.js --name medium
223 |
224 | # make sure it's there and get url
225 | wt ls
226 | ```
227 |
228 | ## Authors
229 |
230 | - Matthias Kretschmann ([@kremalicious](https://github.com/kremalicious)) - [BigchainDB](https://www.bigchaindb.com) & [Ocean Protocol](https://oceanprotocol.com)
231 | - initial Medium web task by Pedro Gomes ([@pedrouid](https://github.com/pedrouid)) - [Balance](https://balance.io)
232 |
233 | ## License
234 |
235 | ```
236 | Copyright 2018 Ocean Protocol Foundation Ltd.
237 |
238 | Licensed under the Apache License, Version 2.0 (the "License");
239 | you may not use this file except in compliance with the License.
240 | You may obtain a copy of the License at
241 |
242 | http://www.apache.org/licenses/LICENSE-2.0
243 |
244 | Unless required by applicable law or agreed to in writing, software
245 | distributed under the License is distributed on an "AS IS" BASIS,
246 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
247 | See the License for the specific language governing permissions and
248 | limitations under the License.
249 | ```
250 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "webtasks",
3 | "version": "0.1.0",
4 | "private": true,
5 | "scripts": {
6 | "start": "wt serve webtask-meetup.js",
7 | "test": "eslint ./*.js"
8 | },
9 | "dependencies": {
10 | "body-parser": "^1.19.0",
11 | "cors": "^2.8.5",
12 | "express": "^4.17.1",
13 | "ms": "^2.1.2",
14 | "request": "^2.88.0",
15 | "webtask-tools": "^3.4.1"
16 | },
17 | "devDependencies": {
18 | "eslint": "^6.6.0",
19 | "eslint-config-oceanprotocol": "^1.5.0"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/webtask-mailchimp.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const Webtask = require('webtask-tools')
3 | const cors = require('cors')
4 | const crypto = require('crypto')
5 | const bodyParser = require('body-parser')
6 | const request = require('request')
7 |
8 | const server = express()
9 |
10 | server.listen(4430)
11 | server.use(bodyParser.json())
12 |
13 | //
14 | // Allow requests from these domains only
15 | //
16 | const corsOptions = {
17 | origin: ['https://oceanprotocol.com', /\.oceanprotocol\.com$/],
18 | optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
19 | }
20 |
21 | server.use(cors(corsOptions))
22 |
23 | const baseUrl = 'https://us16.api.mailchimp.com/3.0'
24 | const listId = '3c6eed8b71'
25 |
26 | const md5 = data =>
27 | crypto
28 | .createHash('md5')
29 | .update(data)
30 | .digest('hex')
31 |
32 | server.post('/newsletter/:email', (req, res) => {
33 | const { email } = req.params
34 | const { MAILCHIMP_API_KEY } = req.webtaskContext.secrets
35 | const emailDecoded = decodeURIComponent(email)
36 | const subscriberHash = md5(emailDecoded)
37 |
38 | const baseOptions = {
39 | url: `${baseUrl}/lists/${listId}/members/${subscriberHash}`,
40 | auth: {
41 | user: 'oceanprotocol',
42 | pass: MAILCHIMP_API_KEY
43 | }
44 | }
45 |
46 | const optionsCreate = {
47 | ...baseOptions,
48 | json: {
49 | email_address: emailDecoded,
50 | status: 'pending', // double opt-in
51 | merge_fields: {
52 | // our GDPR fallback
53 | GDPR: 'yes'
54 | }
55 | }
56 | }
57 |
58 | const optionsMarketing = marketingPermissionId => ({
59 | ...baseOptions,
60 | json: {
61 | marketing_permissions: [
62 | {
63 | marketing_permission_id: marketingPermissionId,
64 | text: 'Email',
65 | enabled: true
66 | }
67 | ]
68 | }
69 | })
70 |
71 | const addMarketingPermissions = (data, cb) => {
72 | const marketingPermissionId =
73 | data.marketing_permissions[0].marketing_permission_id
74 |
75 | request.patch(
76 | optionsMarketing(marketingPermissionId),
77 | (error, response, body) => {
78 | if (error) res.send(error)
79 |
80 | return cb(body)
81 | }
82 | )
83 | }
84 |
85 | // Check if user exists first
86 | request.get(baseOptions, (error, response, body) => {
87 | if (error) res.send(error)
88 |
89 | const data = JSON.parse(body)
90 |
91 | // Member exists and is subscribed
92 | if (data.status === 'subscribed') {
93 | // Patch in native GDPR permissions
94 | addMarketingPermissions(data, () => {
95 | res.send('{ "status": "exists" }')
96 | })
97 | } else {
98 | // Create user
99 | request.put(optionsCreate, (error2, response, body2) => {
100 | if (error2) res.send(error2)
101 |
102 | if (Number.isInteger(body2.status)) {
103 | res.send(body2)
104 | }
105 |
106 | // Patch in native GDPR permissions
107 | addMarketingPermissions(body2, () => {
108 | res.send('{ "status": "created" }')
109 | })
110 | })
111 | }
112 | })
113 | })
114 |
115 | module.exports = Webtask.fromExpress(server)
116 |
--------------------------------------------------------------------------------
/webtask-medium.js:
--------------------------------------------------------------------------------
1 | 'use strict' // eslint-disable-line
2 |
3 | const express = require('express')
4 | const request = require('request')
5 | const webtask = require('webtask-tools')
6 |
7 | const app = express()
8 |
9 | app.get('/', (req, res) => {
10 | res.status(400).send('Please enter a username as a parameter')
11 | })
12 |
13 | app.get('/:username', (req, res) => {
14 | const url = `https://medium.com/${req.params.username}/?format=json`
15 |
16 | request(url, (error, response) => {
17 | const prefix = '])}while(1);'
18 | if (!response.body.includes(prefix)) {
19 | res.status(500).send({
20 | success: false,
21 | reason: 'Failed getting posts from Medium.'
22 | })
23 | }
24 | const json = JSON.parse(response.body.replace(prefix, ''))
25 |
26 | let posts
27 |
28 | if (json.payload.posts) {
29 | ({ posts } = json.payload.posts)
30 | }
31 | if (json.payload.references.Post) {
32 | posts = Object.keys(json.payload.references.Post).map(
33 | key => json.payload.references.Post[key]
34 | )
35 | }
36 |
37 | const parsedPosts = []
38 | let holder = {}
39 |
40 | if (error) {
41 | res.status(error.status).send({ success: false })
42 | }
43 |
44 | for (let i = 0; i < posts.length; i++) {
45 | holder.id = posts[i].id
46 | holder.date = posts[i].firstPublishedAt
47 | holder.readingTime = posts[i].virtuals.readingTime
48 | holder.title = posts[i].title
49 | holder.subtitle = posts[i].virtuals.subtitle
50 | holder.imageUrl = `https://cdn-images-1.medium.com/max/600/${posts[i].virtuals.previewImage.imageId}`
51 | holder.postUrl = `https://medium.com/${req.params.username}/${posts[i].id}`
52 | parsedPosts.push(holder)
53 | holder = {}
54 | }
55 |
56 | res.send(parsedPosts)
57 | })
58 | })
59 |
60 | app.get('/:username/raw', (req, res) => {
61 | const url = `https://medium.com/${req.params.username}/latest?format=json`
62 |
63 | request(url, (error, response) => {
64 | const json = JSON.parse(response.body.replace('])}while(1);', ''))
65 | const { posts } = json.payload
66 |
67 | if (error) return
68 |
69 | res.send(posts)
70 | })
71 | })
72 |
73 | app.get('/:username/followers', (req, res) => {
74 | const url = `https://medium.com/${req.params.username}?format=json`
75 |
76 | request(url, (error, response) => {
77 | const json = JSON.parse(response.body.replace('])}while(1);', ''))
78 | const { collection } = json.payload
79 |
80 | if (error) return
81 |
82 | res.send(`{ "followers": ${collection.metadata.followerCount} }`)
83 | })
84 | })
85 |
86 | app.get('/:username/categories', (req, res) => {
87 | const url = `https://medium.com/${req.params.username}?format=json`
88 |
89 | request(url, (error, response) => {
90 | const json = JSON.parse(response.body.replace('])}while(1);', ''))
91 | const { navItems } = json.payload.collection
92 | const parsedCategories = []
93 | let holder = {}
94 |
95 | if (error) return
96 |
97 | for (let i = 0; i < navItems.length; i++) {
98 | holder.title = navItems[i].title
99 | holder.url = navItems[i].url
100 | parsedCategories.push(holder)
101 | holder = {}
102 | }
103 |
104 | res.send(parsedCategories)
105 | })
106 | })
107 |
108 | module.exports = webtask.fromExpress(app)
109 |
--------------------------------------------------------------------------------
/webtask-meetup.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const Webtask = require('webtask-tools')
3 | const cors = require('cors')
4 | const bodyParser = require('body-parser')
5 | const request = require('request')
6 |
7 | const server = express()
8 |
9 | server.listen(4430)
10 | server.use(bodyParser.json())
11 |
12 | //
13 | // Allow requests from these domains only
14 | //
15 | const corsOptions = {
16 | origin: ['https://oceanprotocol.com', /\.oceanprotocol\.com$/],
17 | optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
18 | }
19 |
20 | server.use(cors(corsOptions))
21 |
22 | const baseUrl = 'https://api.meetup.com'
23 |
24 | server.get('/', (req, res) => {
25 | const { MEETUP_API_KEY } = req.webtaskContext.secrets
26 |
27 | const options = {
28 | url: `${baseUrl}/pro/data-economy/groups?key=${MEETUP_API_KEY}`
29 | }
30 |
31 | try {
32 | request.get(options, (error, response, body) => {
33 | const data = JSON.parse(body)
34 | let members = []
35 |
36 | if (error) res.send(error)
37 | if (response.statusCode !== 200) res.send(body)
38 |
39 | if (Array.isArray(data)) {
40 | for (const item of data) {
41 | members.push(item.member_count)
42 | }
43 |
44 | members = members.reduce((a, b) => a + b, 0)
45 | }
46 |
47 | res.send({ groups: data, members })
48 | })
49 | } catch (error) {
50 | console.error(error)
51 | res.send(error)
52 | }
53 | })
54 |
55 | module.exports = Webtask.fromExpress(server)
56 |
--------------------------------------------------------------------------------
/webtask-youtube.js:
--------------------------------------------------------------------------------
1 | 'use strict' // eslint-disable-line
2 |
3 | const express = require('express')
4 | const request = require('request')
5 | const webtask = require('webtask-tools')
6 |
7 | const app = express()
8 |
9 | const makeRequest = (options, cb) => {
10 | request(options, (error, response, body) => {
11 | const json = JSON.parse(body)
12 | const videos = json.items
13 |
14 | if (error) {
15 | return cb(error)
16 | }
17 |
18 | if (json.error) {
19 | return cb(json.error)
20 | }
21 |
22 | return cb(videos)
23 | })
24 | }
25 |
26 | app.get('/', (req, res) => {
27 | res.send(
28 | 'Please use /channel or /playlist endpoints, appended with the channel or playlist ID as parameter.'
29 | )
30 | })
31 |
32 | app.get('/channel/:channelId', (req, res) => {
33 | const options = {
34 | url: `https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${
35 | req.params.channelId
36 | }&maxResults=10&order=date&type=video&key=${
37 | req.webtaskContext.secrets.YOUTUBE_API_KEY
38 | }`,
39 | headers: { referer: req.headers.host }
40 | }
41 |
42 | const parsedPosts = []
43 | let holder = {}
44 |
45 | makeRequest(options, videos => {
46 | for (let i = 0; i < videos.length; i++) {
47 | holder.id = videos[i].id.videoId
48 | holder.title = videos[i].snippet.title
49 | holder.description = videos[i].snippet.description
50 | holder.imageUrl = videos[i].snippet.thumbnails.medium.url
51 | holder.videoUrl = `https://www.youtube.com/watch?v=${
52 | videos[i].id.videoId
53 | }`
54 | parsedPosts.push(holder)
55 | holder = {}
56 | }
57 |
58 | res.send(parsedPosts)
59 | })
60 | })
61 |
62 | app.get('/channel/:channelId/raw', (req, res) => {
63 | const options = {
64 | url: `https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${
65 | req.params.channelId
66 | }&maxResults=10&order=date&type=video&key=${
67 | req.webtaskContext.secrets.YOUTUBE_API_KEY
68 | }`,
69 | headers: { referer: req.headers.host }
70 | }
71 |
72 | makeRequest(options, videos => {
73 | res.send(videos)
74 | })
75 | })
76 |
77 | app.get('/playlist/:playlistId', (req, res) => {
78 | const options = {
79 | url: `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=10&playlistId=${
80 | req.params.playlistId
81 | }&key=${req.webtaskContext.secrets.YOUTUBE_API_KEY}`,
82 | headers: { referer: req.headers.host }
83 | }
84 |
85 | const parsedPosts = []
86 | let holder = {}
87 |
88 | makeRequest(options, videos => {
89 | for (let i = 0; i < videos.length; i++) {
90 | holder.id = videos[i].snippet.resourceId.videoId
91 | holder.title = videos[i].snippet.title
92 | holder.description = videos[i].snippet.description
93 | holder.imageUrl = videos[i].snippet.thumbnails.medium.url
94 | holder.videoUrl = `https://www.youtube.com/watch?v=${
95 | videos[i].snippet.resourceId.videoId
96 | }`
97 | parsedPosts.push(holder)
98 | holder = {}
99 | }
100 |
101 | res.send(parsedPosts)
102 | })
103 | })
104 |
105 | app.get('/playlist/:playlistId/raw', (req, res) => {
106 | const options = {
107 | url: `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=10&playlistId=${
108 | req.params.playlistId
109 | }&key=${req.webtaskContext.secrets.YOUTUBE_API_KEY}`,
110 | headers: { referer: req.headers.host }
111 | }
112 |
113 | makeRequest(options, videos => {
114 | res.send(videos)
115 | })
116 | })
117 |
118 | module.exports = webtask.fromExpress(app)
119 |
--------------------------------------------------------------------------------