added lbryapi.js and removed electron-specific code from lbry.js

This commit is contained in:
Akinwale Ariwodola 2018-01-15 19:06:44 +01:00
parent e127e3c38d
commit 57e5b4a086
6 changed files with 127 additions and 333 deletions

View file

@ -267,10 +267,6 @@ Lbry.publishDeprecated = function (params, fileListedCallback, publishedCallback
}); });
}; };
Lbry.imagePath = function (file) {
return staticResourcesPath + '/img/' + file;
};
Lbry.getMediaType = function (contentType, fileName) { Lbry.getMediaType = function (contentType, fileName) {
if (contentType) { if (contentType) {
return (/^[^/]+/.exec(contentType)[0] return (/^[^/]+/.exec(contentType)[0]
@ -294,15 +290,6 @@ Lbry.getMediaType = function (contentType, fileName) {
return 'unknown'; return 'unknown';
}; };
Lbry.getAppVersionInfo = function () {
return new Promise(function (resolve) {
/*ipcRenderer.once('version-info-received', (event, versionInfo) => {
resolve(versionInfo);
});
ipcRenderer.send('version-info-requested');*/
});
};
/** /**
* Wrappers for API methods to simulate missing or future behavior. Unlike the old-style stubs, * Wrappers for API methods to simulate missing or future behavior. Unlike the old-style stubs,
* these are designed to be transparent wrappers around the corresponding API methods. * these are designed to be transparent wrappers around the corresponding API methods.
@ -397,33 +384,25 @@ exports.default = lbryProxy;
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.costInfoReducer = exports.LbryApi = exports.Lbry = undefined;
var _lbry = __webpack_require__(0); var _lbry = __webpack_require__(0);
Object.defineProperty(exports, 'lbry', { var _lbry2 = _interopRequireDefault(_lbry);
enumerable: true,
get: function get() {
return _lbry.lbry;
}
});
var _lbryio = __webpack_require__(3); var _lbryapi = __webpack_require__(3);
Object.defineProperty(exports, 'lbryio', { var _lbryapi2 = _interopRequireDefault(_lbryapi);
enumerable: true,
get: function get() {
return _lbryio.lbryio;
}
});
var _cost_info = __webpack_require__(8); var _cost_info = __webpack_require__(8);
Object.defineProperty(exports, 'costInfoReducer', { var _cost_info2 = _interopRequireDefault(_cost_info);
enumerable: true,
get: function get() { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
return _cost_info.costInfoReducer;
} var Lbry = exports.Lbry = _lbry2.default;
}); var LbryApi = exports.LbryApi = _lbryapi2.default;
var costInfoReducer = exports.costInfoReducer = _cost_info2.default;
/***/ }), /***/ }),
/* 2 */ /* 2 */
@ -535,9 +514,7 @@ var _querystring2 = _interopRequireDefault(_querystring);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Lbryio = { var LbryApi = {
enabled: true,
authenticationPromise: null,
exchangePromise: null, exchangePromise: null,
exchangeLastFetched: null exchangeLastFetched: null
}; };
@ -547,10 +524,10 @@ var CONNECTION_STRING = process.env.LBRY_APP_API_URL ? process.env.LBRY_APP_API_
var EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000; var EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000;
Lbryio.getExchangeRates = function () { LbryApi.getExchangeRates = function () {
if (!Lbryio.exchangeLastFetched || Date.now() - Lbryio.exchangeLastFetched > EXCHANGE_RATE_TIMEOUT) { if (!LbryApi.exchangeLastFetched || Date.now() - LbryApi.exchangeLastFetched > EXCHANGE_RATE_TIMEOUT) {
Lbryio.exchangePromise = new Promise(function (resolve, reject) { LbryApi.exchangePromise = new Promise(function (resolve, reject) {
Lbryio.call('lbc', 'exchange_rate', {}, 'get', true).then(function (_ref) { LbryApi.call('lbc', 'exchange_rate', {}, 'get', true).then(function (_ref) {
var LBC_USD = _ref.lbc_usd, var LBC_USD = _ref.lbc_usd,
LBC_BTC = _ref.lbc_btc, LBC_BTC = _ref.lbc_btc,
BTC_USD = _ref.btc_usd; BTC_USD = _ref.btc_usd;
@ -559,12 +536,12 @@ Lbryio.getExchangeRates = function () {
resolve(rates); resolve(rates);
}).catch(reject); }).catch(reject);
}); });
Lbryio.exchangeLastFetched = Date.now(); LbryApi.exchangeLastFetched = Date.now();
} }
return Lbryio.exchangePromise; return LbryApi.exchangePromise;
}; };
Lbryio.call = function (resource, action) { LbryApi.call = function (resource, action) {
var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var method = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'get'; var method = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'get';
@ -597,113 +574,31 @@ Lbryio.call = function (resource, action) {
return fetch(url, options).then(checkAndParse); return fetch(url, options).then(checkAndParse);
} }
return Lbryio.getAuthToken().then(function (token) { var fullParams = _extends({}, params);
var fullParams = _extends({ auth_token: token }, params); var qs = _querystring2.default.stringify(fullParams);
var qs = _querystring2.default.stringify(fullParams); var url = '' + CONNECTION_STRING + resource + '/' + action + '?' + qs;
var url = '' + CONNECTION_STRING + resource + '/' + action + '?' + qs;
var options = { var options = {
method: 'GET' method: 'GET'
};
if (method === 'post') {
options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: qs
}; };
url = '' + CONNECTION_STRING + resource + '/' + action;
}
if (method === 'post') { return makeRequest(url, options).then(function (response) {
options = { return response.data;
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: qs
};
url = '' + CONNECTION_STRING + resource + '/' + action;
}
return makeRequest(url, options).then(function (response) {
return response.data;
});
}); });
}; };
Lbryio.authToken = null; exports.default = LbryApi;
Lbryio.getAuthToken = function () {
return new Promise(function (resolve) {
if (Lbryio.authToken) {
resolve(Lbryio.authToken);
} else {
/*ipcRenderer.once('auth-token-response', (event, token) => {
Lbryio.authToken = token;
return resolve(token);
});
ipcRenderer.send('get-auth-token');*/
}
});
};
Lbryio.setAuthToken = function (token) {
Lbryio.authToken = token ? token.toString().trim() : null;
//ipcRenderer.send('set-auth-token', token);
};
Lbryio.getCurrentUser = function () {
return Lbryio.call('user', 'me');
};
Lbryio.authenticate = function () {
if (!Lbryio.enabled) {
return new Promise(function (resolve) {
resolve({
id: 1,
language: 'en',
primary_email: 'disabled@lbry.io',
has_verified_email: true,
is_identity_verified: true,
is_reward_approved: false
});
});
}
if (Lbryio.authenticationPromise === null) {
Lbryio.authenticationPromise = new Promise(function (resolve, reject) {
Lbryio.getAuthToken().then(function (token) {
if (!token || token.length > 60) {
return false;
}
// check that token works
return Lbryio.getCurrentUser().then(function () {
return true;
}).catch(function () {
return false;
});
}).then(function (isTokenValid) {
if (isTokenValid) {
return reject;
}
return _lbry2.default.status().then(function (status) {
return Lbryio.call('user', 'new', {
auth_token: '',
language: 'en',
app_id: status.installation_id
}, 'post');
}).then(function (response) {
if (!response.auth_token) {
throw new Error(__('auth_token is missing from response'));
}
return Lbryio.setAuthToken(response.auth_token);
});
}).then(Lbryio.getCurrentUser).then(resolve, reject);
});
}
return Lbryio.authenticationPromise;
};
Lbryio.getStripeToken = function () {
return CONNECTION_STRING.startsWith('http://localhost:') ? 'pk_test_NoL1JWL7i1ipfhVId5KfDZgo' : 'pk_live_e8M4dRNnCCbmpZzduEUZBgJO';
};
exports.default = Lbryio;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4))) /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ }), /***/ }),

