Skip to content

Commit

Permalink
Complete refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
jlobos committed Apr 14, 2018
1 parent c111093 commit a4b2f12
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 68 deletions.
32 changes: 32 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
version: 2
jobs:
build:
docker:
- image: circleci/node:latest

working_directory: ~/repo

steps:
- checkout

# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum "package.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-

- run: npm install

- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package.json" }}

# get cookies
- run: openssl aes-256-cbc -d -in test/cookies.json-cipher -out test/cookie.json -k $KEY

# run tests!
- run: npm test


4 changes: 0 additions & 4 deletions .travis.yml

This file was deleted.

50 changes: 35 additions & 15 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Native
const fs = require('fs')
const crypto = require('crypto')

// Packages
const request = require('request-promise-native')
Expand All @@ -10,23 +11,15 @@ const useragentFromSeed = require('useragent-from-seed')
const baseUrl = 'https://www.instagram.com'

class Instagram {
constructor(
{ username, password, cookies, cookieStore },
{ language, proxy } = {}
) {
constructor({ username, password, cookieStore }, { language, proxy } = {}) {
this.credentials = {
username,
password,
cookies
password
}

const jar = request.jar(cookieStore)
let csrftoken

if (cookies) {
cookies.forEach(cookie => jar.setCookie(Cookie.fromJSON(cookie), baseUrl))
csrftoken = cookies.find(({ key }) => key === 'csrftoken').value
}
const { value: csrftoken } =
jar.getCookies(baseUrl).find(({ key }) => key === 'csrftoken') || {}

const userAgent = useragentFromSeed(username)

Expand All @@ -46,7 +39,7 @@ class Instagram {
})
}

async login({ username, password } = {}) {
async login({ username, password } = {}, { _sharedData = true } = {}) {
username = username || this.credentials.username
password = password || this.credentials.password

Expand Down Expand Up @@ -85,19 +78,46 @@ class Instagram {
cookies: cookies.map(cookie => cookie.toJSON())
}

// Provide _sharedData
if (_sharedData) {
this._sharedData = await this._getSharedData()
}

return res.body
}

_getSharedData(url = '/') {
return this.request(url)
.then(html => /window._sharedData = (.*);/.exec(html)[1])
.then(_sharedData => JSON.parse(_sharedData))
}

async _getGis(path) {
const { rhx_gis, config: { csrf_token } } =
this._sharedData || (await this._getSharedData(path))

return crypto
.createHash('md5')
.update(`${rhx_gis}:${csrf_token}:${path}`)
.digest('hex')
}

logout() {
return this.request('/accounts/logout/ajax/')
}

// https://github.com/jlobos/instagram-web-api/issues/23
getHome() {
return this.request('/?__a=1').then(data => data.graphql.user)
}

getUserByUsername({ username }) {
return this.request(`/${username}/?__a=1`).then(data => data.graphql.user)
async getUserByUsername({ username }) {
return this.request({
uri: `/${username}/?__a=1`,
headers: {
'x-instagram-gis': await this._getGis(`/${username}/`)
}
}).then(data => data.graphql.user)
}

_getFollowData({ fieldName, queryHash, variables }) {
Expand Down
20 changes: 20 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@
"repository": "jlobos/instagram-web-api",
"author": "Jesus Lobos <[email protected]> (https://jlobos.com)",
"scripts": {
"lint": "xo",
"test": "xo && ava",
"precommit": "lint-staged"
},
"files": [
"lib"
],
"prettier": {
"semi": false,
"singleQuote": true
},
"keywords": [
"❤️",
"🤳",
Expand Down Expand Up @@ -57,6 +62,7 @@
"husky": "^0.14.3",
"lint-staged": "^7.0.0",
"prettier": "^1.11.1",
"tough-cookie-filestore": "0.0.1",
"xo": "^0.20.3"
}
}
Binary file added test/cookies.json-cipher
Binary file not shown.
54 changes: 5 additions & 49 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,13 @@
import path from 'path'
import test from 'ava'
import FileCookieStore from 'tough-cookie-filestore'
import Instagram from '../lib'
import { media, users, locations, tags } from './helpers'

const { username, password } = process.env
const cookieStore = new FileCookieStore(path.join(__dirname, './cookies.json'))

const client = new Instagram({ username, password })
let authentication
const client = new Instagram({ cookieStore })
let commentId
let profile

test.before(async () => {
authentication = await client.login()
})

test('authentication', t => {
t.is(authentication.status, 'ok')
t.is(client.credentials.username, username)
t.is(client.credentials.password, password)
t.true(authentication.authenticated)
t.true(Array.isArray(client.credentials.cookies))
})

test('getHome', async t => {
const user = await client.getHome()

t.true('id' in user)
t.true('profile_pic_url' in user)
t.true('username' in user)
})

test('getActivity', async t => {
const user = await client.getActivity()
Expand All @@ -37,35 +17,11 @@ test('getActivity', async t => {
})

test('getProfile', async t => {
profile = await client.getProfile()
const profile = await client.getProfile()

t.is(typeof profile, 'object')
})

test.after('updateProfile', async t => {
const {
first_name: firstName,
email,
username,
phone_number: phoneNumber,
gender,
biography,
external_url: website,
chaining_enabled: similarAccountSuggestions
} = profile
const { status } = await client.updateProfile({
firstName,
email,
username,
phoneNumber,
gender,
biography,
website,
similarAccountSuggestions
})
t.is(status, 'ok')
})

test('getMediaFeedByLocation', async t => {
const { id, name } = await client.getMediaFeedByLocation({
locationId: locations.Santiago.id
Expand Down

0 comments on commit a4b2f12

Please sign in to comment.