Compare commits

...
44 Commits
Author SHA1 Message Date
Akinwale Ariwodola 1637752b02 Merge pull request #510 from lbryio/release-0.6.1 2019-04-02 14:51:57 +01:00
Akinwale Ariwodola 4ce424d4db move unclaimed reward amount to the left of floating wallet balance 2019-04-02 12:00:33 +01:00
Akinwale Ariwodola 916af88c53 bumpversion 0.6.0 --> 0.6.1 2019-04-02 11:40:58 +01:00
Akinwale Ariwodola b21776c517 Merge pull request #509 from lbryio/sdk-requirements-cleanup
clean up python sdk requirements
2019-03-31 06:51:37 +01:00
Akinwale Ariwodola 6bb128e38a clean up python sdk requirements 2019-03-30 23:51:38 +01:00
Akinwale Ariwodola 8b2694efb7 New build (#508)
* fix build for openssl 1.1.1b required for sdk
(cherry picked from commit aa49e3b2755b97b6331cdbbb89efc954de8d5977)

* use js code from master

* fix openssl recipe and tweak build
(cherry picked from commit 6e94c27021c7bd7b1e880c2fc314850e36a5a38e)

* remove unused build recipes
(cherry picked from commit f5c0577bdb175bfc0990602936bbc9e2052e1f25)
2019-03-30 21:58:45 +01:00
Akinwale Ariwodola f853132e9b use different gradle output (until sync build update) 2019-03-30 21:19:31 +01:00
Akinwale Ariwodola 39e8d5513a add modified mangled-glibc-syscalls.h for crystax build 2019-03-30 20:43:15 +01:00
Akinwale Ariwodola 6feadf73dd revert to default gradle apk output folder 2019-03-30 20:36:56 +01:00
Akinwale Ariwodola d683c48338 add pipeline status to README.md 2019-03-30 10:24:20 +01:00
Akinwale Ariwodola 4a684b0bec Merge pull request #502 from lbryio/search-fix
fix search and related content
2019-03-28 18:01:47 +01:00
Akinwale Ariwodola 6d7768e904 Merge pull request #503 from lbryio/file-page-tweaks
some pre-redesign tweaks to the file page
2019-03-27 10:17:16 +01:00
Akinwale Ariwodola a645c4530f some pre-redesign tweaks to the file page 2019-03-27 10:13:13 +01:00
Akinwale Ariwodola 4d61462290 fix search and related content 2019-03-27 08:13:09 +01:00
Akinwale Ariwodola 877ce8d008 fix imports on trending page 2019-03-26 16:21:38 +01:00
Akinwale Ariwodola fbff91774e use pipeline number as build number 2019-03-26 15:49:08 +01:00
Akinwale Ariwodola 53fb072373 Collapse description (#490)
* collapse file description by default and add display toggle
2019-03-26 15:10:07 +01:00
Akinwale Ariwodola f30f1f47d5 Gitlab CI (#498) 2019-03-26 15:08:50 +01:00
Akinwale Ariwodola d8b0e89c6c Build update (#495)
* package and build updates
* add sdk preview license to build
* use build tools 26.0.2
* use different libgmp mirror
2019-03-25 07:45:19 +01:00
Akinwale Ariwodola a353f13ebb Merge pull request #494 from lbryio/lbry-dependencies
update to use new imports from lbryinc and lbry-redux
2019-03-22 08:22:29 +01:00
Akinwale Ariwodola 0d3415441f update to use new imports from lbryinc and lbry-redux 2019-03-20 15:37:14 +01:00
Akinwale Ariwodola 860d509d0f Merge pull request #492 from lbryio/lbry.com
update lbry.io references to lbry.com
2019-03-20 15:02:20 +01:00
Akinwale Ariwodola c86fdec8e6 Save media position (#489) 2019-03-20 15:01:21 +01:00
Akinwale Ariwodola ca6fedd05c Merge pull request #488 from lbryio/search-hint
shorten search hint
2019-03-15 14:37:14 +01:00
Akinwale Ariwodola 07209a79de Merge pull request #487 from lbryio/channel-page-header
add channel name to channel page
2019-03-15 14:36:39 +01:00
Akinwale Ariwodola 4132416f0d shorten search hint 2019-03-15 13:18:45 +01:00
Akinwale Ariwodola e62d5741c2 add channel name to channel page 2019-03-15 12:50:58 +01:00
Akinwale Ariwodola 81dca20b17 Merge pull request #480 from lbryio/playable-content
fix Play icon being displayed for non-playable content
2019-03-15 11:58:28 +01:00
Akinwale Ariwodola f203f63c36 update lbry.io references to lbry.com 2019-03-11 18:16:17 +01:00
Akinwale Ariwodola 26cd218ec0 fix play icon being displayed for non-playable content 2019-03-11 12:11:42 +01:00
Akinwale Ariwodola e402a0376a implement direct search and show featured claim result (#468) 2019-03-11 12:09:08 +01:00
Akinwale Ariwodola bac202d4ec Pending Rewards (#467)
* show unclaimed rewards amount beside floating wallet balance
2019-03-11 09:47:14 +01:00
Akinwale Ariwodola bb8d856d17 Merge pull request #469 from lbryio/send-log-android6
fix send log error on devices running Android 6 and lower
2019-03-09 08:41:14 +01:00
Akinwale Ariwodola 42075291ce fix send log error on devices running Android 6 and lower 2019-03-08 17:23:09 +01:00
Akinwale Ariwodola 32b128fe40 upgrade to sdk 0.32.4 (#458)
* upgrade to sdk 0.32.4
* update aiohttp version
* fix top margin on explore page
2019-03-06 15:11:26 +01:00
Akinwale Ariwodola df63ab5f91 fix lodash vulnerability 2019-03-06 12:37:56 +01:00
Akinwale Ariwodola 88e3670493 fix merge module in package.json 2019-03-06 07:30:34 +01:00
Akinwale Ariwodola eceeed8290 bumpversion 0.5.0 --> 0.6.0 2019-03-05 14:46:59 +01:00
Akinwale Ariwodola caa9c80d44 Improved uri bar (#450)
* add descriptions to uri bar items
2019-03-05 10:17:50 +01:00
Akinwale Ariwodola 7e76e47d77 Merge pull request #449 from lbryio/improve-suggested-subs
add button to view subscriptions from the suggested subscriptions view
2019-03-05 10:17:22 +01:00
Akinwale Ariwodola ba76c9c17e fix missing import on transaction history page 2019-03-04 17:14:55 +01:00
Akinwale Ariwodola 9555c6fa76 add button to view subscriptions from the suggested subscriptions view 2019-03-04 16:06:51 +01:00
Akinwale Ariwodola c37a6f5c27 move uri omnibar to top (#444) 2019-03-01 19:25:16 +01:00
Akinwale Ariwodola b5af71d798 improved back navigation with file URIs and drawer menu items (#443) 2019-03-01 19:25:01 +01:00
420 changed files with 16189 additions and 6502 deletions

No files matched your search

+2
View File
@@ -9,3 +9,5 @@ src/main/assets/index.android.bundle.meta
*.log
.vagrant
lbry-android.keystore
.gitsecret/keys/random_seed
+58
View File
@@ -0,0 +1,58 @@
stages:
- build
- deploy
- release
build apk:
stage: build
image: lbry/android-base:latest
before_script:
- export BUILD_VERSION=$(cat $CI_PROJECT_DIR/src/main/python/main.py | grep --color=never -oP '([0-9]+\.?)+')
artifacts:
paths:
- bin/browser-*-release.apk
script:
- export PATH=/usr/bin:$PATH
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- cd app
- npm install
- cd ..
- wget -q 'https://eu.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz' -P ~/.buildozer/android/
- tar -xf ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz -C ~/.buildozer/android/
- rm -rf ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
- ln -s ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21 ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
- cp -f $CI_PROJECT_DIR/scripts/build-target-python.sh ~/.buildozer/android/crystax-ndk-10.3.2/build/tools/build-target-python.sh
- cp -f $CI_PROJECT_DIR/scripts/mangled-glibc-syscalls.h ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21/arch-arm/usr/include/crystax/bionic/libc/include/sys/mangled-glibc-syscalls.h
- rm ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz
- git secret reveal
- mv buildozer.spec.travis buildozer.spec
- "./release.sh | grep -Fv -e 'working:' -e 'copy' -e 'Compiling' --line-buffered"
- cp $CI_PROJECT_DIR/bin/browser-$BUILD_VERSION-release.apk /dev/null
deploy build.lbry.io:
image: python:latest
stage: deploy
dependencies:
- build apk
before_script:
- pip install awscli
- export BUILD_VERSION=$(cat $CI_PROJECT_DIR/src/main/python/main.py | grep --color=never -oP '([0-9]+\.?)+')
- export BUILD_APK_FILENAME=browser-$BUILD_VERSION-release.apk
script:
- aws s3 cp bin/$BUILD_APK_FILENAME s3://build.lbry.io/android/build-${CI_PIPELINE_IID}_commit-${CI_COMMIT_SHA:0:7}/$BUILD_APK_FILENAME
- aws s3 cp bin/$BUILD_APK_FILENAME s3://build.lbry.io/android/push.apk
release apk:
image: python:latest
stage: release
only:
- tags
dependencies:
- build apk
before_script:
- pip install awscli githubrelease
- export BUILD_VERSION=$(cat $CI_PROJECT_DIR/src/main/python/main.py | grep --color=never -oP '([0-9]+\.?)+')
- export BUILD_APK_FILENAME=browser-$BUILD_VERSION-release.apk
script:
- githubrelease release lbryio/lbry-android create $CI_COMMIT_TAG --publish bin/$BUILD_APK_FILENAME
- aws s3 cp bin/$BUILD_APK_FILENAME s3://build.lbry.io/android/latest.apk
View File
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
lbry-android.keystore:
+5 -4
View File
@@ -28,10 +28,10 @@ install:
- cd ..
- mv buildozer.spec.travis buildozer.spec
- mkdir -p cd ~/.buildozer/android/platform/
- wget -q 'https://us.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz' -P ~/.buildozer/android/
- wget -q 'https://dist.testnet.lbry.tech/crystax-ndk-10.3.2-linux-x86_64.tar.xz' -P ~/.buildozer/android/
- wget -q 'https://dl.google.com/android/android-sdk_r23-linux.tgz' -P ~/.buildozer/android/platform/
- wget -q 'https://dl.google.com/android/repository/platform-27_r01.zip' -P ~/.buildozer/android/platform/
- wget -q 'https://dl.google.com/android/repository/build-tools_r26.0.1-linux.zip' -P ~/.buildozer/android/platform/
- wget -q 'https://dl.google.com/android/repository/build-tools_r26.0.2-linux.zip' -P ~/.buildozer/android/platform/
- tar -xf ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz -C ~/.buildozer/android/
- cp -f $TRAVIS_BUILD_DIR/scripts/build-target-python.sh ~/.buildozer/android/crystax-ndk-10.3.2/build/tools/build-target-python.sh
- rm -rf ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
@@ -41,10 +41,11 @@ install:
- unzip -qq ~/.buildozer/android/platform/platform-27_r01.zip -d ~/.buildozer/android/platform/android-sdk-23/platforms
- mv ~/.buildozer/android/platform/android-sdk-23/platforms/android-8.1.0 ~/.buildozer/android/platform/android-sdk-23/platforms/android-27
- mkdir -p ~/.buildozer/android/platform/android-sdk-23/build-tools
- unzip -qq ~/.buildozer/android/platform/build-tools_r26.0.1-linux.zip -d ~/.buildozer/android/platform/android-sdk-23/build-tools
- mv ~/.buildozer/android/platform/android-sdk-23/build-tools/android-8.0.0 ~/.buildozer/android/platform/android-sdk-23/build-tools/26.0.1
- unzip -qq ~/.buildozer/android/platform/build-tools_r26.0.2-linux.zip -d ~/.buildozer/android/platform/android-sdk-23/build-tools
- mv ~/.buildozer/android/platform/android-sdk-23/build-tools/android-8.1.0 ~/.buildozer/android/platform/android-sdk-23/build-tools/26.0.2
- mkdir -p ~/.buildozer/android/platform/android-sdk-23/licenses
- echo $'\nd56f5187479451eabf01fb78af6dfcb131a6481e' > ~/.buildozer/android/platform/android-sdk-23/licenses/android-sdk-license
- echo $'\n84831b9409646a918e30573bab4c9c91346d8abd' > ~/.buildozer/android/platform/android-sdk-23/licenses/android-sdk-preview-license
script:
- "./release.sh | grep -Fv -e 'working:' -e 'copy' -e 'Compiling' --line-buffered"
- cp $TRAVIS_BUILD_DIR/bin/*.apk /dev/null
+1 -1
View File
@@ -1,5 +1,5 @@
# LBRY Android
[![Build Status](https://travis-ci.org/lbryio/lbry-android.svg?branch=master)](https://travis-ci.org/lbryio/lbry-android)
[![pipeline status](https://ci.lbry.tech/lbry/lbry-android/badges/master/pipeline.svg)](https://ci.lbry.tech/lbry/lbry-android/commits/master)
An Android browser and wallet for the [LBRY](https://lbry.io) network. This app bundles [lbrynet-daemon](https://github.com/lbryio/lbry) as a background service with a UI layer built with React Native. The APK is built using buildozer and the Gradle build tool.
+922 -914
View File
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -8,15 +8,17 @@
"dependencies": {
"base-64": "^0.1.0",
"@expo/vector-icons": "^8.1.0",
"lbry-redux": "lbryio/lbry-redux#old-search",
"lbry-redux": "lbryio/lbry-redux",
"lbryinc": "lbryio/lbryinc",
"lodash": ">=4.17.11",
"merge": ">=1.2.1",
"moment": "^2.22.1",
"react": "16.2.0",
"react-native": "0.55.3",
"react-native-country-picker-modal": "^0.6.2",
"react-native-exception-handler": "2.9.0",
"react-native-fast-image": "^5.0.3",
"react-native-fetch-blob": "^0.10.8",
"rn-fetch-blob": "^0.10.15",
"react-native-image-zoom-viewer": "^2.2.5",
"react-native-phone-input": "lbryio/react-native-phone-input",
"react-native-vector-icons": "^5.0.0",
@@ -27,7 +29,7 @@
"redux": "^3.6.0",
"redux-logger": "3.0.6",
"redux-persist": "^4.8.0",
"redux-persist-filesystem-storage": "^1.2.0",
"redux-persist-filesystem-storage": "^1.3.2",
"redux-persist-transform-compress": "^4.2.0",
"redux-persist-transform-filter": "0.0.10",
"redux-thunk": "^2.2.0"
+31 -37
View File
@@ -1,18 +1,18 @@
import React from 'react';
import AboutPage from '../page/about';
import DiscoverPage from '../page/discover';
import DownloadsPage from '../page/downloads';
import FilePage from '../page/file';
import FirstRunScreen from '../page/firstRun';
import RewardsPage from '../page/rewards';
import TrendingPage from '../page/trending';
import SearchPage from '../page/search';
import SettingsPage from '../page/settings';
import SplashScreen from '../page/splash';
import SubscriptionsPage from '../page/subscriptions';
import TransactionHistoryPage from '../page/transactionHistory';
import WalletPage from '../page/wallet';
import SearchInput from '../component/searchInput';
import AboutPage from 'page/about';
import DiscoverPage from 'page/discover';
import DownloadsPage from 'page/downloads';
import FilePage from 'page/file';
import FirstRunScreen from 'page/firstRun';
import RewardsPage from 'page/rewards';
import TrendingPage from 'page/trending';
import SearchPage from 'page/search';
import SettingsPage from 'page/settings';
import SplashScreen from 'page/splash';
import SubscriptionsPage from 'page/subscriptions';
import TransactionHistoryPage from 'page/transactionHistory';
import WalletPage from 'page/wallet';
import SearchInput from 'component/searchInput';
import {
createDrawerNavigator,
createStackNavigator,
@@ -33,7 +33,6 @@ import {
TextInput,
ToastAndroid
} from 'react-native';
import { doPopDrawerStack } from 'redux/actions/drawer';
import { doDeleteCompleteBlobs } from 'redux/actions/file';
import { selectDrawerStack } from 'redux/selectors/drawer';
import { SETTINGS, doDismissToast, doToast, selectToast } from 'lbry-redux';
@@ -69,9 +68,8 @@ const discoverStack = createStackNavigator({
screen: DiscoverPage,
navigationOptions: ({ navigation }) => ({
title: 'Explore',
headerLeft: menuNavigationButton(navigation),
headerTitleStyle: discoverStyle.titleText
})
header: null
}),
},
File: {
screen: FilePage,
@@ -82,18 +80,19 @@ const discoverStack = createStackNavigator({
Search: {
screen: SearchPage,
navigationOptions: ({ navigation }) => ({
headerTitleStyle: discoverStyle.titleText
header: null
})
}
}, {
headerMode: 'screen'
headerMode: 'screen',
transitionConfig: () => ({ screenInterpolator: () => null }),
});
discoverStack.navigationOptions = ({ navigation }) => {
let drawerLockMode = 'unlocked';
if (navigation.state.index > 0) {
/*if (navigation.state.index > 0) {
drawerLockMode = 'locked-closed';
}
}*/
return {
drawerLockMode
@@ -105,8 +104,7 @@ const trendingStack = createStackNavigator({
screen: TrendingPage,
navigationOptions: ({ navigation }) => ({
title: 'Trending',
headerLeft: menuNavigationButton(navigation),
headerTitleStyle: discoverStyle.titleText
header: null
})
}
});
@@ -116,8 +114,7 @@ const myLbryStack = createStackNavigator({
screen: DownloadsPage,
navigationOptions: ({ navigation }) => ({
title: 'Downloads',
headerLeft: menuNavigationButton(navigation),
headerTitleStyle: discoverStyle.titleText
header: null
})
}
});
@@ -127,8 +124,7 @@ const mySubscriptionsStack = createStackNavigator({
screen: SubscriptionsPage,
navigationOptions: ({ navigation }) => ({
title: 'Subscriptions',
headerLeft: menuNavigationButton(navigation),
headerTitleStyle: discoverStyle.titleText
header: null
})
}
});
@@ -138,8 +134,7 @@ const rewardsStack = createStackNavigator({
screen: RewardsPage,
navigationOptions: ({ navigation }) => ({
title: 'Rewards',
headerLeft: menuNavigationButton(navigation),
headerTitleStyle: discoverStyle.titleText
header: null
})
}
});
@@ -149,20 +144,19 @@ const walletStack = createStackNavigator({
screen: WalletPage,
navigationOptions: ({ navigation }) => ({
title: 'Wallet',
headerLeft: menuNavigationButton(navigation),
headerTitleStyle: discoverStyle.titleText
header: null
})
},
TransactionHistory: {
screen: TransactionHistoryPage,
navigationOptions: {
title: 'Transaction History',
drawerLockMode: 'locked-closed',
headerTitleStyle: discoverStyle.titleText
header: null
}
}
}, {
headerMode: 'screen'
headerMode: 'screen',
transitionConfig: () => ({ screenInterpolator: () => null }),
});
const drawer = createDrawerNavigator({
@@ -246,7 +240,7 @@ class AppWithNavigationState extends React.Component {
componentWillMount() {
AppState.addEventListener('change', this._handleAppStateChange);
BackHandler.addEventListener('hardwareBackPress', function() {
const { dispatch, nav, drawerStack, popDrawerStack } = this.props;
const { dispatch, nav, drawerStack } = this.props;
// There should be a better way to check this
if (nav.routes.length > 0) {
if (nav.routes[0].routeName === 'Main') {
@@ -255,7 +249,7 @@ class AppWithNavigationState extends React.Component {
mainRoute.routes[0].index > 0 /* Discover stack index */ ||
mainRoute.routes[4].index > 0 /* Wallet stack index */ ||
mainRoute.index >= 5 /* Settings and About screens */) {
dispatchNavigateBack(dispatch, nav, drawerStack, doPopDrawerStack);
dispatchNavigateBack(dispatch, nav, drawerStack);
return true;
}
}
@@ -1,11 +1,10 @@
import { connect } from 'react-redux';
import {
doFetchCostInfoForUri,
makeSelectFileInfoForUri,
makeSelectDownloadingForUri,
makeSelectLoadingForUri,
makeSelectCostInfoForUri
} from 'lbry-redux';
import { doFetchCostInfoForUri, makeSelectCostInfoForUri } from 'lbryinc';
import { doPurchaseUri, doStartDownload } from 'redux/actions/file';
import FileDownloadButton from './view';
+9 -2
View File
@@ -51,6 +51,7 @@ class FileListItem extends React.PureComponent {
claim,
fileInfo,
metadata,
featuredResult,
isResolvingUri,
isDownloaded,
style,
@@ -72,6 +73,10 @@ class FileListItem extends React.PureComponent {
fullChannelUri = channelClaimId ? `${channel}#${channelClaimId}` : channel;
}
if (featuredResult && !isResolvingUri && !claim && !title && !name) {
return null;
}
return (
<View style={style}>
<TouchableOpacity style={style} onPress={onPress}>
@@ -81,15 +86,17 @@ class FileListItem extends React.PureComponent {
title={(title || name)}
thumbnail={metadata ? metadata.thumbnail : null} />
<View style={fileListStyle.detailsContainer}>
{featuredResult && <Text style={fileListStyle.featuredUri} numberOfLines={1}>{uri}</Text>}
{!title && !name && !channel && isResolving && (
<View>
{(!title && !name) && <Text style={fileListStyle.uri}>{uri}</Text>}
{(!title && !name) && <View style={fileListStyle.row}>
<ActivityIndicator size={"small"} color={Colors.LbryGreen} />
<ActivityIndicator size={"small"} color={featuredResult ? Colors.White : Colors.LbryGreen} />
</View>}
</View>)}
{(title || name) && <Text style={fileListStyle.title}>{this.formatTitle(title) || this.formatTitle(name)}</Text>}
{(title || name) && <Text style={featuredResult ? fileListStyle.featuredTitle : fileListStyle.title}>{this.formatTitle(title) || this.formatTitle(name)}</Text>}
{channel &&
<Link style={fileListStyle.publisher} text={channel} onPress={() => {
navigateToUri(navigation, normalizeURI(fullChannelUri));
+2 -6
View File
@@ -1,10 +1,6 @@
import { connect } from 'react-redux';
import {
doFetchCostInfoForUri,
makeSelectCostInfoForUri,
makeSelectFetchingCostInfoForUri,
makeSelectClaimForUri
} from 'lbry-redux';
import { makeSelectClaimForUri } from 'lbry-redux';
import { doFetchCostInfoForUri, makeSelectCostInfoForUri, makeSelectFetchingCostInfoForUri } from 'lbryinc';
import FilePrice from './view';
const select = (state, props) => ({
@@ -1,9 +1,11 @@
import { connect } from 'react-redux';
import { selectBalance } from 'lbry-redux';
import FloatingWalletBalance from './view';
import { doRewardList, selectUnclaimedRewardValue, selectFetchingRewards, selectUser } from 'lbryinc';
const select = state => ({
balance: selectBalance(state),
unclaimedRewardAmount: selectUnclaimedRewardValue(state),
});
export default connect(select, null)(FloatingWalletBalance);
+21 -12
View File
@@ -2,10 +2,11 @@
import React from 'react';
import { ActivityIndicator, Text, TouchableOpacity, View } from 'react-native';
import { formatCredits } from 'lbry-redux'
import Address from '../address';
import Button from '../button';
import Colors from '../../styles/colors';
import floatingButtonStyle from '../../styles/floatingButton';
import Address from 'component/address';
import Button from 'component/button';
import Colors from 'styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5';
import floatingButtonStyle from 'styles/floatingButton';
type Props = {
balance: number,
@@ -13,16 +14,24 @@ type Props = {
class FloatingWalletBalance extends React.PureComponent<Props> {
render() {
const { balance, navigation } = this.props;
const { balance, navigation, unclaimedRewardAmount } = this.props;
return (
<TouchableOpacity style={[floatingButtonStyle.container, floatingButtonStyle.bottomRight]}
onPress={() => navigation && navigation.navigate({ routeName: 'WalletStack' })}>
{isNaN(balance) && <ActivityIndicator size="small" color={Colors.White} />}
<Text style={floatingButtonStyle.text}>
{(balance || balance === 0) && (formatCredits(parseFloat(balance), 2) + ' LBC')}
</Text>
</TouchableOpacity>
<View style={[floatingButtonStyle.view, floatingButtonStyle.bottomRight]}>
{unclaimedRewardAmount > 0 &&
<TouchableOpacity style={floatingButtonStyle.pendingContainer}
onPress={() => navigation && navigation.navigate({ routeName: 'Rewards' })} >
<Icon name="award" size={18} style={floatingButtonStyle.rewardIcon} />
<Text style={floatingButtonStyle.text}>{unclaimedRewardAmount}</Text>
</TouchableOpacity>}
<TouchableOpacity style={floatingButtonStyle.container}
onPress={() => navigation && navigation.navigate({ routeName: 'WalletStack' })}>
{isNaN(balance) && <ActivityIndicator size="small" color={Colors.White} />}
<Text style={floatingButtonStyle.text}>
{(balance || balance === 0) && (formatCredits(parseFloat(balance), 2) + ' LBC')}
</Text>
</TouchableOpacity>
</View>
);
}
}
+7 -3
View File
@@ -1,10 +1,14 @@
import { connect } from 'react-redux';
import { SETTINGS } from 'lbry-redux';
import { SETTINGS, savePosition } from 'lbry-redux';
import { makeSelectClientSetting } from '../../redux/selectors/settings';
import MediaPlayer from './view';
const select = state => ({
backgroundPlayEnabled: makeSelectClientSetting(SETTINGS.BACKGROUND_PLAY_ENABLED)(state),
backgroundPlayEnabled: makeSelectClientSetting(SETTINGS.BACKGROUND_PLAY_ENABLED)(state),
});
export default connect(select, null)(MediaPlayer);
const perform = dispatch => ({
savePosition: (claimId, outpoint, position) => dispatch(savePosition(claimId, outpoint, position)),
});
export default connect(select, perform)(MediaPlayer);
+11 -1
View File
@@ -81,13 +81,22 @@ class MediaPlayer extends React.PureComponent {
this.setState({
duration: data.duration
});
const { position } = this.props;
if (!isNaN(parseFloat(position)) && position > 0) {
this.video.seek(position);
}
if (this.props.onMediaLoaded) {
this.props.onMediaLoaded();
}
}
onProgress = (data) => {
this.setState({ currentTime: data.currentTime });
const { savePosition, fileInfo } = this.props;
this.setState({ currentTime: data.currentTime }, () => savePosition(fileInfo.claim_id, fileInfo.outpoint, data.currentTime));
if (!this.state.seeking) {
this.setSeekerPosition(this.calculateSeekerPosition());
@@ -98,6 +107,7 @@ class MediaPlayer extends React.PureComponent {
this.props.onPlaybackStarted();
}
this.setState({ firstPlay: false });
this.hidePlayerControls();
}
}
@@ -213,7 +213,7 @@ class PhoneNumberRewardSubcard extends React.PureComponent {
{this.state.phoneVerifyFailed &&
<View style={rewardStyle.failureFootnote}>
<Text style={rewardStyle.subcardText}>
Sorry, we were unable to verify your phone number. Please go to <Link style={rewardStyle.textLink} href="http://chat.lbry.io" text="chat.lbry.io" /> for manual verification if this keeps happening.
Sorry, we were unable to verify your phone number. Please go to <Link style={rewardStyle.textLink} href="http://chat.lbry.com" text="chat.lbry.com" /> for manual verification if this keeps happening.
</Text>
</View>}
</View>
+1 -1
View File
@@ -14,7 +14,7 @@ const select = (state, props) => ({
});
const perform = dispatch => ({
search: query => dispatch(doSearch(query, 10, undefined, true)),
search: query => dispatch(doSearch(query, 20, undefined, true)),
});
export default connect(
+5 -5
View File
@@ -1,10 +1,10 @@
import React from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import { navigateToUri } from '../../utils/helper';
import Colors from '../../styles/colors';
import FileListItem from '../fileListItem';
import fileListStyle from '../../styles/fileList';
import relatedContentStyle from '../../styles/relatedContent';
import { navigateToUri } from 'utils/helper';
import Colors from 'styles/colors';
import FileListItem from 'component/fileListItem';
import fileListStyle from 'styles/fileList';
import relatedContentStyle from 'styles/relatedContent';
export default class RelatedContent extends React.PureComponent<Props> {
constructor() {
+1 -1
View File
@@ -83,7 +83,7 @@ class RewardCard extends React.PureComponent<Props> {
<Text style={rewardStyle.rewardTitle}>{reward.reward_title}</Text>
<Text style={rewardStyle.rewardDescription}>{reward.reward_description}</Text>
{claimed && <Link style={rewardStyle.link}
href={`https://explorer.lbry.io/tx/${reward.transaction_id}`}
href={`https://explorer.lbry.com/tx/${reward.transaction_id}`}
text={reward.transaction_id.substring(0, 7)}
error={'The transaction URL could not be opened'} />}
</View>
+4 -6
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { AsyncStorage, NativeModules, Text, TouchableOpacity } from 'react-native';
import { AsyncStorage, NativeModules, Text, TouchableOpacity, View } from 'react-native';
import Button from '../../component/button';
import rewardStyle from '../../styles/reward';
@@ -56,14 +56,12 @@ class RewardSummary extends React.Component {
}
return (
<TouchableOpacity style={rewardStyle.summaryContainer} onPress={() => {
navigation.navigate('Rewards');
}}>
<View style={rewardStyle.summaryContainer}>
<Text style={rewardStyle.summaryText}>
You have {unclaimedRewardAmount} LBC in unclaimed rewards. You have {this.state.actionsLeft} action{this.state.actionsLeft === 1 ? '' : 's'} left to claim your first reward. Tap here to continue.
You have {unclaimedRewardAmount} LBC in unclaimed rewards. LBC stands for LBRY Credits which are tokens that you can use in the digital marketplace. You have {this.state.actionsLeft} action{this.state.actionsLeft === 1 ? '' : 's'} left to claim your first reward.
</Text>
<Button style={rewardStyle.dismissButton} theme={"light"} text={"Dismiss"} onPress={this.onDismissPressed} />
</TouchableOpacity>
</View>
);
}
}
@@ -43,7 +43,7 @@ class SuggestedSubscriptionItem extends React.PureComponent {
return (
<View style={subscriptionsStyle.suggestedContainer}>
<FileItem
style={subscriptionsStyle.fileItem}
style={subscriptionsStyle.compactMainFileItem}
mediaStyle={subscriptionsStyle.fileItemMedia}
uri={this.uriForClaim(claims[0])}
navigation={navigation} />
@@ -37,7 +37,7 @@ class TransactionListItem extends React.PureComponent {
<View style={transactionListStyle.col}>
<Link style={transactionListStyle.smallLink}
text={txid.substring(0, 8)}
href={`https://explorer.lbry.io/tx/${txid}`}
href={`https://explorer.lbry.com/tx/${txid}`}
error={'The transaction URL could not be opened'} />
</View>
<View style={transactionListStyle.col}>
@@ -29,7 +29,14 @@ class UriBarItem extends React.PureComponent {
return (
<TouchableOpacity style={uriBarStyle.item} onPress={onPress}>
{icon}
<Text style={uriBarStyle.itemText} numberOfLines={1}>{shorthand || value} - {type === 'search' ? 'Search' : value}</Text>
<View style={uriBarStyle.itemContent}>
<Text style={uriBarStyle.itemText} numberOfLines={1}>{shorthand || value} - {type === SEARCH_TYPES.SEARCH ? 'Search' : value}</Text>
<Text style={uriBarStyle.itemDesc} numberOfLines={1}>
{type === SEARCH_TYPES.SEARCH && `Search for '${value}'`}
{type === SEARCH_TYPES.CHANNEL && `View the @${shorthand} channel`}
{type === SEARCH_TYPES.FILE && `View content at ${value}`}
</Text>
</View>
</TouchableOpacity>
)
}
+39 -16
View File
@@ -2,12 +2,14 @@
import React from 'react';
import { SEARCH_TYPES, isNameValid, isURIValid, normalizeURI } from 'lbry-redux';
import { FlatList, Keyboard, TextInput, View } from 'react-native';
import { navigateToUri } from '../../utils/helper';
import { navigateToUri } from 'utils/helper';
import UriBarItem from './internal/uri-bar-item';
import uriBarStyle from '../../styles/uriBar';
import NavigationButton from 'component/navigationButton';
import discoverStyle from 'styles/discover';
import uriBarStyle from 'styles/uriBar';
class UriBar extends React.PureComponent {
static INPUT_TIMEOUT = 500;
static INPUT_TIMEOUT = 1000; // 1 second
textInput = null;
@@ -30,17 +32,29 @@ class UriBar extends React.PureComponent {
changeTextTimeout: null,
currentValue: null,
inputText: null,
focused: false
focused: false,
// TODO: Add a setting to enable / disable direct search?
directSearch: true
};
}
handleChangeText = text => {
const newValue = text ? text : '';
clearTimeout(this.state.changeTextTimeout);
const { updateSearchQuery } = this.props;
const { updateSearchQuery, onSearchSubmitted, navigation } = this.props;
let timeout = setTimeout(() => {
updateSearchQuery(text);
if (!text.startsWith('lbry://')) {
// not a URI input, so this is a search, perform a direct search
if (onSearchSubmitted) {
onSearchSubmitted(text);
} else {
navigation.navigate({ routeName: 'Search', key: 'searchPage', params: { searchQuery: text }});
}
}
}, UriBar.INPUT_TIMEOUT);
this.setState({ inputText: newValue, currentValue: newValue, changeTextTimeout: timeout });
}
@@ -93,22 +107,18 @@ class UriBar extends React.PureComponent {
return (
<View style={style}>
{this.state.focused && (
<View style={uriBarStyle.suggestions}>
<FlatList style={uriBarStyle.suggestionList}
data={suggestions}
keyboardShouldPersistTaps={'handled'}
keyExtractor={(item, value) => item.value}
renderItem={({item}) => <UriBarItem item={item}
navigation={navigation}
onPress={() => this.handleItemPress(item)} />} />
</View>)}
<View style={uriBarStyle.uriContainer}>
<NavigationButton
name="bars"
size={24}
style={uriBarStyle.drawerMenuButton}
iconStyle={discoverStyle.drawerHamburger}
onPress={() => navigation.openDrawer() } />
<TextInput ref={(ref) => { this.textInput = ref }}
style={uriBarStyle.uriText}
onLayout={() => { this.setSelection(); }}
selectTextOnFocus={true}
placeholder={'Search for videos, music, games and more'}
placeholder={'Search movies, music, and more'}
underlineColorAndroid={'transparent'}
numberOfLines={1}
clearButtonMode={'while-editing'}
@@ -143,6 +153,19 @@ class UriBar extends React.PureComponent {
}
}}/>
</View>
{(this.state.focused && !this.state.directSearch) && (
<View style={uriBarStyle.suggestions}>
<FlatList style={uriBarStyle.suggestionList}
data={suggestions}
keyboardShouldPersistTaps={'handled'}
keyExtractor={(item, value) => item.value}
renderItem={({item}) => (
<UriBarItem
item={item}
navigation={navigation}
onPress={() => this.handleItemPress(item)}
/>)} />
</View>)}
</View>
);
}
+5 -1
View File
@@ -27,6 +27,8 @@ const Constants = {
DRAWER_ROUTE_WALLET: "Wallet",
DRAWER_ROUTE_SETTINGS: "Settings",
DRAWER_ROUTE_ABOUT: "About",
DRAWER_ROUTE_SEARCH: "Search",
DRAWER_ROUTE_TRANSACTION_HISTORY: "TransactionHistory",
SUBSCRIPTIONS_VIEW_ALL: 'view_all',
SUBSCRIPTIONS_VIEW_LATEST_FIRST: 'view_latest_first',
@@ -45,5 +47,7 @@ export const DrawerRoutes = [
Constants.DRAWER_ROUTE_REWARDS,
Constants.DRAWER_ROUTE_WALLET,
Constants.DRAWER_ROUTE_SETTINGS,
Constants.DRAWER_ROUTE_ABOUT
Constants.DRAWER_ROUTE_ABOUT,
Constants.DRAWER_ROUTE_SEARCH,
Constants.DRAWER_ROUTE_TRANSACTION_HISTORY
];
+14 -4
View File
@@ -11,15 +11,22 @@ import {
} from 'react-native';
import {
Lbry,
blacklistReducer,
claimsReducer,
costInfoReducer,
contentReducer,
fileInfoReducer,
notificationsReducer,
searchReducer,
walletReducer
} from 'lbry-redux';
import { authReducer, rewardsReducer, subscriptionsReducer, userReducer } from 'lbryinc';
import {
authReducer,
blacklistReducer,
costInfoReducer,
homepageReducer,
rewardsReducer,
subscriptionsReducer,
userReducer
} from 'lbryinc';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { createLogger } from 'redux-logger';
import { AppNavigator } from 'component/AppNavigator';
@@ -81,9 +88,11 @@ const reducers = combineReducers({
auth: authReducer,
blacklist: blacklistReducer,
claims: claimsReducer,
content: contentReducer,
costInfo: costInfoReducer,
drawer: drawerReducer,
fileInfo: fileInfoReducer,
homepage: homepageReducer,
nav: navigatorReducer,
notifications: notificationsReducer,
rewards: rewardsReducer,
@@ -113,13 +122,14 @@ window.store = store;
const compressor = createCompressor();
const authFilter = createFilter('auth', ['authToken']);
const contentFilter = createFilter('content', ['positions']);
const saveClaimsFilter = createFilter('claims', ['byId', 'claimsByUri']);
const subscriptionsFilter = createFilter('subscriptions', ['enabledChannelNotifications', 'subscriptions']);
const settingsFilter = createFilter('settings', ['clientSettings']);
const walletFilter = createFilter('wallet', ['receiveAddress']);
const persistOptions = {
whitelist: ['auth', 'claims', 'subscriptions', 'settings', 'wallet'],
whitelist: ['auth', 'claims', 'content', 'subscriptions', 'settings', 'wallet'],
// Order is important. Needs to be compressed last or other transforms can't
// read the data
transforms: [authFilter, saveClaimsFilter, subscriptionsFilter, settingsFilter, walletFilter, compressor],
+4 -4
View File
@@ -52,9 +52,9 @@ class AboutPage extends React.PureComponent {
digital content they are interested in.
</Text>
<View style={aboutStyle.links}>
<Link style={aboutStyle.link} href="https://lbry.io/faq/what-is-lbry" text="What is LBRY?" />
<Link style={aboutStyle.link} href="https://lbry.io/faq/android-basics" text="Android App Basics" />
<Link style={aboutStyle.link} href="https://lbry.io/faq" text="Frequently Asked Questions" />
<Link style={aboutStyle.link} href="https://lbry.com/faq/what-is-lbry" text="What is LBRY?" />
<Link style={aboutStyle.link} href="https://lbry.com/faq/android-basics" text="Android App Basics" />
<Link style={aboutStyle.link} href="https://lbry.com/faq" text="Frequently Asked Questions" />
</View>
<Text style={aboutStyle.socialTitle}>Get Social</Text>
<Text style={aboutStyle.paragraph}>
@@ -78,7 +78,7 @@ class AboutPage extends React.PureComponent {
<View>
<Link
style={aboutStyle.listLink}
href={`http://lbry.io/list/edit/${accessToken}`}
href={`http://lbry.com/list/edit/${accessToken}`}
text="Update mailing preferences" />
</View>
</View>}
+6 -2
View File
@@ -6,6 +6,7 @@ import Colors from 'styles/colors';
import Button from 'component/button';
import FileList from 'component/fileList';
import PageHeader from 'component/pageHeader';
import SubscribeButton from 'component/subscribeButton';
import UriBar from 'component/uriBar';
import channelPageStyle from 'styles/channelPage';
@@ -82,7 +83,11 @@ class ChannelPage extends React.PureComponent {
return (
<View style={channelPageStyle.container}>
<PageHeader title={name} onBackPressed={() => navigateBack(navigation, drawerStack, popDrawerStack)} />
<UriBar value={uri} navigation={navigation} />
<View style={channelPageStyle.channelHeader}>
<Text style={channelPageStyle.channelName}>{name}</Text>
<SubscribeButton style={channelPageStyle.subscribeButton} uri={uri} name={name} />
</View>
{contentList}
{(totalPages > 1) && this.state.showPageButtons &&
<View style={channelPageStyle.pageButtons}>
@@ -99,7 +104,6 @@ class ChannelPage extends React.PureComponent {
disabled={!!fetching}
onPress={this.handleNextPage} />}
</View>}
<UriBar value={uri} navigation={navigation} />
</View>
)
}
+3 -3
View File
@@ -1,15 +1,15 @@
import { connect } from 'react-redux';
import {
doFetchFeaturedUris,
selectBalance,
selectFeaturedUris,
selectFetchingFeaturedUris,
} from 'lbry-redux';
import {
doFetchFeaturedUris,
doFetchRewardedContent,
doFetchMySubscriptions,
doRemoveUnreadSubscriptions,
selectEnabledChannelNotifications,
selectFeaturedUris,
selectFetchingFeaturedUris,
selectSubscriptionClaims,
selectUnreadSubscriptions,
} from 'lbryinc';
+1 -3
View File
@@ -17,7 +17,6 @@ import Colors from 'styles/colors';
import discoverStyle from 'styles/discover';
import FloatingWalletBalance from 'component/floatingWalletBalance';
import FileItem from 'component/fileItem';
import RewardSummary from 'component/rewardSummary';
import UriBar from 'component/uriBar';
class DiscoverPage extends React.PureComponent {
@@ -158,7 +157,7 @@ class DiscoverPage extends React.PureComponent {
return (
<View style={discoverStyle.container}>
<RewardSummary navigation={navigation} />
<UriBar navigation={navigation} />
{!hasContent && fetchingFeaturedUris && (
<View style={discoverStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.LbryGreen} />
@@ -186,7 +185,6 @@ class DiscoverPage extends React.PureComponent {
/>)
}
<FloatingWalletBalance navigation={navigation} />
<UriBar navigation={navigation} />
</View>
);
}
+1 -1
View File
@@ -36,6 +36,7 @@ class DownloadsPage extends React.PureComponent {
return (
<View style={downloadsStyle.container}>
<UriBar navigation={navigation} />
{!fetching && !hasDownloads &&
<View style={downloadsStyle.busyContainer}>
<Text style={downloadsStyle.noDownloadsText}>You have not downloaded anything from LBRY yet.</Text>
@@ -69,7 +70,6 @@ class DownloadsPage extends React.PureComponent {
/>
</View>}
<FloatingWalletBalance navigation={navigation} />
<UriBar navigation={navigation} />
</View>
);
}
+8 -4
View File
@@ -1,21 +1,24 @@
import { connect } from 'react-redux';
import {
doFetchFileInfo,
doFetchCostInfoForUri,
doResolveUri,
doSendTip,
doToast,
makeSelectIsUriResolving,
makeSelectCostInfoForUri,
makeSelectFileInfoForUri,
makeSelectChannelForClaimUri,
makeSelectClaimForUri,
makeSelectContentPositionForUri,
makeSelectContentTypeForUri,
makeSelectMetadataForUri,
selectBalance,
selectBlackListedOutpoints,
} from 'lbry-redux';
import { selectRewardContentClaimIds } from 'lbryinc';
import {
doFetchCostInfoForUri,
makeSelectCostInfoForUri,
selectRewardContentClaimIds,
selectBlackListedOutpoints
} from 'lbryinc';
import { doDeleteFile, doPurchaseUri, doStopDownloadingFile } from 'redux/actions/file';
import FilePage from './view';
@@ -34,6 +37,7 @@ const select = (state, props) => {
fileInfo: makeSelectFileInfoForUri(selectProps.uri)(state),
rewardedContentClaimIds: selectRewardContentClaimIds(state, selectProps),
channelUri: makeSelectChannelForClaimUri(selectProps.uri, true)(state),
position: makeSelectContentPositionForUri(selectProps.uri)(state)
};
};
+43 -38
View File
@@ -16,6 +16,7 @@ import {
WebView
} from 'react-native';
import { navigateToUri } from 'utils/helper';
import Icon from 'react-native-vector-icons/FontAwesome5';
import ImageViewer from 'react-native-image-zoom-viewer';
import Button from 'component/button';
import Colors from 'styles/colors';
@@ -62,6 +63,7 @@ class FilePage extends React.PureComponent {
mediaLoaded: false,
pageSuspended: false,
relatedContentY: 0,
showDescription: false,
showImageViewer: false,
showWebView: false,
showTipView: false,
@@ -368,6 +370,7 @@ class FilePage extends React.PureComponent {
isResolvingUri,
blackListedOutpoints,
navigation,
position,
purchaseUri
} = this.props;
const { uri, autoplay } = navigation.state.params;
@@ -413,7 +416,7 @@ class FilePage extends React.PureComponent {
<Text style={filePageStyle.dmcaText}>
In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications.
</Text>
<Link style={filePageStyle.dmcaLink} href="https://lbry.io/faq/dmca" text="Read More" />
<Link style={filePageStyle.dmcaLink} href="https://lbry.com/faq/dmca" text="Read More" />
</View>
<UriBar value={uri} navigation={navigation} />
</View>
@@ -480,6 +483,7 @@ class FilePage extends React.PureComponent {
innerContent = (
<View style={filePageStyle.pageContainer}>
{!this.state.fullscreenMode && <UriBar value={uri} navigation={navigation} />}
{this.state.showWebView && isWebViewable && <WebView source={{ uri: localFileUri }}
style={filePageStyle.viewer} />}
@@ -510,40 +514,36 @@ class FilePage extends React.PureComponent {
onStartDownloadFailed={this.startDownloadFailed} />}
{!fileInfo && <FilePrice uri={uri} style={filePageStyle.filePriceContainer} textStyle={filePageStyle.filePriceText} />}
</View>
{canLoadMedia && fileInfo && <View style={playerBgStyle}
ref={(ref) => { this.playerBackground = ref; }}
onLayout={(evt) => {
if (!this.state.playerBgHeight) {
this.setState({ playerBgHeight: evt.nativeEvent.layout.height });
}
}} />}
{canLoadMedia && fileInfo && <MediaPlayer
fileInfo={fileInfo}
assignPlayer={(ref) => { this.player = ref; }}
uri={uri}
style={playerStyle}
autoPlay={autoplay || this.state.autoPlayMedia}
onFullscreenToggled={this.handleFullscreenToggle}
onLayout={(evt) => {
if (!this.state.playerHeight) {
this.setState({ playerHeight: evt.nativeEvent.layout.height });
}
}}
onMediaLoaded={() => this.onMediaLoaded(channelName, title, uri)}
onPlaybackStarted={this.onPlaybackStarted}
onPlaybackFinished={this.onPlaybackFinished}
thumbnail={metadata.thumbnail}
/>}
{(canLoadMedia && fileInfo && isPlayable) &&
<View style={playerBgStyle}
ref={(ref) => { this.playerBackground = ref; }}
onLayout={(evt) => {
if (!this.state.playerBgHeight) {
this.setState({ playerBgHeight: evt.nativeEvent.layout.height });
}
}} />}
{(canLoadMedia && fileInfo && isPlayable) &&
<MediaPlayer
fileInfo={fileInfo}
assignPlayer={(ref) => { this.player = ref; }}
uri={uri}
style={playerStyle}
autoPlay={autoplay || this.state.autoPlayMedia}
onFullscreenToggled={this.handleFullscreenToggle}
onLayout={(evt) => {
if (!this.state.playerHeight) {
this.setState({ playerHeight: evt.nativeEvent.layout.height });
}
}}
onMediaLoaded={() => this.onMediaLoaded(channelName, title, uri)}
onPlaybackStarted={this.onPlaybackStarted}
onPlaybackFinished={this.onPlaybackFinished}
thumbnail={metadata.thumbnail}
position={position}
/>}
{showActions &&
{(showActions && showFileActions) &&
<View style={filePageStyle.actions}>
<View style={filePageStyle.socialActions}>
<Button style={filePageStyle.actionButton}
theme={"light"}
icon={"gift"}
text={"Send a tip"}
onPress={() => this.setState({ showTipView: true })} />
</View>
{showFileActions &&
<View style={filePageStyle.fileActions}>
{completed && <Button style={filePageStyle.actionButton}
@@ -565,7 +565,13 @@ class FilePage extends React.PureComponent {
style={showActions ? filePageStyle.scrollContainerActions : filePageStyle.scrollContainer}
contentContainerstyle={showActions ? null : filePageStyle.scrollContent}
ref={(ref) => { this.scrollView = ref; }}>
<Text style={filePageStyle.title} selectable={true}>{title}</Text>
<View style={filePageStyle.titleRow}>
<Text style={filePageStyle.title} selectable={true}>{title}</Text>
<TouchableOpacity style={filePageStyle.descriptionToggle}
onPress={() => this.setState({ showDescription: !this.state.showDescription })}>
<Icon name={this.state.showDescription ? "caret-up" : "caret-down"} size={24} />
</TouchableOpacity>
</View>
{channelName &&
<View style={filePageStyle.channelRow}>
<View style={filePageStyle.publishInfo}>
@@ -597,9 +603,9 @@ class FilePage extends React.PureComponent {
</View>
}
{description && description.length > 0 && <View style={filePageStyle.divider} />}
{description && <Text style={filePageStyle.description} selectable={true}>{this.linkify(description)}</Text>}
{(this.state.showDescription && description && description.length > 0) && <View style={filePageStyle.divider} />}
{(this.state.showDescription && description) &&
<Text style={filePageStyle.description} selectable={true}>{this.linkify(description)}</Text>}
<View onLayout={this.setRelatedContentPosition} />
<RelatedContent navigation={navigation} uri={uri} />
@@ -624,7 +630,6 @@ class FilePage extends React.PureComponent {
</View>
)}
{!this.state.fullscreenMode && <FloatingWalletBalance navigation={navigation} />}
{!this.state.fullscreenMode && <UriBar value={uri} navigation={navigation} />}
</View>
);
}
+13 -9
View File
@@ -7,14 +7,16 @@ import {
Text,
View
} from 'react-native';
import Colors from '../../styles/colors';
import Link from '../../component/link';
import CustomRewardCard from '../../component/customRewardCard';
import PhoneNumberRewardSubcard from '../../component/phoneNumberRewardSubcard';
import EmailRewardSubcard from '../../component/emailRewardSubcard';
import PageHeader from '../../component/pageHeader';
import RewardCard from '../../component/rewardCard';
import rewardStyle from '../../styles/reward';
import Colors from 'styles/colors';
import Link from 'component/link';
import CustomRewardCard from 'component/customRewardCard';
import PhoneNumberRewardSubcard from 'component/phoneNumberRewardSubcard';
import EmailRewardSubcard from 'component/emailRewardSubcard';
import PageHeader from 'component/pageHeader';
import RewardCard from 'component/rewardCard';
import RewardSummary from 'component/rewardSummary';
import UriBar from 'component/uriBar';
import rewardStyle from 'styles/reward';
class RewardsPage extends React.PureComponent {
state = {
@@ -134,14 +136,16 @@ class RewardsPage extends React.PureComponent {
}
render() {
const { user } = this.props;
const { user, navigation } = this.props;
return (
<View style={rewardStyle.container}>
<UriBar navigation={navigation} />
<ScrollView
keyboardShouldPersistTaps={'handled'}
style={rewardStyle.scrollContainer}
contentContainerStyle={rewardStyle.scrollContentContainer}>
<RewardSummary navigation={navigation} />
{this.renderVerification()}
{this.renderUnclaimedRewards()}
{this.renderClaimedRewards()}
+11 -3
View File
@@ -1,20 +1,28 @@
import { connect } from 'react-redux';
import {
doSearch,
doUpdateSearchQuery,
makeSelectSearchUris,
selectIsSearching,
selectSearchValue
selectSearchValue,
makeSelectQueryWithOptions,
selectSearchUrisByQuery
} from 'lbry-redux';
import { doPushDrawerStack } from 'redux/actions/drawer';
import Constants from 'constants';
import SearchPage from './view';
const select = (state) => ({
isSearching: selectIsSearching(state),
query: selectSearchValue(state),
uris: makeSelectSearchUris(selectSearchValue(state))(state)
uris: makeSelectSearchUris(makeSelectQueryWithOptions(null, 25)(state))(state),
urisByQuery: selectSearchUrisByQuery(state),
});
const perform = dispatch => ({
search: (query) => dispatch(doSearch(query, 25))
search: (query) => dispatch(doSearch(query, 25)),
updateSearchQuery: query => dispatch(doUpdateSearchQuery(query)),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_SEARCH)),
});
export default connect(select, perform)(SearchPage);
+36 -12
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import { Lbry, parseURI, normalizeURI, isURIValid } from 'lbry-redux';
import {
ActivityIndicator,
Button,
@@ -8,36 +8,63 @@ import {
View,
ScrollView
} from 'react-native';
import { navigateToUri } from '../../utils/helper';
import Colors from '../../styles/colors';
import PageHeader from '../../component/pageHeader';
import FileListItem from '../../component/fileListItem';
import FloatingWalletBalance from '../../component/floatingWalletBalance';
import UriBar from '../../component/uriBar';
import searchStyle from '../../styles/search';
import { navigateToUri } from 'utils/helper';
import Colors from 'styles/colors';
import PageHeader from 'component/pageHeader';
import FileListItem from 'component/fileListItem';
import FloatingWalletBalance from 'component/floatingWalletBalance';
import UriBar from 'component/uriBar';
import searchStyle from 'styles/search';
class SearchPage extends React.PureComponent {
state = {
currentUri: null
}
static navigationOptions = {
title: 'Search Results'
};
componentWillMount() {
this.props.pushDrawerStack();
}
componentDidMount() {
const { navigation, search } = this.props;
const { searchQuery } = navigation.state.params;
if (searchQuery && searchQuery.trim().length > 0) {
this.setState({ currentUri: (isURIValid(searchQuery)) ? normalizeURI(searchQuery) : null })
search(searchQuery);
}
}
handleSearchSubmitted = (keywords) => {
const { search } = this.props;
this.setState({ currentUri: (isURIValid(keywords)) ? normalizeURI(keywords) : null });
search(keywords);
}
render() {
const { isSearching, navigation, query, search, uris } = this.props;
const { isSearching, navigation, query, uris, urisByQuery } = this.props;
const { searchQuery } = navigation.state.params;
return (
<View style={searchStyle.container}>
<UriBar value={searchQuery}
navigation={navigation}
onSearchSubmitted={this.handleSearchSubmitted} />
{!isSearching && (!uris || uris.length === 0) &&
<Text style={searchStyle.noResultsText}>No results to display.</Text>}
<ScrollView style={searchStyle.scrollContainer} contentContainerStyle={searchStyle.scrollPadding}>
{this.state.currentUri &&
<FileListItem
key={this.state.currentUri}
uri={this.state.currentUri}
featuredResult={true}
style={searchStyle.featuredResultItem}
navigation={navigation}
onPress={() => navigateToUri(navigation, this.state.currentUri)}
/>}
{!isSearching && uris && uris.length ? (
uris.map(uri => <FileListItem key={uri}
uri={uri}
@@ -48,9 +75,6 @@ class SearchPage extends React.PureComponent {
</ScrollView>
{isSearching && <ActivityIndicator size="large" color={Colors.LbryGreen} style={searchStyle.loading} /> }
<FloatingWalletBalance navigation={navigation} />
<UriBar value={searchQuery}
navigation={navigation}
onSearchSubmitted={(keywords) => search(keywords)} />
</View>
);
}
+2 -1
View File
@@ -1,7 +1,8 @@
import { connect } from 'react-redux';
import { doBalanceSubscribe, doBlackListedOutpointsSubscribe, doUpdateBlockHeight, doToast } from 'lbry-redux';
import { doBalanceSubscribe, doUpdateBlockHeight, doToast } from 'lbry-redux';
import {
doAuthenticate,
doBlackListedOutpointsSubscribe,
doCheckSubscriptionsInit,
doFetchMySubscriptions,
doFetchRewardedContent,
+49 -36
View File
@@ -63,10 +63,49 @@ class SplashScreen extends React.PureComponent {
});
}
navigateToMain = () => {
const { navigation } = this.props;
const resetAction = StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Main'})
]
});
navigation.dispatch(resetAction);
const launchUrl = navigation.state.params.launchUrl || this.state.launchUrl;
if (launchUrl) {
if (launchUrl.startsWith('lbry://?verify=')) {
let verification = {};
try {
verification = JSON.parse(atob(launchUrl.substring(15)));
} catch (error) {
console.log(error);
}
if (verification.token && verification.recaptcha) {
AsyncStorage.setItem(Constants.KEY_SHOULD_VERIFY_EMAIL, 'true');
try {
verifyUserEmail(verification.token, verification.recaptcha);
} catch (error) {
const message = 'Invalid Verification Token';
verifyUserEmailFailure(message);
notify({ message });
}
} else {
notify({
message: 'Invalid Verification URI',
});
}
} else {
navigateToUri(navigation, launchUrl);
}
}
}
componentWillReceiveProps(nextProps) {
const {
emailToVerify,
navigation,
getSync,
setEmailToVerify,
verifyUserEmail,
verifyUserEmailFailure
@@ -81,41 +120,15 @@ class SplashScreen extends React.PureComponent {
}
// user is authenticated, navigate to the main view
const resetAction = StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Main'})
]
});
navigation.dispatch(resetAction);
const launchUrl = navigation.state.params.launchUrl || this.state.launchUrl;
if (launchUrl) {
if (launchUrl.startsWith('lbry://?verify=')) {
let verification = {};
try {
verification = JSON.parse(atob(launchUrl.substring(15)));
} catch (error) {
console.log(error);
}
if (verification.token && verification.recaptcha) {
AsyncStorage.setItem(Constants.KEY_SHOULD_VERIFY_EMAIL, 'true');
try {
verifyUserEmail(verification.token, verification.recaptcha);
} catch (error) {
const message = 'Invalid Verification Token';
verifyUserEmailFailure(message);
notify({ message });
}
} else {
notify({
message: 'Invalid Verification URI',
});
}
} else {
navigateToUri(navigation, launchUrl);
}
if (user.has_verified_email) {
NativeModules.UtilityModule.getSecureValue(Constants.KEY_FIRST_RUN_PASSWORD).then(walletPassword => {
getSync(walletPassword);
this.navigateToMain();
});
return;
}
this.navigateToMain();
});
});
}
@@ -229,7 +242,7 @@ class SplashScreen extends React.PureComponent {
isLagging: true,
message: 'Connection Failure',
details:
'We could not establish a connection to the daemon. Your data connection may be preventing LBRY from connecting. Contact hello@lbry.io if you think this is a software bug.'
'We could not establish a connection to the daemon. Your data connection may be preventing LBRY from connecting. Contact hello@lbry.com if you think this is a software bug.'
});
});
}
+100 -76
View File
@@ -13,6 +13,7 @@ import {
import { buildURI, parseURI } from 'lbry-redux';
import { uriFromFileInfo } from 'utils/helper';
import moment from 'moment';
import Button from 'component/button';
import Colors from 'styles/colors';
import Constants from 'constants';
import discoverStyle from 'styles/discover';
@@ -24,6 +25,10 @@ import SuggestedSubscriptions from 'component/suggestedSubscriptions';
import UriBar from 'component/uriBar';
class SubscriptionsPage extends React.PureComponent {
state = {
showingSuggestedSubs: false
};
componentWillMount() {
const {
doFetchMySubscriptions,
@@ -62,95 +67,114 @@ class SubscriptionsPage extends React.PureComponent {
unreadSubscriptions,
navigation,
} = this.props;
const numberOfSubscriptions = subscribedChannels ? subscribedChannels.length : 0;
const hasSubscriptions = numberOfSubscriptions > 0;
if (!hasSubscriptions && !this.state.showingSuggestedSubs) {
this.setState({ showingSuggestedSubs: true });
}
return (
<View style={subscriptionsStyle.container}>
<UriBar navigation={navigation} />
{hasSubscriptions && !loading &&
<View style={subscriptionsStyle.viewModeRow}>
<Link
text={'All Subscriptions'}
style={[subscriptionsStyle.viewModeLink,
((viewMode === Constants.SUBSCRIPTIONS_VIEW_ALL) ? subscriptionsStyle.activeMode : subscriptionsStyle.inactiveMode)]}
onPress={() => this.changeViewMode(Constants.SUBSCRIPTIONS_VIEW_ALL)}
/>
<Link
text={'Latest Only'}
style={[subscriptionsStyle.viewModeLink,
((viewMode === Constants.SUBSCRIPTIONS_VIEW_LATEST_FIRST) ? subscriptionsStyle.activeMode : subscriptionsStyle.inactiveMode)]}
onPress={() => this.changeViewMode(Constants.SUBSCRIPTIONS_VIEW_LATEST_FIRST)}
/>
</View>}
{(hasSubscriptions && !loading) &&
<View style={subscriptionsStyle.container}>
{(viewMode === Constants.SUBSCRIPTIONS_VIEW_ALL) &&
<FlatList
style={subscriptionsStyle.scrollContainer}
contentContainerStyle={subscriptionsStyle.scrollPadding}
renderItem={ ({item}) => (
<FileItem
style={subscriptionsStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={item}
uri={uriFromFileInfo(item)}
navigation={navigation}
compactView={false}
showDetails={true} />
)
}
data={allSubscriptions.sort((a, b) => {
return b.height - a.height;
})}
keyExtractor={(item, index) => uriFromFileInfo(item)} />}
{(viewMode === Constants.SUBSCRIPTIONS_VIEW_LATEST_FIRST) &&
<View style={subscriptionsStyle.container}>
{unreadSubscriptions.length ?
(<ScrollView
style={subscriptionsStyle.scrollContainer}
contentContainerStyle={subscriptionsStyle.scrollPadding}>
{unreadSubscriptions.map(({ channel, uris }) => {
const { claimName } = parseURI(channel);
return uris.map(uri => (
<FileItem
style={subscriptionsStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={uri}
uri={uri}
navigation={navigation}
compactView={false}
showDetails={true} />));
})}
</ScrollView>) :
(<View style={subscriptionsStyle.contentContainer}>
<Text style={subscriptionsStyle.contentText}>All caught up! You might like the channels below.</Text>
<SuggestedSubscriptions navigation={navigation} />
</View>)
}
{(!this.state.showingSuggestedSubs && hasSubscriptions && !loading) &&
<View style={subscriptionsStyle.viewModeRow}>
<Link
text={'All Subscriptions'}
style={[subscriptionsStyle.viewModeLink,
((viewMode === Constants.SUBSCRIPTIONS_VIEW_ALL) ? subscriptionsStyle.activeMode : subscriptionsStyle.inactiveMode)]}
onPress={() => this.changeViewMode(Constants.SUBSCRIPTIONS_VIEW_ALL)}
/>
<Link
text={'Latest Only'}
style={[subscriptionsStyle.viewModeLink,
((viewMode === Constants.SUBSCRIPTIONS_VIEW_LATEST_FIRST) ? subscriptionsStyle.activeMode : subscriptionsStyle.inactiveMode)]}
onPress={() => this.changeViewMode(Constants.SUBSCRIPTIONS_VIEW_LATEST_FIRST)}
/>
</View>}
</View>}
{(!this.state.showingSuggestedSubs && hasSubscriptions && !loading) &&
<View style={subscriptionsStyle.subContainer}>
{(viewMode === Constants.SUBSCRIPTIONS_VIEW_ALL) &&
<FlatList
style={subscriptionsStyle.scrollContainer}
contentContainerStyle={subscriptionsStyle.scrollPadding}
renderItem={ ({item}) => (
<FileItem
style={subscriptionsStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={item}
uri={uriFromFileInfo(item)}
navigation={navigation}
compactView={false}
showDetails={true} />
)
}
data={allSubscriptions.sort((a, b) => {
return b.height - a.height;
})}
keyExtractor={(item, index) => uriFromFileInfo(item)} />}
{(hasSubscriptions && loading) &&
<View style={subscriptionsStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.LbryGreen} style={subscriptionsStyle.loading} />
</View>
}
{(viewMode === Constants.SUBSCRIPTIONS_VIEW_LATEST_FIRST) &&
<View style={subscriptionsStyle.subContainer}>
{unreadSubscriptions.length ?
(<ScrollView
style={subscriptionsStyle.scrollContainer}
contentContainerStyle={subscriptionsStyle.scrollPadding}>
{unreadSubscriptions.map(({ channel, uris }) => {
const { claimName } = parseURI(channel);
return uris.map(uri => (
<FileItem
style={subscriptionsStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={uri}
uri={uri}
navigation={navigation}
compactView={false}
showDetails={true} />));
})}
</ScrollView>) :
(<View style={subscriptionsStyle.contentContainer}>
<Text style={subscriptionsStyle.contentText}>All caught up! You might like the channels below.</Text>
<SuggestedSubscriptions navigation={navigation} />
</View>)
}
</View>}
{(!hasSubscriptions && !loading) &&
<View style={subscriptionsStyle.container}>
<Text style={subscriptionsStyle.infoText}>
You are not subscribed to any channels at the moment. Here are some channels that we think you might enjoy.
</Text>
{loadingSuggested && <ActivityIndicator size="large" colors={Colors.LbryGreen} style={subscriptionsStyle.loading} />}
{!loadingSuggested && <SuggestedSubscriptions navigation={navigation} />}
</View>}
{(hasSubscriptions && loading) &&
<View style={subscriptionsStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.LbryGreen} style={subscriptionsStyle.loading} />
</View>
}
{this.state.showingSuggestedSubs &&
<View style={subscriptionsStyle.suggestedSubsContainer}>
{!hasSubscriptions &&
<Text style={subscriptionsStyle.infoText}>
You are not subscribed to any channels at the moment. Here are some channels that we think you might enjoy.
</Text>}
{hasSubscriptions &&
<View>
<Text style={subscriptionsStyle.infoText}>
You are currently subscribed to {numberOfSubscriptions} channel{(numberOfSubscriptions > 1) ? 's' : ''}.
</Text>
<Button
style={subscriptionsStyle.button}
text={"View my subscriptions"}
onPress={() => this.setState({ showingSuggestedSubs: false })} />
</View>
}
{loadingSuggested && <ActivityIndicator size="large" colors={Colors.LbryGreen} style={subscriptionsStyle.loading} />}
{!loadingSuggested && <SuggestedSubscriptions navigation={navigation} />}
</View>}
<FloatingWalletBalance navigation={navigation} />
<UriBar navigation={navigation} />
</View>
)
}
+3
View File
@@ -4,6 +4,8 @@ import {
selectTransactionItems,
selectIsFetchingTransactions,
} from 'lbry-redux';
import { doPushDrawerStack } from 'redux/actions/drawer';
import Constants from 'constants';
import TransactionHistoryPage from './view';
const select = state => ({
@@ -13,6 +15,7 @@ const select = state => ({
const perform = dispatch => ({
fetchTransactions: () => dispatch(doFetchTransactions()),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_TRANSACTION_HISTORY)),
});
export default connect(select, perform)(TransactionHistoryPage);
+23 -15
View File
@@ -1,9 +1,14 @@
import React from 'react';
import { View, ScrollView, Text } from 'react-native';
import TransactionList from '../../component/transactionList';
import walletStyle from '../../styles/wallet';
import TransactionList from 'component/transactionList';
import UriBar from 'component/uriBar';
import walletStyle from 'styles/wallet';
class TransactionHistoryPage extends React.PureComponent {
componentWillMount() {
this.props.pushDrawerStack();
}
componentDidMount() {
this.props.fetchTransactions();
}
@@ -12,19 +17,22 @@ class TransactionHistoryPage extends React.PureComponent {
const { fetchingTransactions, transactions, navigation } = this.props;
return (
<ScrollView>
<View style={walletStyle.historyList}>
{fetchingTransactions && !transactions.length && (
<Text style={walletStyle.infoText}>Loading transactions...</Text>
)}
{!fetchingTransactions && transactions.length === 0 && (
<Text style={walletStyle.infoText}>No transactions to list.</Text>
)}
{!fetchingTransactions && transactions && (transactions.length > 0) && (
<TransactionList navigation={navigation} transactions={transactions} />
)}
</View>
</ScrollView>
<View>
<UriBar navigation={navigation} />
<ScrollView style={walletStyle.transactionHistoryScroll}>
<View style={walletStyle.historyList}>
{fetchingTransactions && !transactions.length && (
<Text style={walletStyle.infoText}>Loading transactions...</Text>
)}
{!fetchingTransactions && transactions.length === 0 && (
<Text style={walletStyle.infoText}>No transactions to list.</Text>
)}
{!fetchingTransactions && transactions && (transactions.length > 0) && (
<TransactionList navigation={navigation} transactions={transactions} />
)}
</View>
</ScrollView>
</View>
);
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { connect } from 'react-redux';
import { doFetchTrendingUris, selectTrendingUris, selectFetchingTrendingUris } from 'lbry-redux';
import { doFetchTrendingUris, selectTrendingUris, selectFetchingTrendingUris } from 'lbryinc';
import { doPushDrawerStack } from 'redux/actions/drawer';
import Constants from 'constants';
import TrendingPage from './view';
+1 -1
View File
@@ -30,6 +30,7 @@ class TrendingPage extends React.PureComponent {
return (
<View style={discoverStyle.container}>
<UriBar navigation={navigation} />
{!hasContent && fetchingTrendingUris && (
<View style={discoverStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.LbryGreen} />
@@ -54,7 +55,6 @@ class TrendingPage extends React.PureComponent {
/>
}
<FloatingWalletBalance navigation={navigation} />
<UriBar navigation={navigation} />
</View>
);
}
+18 -13
View File
@@ -5,7 +5,8 @@ import WalletAddress from 'component/walletAddress';
import WalletBalance from 'component/walletBalance';
import WalletSend from 'component/walletSend';
import Button from 'component/button';
import Link from 'component/link'
import Link from 'component/link';
import UriBar from 'component/uriBar';
import Constants from 'constants';
import walletStyle from 'styles/wallet';
@@ -15,11 +16,12 @@ class WalletPage extends React.PureComponent {
}
render() {
const { understandsRisks, setClientSetting } = this.props;
const { understandsRisks, setClientSetting, navigation } = this.props;
if (!understandsRisks) {
return (
<View>
<UriBar navigation={navigation} />
<View style={walletStyle.warning}>
<Text style={walletStyle.warningText}>
This is beta software. You may lose any LBC that you send to your wallet due to uninstallation, software bugs, deleted files, or malicious third-party software. You should not use this wallet as your primary wallet. If you understand the risks and you wish to continue, please tap the button below.
@@ -32,18 +34,21 @@ class WalletPage extends React.PureComponent {
}
return (
<ScrollView keyboardShouldPersistTaps={'handled'}>
<View style={walletStyle.warningCard}>
<Text style={walletStyle.warningText}>
Please backup your wallet file using the instructions at <Link style={walletStyle.warningText} text="https://lbry.io/faq/how-to-backup-wallet#android" href="https://lbry.io/faq/how-to-backup-wallet#android" />.
</Text>
</View>
<View>
<UriBar navigation={navigation} />
<ScrollView keyboardShouldPersistTaps={'handled'}>
<View style={walletStyle.warningCard}>
<Text style={walletStyle.warningText}>
Please backup your wallet file using the instructions at <Link style={walletStyle.warningText} text="https://lbry.com/faq/how-to-backup-wallet#android" href="https://lbry.com/faq/how-to-backup-wallet#android" />.
</Text>
</View>
<WalletBalance />
<WalletAddress />
<WalletSend />
<TransactionListRecent navigation={this.props.navigation} />
</ScrollView>
<WalletBalance />
<WalletAddress />
<WalletSend />
<TransactionListRecent navigation={this.props.navigation} />
</ScrollView>
</View>
);
}
}
+3 -4
View File
@@ -4,14 +4,13 @@ import {
doToast,
formatCredits,
selectBalance,
makeSelectCostInfoForUri,
makeSelectFileInfoForUri,
makeSelectMetadataForUri,
selectDownloadingByOutpoint,
} from 'lbry-redux';
import { doClaimEligiblePurchaseRewards } from 'lbryinc';
import { doClaimEligiblePurchaseRewards, makeSelectCostInfoForUri } from 'lbryinc';
import { Alert, NativeModules } from 'react-native';
import Constants from '../../constants';
import Constants from 'constants';
const DOWNLOAD_POLL_INTERVAL = 250;
@@ -221,7 +220,7 @@ export function doLoadVideo(uri, failureCallback) {
});
dispatch(doToast({
message: `Failed to download ${uri}, please try again. If this problem persists, visit https://lbry.io/faq/support for support.`,
message: `Failed to download ${uri}, please try again. If this problem persists, visit https://lbry.com/faq/support for support.`,
}));
if (failureCallback) {
+1 -1
View File
@@ -9,7 +9,7 @@ reducers[Constants.ACTION_PUSH_DRAWER_STACK] = (state, action) => {
const routeName = action.data;
const newStack = state.stack.slice();
if (routeName !== newStack[newStack.length -1]) {
if (routeName !== newStack[newStack.length - 1]) {
newStack.push(routeName);
}
+19 -3
View File
@@ -11,8 +11,7 @@ const channelPageStyle = StyleSheet.create({
},
fileList: {
flex: 1,
paddingTop: 30,
marginBottom: 60,
paddingTop: 30
},
fileListContent: {
paddingBottom: 16
@@ -40,7 +39,7 @@ const channelPageStyle = StyleSheet.create({
flexDirection: 'row',
justifyContent: 'space-between',
position: 'absolute',
bottom: 76,
bottom: 16,
paddingLeft: 16,
paddingRight: 16
},
@@ -51,6 +50,23 @@ const channelPageStyle = StyleSheet.create({
},
nextButton: {
alignSelf: 'flex-end'
},
channelHeader: {
marginTop: 60,
marginLeft: 16,
marginRight: 16
},
channelName: {
fontFamily: 'Inter-UI-SemiBold',
fontSize: 24,
marginTop: 16,
marginBottom: 8
},
subscribeButton: {
alignSelf: 'flex-start',
backgroundColor: Colors.White,
paddingLeft: 16,
paddingRight: 16
}
});
+1
View File
@@ -11,6 +11,7 @@ const Colors = {
Red: '#ff0000',
VeryLightGrey: '#f1f1f1',
White: '#ffffff',
UriDescBlue: '#3971db',
StatsAudio: '#f6a637',
StatsImage: '#ff4a7d',
+4 -4
View File
@@ -14,16 +14,16 @@ export const mediaHeight = ((screenWidth / screenHeight) * ((screenWidthPixels <
const discoverStyle = StyleSheet.create({
container: {
flex: 1
flex: 1,
},
scrollContainer: {
flex: 1,
marginBottom: 60,
paddingTop: 12
paddingTop: 12,
marginTop: 60,
},
trendingContainer: {
flex: 1,
marginBottom: 60,
marginTop: 60,
paddingTop: 30
},
busyContainer: {
+2 -1
View File
@@ -11,7 +11,8 @@ const downloadsStyle = StyleSheet.create({
flexDirection: 'row'
},
subContainer: {
flex: 1
flex: 1,
marginTop: 60
},
itemList: {
flex: 1,
+13 -3
View File
@@ -20,6 +20,16 @@ const fileListStyle = StyleSheet.create({
detailsContainer: {
flex: 1
},
featuredUri: {
fontFamily: 'Inter-UI-SemiBold',
fontSize: 24,
color: Colors.White
},
featuredTitle: {
fontFamily: 'Inter-UI-SemiBold',
fontSize: (screenWidthPixels <= 720) ? 12 : 16,
color: Colors.White
},
thumbnail: {
width: thumbnailWidth,
height: thumbnailHeight,
@@ -29,7 +39,7 @@ const fileListStyle = StyleSheet.create({
},
title: {
fontFamily: 'Inter-UI-SemiBold',
fontSize: (screenWidthPixels <= 720) ? 12 : 16
fontSize: (screenWidthPixels <= 720) ? 12 : 14
},
uri: {
fontFamily: 'Inter-UI-SemiBold',
@@ -38,7 +48,7 @@ const fileListStyle = StyleSheet.create({
},
publisher: {
fontFamily: 'Inter-UI-SemiBold',
fontSize: (screenWidthPixels <= 720) ? 12 : 14,
fontSize: (screenWidthPixels <= 720) ? 11 : 12,
marginTop: (screenWidthPixels <= 720) ? 1 : 3,
color: Colors.LbryGreen
},
@@ -52,7 +62,7 @@ const fileListStyle = StyleSheet.create({
},
infoText: {
fontFamily: 'Inter-UI-Regular',
fontSize: (screenWidthPixels <= 720) ? 12 : 14,
fontSize: (screenWidthPixels <= 720) ? 11 : 12,
color: Colors.ChannelGrey
},
downloadInfo: {
+33 -18
View File
@@ -22,8 +22,7 @@ const filePageStyle = StyleSheet.create({
marginBottom: 20
},
innerPageContainer: {
flex: 1,
marginBottom: 60
flex: 1
},
innerPageContainerFsMode: {
flex: 1,
@@ -32,7 +31,9 @@ const filePageStyle = StyleSheet.create({
mediaContainer: {
alignItems: 'center',
width: screenWidth,
height: containedMediaHeightWithControls
height: containedMediaHeightWithControls,
marginTop: 60,
marginBottom: -17
},
emptyClaimText: {
fontFamily: 'Inter-UI-Regular',
@@ -42,8 +43,7 @@ const filePageStyle = StyleSheet.create({
marginRight: 16
},
scrollContainer: {
flex: 1,
marginTop: -16
flex: 1
},
scrollContent: {
paddingTop: 10
@@ -53,17 +53,23 @@ const filePageStyle = StyleSheet.create({
},
title: {
fontFamily: 'Inter-UI-Bold',
fontSize: 24,
fontSize: 16,
flex: 18
},
titleRow: {
flexDirection: 'row',
marginTop: 12,
marginLeft: 20,
marginRight: 20,
marginBottom: 8
marginBottom: 2,
marginLeft: 12,
marginRight: 12,
alignItems: 'center',
justifyContent: 'center'
},
channelRow: {
flexDirection: 'row',
justifyContent: 'space-between',
marginLeft: 20,
marginRight: 20,
marginLeft: 12,
marginRight: 12,
marginBottom: 16,
},
subscriptionRow: {
@@ -76,7 +82,7 @@ const filePageStyle = StyleSheet.create({
},
channelName: {
fontFamily: 'Inter-UI-SemiBold',
fontSize: 20,
fontSize: 14,
color: Colors.LbryGreen
},
publishDateText: {
@@ -90,10 +96,10 @@ const filePageStyle = StyleSheet.create({
description: {
color: Colors.DescriptionGrey,
fontFamily: 'Inter-UI-Regular',
fontSize: 16,
lineHeight: 20,
marginLeft: 20,
marginRight: 20,
fontSize: 13,
lineHeight: 18,
marginLeft: 12,
marginRight: 12,
marginBottom: 16
},
thumbnail: {
@@ -116,10 +122,12 @@ const filePageStyle = StyleSheet.create({
containedPlayer: {
width: '100%',
height: containedMediaHeightWithControls,
top: 60
},
containedPlayerLandscape: {
width: '100%',
height: '100%'
height: '100%',
top: 60
},
fullscreenPlayer: {
width: '100%',
@@ -137,6 +145,7 @@ const filePageStyle = StyleSheet.create({
},
containedPlayerBackground: {
width: '100%',
marginTop: 60,
height: containedMediaHeight,
},
fullscreenPlayerBackground: {
@@ -168,7 +177,6 @@ const filePageStyle = StyleSheet.create({
paddingRight: 16,
paddingTop: 16,
paddingBottom: 8,
marginTop: -14,
width: '100%',
},
fileActions: {
@@ -279,6 +287,13 @@ const filePageStyle = StyleSheet.create({
alignSelf: 'flex-start',
marginTop: 17
},
descriptionToggle: {
alignItems: 'center',
justifyContent: 'center',
width: 36,
height: 36,
marginTop: -8
},
text: {
fontFamily: 'Inter-UI-Regular',
fontSize: 16,
+26 -3
View File
@@ -2,8 +2,15 @@ import { StyleSheet } from 'react-native';
import Colors from './colors';
const floatingButtonStyle = StyleSheet.create({
container: {
view: {
position: 'absolute',
zIndex: 100,
borderRadius: 24,
padding: 14,
justifyContent: 'flex-end',
flexDirection: 'row'
},
container: {
zIndex: 100,
borderRadius: 24,
padding: 14,
@@ -11,7 +18,7 @@ const floatingButtonStyle = StyleSheet.create({
paddingRight: 20,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: Colors.BrighterLbryGreen,
backgroundColor: Colors.LbryGreen,
shadowColor: 'black',
shadowOpacity: 0.1,
shadowRadius: StyleSheet.hairlineWidth,
@@ -20,6 +27,18 @@ const floatingButtonStyle = StyleSheet.create({
},
elevation: 4
},
pendingContainer: {
borderRadius: 24,
padding: 14,
paddingLeft: 20,
paddingRight: 70,
marginRight: -60,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: Colors.BrighterLbryGreen,
flexDirection: 'row',
elevation: 3
},
text: {
color: Colors.White,
fontFamily: 'Inter-UI-Bold',
@@ -27,7 +46,11 @@ const floatingButtonStyle = StyleSheet.create({
},
bottomRight: {
right: 10,
bottom: 70
bottom: 10
},
rewardIcon: {
color: Colors.White,
marginRight: 4
}
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { Platform, StyleSheet } from 'react-native';
const STATUSBAR_HEIGHT = Platform.OS === 'ios' ? 20 : 0;
const TITLE_OFFSET = Platform.OS === 'ios' ? 70 : 56;
export const TITLE_OFFSET = Platform.OS === 'ios' ? 70 : 56;
let platformContainerStyles;
if (Platform.OS === 'ios') {
+2 -2
View File
@@ -6,8 +6,8 @@ const relatedContentStyle = StyleSheet.create({
flex: 1,
paddingTop: 16,
paddingBottom: 16,
paddingLeft: 24,
paddingRight: 24,
paddingLeft: 16,
paddingRight: 16,
borderTopColor: Colors.LighterGrey,
borderTopWidth: 1
},
+12 -9
View File
@@ -29,6 +29,9 @@ const rewardStyle = StyleSheet.create({
rewardsContainer: {
flex: 1
},
scrollContainer: {
marginTop: 60
},
scrollContentContainer: {
paddingBottom: 16
},
@@ -156,15 +159,15 @@ const rewardStyle = StyleSheet.create({
summaryContainer: {
backgroundColor: Colors.LbryGreen,
padding: 12,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
marginTop: 16,
marginLeft: 16,
marginRight: 16,
},
summaryText: {
color: Colors.White,
fontFamily: 'Inter-UI-Regular',
fontSize: 14,
lineHeight: 20,
fontSize: 16,
lineHeight: 24,
flex: 0.7
},
phoneVerificationContainer: {
@@ -197,11 +200,11 @@ const rewardStyle = StyleSheet.create({
marginBottom: 32
},
dismissButton: {
alignSelf: 'center',
alignSelf: 'flex-end',
backgroundColor: Colors.White,
paddingLeft: 4,
paddingRight: 4,
flex: 0.2
paddingLeft: 16,
paddingRight: 16,
marginTop: 8,
},
customCodeInput: {
fontFamily: 'Inter-UI-Regular',
+15 -4
View File
@@ -1,4 +1,5 @@
import { StyleSheet } from 'react-native';
import Colors from 'styles/colors';
const searchStyle = StyleSheet.create({
container: {
@@ -10,9 +11,7 @@ const searchStyle = StyleSheet.create({
flex: 1,
width: '100%',
height: '100%',
paddingLeft: 16,
paddingRight: 16,
marginBottom: 60
marginTop: 60
},
scrollPadding: {
paddingBottom: 16
@@ -21,7 +20,19 @@ const searchStyle = StyleSheet.create({
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 8
marginTop: 8,
marginLeft: 8,
marginRight: 8
},
featuredResultItem: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
paddingTop: 8,
paddingBottom: 8,
paddingLeft: 8,
paddingRight: 8,
backgroundColor: Colors.Black
},
searchInput: {
width: '100%',
+21 -3
View File
@@ -11,6 +11,21 @@ const subscriptionsStyle = StyleSheet.create({
container: {
flex: 1,
},
subContainer: {
flex: 1,
},
suggestedSubsContainer: {
flex: 1,
marginTop: 60
},
button: {
alignSelf: 'flex-start',
backgroundColor: Colors.LbryGreen,
paddingLeft: 16,
paddingRight: 16,
marginLeft: 16,
marginBottom: 16
},
busyContainer: {
flex: 1,
justifyContent: 'center',
@@ -19,8 +34,7 @@ const subscriptionsStyle = StyleSheet.create({
padding: 16
},
scrollContainer: {
flex: 1,
marginBottom: 60
flex: 1
},
scrollPadding: {
paddingTop: 24
@@ -49,6 +63,10 @@ const subscriptionsStyle = StyleSheet.create({
marginRight: 24,
marginBottom: 24
},
compactMainFileItem: {
marginLeft: 24,
marginRight: 24
},
compactItems: {
flex: 1,
marginTop: 6,
@@ -102,7 +120,7 @@ const subscriptionsStyle = StyleSheet.create({
flexDirection: 'row',
marginLeft: 24,
marginRight: 24,
marginTop: 24
marginTop: 84
},
viewModeLink: {
marginRight: 24,
+25 -8
View File
@@ -1,11 +1,13 @@
import { StyleSheet } from 'react-native';
import { TITLE_OFFSET } from 'styles/pageHeader';
import Colors from './colors';
const uriBarStyle = StyleSheet.create({
uriContainer: {
flexDirection: 'row',
backgroundColor: Colors.White,
padding: 8,
alignSelf: 'flex-end',
alignSelf: 'flex-start',
height: 60,
width: '100%',
shadowColor: Colors.Black,
@@ -24,12 +26,12 @@ const uriBarStyle = StyleSheet.create({
borderRadius: 4,
fontFamily: 'Inter-UI-Regular',
fontSize: 16,
width: '100%'
flex: 17
},
overlay: {
position: 'absolute',
backgroundColor: 'transparent',
bottom: 0,
top: 0,
width: '100%',
zIndex: 200,
elevation: 16
@@ -43,15 +45,30 @@ const uriBarStyle = StyleSheet.create({
},
item: {
flexDirection: 'row',
justifyContent: 'flex-start',
padding: 12
alignItems: 'center',
padding: 12,
paddingTop: 8,
paddingBottom: 8
},
itemContent: {
marginLeft: 12,
marginRight: 12,
flex: 1
},
itemText: {
fontFamily: 'Inter-UI-Regular',
fontSize: 16,
marginLeft: 12,
marginRight: 12
}
},
itemDesc: {
fontFamily: 'Inter-UI-Regular',
fontSize: 14,
color: Colors.UriDescBlue
},
drawerMenuButton: {
height: '100%',
justifyContent: 'center',
flex: 3
},
});
export default uriBarStyle;
+6 -2
View File
@@ -37,7 +37,7 @@ const walletStyle = StyleSheet.create({
backgroundColor: Colors.Orange,
padding: 16,
marginLeft: 16,
marginTop: 16,
marginTop: 76,
marginRight: 16
},
transactionsCard: {
@@ -132,7 +132,8 @@ const walletStyle = StyleSheet.create({
warning: {
backgroundColor: Colors.Orange,
padding: 16,
margin: 16
margin: 16,
marginTop: 76
},
warningText: {
color: Colors.White,
@@ -161,6 +162,9 @@ const walletStyle = StyleSheet.create({
},
bottomMarginLarge: {
marginBottom: 24
},
transactionHistoryScroll: {
marginTop: 60
}
});
+32 -26
View File
@@ -1,5 +1,6 @@
import { NavigationActions, StackActions } from 'react-navigation';
import { buildURI } from 'lbry-redux';
import { buildURI, isURIValid } from 'lbry-redux';
import { doPopDrawerStack, doPushDrawerStack } from 'redux/actions/drawer';
import { DrawerRoutes } from 'constants';
import Constants from 'constants';
@@ -18,7 +19,7 @@ function getRouteForSpecialUri(uri) {
return targetRoute;
}
export function dispatchNavigateToUri(dispatch, nav, uri) {
export function dispatchNavigateToUri(dispatch, nav, uri, isNavigatingBack) {
if (uri.startsWith('lbry://?')) {
dispatch(NavigationActions.navigate({ routeName: getRouteForSpecialUri(uri) }));
return;
@@ -32,6 +33,11 @@ export function dispatchNavigateToUri(dispatch, nav, uri) {
}
const params = { uri, uriVars };
if (!isNavigatingBack) {
dispatch(doPushDrawerStack(uri));
}
if (nav && nav.routes && nav.routes.length > 0 && 'Main' === nav.routes[0].routeName) {
const mainRoute = nav.routes[0];
const discoverRoute = mainRoute.routes[0];
@@ -86,7 +92,7 @@ function parseUriVars(vars) {
return uriVars;
}
export function navigateToUri(navigation, uri, additionalParams) {
export function navigateToUri(navigation, uri, additionalParams, isNavigatingBack) {
if (!navigation) {
return;
}
@@ -107,49 +113,49 @@ export function navigateToUri(navigation, uri, additionalParams) {
uriVars = parseUriVars(uriVarsStr);
}
const { store } = window;
const params = Object.assign({ uri, uriVars }, additionalParams);
if ('File' === navigation.state.routeName) {
const stackAction = StackActions.replace({ routeName: 'File', newKey: uri, params });
navigation.dispatch(stackAction);
if (store && store.dispatch && !isNavigatingBack) {
store.dispatch(doPushDrawerStack(uri));
}
return;
}
navigation.navigate({ routeName: 'File', key: uri, params });
if (store && store.dispatch && !isNavigatingBack) {
store.dispatch(doPushDrawerStack(uri));
}
}
export function navigateBack(navigation, drawerStack, popDrawerStack) {
const shouldPopStack = DrawerRoutes.indexOf(navigation.state.routeName) > -1;
if (shouldPopStack) {
navigation.goBack();
if (popDrawerStack) {
popDrawerStack();
}
navigation.navigate({ routeName: drawerStack[drawerStack.length > 1 ? drawerStack.length - 2 : 0] });
return;
if (popDrawerStack) {
popDrawerStack();
}
const target = drawerStack[drawerStack.length > 1 ? drawerStack.length - 2 : 0];
navigation.goBack(navigation.state.key);
if (DrawerRoutes.indexOf(target) === -1 && isURIValid(target)) {
navigateToUri(navigation, target, null, true);
} else {
navigation.navigate({ routeName: target });
}
}
export function dispatchNavigateBack(dispatch, nav, drawerStack, popDrawerStack) {
const drawerRouteIndex = nav.routes[0].index;
const shouldPopStack = (
(drawerRouteIndex > 0 && drawerRouteIndex !== 3) || // not the discover nor wallet stack
(drawerRouteIndex === 3 && nav.routes[0].routes[drawerRouteIndex].index === 0) // wallet stack, and tx history page not active
);
if (shouldPopStack) {
dispatch(NavigationActions.back());
if (popDrawerStack) {
dispatch(popDrawerStack());
}
export function dispatchNavigateBack(dispatch, nav, drawerStack) {
dispatch(doPopDrawerStack());
const target = drawerStack[drawerStack.length > 1 ? drawerStack.length - 2 : 0];
dispatch(NavigationActions.back());
if (DrawerRoutes.indexOf(target) === -1 && isURIValid(target)) {
dispatchNavigateToUri(dispatch, nav, target, true);
} else {
const navigateAction = NavigationActions.navigate({ routeName: drawerStack[drawerStack.length > 1 ? drawerStack.length - 2 : 0] });
dispatch(navigateAction);
return;
}
dispatch(NavigationActions.back());
}
export function uriFromFileInfo(fileInfo) {
+1 -1
View File
@@ -36,7 +36,7 @@ version.filename = %(source.dir)s/main.py
# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = python3crystax, openssl, sqlite3, hostpython3crystax, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, miniupnpc==1.9, gmpy, appdirs==1.4.3, argparse==1.2.1, docopt, base58==1.0.0, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2, pyyaml, qrcode==5.2.2, requests, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, txJSON-RPC, zope.interface==4.3.3, protobuf==3.6.1, keyring==10.4.0, txupnp, git+https://github.com/lbryio/lbryschema.git#egg=lbryschema, git+https://github.com/lbryio/lbry.git@v0.32.3#egg=lbrynet, git+https://github.com/lbryio/aioupnp.git#egg=aioupnp, asn1crypto, treq==17.8.0, funcsigs, mock, pbr, pyopenssl, twisted, idna, Automat, hyperlink, PyHamcrest, netifaces, cryptography, aiohttp==3.4.4, multidict==4.5.2, idna_ssl==1.1.0, typing_extensions==3.6.5, yarl, chardet==3.0.4, async_timeout==3.0.1, aiorpcX==0.9.0, git+https://github.com/lbryio/torba#egg=torba, coincurve
requirements = python3crystax, openssl, sqlite3, hostpython3crystax, android, distro==1.4.0, pyjnius, certifi==2018.11.29, appdirs==1.4.3, docopt==0.6.2, base58==1.0.0, colorama==0.3.7, ecdsa==0.13, jsonschema==2.6.0, pbkdf2==1.3, pyyaml, protobuf==3.6.1, keyring==10.4.0, git+https://github.com/lbryio/lbry.git@v0.34.0#egg=lbrynet, git+https://github.com/lbryio/aioupnp.git#egg=aioupnp, asn1crypto, mock, netifaces, cryptography, aiohttp==3.5.4, multidict==4.5.2, yarl==1.3.0, chardet==3.0.4, async_timeout==3.0.1, git+https://github.com/lbryio/torba#egg=torba, coincurve, msgpack==0.6.1, six, attrs==18.2.0, pylru
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
+1 -1
View File
@@ -36,7 +36,7 @@ version.filename = %(source.dir)s/main.py
# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = python3crystax, openssl, sqlite3, hostpython3crystax, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, miniupnpc==1.9, gmpy, appdirs==1.4.3, argparse==1.2.1, docopt, base58==1.0.0, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2, pyyaml, qrcode==5.2.2, requests, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, txJSON-RPC, zope.interface==4.3.3, protobuf==3.6.1, keyring==10.4.0, txupnp, git+https://github.com/lbryio/lbryschema.git#egg=lbryschema, git+https://github.com/lbryio/lbry.git@v0.32.3#egg=lbrynet, git+https://github.com/lbryio/aioupnp.git#egg=aioupnp, asn1crypto, treq==17.8.0, funcsigs, mock, pbr, pyopenssl, twisted, idna, Automat, hyperlink, PyHamcrest, netifaces, cryptography, aiohttp==3.4.4, multidict==4.5.2, idna_ssl==1.1.0, typing_extensions==3.6.5, yarl, chardet==3.0.4, async_timeout==3.0.1, aiorpcX==0.9.0, git+https://github.com/lbryio/torba#egg=torba, coincurve
requirements = python3crystax, openssl, sqlite3, hostpython3crystax, android, distro==1.4.0, pyjnius, certifi==2018.11.29, appdirs==1.4.3, docopt==0.6.2, base58==1.0.0, colorama==0.3.7, ecdsa==0.13, jsonschema==2.6.0, pbkdf2==1.3, pyyaml, protobuf==3.6.1, keyring==10.4.0, git+https://github.com/lbryio/lbry.git@v0.34.0#egg=lbrynet, git+https://github.com/lbryio/aioupnp.git#egg=aioupnp, asn1crypto, mock, netifaces, cryptography, aiohttp==3.5.4, multidict==4.5.2, yarl==1.3.0, chardet==3.0.4, async_timeout==3.0.1, git+https://github.com/lbryio/torba#egg=torba, coincurve, msgpack==0.6.1, six, attrs==18.2.0, pylru
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
+1 -1
View File
@@ -36,7 +36,7 @@ version.filename = %(source.dir)s/main.py
# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = python3crystax, openssl, sqlite3, hostpython3crystax, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, miniupnpc==1.9, gmpy, appdirs==1.4.3, argparse==1.2.1, docopt, base58==1.0.0, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2, pyyaml, qrcode==5.2.2, requests, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, txJSON-RPC, zope.interface==4.3.3, protobuf==3.6.1, keyring==10.4.0, txupnp, git+https://github.com/lbryio/lbryschema.git#egg=lbryschema, git+https://github.com/lbryio/lbry.git@v0.32.3#egg=lbrynet, git+https://github.com/lbryio/aioupnp.git#egg=aioupnp, asn1crypto, treq==17.8.0, funcsigs, mock, pbr, pyopenssl, twisted, idna, Automat, hyperlink, PyHamcrest, netifaces, cryptography, aiohttp==3.4.4, multidict==4.5.2, idna_ssl==1.1.0, typing_extensions==3.6.5, yarl, chardet==3.0.4, async_timeout==3.0.1, aiorpcX==0.9.0, git+https://github.com/lbryio/torba#egg=torba, coincurve
requirements = python3crystax, openssl, sqlite3, hostpython3crystax, android, distro==1.4.0, pyjnius, certifi==2018.11.29, appdirs==1.4.3, docopt==0.6.2, base58==1.0.0, colorama==0.3.7, ecdsa==0.13, jsonschema==2.6.0, pbkdf2==1.3, pyyaml, protobuf==3.6.1, keyring==10.4.0, git+https://github.com/lbryio/lbry.git@v0.34.0#egg=lbrynet, git+https://github.com/lbryio/aioupnp.git#egg=aioupnp, asn1crypto, mock, netifaces, cryptography, aiohttp==3.5.4, multidict==4.5.2, yarl==1.3.0, chardet==3.0.4, async_timeout==3.0.1, git+https://github.com/lbryio/torba#egg=torba, coincurve, msgpack==0.6.1, six, attrs==18.2.0, pylru
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
Binary file not shown.
+115 -44
View File
@@ -1,10 +1,10 @@
from os.path import (join, dirname)
from os import environ, uname
import sys
from distutils.spawn import find_executable
from os import environ
from os.path import (exists, join, dirname, split)
from glob import glob
from pythonforandroid.logger import warning
from pythonforandroid.recipe import Recipe
from pythonforandroid.util import BuildInterruptingException, build_platform
class Arch(object):
@@ -19,6 +19,12 @@ class Arch(object):
super(Arch, self).__init__()
self.ctx = ctx
# Allows injecting additional linker paths used by any recipe.
# This can also be modified by recipes (like the librt recipe)
# to make sure that some sort of global resource is available &
# linked for all others.
self.extra_global_link_paths = []
def __str__(self):
return self.arch
@@ -30,24 +36,65 @@ class Arch(object):
d.format(arch=self))
for d in self.ctx.include_dirs]
def get_env(self, with_flags_in_cc=True):
@property
def target(self):
target_data = self.command_prefix.split('-')
return '-'.join(
[target_data[0], 'none', target_data[1], target_data[2]])
def get_env(self, with_flags_in_cc=True, clang=False):
env = {}
env["CFLAGS"] = " ".join([
"-DANDROID", "-mandroid", "-fomit-frame-pointer",
"--sysroot", self.ctx.ndk_platform])
cflags = [
'-DANDROID',
'-fomit-frame-pointer',
'-D__ANDROID_API__={}'.format(self.ctx.ndk_api)]
if not clang:
cflags.append('-mandroid')
else:
cflags.append('-target ' + self.target)
toolchain = '{android_host}-{toolchain_version}'.format(
android_host=self.ctx.toolchain_prefix,
toolchain_version=self.ctx.toolchain_version)
toolchain = join(self.ctx.ndk_dir, 'toolchains', toolchain,
'prebuilt', build_platform)
cflags.append('-gcc-toolchain {}'.format(toolchain))
env['CFLAGS'] = ' '.join(cflags)
# Link the extra global link paths first before anything else
# (such that overriding system libraries with them is possible)
env['LDFLAGS'] = ' ' + " ".join([
"-L'" + l.replace("'", "'\"'\"'") + "'" # no shlex.quote in py2
for l in self.extra_global_link_paths
]) + ' '
sysroot = join(self.ctx._ndk_dir, 'sysroot')
if exists(sysroot):
# post-15 NDK per
# https://android.googlesource.com/platform/ndk/+/ndk-r15-release/docs/UnifiedHeaders.md
env['CFLAGS'] += ' -isystem {}/sysroot/usr/include/{}'.format(
self.ctx.ndk_dir, self.ctx.toolchain_prefix)
env['CFLAGS'] += ' -I{}/sysroot/usr/include/{}'.format(
self.ctx.ndk_dir, self.command_prefix)
else:
sysroot = self.ctx.ndk_platform
env['CFLAGS'] += ' -I{}'.format(self.ctx.ndk_platform)
env['CFLAGS'] += ' -isysroot {} '.format(sysroot)
env['CFLAGS'] += '-I' + join(self.ctx.get_python_install_dir(),
'include/python{}'.format(
self.ctx.python_recipe.version[0:3])
)
env['LDFLAGS'] += '--sysroot={} '.format(self.ctx.ndk_platform)
env["CXXFLAGS"] = env["CFLAGS"]
env["LDFLAGS"] = " ".join(['-lm', '-L' + self.ctx.get_libs_dir(self.arch)])
env["LDFLAGS"] += " ".join(['-lm', '-L' + self.ctx.get_libs_dir(self.arch)])
if self.ctx.ndk == 'crystax':
env['LDFLAGS'] += ' -L{}/sources/crystax/libs/{} -lcrystax'.format(self.ctx.ndk_dir, self.arch)
py_platform = sys.platform
if py_platform in ['linux2', 'linux3']:
py_platform = 'linux'
toolchain_prefix = self.ctx.toolchain_prefix
toolchain_version = self.ctx.toolchain_version
command_prefix = self.command_prefix
@@ -63,53 +110,71 @@ class Arch(object):
env['NDK_CCACHE'] = self.ctx.ccache
env.update({k: v for k, v in environ.items() if k.startswith('CCACHE_')})
cc = find_executable('{command_prefix}-gcc'.format(
command_prefix=command_prefix), path=environ['PATH'])
if clang:
llvm_dirname = split(
glob(join(self.ctx.ndk_dir, 'toolchains', 'llvm*'))[-1])[-1]
clang_path = join(self.ctx.ndk_dir, 'toolchains', llvm_dirname,
'prebuilt', build_platform, 'bin')
environ['PATH'] = '{clang_path}:{path}'.format(
clang_path=clang_path, path=environ['PATH'])
exe = join(clang_path, 'clang')
execxx = join(clang_path, 'clang++')
else:
exe = '{command_prefix}-gcc'.format(command_prefix=command_prefix)
execxx = '{command_prefix}-g++'.format(command_prefix=command_prefix)
cc = find_executable(exe, path=environ['PATH'])
if cc is None:
print('Searching path are: {!r}'.format(environ['PATH']))
warning('Couldn\'t find executable for CC. This indicates a '
'problem locating the {} executable in the Android '
'NDK, not that you don\'t have a normal compiler '
'installed. Exiting.')
exit(1)
raise BuildInterruptingException(
'Couldn\'t find executable for CC. This indicates a '
'problem locating the {} executable in the Android '
'NDK, not that you don\'t have a normal compiler '
'installed. Exiting.'.format(exe))
if with_flags_in_cc:
env['CC'] = '{ccache}{command_prefix}-gcc {cflags}'.format(
command_prefix=command_prefix,
env['CC'] = '{ccache}{exe} {cflags}'.format(
exe=exe,
ccache=ccache,
cflags=env['CFLAGS'])
env['CXX'] = '{ccache}{command_prefix}-g++ {cxxflags}'.format(
command_prefix=command_prefix,
env['CXX'] = '{ccache}{execxx} {cxxflags}'.format(
execxx=execxx,
ccache=ccache,
cxxflags=env['CXXFLAGS'])
else:
env['CC'] = '{ccache}{command_prefix}-gcc'.format(
command_prefix=command_prefix,
env['CC'] = '{ccache}{exe}'.format(
exe=exe,
ccache=ccache)
env['CXX'] = '{ccache}{command_prefix}-g++'.format(
command_prefix=command_prefix,
env['CXX'] = '{ccache}{execxx}'.format(
execxx=execxx,
ccache=ccache)
env['AR'] = '{}-ar'.format(command_prefix)
env['RANLIB'] = '{}-ranlib'.format(command_prefix)
env['LD'] = '{}-ld'.format(command_prefix)
# env['LDSHARED'] = join(self.ctx.root_dir, 'tools', 'liblink')
# env['LDSHARED'] = env['LD']
env['LDSHARED'] = env["CC"] + " -pthread -shared " +\
"-Wl,-O1 -Wl,-Bsymbolic-functions "
if self.ctx.python_recipe and self.ctx.python_recipe.from_crystax:
# For crystax python, we can't use the host python headers:
env["CFLAGS"] += ' -I{}/sources/python/{}/include/python/'.\
format(self.ctx.ndk_dir, self.ctx.python_recipe.version[0:3])
env['STRIP'] = '{}-strip --strip-unneeded'.format(command_prefix)
env['MAKE'] = 'make -j5'
env['READELF'] = '{}-readelf'.format(command_prefix)
env['NM'] = '{}-nm'.format(command_prefix)
hostpython_recipe = Recipe.get_recipe('hostpython2', self.ctx)
# AND: This hardcodes python version 2.7, needs fixing
hostpython_recipe = Recipe.get_recipe(
'host' + self.ctx.python_recipe.name, self.ctx)
env['BUILDLIB_PATH'] = join(
hostpython_recipe.get_build_dir(self.arch),
'build', 'lib.linux-{}-2.7'.format(uname()[-1]))
'build', 'lib.{}-{}'.format(
build_platform, self.ctx.python_recipe.major_minor_version_string)
)
env['PATH'] = environ['PATH']
env['ARCH'] = self.arch
env['NDK_API'] = 'android-{}'.format(str(self.ctx.ndk_api))
if self.ctx.python_recipe and self.ctx.python_recipe.from_crystax:
env['CRYSTAX_PYTHON_VERSION'] = self.ctx.python_recipe.version
@@ -123,12 +188,18 @@ class ArchARM(Arch):
command_prefix = 'arm-linux-androideabi'
platform_dir = 'arch-arm'
@property
def target(self):
target_data = self.command_prefix.split('-')
return '-'.join(
['armv7a', 'none', target_data[1], target_data[2]])
class ArchARMv7_a(ArchARM):
arch = 'armeabi-v7a'
def get_env(self, with_flags_in_cc=True):
env = super(ArchARMv7_a, self).get_env(with_flags_in_cc)
def get_env(self, with_flags_in_cc=True, clang=False):
env = super(ArchARMv7_a, self).get_env(with_flags_in_cc, clang=clang)
env['CFLAGS'] = (env['CFLAGS'] +
(' -march=armv7-a -mfloat-abi=softfp '
'-mfpu=vfp -mthumb'))
@@ -142,8 +213,8 @@ class Archx86(Arch):
command_prefix = 'i686-linux-android'
platform_dir = 'arch-x86'
def get_env(self, with_flags_in_cc=True):
env = super(Archx86, self).get_env(with_flags_in_cc)
def get_env(self, with_flags_in_cc=True, clang=False):
env = super(Archx86, self).get_env(with_flags_in_cc, clang=clang)
env['CFLAGS'] = (env['CFLAGS'] +
' -march=i686 -mtune=intel -mssse3 -mfpmath=sse -m32')
env['CXXFLAGS'] = env['CFLAGS']
@@ -152,12 +223,12 @@ class Archx86(Arch):
class Archx86_64(Arch):
arch = 'x86_64'
toolchain_prefix = 'x86'
toolchain_prefix = 'x86_64'
command_prefix = 'x86_64-linux-android'
platform_dir = 'arch-x86'
platform_dir = 'arch-x86_64'
def get_env(self, with_flags_in_cc=True):
env = super(Archx86_64, self).get_env(with_flags_in_cc)
def get_env(self, with_flags_in_cc=True, clang=False):
env = super(Archx86_64, self).get_env(with_flags_in_cc, clang=clang)
env['CFLAGS'] = (env['CFLAGS'] +
' -march=x86-64 -msse4.2 -mpopcnt -m64 -mtune=intel')
env['CXXFLAGS'] = env['CFLAGS']
@@ -170,8 +241,8 @@ class ArchAarch_64(Arch):
command_prefix = 'aarch64-linux-android'
platform_dir = 'arch-arm64'
def get_env(self, with_flags_in_cc=True):
env = super(ArchAarch_64, self).get_env(with_flags_in_cc)
def get_env(self, with_flags_in_cc=True, clang=False):
env = super(ArchAarch_64, self).get_env(with_flags_in_cc, clang=clang)
incpath = ' -I' + join(dirname(__file__), 'includes', 'arm64-v8a')
env['EXTRA_CFLAGS'] = incpath
env['CFLAGS'] += incpath
+55 -30
View File
@@ -1,17 +1,39 @@
from os.path import (join, dirname, isdir, splitext, basename)
from os import listdir
from os.path import (join, dirname, isdir, normpath, splitext, basename)
from os import listdir, walk, sep
import sh
import shlex
import glob
import json
import importlib
import os
import shutil
from pythonforandroid.logger import (warning, shprint, info, logger,
debug)
from pythonforandroid.util import (current_directory, ensure_dir,
temp_directory, which)
temp_directory)
from pythonforandroid.recipe import Recipe
def copy_files(src_root, dest_root, override=True):
for root, dirnames, filenames in walk(src_root):
for filename in filenames:
subdir = normpath(root.replace(src_root, ""))
if subdir.startswith(sep): # ensure it is relative
subdir = subdir[1:]
dest_dir = join(dest_root, subdir)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
src_file = join(root, filename)
dest_file = join(dest_dir, filename)
if os.path.isfile(src_file):
if override and os.path.exists(dest_file):
os.unlink(dest_file)
if not os.path.exists(dest_file):
shutil.copy(src_file, dest_file)
else:
os.makedirs(dest_file)
class Bootstrap(object):
'''An Android project template, containing recipe stuff for
compilation and templated fields for APK info.
@@ -27,7 +49,11 @@ class Bootstrap(object):
dist_name = None
distribution = None
recipe_depends = ['sdl2']
# All bootstraps should include Python in some way:
recipe_depends = [
("python2", "python2legacy", "python3", "python3crystax"),
'android',
]
can_be_chosen_automatically = True
'''Determines whether the bootstrap can be chosen as one that
@@ -78,6 +104,9 @@ class Bootstrap(object):
def get_dist_dir(self, name):
return join(self.ctx.dist_dir, name)
def get_common_dir(self):
return os.path.abspath(join(self.bootstrap_dir, "..", 'common'))
@property
def name(self):
modname = self.__class__.__module__
@@ -87,9 +116,10 @@ class Bootstrap(object):
'''Ensure that a build dir exists for the recipe. This same single
dir will be used for building all different archs.'''
self.build_dir = self.get_build_dir()
shprint(sh.cp, '-r',
join(self.bootstrap_dir, 'build'),
self.build_dir)
self.common_dir = self.get_common_dir()
copy_files(join(self.bootstrap_dir, 'build'), self.build_dir)
copy_files(join(self.common_dir, 'build'), self.build_dir,
override=False)
if self.ctx.symlink_java_src:
info('Symlinking java src instead of copying')
shprint(sh.rm, '-r', join(self.build_dir, 'src'))
@@ -102,26 +132,15 @@ class Bootstrap(object):
fileh.write('target=android-{}'.format(self.ctx.android_api))
def prepare_dist_dir(self, name):
# self.dist_dir = self.get_dist_dir(name)
ensure_dir(self.dist_dir)
def run_distribute(self):
# print('Default bootstrap being used doesn\'t know how '
# 'to distribute...failing.')
# exit(1)
with current_directory(self.dist_dir):
info('Saving distribution info')
with open('dist_info.json', 'w') as fileh:
json.dump({'dist_name': self.ctx.dist_name,
'bootstrap': self.ctx.bootstrap.name,
'archs': [arch.arch for arch in self.ctx.archs],
'recipes': self.ctx.recipe_build_order + self.ctx.python_modules},
fileh)
self.distribution.save_info(self.dist_dir)
@classmethod
def list_bootstraps(cls):
'''Find all the available bootstraps and return them.'''
forbidden_dirs = ('__pycache__', )
forbidden_dirs = ('__pycache__', 'common')
bootstraps_dir = join(dirname(__file__), 'bootstraps')
for name in listdir(bootstraps_dir):
if name in forbidden_dirs:
@@ -152,7 +171,7 @@ class Bootstrap(object):
for recipe in recipes:
try:
recipe = Recipe.get_recipe(recipe, ctx)
except IOError:
except ValueError:
conflicts = []
else:
conflicts = recipe.conflicts
@@ -160,7 +179,7 @@ class Bootstrap(object):
for conflict in conflicts]):
ok = False
break
if ok:
if ok and bs not in acceptable_bootstraps:
acceptable_bootstraps.append(bs)
info('Found {} acceptable bootstraps: {}'.format(
len(acceptable_bootstraps),
@@ -249,16 +268,22 @@ class Bootstrap(object):
info('Python was loaded from CrystaX, skipping strip')
return
env = arch.get_env()
strip = which('arm-linux-androideabi-strip', env['PATH'])
if strip is None:
warning('Can\'t find strip in PATH...')
return
strip = sh.Command(strip)
filens = shprint(sh.find, join(self.dist_dir, 'private'),
join(self.dist_dir, 'libs'),
tokens = shlex.split(env['STRIP'])
strip = sh.Command(tokens[0])
if len(tokens) > 1:
strip = strip.bake(tokens[1:])
libs_dir = join(self.dist_dir, '_python_bundle',
'_python_bundle', 'modules')
if self.ctx.python_recipe.name == 'python2legacy':
libs_dir = join(self.dist_dir, 'private')
filens = shprint(sh.find, libs_dir, join(self.dist_dir, 'libs'),
'-iname', '*.so', _env=env).stdout.decode('utf-8')
logger.info('Stripping libraries in private dir')
for filen in filens.split('\n'):
if not filen:
continue # skip the last ''
try:
strip(filen, _env=env)
except sh.ErrorReturnCode_1:
@@ -0,0 +1,22 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked into Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.
source.absolute.dir = tmp-src
resource.absolute.dir = src/main/res
asset.absolute.dir = src/main/assets
@@ -0,0 +1,795 @@
#!/usr/bin/env python2.7
from __future__ import print_function
import json
from os.path import (
dirname, join, isfile, realpath,
relpath, split, exists, basename
)
from os import listdir, makedirs, remove
import os
import shlex
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
from zipfile import ZipFile
from distutils.version import LooseVersion
from fnmatch import fnmatch
import jinja2
def get_dist_info_for(key):
try:
with open(join(dirname(__file__), 'dist_info.json'), 'r') as fileh:
info = json.load(fileh)
value = str(info[key])
except (OSError, KeyError) as e:
print("BUILD FAILURE: Couldn't extract the key `" + key + "` " +
"from dist_info.json: " + str(e))
sys.exit(1)
return value
def get_hostpython():
return get_dist_info_for('hostpython')
def get_python_version():
return get_dist_info_for('python_version')
def get_bootstrap_name():
return get_dist_info_for('bootstrap')
if os.name == 'nt':
ANDROID = 'android.bat'
ANT = 'ant.bat'
else:
ANDROID = 'android'
ANT = 'ant'
curdir = dirname(__file__)
PYTHON = get_hostpython()
PYTHON_VERSION = get_python_version()
if PYTHON is not None and not exists(PYTHON):
PYTHON = None
BLACKLIST_PATTERNS = [
# code versionning
'^*.hg/*',
'^*.git/*',
'^*.bzr/*',
'^*.svn/*',
# temp files
'~',
'*.bak',
'*.swp',
]
# pyc/py
if PYTHON is not None:
BLACKLIST_PATTERNS.append('*.py')
if PYTHON_VERSION and int(PYTHON_VERSION[0]) == 2:
# we only blacklist `.pyc` for python2 because in python3 the compiled
# extension is `.pyc` (.pyo files not exists for python >= 3.6)
BLACKLIST_PATTERNS.append('*.pyc')
WHITELIST_PATTERNS = []
if get_bootstrap_name() in ('sdl2', 'webview', 'service_only'):
WHITELIST_PATTERNS.append('pyconfig.h')
python_files = []
environment = jinja2.Environment(loader=jinja2.FileSystemLoader(
join(curdir, 'templates')))
def try_unlink(fn):
if exists(fn):
os.unlink(fn)
def ensure_dir(path):
if not exists(path):
makedirs(path)
def render(template, dest, **kwargs):
'''Using jinja2, render `template` to the filename `dest`, supplying the
keyword arguments as template parameters.
'''
dest_dir = dirname(dest)
if dest_dir and not exists(dest_dir):
makedirs(dest_dir)
template = environment.get_template(template)
text = template.render(**kwargs)
f = open(dest, 'wb')
f.write(text.encode('utf-8'))
f.close()
def is_whitelist(name):
return match_filename(WHITELIST_PATTERNS, name)
def is_blacklist(name):
if is_whitelist(name):
return False
return match_filename(BLACKLIST_PATTERNS, name)
def match_filename(pattern_list, name):
for pattern in pattern_list:
if pattern.startswith('^'):
pattern = pattern[1:]
else:
pattern = '*/' + pattern
if fnmatch(name, pattern):
return True
def listfiles(d):
basedir = d
subdirlist = []
for item in os.listdir(d):
fn = join(d, item)
if isfile(fn):
yield fn
else:
subdirlist.append(join(basedir, item))
for subdir in subdirlist:
for fn in listfiles(subdir):
yield fn
def make_python_zip():
'''
Search for all the python related files, and construct the pythonXX.zip
According to
# http://randomsplat.com/id5-cross-compiling-python-for-embedded-linux.html
site-packages, config and lib-dynload will be not included.
'''
if not exists('private'):
print('No compiled python is present to zip, skipping.')
return
global python_files
d = realpath(join('private', 'lib', 'python2.7'))
def select(fn):
if is_blacklist(fn):
return False
fn = realpath(fn)
assert(fn.startswith(d))
fn = fn[len(d):]
if (fn.startswith('/site-packages/')
or fn.startswith('/config/')
or fn.startswith('/lib-dynload/')
or fn.startswith('/libpymodules.so')):
return False
return fn
# get a list of all python file
python_files = [x for x in listfiles(d) if select(x)]
# create the final zipfile
zfn = join('private', 'lib', 'python27.zip')
zf = ZipFile(zfn, 'w')
# put all the python files in it
for fn in python_files:
afn = fn[len(d):]
zf.write(fn, afn)
zf.close()
def make_tar(tfn, source_dirs, ignore_path=[], optimize_python=True):
'''
Make a zip file `fn` from the contents of source_dis.
'''
# selector function
def select(fn):
rfn = realpath(fn)
for p in ignore_path:
if p.endswith('/'):
p = p[:-1]
if rfn.startswith(p):
return False
if rfn in python_files:
return False
return not is_blacklist(fn)
# get the files and relpath file of all the directory we asked for
files = []
for sd in source_dirs:
sd = realpath(sd)
compile_dir(sd, optimize_python=optimize_python)
files += [(x, relpath(realpath(x), sd)) for x in listfiles(sd)
if select(x)]
# create tar.gz of thoses files
tf = tarfile.open(tfn, 'w:gz', format=tarfile.USTAR_FORMAT)
dirs = []
for fn, afn in files:
dn = dirname(afn)
if dn not in dirs:
# create every dirs first if not exist yet
d = ''
for component in split(dn):
d = join(d, component)
if d.startswith('/'):
d = d[1:]
if d == '' or d in dirs:
continue
dirs.append(d)
tinfo = tarfile.TarInfo(d)
tinfo.type = tarfile.DIRTYPE
tf.addfile(tinfo)
# put the file
tf.add(fn, afn)
tf.close()
def compile_dir(dfn, optimize_python=True):
'''
Compile *.py in directory `dfn` to *.pyo
'''
if PYTHON is None:
return
if int(PYTHON_VERSION[0]) >= 3:
args = [PYTHON, '-m', 'compileall', '-b', '-f', dfn]
else:
args = [PYTHON, '-m', 'compileall', '-f', dfn]
if optimize_python:
# -OO = strip docstrings
args.insert(1, '-OO')
return_code = subprocess.call(args)
if return_code != 0:
print('Error while running "{}"'.format(' '.join(args)))
print('This probably means one of your Python files has a syntax '
'error, see logs above')
exit(1)
def make_package(args):
# If no launcher is specified, require a main.py/main.pyo:
if (get_bootstrap_name() != "sdl" or args.launcher is None) and \
get_bootstrap_name() != "webview":
# (webview doesn't need an entrypoint, apparently)
if args.private is None or (
not exists(join(realpath(args.private), 'main.py')) and
not exists(join(realpath(args.private), 'main.pyo'))):
print('''BUILD FAILURE: No main.py(o) found in your app directory. This
file must exist to act as the entry point for you app. If your app is
started by a file with a different name, rename it to main.py or add a
main.py that loads it.''')
sys.exit(1)
assets_dir = "src/main/assets"
# Delete the old assets.
try_unlink(join(assets_dir, 'public.mp3'))
try_unlink(join(assets_dir, 'private.mp3'))
ensure_dir(assets_dir)
# In order to speedup import and initial depack,
# construct a python27.zip
make_python_zip()
# Add extra environment variable file into tar-able directory:
env_vars_tarpath = tempfile.mkdtemp(prefix="p4a-extra-env-")
with open(os.path.join(env_vars_tarpath, "p4a_env_vars.txt"), "w") as f:
f.write("P4A_IS_WINDOWED=" + str(args.window) + "\n")
if hasattr(args, "orientation"):
f.write("P4A_ORIENTATION=" + str(args.orientation) + "\n")
f.write("P4A_NUMERIC_VERSION=" + str(args.numeric_version) + "\n")
f.write("P4A_MINSDK=" + str(args.min_sdk_version) + "\n")
# Package up the private data (public not supported).
tar_dirs = [env_vars_tarpath]
if args.private:
tar_dirs.append(args.private)
for python_bundle_dir in ('private', 'crystax_python', '_python_bundle'):
if exists(python_bundle_dir):
tar_dirs.append(python_bundle_dir)
if get_bootstrap_name() == "webview":
tar_dirs.append('webview_includes')
if args.private or args.launcher:
make_tar(
join(assets_dir, 'private.mp3'), tar_dirs, args.ignore_path,
optimize_python=args.optimize_python)
# Remove extra env vars tar-able directory:
shutil.rmtree(env_vars_tarpath)
# Prepare some variables for templating process
res_dir = "src/main/res"
default_icon = 'templates/kivy-icon.png'
default_presplash = 'templates/kivy-presplash.jpg'
shutil.copy(
args.icon or default_icon,
join(res_dir, 'drawable/icon.png')
)
if get_bootstrap_name() != "service_only":
shutil.copy(
args.presplash or default_presplash,
join(res_dir, 'drawable/presplash.jpg')
)
# If extra Java jars were requested, copy them into the libs directory
jars = []
if args.add_jar:
for jarname in args.add_jar:
if not exists(jarname):
print('Requested jar does not exist: {}'.format(jarname))
sys.exit(-1)
shutil.copy(jarname, 'src/main/libs')
jars.append(basename(jarname))
# If extra aar were requested, copy them into the libs directory
aars = []
if args.add_aar:
ensure_dir("libs")
for aarname in args.add_aar:
if not exists(aarname):
print('Requested aar does not exists: {}'.format(aarname))
sys.exit(-1)
shutil.copy(aarname, 'libs')
aars.append(basename(aarname).rsplit('.', 1)[0])
versioned_name = (args.name.replace(' ', '').replace('\'', '') +
'-' + args.version)
version_code = 0
if not args.numeric_version:
# Set version code in format (arch-minsdk-app_version)
with open(join(dirname(__file__), 'dist_info.json'), 'r') as dist_info:
dist_data = json.load(dist_info)
arch = dist_data["archs"][0]
arch_dict = {"x86_64": "9", "arm64-v8a": "8", "armeabi-v7a": "7", "x86": "6"}
arch_code = arch_dict.get(arch, '1')
min_sdk = args.min_sdk_version
for i in args.version.split('.'):
version_code *= 100
version_code += int(i)
args.numeric_version = "{}{}{}".format(arch_code, min_sdk, version_code)
if args.intent_filters:
with open(args.intent_filters) as fd:
args.intent_filters = fd.read()
if not args.add_activity:
args.add_activity = []
if not args.activity_launch_mode:
args.activity_launch_mode = ''
if args.extra_source_dirs:
esd = []
for spec in args.extra_source_dirs:
if ':' in spec:
specdir, specincludes = spec.split(':')
else:
specdir = spec
specincludes = '**'
esd.append((realpath(specdir), specincludes))
args.extra_source_dirs = esd
else:
args.extra_source_dirs = []
service = False
if args.private:
service_main = join(realpath(args.private), 'service', 'main.py')
if exists(service_main) or exists(service_main + 'o'):
service = True
service_names = []
for sid, spec in enumerate(args.services):
spec = spec.split(':')
name = spec[0]
entrypoint = spec[1]
options = spec[2:]
foreground = 'foreground' in options
sticky = 'sticky' in options
service_names.append(name)
service_target_path =\
'src/main/java/{}/Service{}.java'.format(
args.package.replace(".", "/"),
name.capitalize()
)
render(
'Service.tmpl.java',
service_target_path,
name=name,
entrypoint=entrypoint,
args=args,
foreground=foreground,
sticky=sticky,
service_id=sid + 1,
)
# Find the SDK directory and target API
with open('project.properties', 'r') as fileh:
target = fileh.read().strip()
android_api = target.split('-')[1]
try:
int(android_api)
except (ValueError, TypeError):
raise ValueError(
"failed to extract the Android API level from " +
"build.properties. expected int, got: '" +
str(android_api) + "'"
)
with open('local.properties', 'r') as fileh:
sdk_dir = fileh.read().strip()
sdk_dir = sdk_dir[8:]
# Try to build with the newest available build tools
ignored = {".DS_Store", ".ds_store"}
build_tools_versions = [x for x in listdir(join(sdk_dir, 'build-tools')) if x not in ignored]
build_tools_versions = sorted(build_tools_versions,
key=LooseVersion)
build_tools_version = build_tools_versions[-1]
# Folder name for launcher (used by SDL2 bootstrap)
url_scheme = 'kivy'
# Render out android manifest:
manifest_path = "src/main/AndroidManifest.xml"
render_args = {
"args": args,
"service": service,
"service_names": service_names,
"android_api": android_api
}
if get_bootstrap_name() == "sdl2":
render_args["url_scheme"] = url_scheme
render(
'AndroidManifest.tmpl.xml',
manifest_path,
**render_args)
# Copy the AndroidManifest.xml to the dist root dir so that ant
# can also use it
if exists('AndroidManifest.xml'):
remove('AndroidManifest.xml')
shutil.copy(manifest_path, 'AndroidManifest.xml')
# gradle build templates
render(
'build.tmpl.gradle',
'build.gradle',
args=args,
aars=aars,
jars=jars,
android_api=android_api,
build_tools_version=build_tools_version
)
# ant build templates
render(
'build.tmpl.xml',
'build.xml',
args=args,
versioned_name=versioned_name)
# String resources:
render_args = {
"args": args,
"private_version": str(time.time())
}
if get_bootstrap_name() == "sdl2":
render_args["url_scheme"] = url_scheme
render(
'strings.tmpl.xml',
join(res_dir, 'values/strings.xml'),
**render_args)
if exists(join("templates", "custom_rules.tmpl.xml")):
render(
'custom_rules.tmpl.xml',
'custom_rules.xml',
args=args)
if get_bootstrap_name() == "webview":
render('WebViewLoader.tmpl.java',
'src/main/java/org/kivy/android/WebViewLoader.java',
args=args)
if args.sign:
render('build.properties', 'build.properties')
else:
if exists('build.properties'):
os.remove('build.properties')
# Apply java source patches if any are present:
if exists(join('src', 'patches')):
print("Applying Java source code patches...")
for patch_name in os.listdir(join('src', 'patches')):
patch_path = join('src', 'patches', patch_name)
print("Applying patch: " + str(patch_path))
try:
subprocess.check_output([
# -N: insist this is FORWARd patch, don't reverse apply
# -p1: strip first path component
# -t: batch mode, don't ask questions
"patch", "-N", "-p1", "-t", "-i", patch_path
])
except subprocess.CalledProcessError as e:
if e.returncode == 1:
# Return code 1 means it didn't apply, this will
# usually mean it is already applied.
print("Warning: failed to apply patch (" +
"exit code 1), " +
"assuming it is already applied: " +
str(patch_path)
)
else:
raise e
def parse_args(args=None):
global BLACKLIST_PATTERNS, WHITELIST_PATTERNS, PYTHON
# Get the default minsdk, equal to the NDK API that this dist is built against
try:
with open('dist_info.json', 'r') as fileh:
info = json.load(fileh)
default_min_api = int(info['ndk_api'])
ndk_api = default_min_api
except (OSError, KeyError, ValueError, TypeError):
print('WARNING: Failed to read ndk_api from dist info, defaulting to 12')
default_min_api = 12 # The old default before ndk_api was introduced
ndk_api = 12
import argparse
ap = argparse.ArgumentParser(description='''\
Package a Python application for Android (using
bootstrap ''' + get_bootstrap_name() + ''').
For this to work, Java and Ant need to be in your path, as does the
tools directory of the Android SDK.
''')
# --private is required unless for sdl2, where there's also --launcher
ap.add_argument('--private', dest='private',
help='the directory with the app source code files' +
' (containing your main.py entrypoint)',
required=(get_bootstrap_name() != "sdl2"))
ap.add_argument('--package', dest='package',
help=('The name of the java package the project will be'
' packaged under.'),
required=True)
ap.add_argument('--name', dest='name',
help=('The human-readable name of the project.'),
required=True)
ap.add_argument('--numeric-version', dest='numeric_version',
help=('The numeric version number of the project. If not '
'given, this is automatically computed from the '
'version.'))
ap.add_argument('--version', dest='version',
help=('The version number of the project. This should '
'consist of numbers and dots, and should have the '
'same number of groups of numbers as previous '
'versions.'),
required=True)
if get_bootstrap_name() == "sdl2":
ap.add_argument('--launcher', dest='launcher', action='store_true',
help=('Provide this argument to build a multi-app '
'launcher, rather than a single app.'))
ap.add_argument('--permission', dest='permissions', action='append', default=[],
help='The permissions to give this app.', nargs='+')
ap.add_argument('--meta-data', dest='meta_data', action='append', default=[],
help='Custom key=value to add in application metadata')
ap.add_argument('--uses-library', dest='android_used_libs', action='append', default=[],
help='Used shared libraries included using <uses-library> tag in AndroidManifest.xml')
ap.add_argument('--icon', dest='icon',
help=('A png file to use as the icon for '
'the application.'))
ap.add_argument('--service', dest='services', action='append', default=[],
help='Declare a new service entrypoint: '
'NAME:PATH_TO_PY[:foreground]')
if get_bootstrap_name() != "service_only":
ap.add_argument('--presplash', dest='presplash',
help=('A jpeg file to use as a screen while the '
'application is loading.'))
ap.add_argument('--presplash-color',
dest='presplash_color',
default='#000000',
help=('A string to set the loading screen '
'background color. '
'Supported formats are: '
'#RRGGBB #AARRGGBB or color names '
'like red, green, blue, etc.'))
ap.add_argument('--window', dest='window', action='store_true',
default=False,
help='Indicate if the application will be windowed')
ap.add_argument('--orientation', dest='orientation',
default='portrait',
help=('The orientation that the game will '
'display in. '
'Usually one of "landscape", "portrait", '
'"sensor", or "user" (the same as "sensor" '
'but obeying the '
'user\'s Android rotation setting). '
'The full list of options is given under '
'android_screenOrientation at '
'https://developer.android.com/guide/'
'topics/manifest/'
'activity-element.html'))
ap.add_argument('--wakelock', dest='wakelock', action='store_true',
help=('Indicate if the application needs the device '
'to stay on'))
ap.add_argument('--blacklist', dest='blacklist',
default=join(curdir, 'blacklist.txt'),
help=('Use a blacklist file to match unwanted file in '
'the final APK'))
ap.add_argument('--whitelist', dest='whitelist',
default=join(curdir, 'whitelist.txt'),
help=('Use a whitelist file to prevent blacklisting of '
'file in the final APK'))
ap.add_argument('--add-jar', dest='add_jar', action='append',
help=('Add a Java .jar to the libs, so you can access its '
'classes with pyjnius. You can specify this '
'argument more than once to include multiple jars'))
ap.add_argument('--add-aar', dest='add_aar', action='append',
help=('Add an aar dependency manually'))
ap.add_argument('--depend', dest='depends', action='append',
help=('Add a external dependency '
'(eg: com.android.support:appcompat-v7:19.0.1)'))
# The --sdk option has been removed, it is ignored in favour of
# --android-api handled by toolchain.py
ap.add_argument('--sdk', dest='sdk_version', default=-1,
type=int, help=('Deprecated argument, does nothing'))
ap.add_argument('--minsdk', dest='min_sdk_version',
default=default_min_api, type=int,
help=('Minimum Android SDK version that the app supports. '
'Defaults to {}.'.format(default_min_api)))
ap.add_argument('--allow-minsdk-ndkapi-mismatch', default=False,
action='store_true',
help=('Allow the --minsdk argument to be different from '
'the discovered ndk_api in the dist'))
ap.add_argument('--intent-filters', dest='intent_filters',
help=('Add intent-filters xml rules to the '
'AndroidManifest.xml file. The argument is a '
'filename containing xml. The filename should be '
'located relative to the python-for-android '
'directory'))
ap.add_argument('--with-billing', dest='billing_pubkey',
help='If set, the billing service will be added (not implemented)')
ap.add_argument('--add-source', dest='extra_source_dirs', action='append',
help='Include additional source dirs in Java build')
if get_bootstrap_name() == "webview":
ap.add_argument('--port',
help='The port on localhost that the WebView will access',
default='5000')
ap.add_argument('--try-system-python-compile', dest='try_system_python_compile',
action='store_true',
help='Use the system python during compileall if possible.')
ap.add_argument('--no-compile-pyo', dest='no_compile_pyo', action='store_true',
help='Do not optimise .py files to .pyo.')
ap.add_argument('--sign', action='store_true',
help=('Try to sign the APK with your credentials. You must set '
'the appropriate environment variables.'))
ap.add_argument('--add-activity', dest='add_activity', action='append',
help='Add this Java class as an Activity to the manifest.')
ap.add_argument('--activity-launch-mode',
dest='activity_launch_mode',
default='singleTask',
help='Set the launch mode of the main activity in the manifest.')
ap.add_argument('--allow-backup', dest='allow_backup', default='true',
help="if set to 'false', then android won't backup the application.")
ap.add_argument('--no-optimize-python', dest='optimize_python',
action='store_false', default=True,
help=('Whether to compile to optimised .pyo files, using -OO '
'(strips docstrings and asserts)'))
# Put together arguments, and add those from .p4a config file:
if args is None:
args = sys.argv[1:]
def _read_configuration():
if not exists(".p4a"):
return
print("Reading .p4a configuration")
with open(".p4a") as fd:
lines = fd.readlines()
lines = [shlex.split(line)
for line in lines if not line.startswith("#")]
for line in lines:
for arg in line:
args.append(arg)
_read_configuration()
args = ap.parse_args(args)
args.ignore_path = []
if args.name and args.name[0] == '"' and args.name[-1] == '"':
args.name = args.name[1:-1]
if ndk_api != args.min_sdk_version:
print(('WARNING: --minsdk argument does not match the api that is '
'compiled against. Only proceed if you know what you are '
'doing, otherwise use --minsdk={} or recompile against api '
'{}').format(ndk_api, args.min_sdk_version))
if not args.allow_minsdk_ndkapi_mismatch:
print('You must pass --allow-minsdk-ndkapi-mismatch to build '
'with --minsdk different to the target NDK api from the '
'build step')
sys.exit(1)
else:
print('Proceeding with --minsdk not matching build target api')
if args.billing_pubkey:
print('Billing not yet supported!')
sys.exit(1)
if args.sdk_version == -1:
print('WARNING: Received a --sdk argument, but this argument is '
'deprecated and does nothing.')
args.sdk_version = -1 # ensure it is not used
if args.permissions and isinstance(args.permissions[0], list):
args.permissions = [p for perm in args.permissions for p in perm]
if args.try_system_python_compile:
# Hardcoding python2.7 is okay for now, as python3 skips the
# compilation anyway
if not exists('crystax_python'):
python_executable = 'python2.7'
try:
subprocess.call([python_executable, '--version'])
except (OSError, subprocess.CalledProcessError):
pass
else:
PYTHON = python_executable
if args.no_compile_pyo:
PYTHON = None
BLACKLIST_PATTERNS.remove('*.py')
if args.blacklist:
with open(args.blacklist) as fd:
patterns = [x.strip() for x in fd.read().splitlines()
if x.strip() and not x.strip().startswith('#')]
BLACKLIST_PATTERNS += patterns
if args.whitelist:
with open(args.whitelist) as fd:
patterns = [x.strip() for x in fd.read().splitlines()
if x.strip() and not x.strip().startswith('#')]
WHITELIST_PATTERNS += patterns
if args.private is None and \
get_bootstrap_name() == 'sdl2' and args.launcher is None:
print('Need --private directory or ' +
'--launcher (SDL2 bootstrap only)' +
'to have something to launch inside the .apk!')
sys.exit(1)
make_package(args)
return args
if __name__ == "__main__":
parse_args()
@@ -0,0 +1,6 @@
#Mon Mar 09 17:19:02 CET 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1 @@
include $(call all-subdir-makefiles)
@@ -0,0 +1 @@
include $(call all-subdir-makefiles)
@@ -0,0 +1,27 @@
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := main
SDL_PATH := ../../SDL
LOCAL_C_INCLUDES := $(LOCAL_PATH)/$(SDL_PATH)/include
# Add your application source files here...
LOCAL_SRC_FILES := $(SDL_PATH)/src/main/android/SDL_android_main.c \
start.c
LOCAL_CFLAGS += -I$(PYTHON_INCLUDE_ROOT) $(EXTRA_CFLAGS)
LOCAL_SHARED_LIBRARIES := SDL2 python_shared
LOCAL_LDLIBS := -lGLESv1_CM -lGLESv2 -llog $(EXTRA_LDLIBS)
LOCAL_LDFLAGS += -L$(PYTHON_LINK_ROOT) $(APPLICATION_ADDITIONAL_LDFLAGS)
include $(BUILD_SHARED_LIBRARY)
ifdef CRYSTAX_PYTHON_VERSION
$(call import-module,python/$(CRYSTAX_PYTHON_VERSION))
endif
@@ -1,5 +1,4 @@
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#ifndef Py_PYTHON_H
@@ -15,6 +14,16 @@
#include <sys/types.h>
#include <errno.h>
#include "bootstrap_name.h"
#ifndef BOOTSTRAP_USES_NO_SDL_HEADERS
#include "SDL.h"
#ifndef BOOTSTRAP_NAME_PYGAME
#include "SDL_opengles2.h"
#endif
#endif
#ifdef BOOTSTRAP_NAME_PYGAME
#include "jniwrapperstuff.h"
#endif
#include "android/log.h"
#define ENTRYPOINT_MAXLEN 128
@@ -58,7 +67,7 @@ int dir_exists(char *filename) {
int file_exists(const char *filename) {
FILE *file;
if (file = fopen(filename, "r")) {
if ((file = fopen(filename, "r"))) {
fclose(file);
return 1;
}
@@ -75,25 +84,79 @@ int main(int argc, char *argv[]) {
int ret = 0;
FILE *fd;
/* AND: Several filepaths are hardcoded here, these must be made
configurable */
/* AND: P4A uses env vars...not sure what's best */
LOGP("Initialize Python for Android");
LOGP("Initializing Python for Android");
// Set a couple of built-in environment vars:
setenv("P4A_BOOTSTRAP", bootstrap_name, 1); // env var to identify p4a to applications
env_argument = getenv("ANDROID_ARGUMENT");
setenv("ANDROID_APP_PATH", env_argument, 1);
env_entrypoint = getenv("ANDROID_ENTRYPOINT");
env_logname = getenv("PYTHON_NAME");
if (!getenv("ANDROID_UNPACK")) {
/* ANDROID_UNPACK currently isn't set in services */
setenv("ANDROID_UNPACK", env_argument, 1);
}
if (env_logname == NULL) {
env_logname = "python";
setenv("PYTHON_NAME", "python", 1);
}
// Set additional file-provided environment vars:
LOGP("Setting additional env vars from p4a_env_vars.txt");
char env_file_path[256];
snprintf(env_file_path, sizeof(env_file_path),
"%s/p4a_env_vars.txt", getenv("ANDROID_UNPACK"));
FILE *env_file_fd = fopen(env_file_path, "r");
if (env_file_fd) {
char* line = NULL;
size_t len = 0;
while (getline(&line, &len, env_file_fd) != -1) {
if (strlen(line) > 0) {
char *eqsubstr = strstr(line, "=");
if (eqsubstr) {
size_t eq_pos = eqsubstr - line;
// Extract name:
char env_name[256];
strncpy(env_name, line, sizeof(env_name));
env_name[eq_pos] = '\0';
// Extract value (with line break removed:
char env_value[256];
strncpy(env_value, (char*)(line + eq_pos + 1), sizeof(env_value));
if (strlen(env_value) > 0 &&
env_value[strlen(env_value)-1] == '\n') {
env_value[strlen(env_value)-1] = '\0';
if (strlen(env_value) > 0 &&
env_value[strlen(env_value)-1] == '\r') {
// Also remove windows line breaks (\r\n)
env_value[strlen(env_value)-1] = '\0';
}
}
// Set value:
setenv(env_name, env_value, 1);
}
}
}
fclose(env_file_fd);
} else {
LOGP("Warning: no p4a_env_vars.txt found / failed to open!");
}
LOGP("Changing directory to the one provided by ANDROID_ARGUMENT");
LOGP(env_argument);
chdir(env_argument);
#if PY_MAJOR_VERSION < 3
Py_NoSiteFlag=1;
#endif
#if PY_MAJOR_VERSION < 3
Py_SetProgramName("android_python");
#else
Py_SetProgramName(L"android_python");
#endif
#if PY_MAJOR_VERSION >= 3
/* our logging module for android
@@ -103,34 +166,55 @@ int main(int argc, char *argv[]) {
LOGP("Preparing to initialize python");
if (dir_exists("crystax_python/")) {
LOGP("crystax_python exists");
char paths[256];
snprintf(paths, 256,
"%s/crystax_python/stdlib.zip:%s/crystax_python/modules",
env_argument, env_argument);
/* snprintf(paths, 256, "%s/stdlib.zip:%s/modules", env_argument,
* env_argument); */
// Set up the python path
char paths[256];
char crystax_python_dir[256];
snprintf(crystax_python_dir, 256,
"%s/crystax_python", getenv("ANDROID_UNPACK"));
char python_bundle_dir[256];
snprintf(python_bundle_dir, 256,
"%s/_python_bundle", getenv("ANDROID_UNPACK"));
if (dir_exists(crystax_python_dir) || dir_exists(python_bundle_dir)) {
if (dir_exists(crystax_python_dir)) {
LOGP("crystax_python exists");
snprintf(paths, 256,
"%s/stdlib.zip:%s/modules",
crystax_python_dir, crystax_python_dir);
}
if (dir_exists(python_bundle_dir)) {
LOGP("_python_bundle dir exists");
snprintf(paths, 256,
"%s/stdlib.zip:%s/modules",
python_bundle_dir, python_bundle_dir);
}
LOGP("calculated paths to be...");
LOGP(paths);
#if PY_MAJOR_VERSION >= 3
wchar_t *wchar_paths = Py_DecodeLocale(paths, NULL);
Py_SetPath(wchar_paths);
#else
char *wchar_paths = paths;
LOGP("Can't Py_SetPath in python2, so crystax python2 doesn't work yet");
exit(1);
#endif
#if PY_MAJOR_VERSION >= 3
wchar_t *wchar_paths = Py_DecodeLocale(paths, NULL);
Py_SetPath(wchar_paths);
#endif
LOGP("set wchar paths...");
LOGP("set wchar paths...");
} else {
LOGP("crystax_python does not exist");
// We do not expect to see crystax_python any more, so no point
// reminding the user about it. If it does exist, we'll have
// logged it earlier.
LOGP("_python_bundle does not exist");
}
Py_Initialize();
#if PY_MAJOR_VERSION < 3
// Can't Py_SetPath in python2 but we can set PySys_SetPath, which must
// be applied after Py_Initialize rather than before like Py_SetPath
#if PY_MICRO_VERSION >= 15
// Only for python native-build
PySys_SetPath(paths);
#endif
PySys_SetArgv(argc, argv);
#endif
@@ -153,8 +237,10 @@ int main(int argc, char *argv[]) {
*/
PyRun_SimpleString("import sys, posix\n");
if (dir_exists("lib")) {
/* If we built our own python, set up the paths correctly */
LOGP("Setting up python from ANDROID_PRIVATE");
/* If we built our own python, set up the paths correctly.
* This is only the case if we are using the python2legacy recipe
*/
LOGP("Setting up python from ANDROID_APP_PATH");
PyRun_SimpleString("private = posix.environ['ANDROID_APP_PATH']\n"
"argument = posix.environ['ANDROID_ARGUMENT']\n"
"sys.path[:] = [ \n"
@@ -165,11 +251,24 @@ int main(int argc, char *argv[]) {
" argument ]\n");
}
if (dir_exists("crystax_python")) {
char add_site_packages_dir[256];
char add_site_packages_dir[256];
if (dir_exists(crystax_python_dir)) {
snprintf(add_site_packages_dir, 256,
"sys.path.append('%s/crystax_python/site-packages')",
env_argument);
"sys.path.append('%s/site-packages')",
crystax_python_dir);
PyRun_SimpleString("import sys\n"
"sys.argv = ['notaninterpreterreally']\n"
"from os.path import realpath, join, dirname");
PyRun_SimpleString(add_site_packages_dir);
/* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */
PyRun_SimpleString("sys.path = ['.'] + sys.path");
}
if (dir_exists(python_bundle_dir)) {
snprintf(add_site_packages_dir, 256,
"sys.path.append('%s/site-packages')",
python_bundle_dir);
PyRun_SimpleString("import sys\n"
"sys.argv = ['notaninterpreterreally']\n"
@@ -210,6 +309,11 @@ int main(int argc, char *argv[]) {
/* Get the entrypoint, search the .pyo then .py
*/
char *dot = strrchr(env_entrypoint, '.');
#if PY_MAJOR_VERSION > 2
char *ext = ".pyc";
#else
char *ext = ".pyo";
#endif
if (dot <= 0) {
LOGP("Invalid entrypoint, abort.");
return -1;
@@ -218,14 +322,14 @@ int main(int argc, char *argv[]) {
LOGP("Entrypoint path is too long, try increasing ENTRYPOINT_MAXLEN.");
return -1;
}
if (!strcmp(dot, ".pyo")) {
if (!strcmp(dot, ext)) {
if (!file_exists(env_entrypoint)) {
/* fallback on .py */
strcpy(entrypoint, env_entrypoint);
entrypoint[strlen(env_entrypoint) - 1] = '\0';
LOGP(entrypoint);
if (!file_exists(entrypoint)) {
LOGP("Entrypoint not found (.pyo, fallback on .py), abort");
LOGP("Entrypoint not found (.pyc/.pyo, fallback on .py), abort");
return -1;
}
} else {
@@ -235,7 +339,11 @@ int main(int argc, char *argv[]) {
/* if .py is passed, check the pyo version first */
strcpy(entrypoint, env_entrypoint);
entrypoint[strlen(env_entrypoint) + 1] = '\0';
#if PY_MAJOR_VERSION > 2
entrypoint[strlen(env_entrypoint)] = 'c';
#else
entrypoint[strlen(env_entrypoint)] = 'o';
#endif
if (!file_exists(entrypoint)) {
/* fallback on pure python version */
if (!file_exists(env_entrypoint)) {
@@ -245,7 +353,7 @@ int main(int argc, char *argv[]) {
strcpy(entrypoint, env_entrypoint);
}
} else {
LOGP("Entrypoint have an invalid extension (must be .py or .pyo), abort.");
LOGP("Entrypoint have an invalid extension (must be .py or .pyc/.pyo), abort.");
return -1;
}
// LOGP("Entrypoint is:");
@@ -260,6 +368,7 @@ int main(int argc, char *argv[]) {
/* run python !
*/
ret = PyRun_SimpleFile(fd, entrypoint);
fclose(fd);
if (PyErr_Occurred() != NULL) {
ret = 1;
@@ -270,19 +379,48 @@ int main(int argc, char *argv[]) {
PyErr_Clear();
}
/* close everything
*/
Py_Finalize();
fclose(fd);
LOGP("Python for android ended.");
/* Shut down: since regular shutdown causes issues sometimes
(seems to be an incomplete shutdown breaking next launch)
we'll use sys.exit(ret) to shutdown, since that one works.
Reference discussion:
https://github.com/kivy/kivy/pull/6107#issue-246120816
*/
char terminatecmd[256];
snprintf(
terminatecmd, sizeof(terminatecmd),
"import sys; sys.exit(%d)\n", ret
);
PyRun_SimpleString(terminatecmd);
/* This should never actually be reached, but we'll leave the clean-up
* here just to be safe.
*/
#if PY_MAJOR_VERSION < 3
Py_Finalize();
LOGP("Unexpectedly reached Py_FinalizeEx(), but was successful.");
#else
if (Py_FinalizeEx() != 0) // properly check success on Python 3
LOGP("Unexpectedly reached Py_FinalizeEx(), and got error!");
else
LOGP("Unexpectedly reached Py_FinalizeEx(), but was successful.");
#endif
return ret;
}
JNIEXPORT void JNICALL Java_org_kivy_android_PythonService_nativeStart(
JNIEnv *env, jobject thiz, jstring j_android_private,
jstring j_android_argument, jstring j_service_entrypoint,
jstring j_python_name, jstring j_python_home, jstring j_python_path,
JNIEnv *env,
jobject thiz,
jstring j_android_private,
jstring j_android_argument,
jstring j_service_entrypoint,
jstring j_python_name,
jstring j_python_home,
jstring j_python_path,
jstring j_arg) {
jboolean iscopy;
const char *android_private =
@@ -308,10 +446,7 @@ JNIEXPORT void JNICALL Java_org_kivy_android_PythonService_nativeStart(
setenv("PYTHONHOME", python_home, 1);
setenv("PYTHONPATH", python_path, 1);
setenv("PYTHON_SERVICE_ARGUMENT", arg, 1);
char ca_path[128];
snprintf(ca_path, 128, "%s/crystax_python/site-packages/certifi/cacert.pem", python_home);
setenv("SSL_CERT_FILE", ca_path, 1);
setenv("P4A_BOOTSTRAP", bootstrap_name, 1);
char *argv[] = {"."};
/* ANDROID_ARGUMENT points to service subdir,
@@ -320,4 +455,47 @@ JNIEXPORT void JNICALL Java_org_kivy_android_PythonService_nativeStart(
main(1, argv);
}
#if defined(BOOTSTRAP_NAME_WEBVIEW) || defined(BOOTSTRAP_NAME_SERVICEONLY)
// Webview and service_only uses some more functions:
void Java_org_kivy_android_PythonActivity_nativeSetenv(
JNIEnv* env, jclass cls,
jstring name, jstring value)
//JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetenv)(
// JNIEnv* env, jclass cls,
// jstring name, jstring value)
{
const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
const char *utfvalue = (*env)->GetStringUTFChars(env, value, NULL);
setenv(utfname, utfvalue, 1);
(*env)->ReleaseStringUTFChars(env, name, utfname);
(*env)->ReleaseStringUTFChars(env, value, utfvalue);
}
void Java_org_kivy_android_PythonActivity_nativeInit(JNIEnv* env, jclass cls, jobject obj)
{
/* This nativeInit follows SDL2 */
/* This interface could expand with ABI negotiation, calbacks, etc. */
/* SDL_Android_Init(env, cls); */
/* SDL_SetMainReady(); */
/* Run the application code! */
int status;
char *argv[2];
argv[0] = "Python_app";
argv[1] = NULL;
/* status = SDL_main(1, argv); */
main(1, argv);
/* Do not issue an exit or the whole application will terminate instead of just the SDL thread */
/* exit(status); */
}
#endif
#endif
@@ -0,0 +1,164 @@
package org.kivy.android;
import android.os.Build;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import android.app.Service;
import android.os.IBinder;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.util.Log;
import android.app.Notification;
import android.app.PendingIntent;
import android.os.Process;
import java.io.File;
import org.kivy.android.PythonUtil;
import org.renpy.android.Hardware;
public class PythonService extends Service implements Runnable {
// Thread for Python code
private Thread pythonThread = null;
// Python environment variables
private String androidPrivate;
private String androidArgument;
private String pythonName;
private String pythonHome;
private String pythonPath;
private String serviceEntrypoint;
// Argument to pass to Python code,
private String pythonServiceArgument;
public static PythonService mService = null;
private Intent startIntent = null;
private boolean autoRestartService = false;
public void setAutoRestartService(boolean restart) {
autoRestartService = restart;
}
public boolean canDisplayNotification() {
return true;
}
public int startType() {
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (pythonThread != null) {
Log.v("python service", "service exists, do not start again");
return START_NOT_STICKY;
}
startIntent = intent;
Bundle extras = intent.getExtras();
androidPrivate = extras.getString("androidPrivate");
androidArgument = extras.getString("androidArgument");
serviceEntrypoint = extras.getString("serviceEntrypoint");
pythonName = extras.getString("pythonName");
pythonHome = extras.getString("pythonHome");
pythonPath = extras.getString("pythonPath");
pythonServiceArgument = extras.getString("pythonServiceArgument");
pythonThread = new Thread(this);
pythonThread.start();
if (canDisplayNotification()) {
doStartForeground(extras);
}
return startType();
}
protected void doStartForeground(Bundle extras) {
String serviceTitle = extras.getString("serviceTitle");
String serviceDescription = extras.getString("serviceDescription");
Notification notification;
Context context = getApplicationContext();
Intent contextIntent = new Intent(context, PythonActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, contextIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(
context.getApplicationInfo().icon, serviceTitle, System.currentTimeMillis());
try {
// prevent using NotificationCompat, this saves 100kb on apk
Method func = notification.getClass().getMethod(
"setLatestEventInfo", Context.class, CharSequence.class,
CharSequence.class, PendingIntent.class);
func.invoke(notification, context, serviceTitle, serviceDescription, pIntent);
} catch (NoSuchMethodException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
}
} else {
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle(serviceTitle);
builder.setContentText(serviceDescription);
builder.setContentIntent(pIntent);
builder.setSmallIcon(context.getApplicationInfo().icon);
notification = builder.build();
}
startForeground(1, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
pythonThread = null;
if (autoRestartService && startIntent != null) {
Log.v("python service", "service restart requested");
startService(startIntent);
}
Process.killProcess(Process.myPid());
}
/**
* Stops the task gracefully when killed.
* Calling stopSelf() will trigger a onDestroy() call from the system.
*/
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
stopSelf();
}
@Override
public void run(){
String app_root = getFilesDir().getAbsolutePath() + "/app";
File app_root_file = new File(app_root);
PythonUtil.loadLibraries(app_root_file,
new File(getApplicationInfo().nativeLibraryDir));
this.mService = this;
nativeStart(
androidPrivate, androidArgument,
serviceEntrypoint, pythonName,
pythonHome, pythonPath,
pythonServiceArgument);
stopSelf();
}
// Native part
public static native void nativeStart(
String androidPrivate, String androidArgument,
String serviceEntrypoint, String pythonName,
String pythonHome, String pythonPath,
String pythonServiceArgument);
}
@@ -0,0 +1,77 @@
package org.kivy.android;
import java.io.File;
import android.util.Log;
import java.util.ArrayList;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
public class PythonUtil {
private static final String TAG = "pythonutil";
protected static void addLibraryIfExists(ArrayList<String> libsList, String pattern, File libsDir) {
// pattern should be the name of the lib file, without the
// preceding "lib" or suffix ".so", for instance "ssl.*" will
// match files of the form "libssl.*.so".
File [] files = libsDir.listFiles();
pattern = "lib" + pattern + "\\.so";
Pattern p = Pattern.compile(pattern);
for (int i = 0; i < files.length; ++i) {
File file = files[i];
String name = file.getName();
Log.v(TAG, "Checking pattern " + pattern + " against " + name);
if (p.matcher(name).matches()) {
Log.v(TAG, "Pattern " + pattern + " matched file " + name);
libsList.add(name.substring(3, name.length() - 3));
}
}
}
protected static ArrayList<String> getLibraries(File libsDir) {
ArrayList<String> libsList = new ArrayList<String>();
addLibraryIfExists(libsList, "crystax", libsDir);
addLibraryIfExists(libsList, "sqlite3", libsDir);
addLibraryIfExists(libsList, "ffi", libsDir);
addLibraryIfExists(libsList, "ssl.*", libsDir);
addLibraryIfExists(libsList, "crypto.*", libsDir);
libsList.add("python2.7");
libsList.add("python3.5m");
libsList.add("python3.6m");
libsList.add("python3.7m");
libsList.add("main");
return libsList;
}
public static void loadLibraries(File filesDir, File libsDir) {
String filesDirPath = filesDir.getAbsolutePath();
boolean foundPython = false;
for (String lib : getLibraries(libsDir)) {
Log.v(TAG, "Loading library: " + lib);
try {
System.loadLibrary(lib);
if (lib.startsWith("python")) {
foundPython = true;
}
} catch(UnsatisfiedLinkError e) {
// If this is the last possible libpython
// load, and it has failed, give a more
// general error
Log.v(TAG, "Library loading error: " + e.getMessage());
if (lib.startsWith("python3.7") && !foundPython) {
throw new java.lang.RuntimeException("Could not load any libpythonXXX.so");
} else if (lib.startsWith("python")) {
continue;
} else {
Log.v(TAG, "An UnsatisfiedLinkError occurred loading " + lib);
throw e;
}
}
}
Log.v(TAG, "Loaded everything!");
}
}
@@ -0,0 +1,115 @@
// This string is autogenerated by ChangeAppSettings.sh, do not change
// spaces amount
package org.renpy.android;
import java.io.*;
import android.app.Activity;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.util.zip.GZIPInputStream;
import android.content.res.AssetManager;
import org.kamranzafar.jtar.*;
public class AssetExtract {
private AssetManager mAssetManager = null;
private Activity mActivity = null;
public AssetExtract(Activity act) {
mActivity = act;
mAssetManager = act.getAssets();
}
public boolean extractTar(String asset, String target) {
byte buf[] = new byte[1024 * 1024];
InputStream assetStream = null;
TarInputStream tis = null;
try {
assetStream = mAssetManager.open(asset, AssetManager.ACCESS_STREAMING);
tis = new TarInputStream(new BufferedInputStream(new GZIPInputStream(new BufferedInputStream(assetStream, 8192)), 8192));
} catch (IOException e) {
Log.e("python", "opening up extract tar", e);
return false;
}
while (true) {
TarEntry entry = null;
try {
entry = tis.getNextEntry();
} catch ( java.io.IOException e ) {
Log.e("python", "extracting tar", e);
return false;
}
if ( entry == null ) {
break;
}
Log.v("python", "extracting " + entry.getName());
if (entry.isDirectory()) {
try {
new File(target +"/" + entry.getName()).mkdirs();
} catch ( SecurityException e ) { };
continue;
}
OutputStream out = null;
String path = target + "/" + entry.getName();
try {
out = new BufferedOutputStream(new FileOutputStream(path), 8192);
} catch ( FileNotFoundException e ) {
} catch ( SecurityException e ) { };
if ( out == null ) {
Log.e("python", "could not open " + path);
return false;
}
try {
while (true) {
int len = tis.read(buf);
if (len == -1) {
break;
}
out.write(buf, 0, len);
}
out.flush();
out.close();
} catch ( java.io.IOException e ) {
Log.e("python", "extracting zip", e);
return false;
}
}
try {
tis.close();
assetStream.close();
} catch (IOException e) {
// pass
}
return true;
}
}
@@ -0,0 +1,54 @@
/**
* This class takes care of managing resources for us. In our code, we
* can't use R, since the name of the package containing R will
* change. (This same code is used in both org.renpy.android and
* org.renpy.pygame.) So this is the next best thing.
*/
package org.renpy.android;
import android.app.Activity;
import android.content.res.Resources;
import android.view.View;
import android.util.Log;
public class ResourceManager {
private Activity act;
private Resources res;
public ResourceManager(Activity activity) {
act = activity;
res = act.getResources();
}
public int getIdentifier(String name, String kind) {
Log.v("SDL", "getting identifier");
Log.v("SDL", "kind is " + kind + " and name " + name);
Log.v("SDL", "result is " + res.getIdentifier(name, kind, act.getPackageName()));
return res.getIdentifier(name, kind, act.getPackageName());
}
public String getString(String name) {
try {
Log.v("SDL", "asked to get string " + name);
return res.getString(getIdentifier(name, "string"));
} catch (Exception e) {
Log.v("SDL", "got exception looking for string!");
return null;
}
}
public View inflateView(String name) {
int id = getIdentifier(name, "layout");
return act.getLayoutInflater().inflate(id, null);
}
public View getViewById(View v, String name) {
int id = getIdentifier(name, "id");
return v.findViewById(id);
}
}
@@ -0,0 +1,77 @@
package {{ args.package }};
import android.os.Build;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import android.content.Intent;
import android.content.Context;
import android.app.Notification;
import android.app.PendingIntent;
import android.os.Bundle;
import org.kivy.android.PythonService;
import org.kivy.android.PythonActivity;
public class Service{{ name|capitalize }} extends PythonService {
{% if sticky %}
@Override
public int startType() {
return START_STICKY;
}
{% endif %}
{% if not foreground %}
@Override
public boolean canDisplayNotification() {
return false;
}
{% endif %}
@Override
protected void doStartForeground(Bundle extras) {
Notification notification;
Context context = getApplicationContext();
Intent contextIntent = new Intent(context, PythonActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, contextIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(
context.getApplicationInfo().icon, "{{ args.name }}", System.currentTimeMillis());
try {
// prevent using NotificationCompat, this saves 100kb on apk
Method func = notification.getClass().getMethod(
"setLatestEventInfo", Context.class, CharSequence.class,
CharSequence.class, PendingIntent.class);
func.invoke(notification, context, "{{ args.name }}", "{{ name| capitalize }}", pIntent);
} catch (NoSuchMethodException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
}
} else {
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("{{ args.name }}");
builder.setContentText("{{ name| capitalize }}");
builder.setContentIntent(pIntent);
builder.setSmallIcon(context.getApplicationInfo().icon);
notification = builder.build();
}
startForeground({{ service_id }}, notification);
}
static public void start(Context ctx, String pythonServiceArgument) {
Intent intent = new Intent(ctx, Service{{ name|capitalize }}.class);
String argument = ctx.getFilesDir().getAbsolutePath() + "/app";
intent.putExtra("androidPrivate", ctx.getFilesDir().getAbsolutePath());
intent.putExtra("androidArgument", argument);
intent.putExtra("serviceEntrypoint", "{{ entrypoint }}");
intent.putExtra("pythonName", "{{ name }}");
intent.putExtra("pythonHome", argument);
intent.putExtra("pythonPath", argument + ":" + argument + "/lib");
intent.putExtra("pythonServiceArgument", pythonServiceArgument);
ctx.startService(intent);
}
static public void stop(Context ctx) {
Intent intent = new Intent(ctx, Service{{ name|capitalize }}.class);
ctx.stopService(intent);
}
}
@@ -0,0 +1,21 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked in Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.
key.store=${env.P4A_RELEASE_KEYSTORE}
key.alias=${env.P4A_RELEASE_KEYALIAS}
key.store.password=${env.P4A_RELEASE_KEYSTORE_PASSWD}
key.alias.password=${env.P4A_RELEASE_KEYALIAS_PASSWD}
@@ -0,0 +1,80 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
}
}
allprojects {
repositories {
google()
jcenter()
flatDir {
dirs 'libs'
}
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion {{ android_api }}
buildToolsVersion '{{ build_tools_version }}'
defaultConfig {
minSdkVersion {{ args.min_sdk_version }}
targetSdkVersion {{ android_api }}
versionCode {{ args.numeric_version }}
versionName '{{ args.version }}'
}
{% if args.sign -%}
signingConfigs {
release {
storeFile file(System.getenv("P4A_RELEASE_KEYSTORE"))
keyAlias System.getenv("P4A_RELEASE_KEYALIAS")
storePassword System.getenv("P4A_RELEASE_KEYSTORE_PASSWD")
keyPassword System.getenv("P4A_RELEASE_KEYALIAS_PASSWD")
}
}
{%- endif %}
buildTypes {
debug {
}
release {
{% if args.sign -%}
signingConfig signingConfigs.release
{%- endif %}
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
sourceSets {
main {
jniLibs.srcDir 'libs'
}
}
}
dependencies {
{%- for aar in aars %}
compile(name: '{{ aar }}', ext: 'aar')
{%- endfor -%}
{%- for jar in jars %}
compile files('src/main/libs/{{ jar }}')
{%- endfor -%}
{%- if args.depends -%}
{%- for depend in args.depends %}
compile '{{ depend }}'
{%- endfor %}
{%- endif %}
}
@@ -0,0 +1,95 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- This should be changed to the name of your project -->
<project name="{{ versioned_name }}" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- if sdk.dir was not set from one of the property file, then
get it from the ANDROID_HOME env var.
This must be done before we load project.properties since
the proguard config can use sdk.dir -->
<property environment="env" />
<condition property="sdk.dir" value="${env.ANDROID_HOME}">
<isset property="env.ANDROID_HOME" />
</condition>
<property file="build.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="CustomRules">
<target name="-pre-build">
<copy todir="tmp-src">
{% if args.launcher %}
<fileset dir="src/main/java" includes="**" />
{% else %}
<fileset dir="src/main/java">
<exclude name="org/kivy/android/ProjectAdapter.java" />
<exclude name="org/kivy/android/ProjectChooser.java" />
</fileset>
{% endif %}
{% for dir, includes in args.extra_source_dirs %}
<fileset dir="{{ dir }}" includes="{{ includes }}" />
{% endfor %}
</copy>
</target>
<target name="-post-build">
<delete dir="tmp-src" />
</target>
</project>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1 @@
# put files here that you need to un-blacklist
@@ -7,13 +7,13 @@ LOCAL_MODULE := main
# Add your application source files here...
LOCAL_SRC_FILES := start.c pyjniusjni.c
LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../other_builds/$(PYTHON2_NAME)/$(ARCH)/python2/python-install/include/python2.7 $(EXTRA_CFLAGS)
LOCAL_CFLAGS += -I$(PYTHON_INCLUDE_ROOT) $(EXTRA_CFLAGS)
LOCAL_SHARED_LIBRARIES := python_shared
LOCAL_LDLIBS := -llog $(EXTRA_LDLIBS)
LOCAL_LDFLAGS += -L$(LOCAL_PATH)/../../../../other_builds/$(PYTHON2_NAME)/$(ARCH)/python2/python-install/lib $(APPLICATION_ADDITIONAL_LDFLAGS)
LOCAL_LDFLAGS += -L$(PYTHON_LINK_ROOT) $(APPLICATION_ADDITIONAL_LDFLAGS)
include $(BUILD_SHARED_LIBRARY)
@@ -0,0 +1,6 @@
#define BOOTSTRAP_NAME_SERVICEONLY
#define BOOTSTRAP_USES_NO_SDL_HEADERS
const char bootstrap_name[] = "service_only";
@@ -3,6 +3,7 @@
com.gamemaker.game
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="{{ args.package }}"
android:versionCode="{{ args.numeric_version }}"
android:versionName="{{ args.version }}"
@@ -142,7 +143,7 @@
{% endif %}
<provider
android:name="android.support.v4.content.FileProvider"
android:name="io.lbry.browser.LocalFileProvider"
android:authorities="io.lbry.browser.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
@@ -1,10 +1,11 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'com.android.tools.build:gradle:3.0.0'
}
}
@@ -93,7 +94,7 @@ subprojects {
dependencies {
compile project(':react-native-exception-handler')
compile project(':react-native-fast-image')
compile project(':react-native-fetch-blob')
compile project(':rn-fetch-blob')
compile project(':react-native-video')
{%- for aar in aars %}
compile(name: '{{ aar }}', ext: 'aar')
@@ -3,7 +3,7 @@ include ':react-native-exception-handler'
project(':react-native-exception-handler').projectDir = new File(rootProject.projectDir, './react/node_modules/react-native-exception-handler/android')
include ':react-native-fast-image'
project(':react-native-fast-image').projectDir = new File(rootProject.projectDir, './react/node_modules/react-native-fast-image/android')
include ':react-native-fetch-blob'
project(':react-native-fetch-blob').projectDir = new File(rootProject.projectDir, './react/node_modules/react-native-fetch-blob/android')
include ':rn-fetch-blob'
project(':rn-fetch-blob').projectDir = new File(rootProject.projectDir, './react/node_modules/rn-fetch-blob/android')
include ':react-native-video'
project(':react-native-video').projectDir = new File(rootProject.projectDir, './react/node_modules/react-native-video/android-exoplayer')
Loaded 100 of 420 files, more files were not shown because too many files have changed in this diff. Show more