View file

@ -1,4 +1,4 @@
export { lbry } from 'lbry'; export { Lbry } from 'lbry';
export { lbryio } from 'lbryio'; export { LbryApi } from 'lbryapi';
export { costInfoReducer } from 'redux/reducers/cost_info'; export { costInfoReducer } from 'redux/reducers/cost_info';

View file

@ -171,8 +171,6 @@ Lbry.publishDeprecated = (params, fileListedCallback, publishedCallback, errorCa
); );
}; };
Lbry.imagePath = file => `${staticResourcesPath}/img/${file}`;
Lbry.getMediaType = (contentType, fileName) => { Lbry.getMediaType = (contentType, fileName) => {
if (contentType) { if (contentType) {
return /^[^/]+/.exec(contentType)[0]; return /^[^/]+/.exec(contentType)[0];
@ -195,14 +193,6 @@ Lbry.getMediaType = (contentType, fileName) => {
return 'unknown'; return 'unknown';
}; };
Lbry.getAppVersionInfo = () =>
new Promise(resolve => {
/*ipcRenderer.once('version-info-received', (event, versionInfo) => {
resolve(versionInfo);
});
ipcRenderer.send('version-info-requested');*/
});
/** /**
* Wrappers for API methods to simulate missing or future behavior. Unlike the old-style stubs, * Wrappers for API methods to simulate missing or future behavior. Unlike the old-style stubs,
* these are designed to be transparent wrappers around the corresponding API methods. * these are designed to be transparent wrappers around the corresponding API methods.

85
src/lbryapi.js Normal file
View file

@ -0,0 +1,85 @@
import Lbry from 'lbry';
import querystring from 'querystring';
const LbryApi = {
exchangePromise: null,
exchangeLastFetched: null,
};
const CONNECTION_STRING = process.env.LBRY_APP_API_URL
? process.env.LBRY_APP_API_URL.replace(/\/*$/, '/') // exactly one slash at the end
: 'https://api.lbry.io/';
const EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000;
LbryApi.getExchangeRates = () => {
if (
!LbryApi.exchangeLastFetched ||
Date.now() - LbryApi.exchangeLastFetched > EXCHANGE_RATE_TIMEOUT
) {
LbryApi.exchangePromise = new Promise((resolve, reject) => {
LbryApi.call('lbc', 'exchange_rate', {}, 'get', true)
.then(({ lbc_usd: LBC_USD, lbc_btc: LBC_BTC, btc_usd: BTC_USD }) => {
const rates = { LBC_USD, LBC_BTC, BTC_USD };
resolve(rates);
})
.catch(reject);
});
LbryApi.exchangeLastFetched = Date.now();
}
return LbryApi.exchangePromise;
};
LbryApi.call = (resource, action, params = {}, method = 'get') => {
if (!Lbryio.enabled) {
console.log(__('Internal API disabled'));
return Promise.reject(new Error(__('LBRY internal API is disabled')));
}
if (!(method === 'get' || method === 'post')) {
return Promise.reject(new Error(__('Invalid method')));
}
function checkAndParse(response) {
if (response.status >= 200 && response.status < 300) {
return response.json();
}
return response.json().then(json => {
let error;
if (json.error) {
error = new Error(json.error);
} else {
error = new Error('Unknown API error signature');
}
error.response = response; // This is primarily a hack used in actions/user.js
return Promise.reject(error);
});
}
function makeRequest(url, options) {
return fetch(url, options).then(checkAndParse);
}
const fullParams = { ...params };
const qs = querystring.stringify(fullParams);
let url = `${CONNECTION_STRING}${resource}/${action}?${qs}`;
let options = {
method: 'GET',
};
if (method === 'post') {
options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: qs,
};
url = `${CONNECTION_STRING}${resource}/${action}`;
}
return makeRequest(url, options).then(response => response.data);
};
export default LbryApi;

View file

@ -1,176 +0,0 @@
import Lbry from 'lbry';
import querystring from 'querystring';
const Lbryio = {
enabled: true,
authenticationPromise: null,
exchangePromise: null,
exchangeLastFetched: null,
};
const CONNECTION_STRING = process.env.LBRY_APP_API_URL
? process.env.LBRY_APP_API_URL.replace(/\/*$/, '/') // exactly one slash at the end
: 'https://api.lbry.io/';
const EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000;
Lbryio.getExchangeRates = () => {
if (
!Lbryio.exchangeLastFetched ||
Date.now() - Lbryio.exchangeLastFetched > EXCHANGE_RATE_TIMEOUT
) {
Lbryio.exchangePromise = new Promise((resolve, reject) => {
Lbryio.call('lbc', 'exchange_rate', {}, 'get', true)
.then(({ lbc_usd: LBC_USD, lbc_btc: LBC_BTC, btc_usd: BTC_USD }) => {
const rates = { LBC_USD, LBC_BTC, BTC_USD };
resolve(rates);
})
.catch(reject);
});
Lbryio.exchangeLastFetched = Date.now();
}
return Lbryio.exchangePromise;
};
Lbryio.call = (resource, action, params = {}, method = 'get') => {
if (!Lbryio.enabled) {
console.log(__('Internal API disabled'));
return Promise.reject(new Error(__('LBRY internal API is disabled')));
}
if (!(method === 'get' || method === 'post')) {
return Promise.reject(new Error(__('Invalid method')));
}
function checkAndParse(response) {
if (response.status >= 200 && response.status < 300) {
return response.json();
}
return response.json().then(json => {
let error;
if (json.error) {
error = new Error(json.error);
} else {
error = new Error('Unknown API error signature');
}
error.response = response; // This is primarily a hack used in actions/user.js
return Promise.reject(error);
});
}
function makeRequest(url, options) {
return fetch(url, options).then(checkAndParse);
}
return Lbryio.getAuthToken().then(token => {
const fullParams = { auth_token: token, ...params };
const qs = querystring.stringify(fullParams);
let url = `${CONNECTION_STRING}${resource}/${action}?${qs}`;
let options = {
method: 'GET',
};
if (method === 'post') {
options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: qs,
};
url = `${CONNECTION_STRING}${resource}/${action}`;
}
return makeRequest(url, options).then(response => response.data);
});
};
Lbryio.authToken = null;
Lbryio.getAuthToken = () =>
new Promise(resolve => {
if (Lbryio.authToken) {
resolve(Lbryio.authToken);
} else {
/*ipcRenderer.once('auth-token-response', (event, token) => {
Lbryio.authToken = token;
return resolve(token);
});
ipcRenderer.send('get-auth-token');*/
}
});
Lbryio.setAuthToken = token => {
Lbryio.authToken = token ? token.toString().trim() : null;
//ipcRenderer.send('set-auth-token', token);
};
Lbryio.getCurrentUser = () => Lbryio.call('user', 'me');
Lbryio.authenticate = () => {
if (!Lbryio.enabled) {
return new Promise(resolve => {
resolve({
id: 1,
language: 'en',
primary_email: 'disabled@lbry.io',
has_verified_email: true,
is_identity_verified: true,
is_reward_approved: false,
});
});
}
if (Lbryio.authenticationPromise === null) {
Lbryio.authenticationPromise = new Promise((resolve, reject) => {
Lbryio.getAuthToken()
.then(token => {
if (!token || token.length > 60) {
return false;
}
// check that token works
return Lbryio.getCurrentUser()
.then(() => true)
.catch(() => false);
})
.then(isTokenValid => {
if (isTokenValid) {
return reject;
}
return Lbry.status()
.then(status =>
Lbryio.call(
'user',
'new',
{
auth_token: '',
language: 'en',
app_id: status.installation_id,
},
'post'
)
)
.then(response => {
if (!response.auth_token) {
throw new Error(__('auth_token is missing from response'));
}
return Lbryio.setAuthToken(response.auth_token);
});
})
.then(Lbryio.getCurrentUser)
.then(resolve, reject);
});
}
return Lbryio.authenticationPromise;
};
Lbryio.getStripeToken = () =>
CONNECTION_STRING.startsWith('http://localhost:')
? 'pk_test_NoL1JWL7i1ipfhVId5KfDZgo'
: 'pk_live_e8M4dRNnCCbmpZzduEUZBgJO';
export default Lbryio;

View file

@ -1,5 +1,5 @@
import * as ACTIONS from 'constants/action_types'; import * as ACTIONS from 'constants/action_types';
import Lbryio from 'lbryio'; import LbryApi from 'lbryapi';
import { selectClaimsByUri } from 'redux/selectors/claims'; import { selectClaimsByUri } from 'redux/selectors/claims';
// eslint-disable-next-line import/prefer-default-export // eslint-disable-next-line import/prefer-default-export
@ -30,7 +30,7 @@ export function doFetchCostInfoForUri(uri) {
} else if (fee.currency === 'LBC') { } else if (fee.currency === 'LBC') {
resolve({ cost: fee.amount, includesData: true }); resolve({ cost: fee.amount, includesData: true });
} else { } else {
Lbryio.getExchangeRates().then(({ LBC_USD }) => { LbryApi.getExchangeRates().then(({ LBC_USD }) => {
resolve({ cost: fee.amount / LBC_USD, includesData: true }); resolve({ cost: fee.amount / LBC_USD, includesData: true });
}); });
} }