Commit 0d992784 by golton_gao

update: first commit

parents
Showing with 4357 additions and 0 deletions
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["istanbul"]
}
}
}
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
build/*.js
config/*.js
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
// 关闭全等
'eqeqeq': [0],
'no-unused-vars': [2, {
// 允许声明未使用变量
'vars': 'local',
// 参数不检查
'args': 'none'
}],
// 关闭语句强制分号结尾
'semi': [0],
// 空行最多不能超过100行
'no-multiple-empty-lines': [0, {'max': 100}],
// 关闭禁止混用tab和空格
'no-mixed-spaces-and-tabs': [0],
// 关闭检测是否是驼峰写法
'camelcase': 0,
// 关闭禁用不必要的转义
'no-useless-escape': 0,
// 关闭禁用抛出异常字面量
'no-throw-literal': 0,
// 关闭禁止重新声明变量
'no-redeclare': 0,
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
.DS_Store
node_modules/
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
plugins: {
autoprefixer: {
browsers: ["Android >= 4.0", "iOS >= 7"]
},
"postcss-pxtorem": {
rootValue: 75,
propList: ["*"]
}
}
};
{
"name": "客诉系统",
"identifier": "com.jffc.biniu.kesu",
"build": 408,
"version": "1.1.1",
"releaseNote": "域名修改"
}
{
"name": "客诉系统",
"identifier": "com.jffc.biniu.kesu",
"build": 3,
"version": "1.0.3",
"releaseNote": "域名修改"
}
{
"name": "客诉系统",
"identifier": "com.jffc.biniu.kesu",
"build": 407,
"version": "1.1.1",
"releaseNote": "域名修改"
}
# vue-cordova-demo
> A VueCordova Project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
# build for production and view the bundle
npm run jffc-build
# check for cordova requirements
npm run jffc-check
# build for ios production with cordova
npm run jffc-ios
# build for android production with cordova
npm run jffc-android
# build for web production with cordova & serve with hot reload at localhost:3040
npm run jffc-browser
# build V+ H5 production
npm run jffc-vbuild
# add cordova platforms ios
npm run jffc-add-ios
# add cordova platforms android
npm run jffc-add-android
# add cordova platforms browser
npm run jffc-add-browser
# save for cordova plugins
npm run jffc-save
# add cordova plugin camera
npm run jffc-add-camera
# add cordova plugin console
npm run jffc-add-console
# add cordova plugin device
npm run jffc-add-device
# add cordova plugin sqlite-storage
npm run jffc-add-sqlite
# add cordova plugin file
npm run jffc-add-file
# add cordova plugin dialogs
npm run jffc-add-dialogs
# add cordova plugin splashscreen
npm run jffc-add-splashscreen
# add cordova plugin statusbar
npm run jffc-add-statusbar
```
For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
require('./check-versions')()
process.env.NODE_ENV = 'production'
var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')
// 设置package.json的name与version跟随config.xml里配置 @add by evanxu 2017-06-29
// 改变package版本号
var fs = require('fs')
var xml2js = require('xml2js')
var parser = new xml2js.Parser({explicitArray: false})
var versiony = require('versiony')
var xml = fs.readFileSync(process.cwd() + '/config.xml', {encoding: 'utf-8'}).toString()
parser.parseString(xml, (err, result) => {
if (err) throw err
versiony.version(result.widget.$.version).major().to('package.json')
})
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
var spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
})
})
var chalk = require('chalk')
var semver = require('semver')
var packageConfig = require('../package.json')
var shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
var versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version),
versionRequirement: packageConfig.engines.node
},
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
var warnings = []
for (var i = 0; i < versionRequirements.length; i++) {
var mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (var i = 0; i < warnings.length; i++) {
var warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}
/* eslint-disable */
require('eventsource-polyfill')
var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true')
hotClient.subscribe(function (event) {
if (event.action === 'reload') {
window.location.reload()
}
})
require('./check-versions')()
var config = require('../config')
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = require('./webpack.dev.conf')
// default port where dev server listens for incoming traffic
var port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
var autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
var proxyTable = config.dev.proxyTable
var app = express()
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {}
})
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)
// serve pure static assets
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static'))
var uri = 'http://localhost:' + port
var _resolve
var readyPromise = new Promise(resolve => {
_resolve = resolve
})
console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
console.log('> Listening at ' + uri + '\n')
// when env is testing, don't need open it
if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
opn(uri)
}
_resolve()
})
var server = app.listen(port)
module.exports = {
ready: readyPromise,
close: () => {
server.close()
}
}
var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
exports.assetsPath = function (_path) {
var assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
var cssLoader = {
loader: 'css-loader',
options: {
minimize: process.env.NODE_ENV === 'production',
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
var loaders = [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
var output = []
var loaders = exports.cssLoaders(options)
for (var extension in loaders) {
var loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
require('./check-versions')()
process.env.NODE_ENV = 'production'
var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prov.conf')
// 设置package.json的name与version跟随config.xml里配置 @add by evanxu 2017-06-29
// 改变package版本号
var fs = require('fs')
var xml2js = require('xml2js')
var parser = new xml2js.Parser({explicitArray: false})
var versiony = require('versiony')
var xml = fs.readFileSync(process.cwd() + '/config.xml', {encoding: 'utf-8'}).toString()
parser.parseString(xml, (err, result) => {
if (err) throw err
versiony.version(result.widget.$.version).major().to('package.json')
})
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
var spinner = ora('building for V+Production...')
spinner.start()
rm(path.join(config.prov.assetsRoot, config.prov.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' V+Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' V+Build complete.\n'))
})
})
/*
* @Author: huangyh
* @Date: 2020-11-06 11:44:07
* @LastEditors: huangyh
* @LastEditTime: 2020-11-06 15:10:50
*/
var utils = require("./utils");
var config = require("../config");
var isProduction = process.env.NODE_ENV === "production";
const autoprefixer = require("autoprefixer");
const pxtorem = require("postcss-pxtorem");
const customization = require("../theme-customization");
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
}),
css: {
sourceMap: false,
loaderOptions: {
less: {
modifyVars: customization.theme
},
postcss: {
plugins: [
autoprefixer({
// 配置使用 autoprefixer
overrideBrowserslist: ["last 15 versions"],
browsers: ["Android >= 4.0", "iOS >= 7"]
}),
pxtorem({
rootValue: 75,
propList: ["*"]
// selectorBlackList: ["van"]
})
]
}
}
}
};
var path = require("path");
var utils = require("./utils");
var config = require("../config");
var vueLoaderConfig = require("./vue-loader.conf");
function resolve(dir) {
return path.join(__dirname, "..", dir);
}
module.exports = {
entry: {
app: ["babel-polyfill", "./src/main.js"]
},
output: {
path: config.build.assetsRoot,
filename: "[name].js",
publicPath:
process.env.NODE_ENV === "production"
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: [".js", ".vue", ".json"],
alias: {
vue$: "vue/dist/vue.esm.js",
"@": resolve("src"),
"@api": resolve("src/api"),
"@assets": resolve("src/assets"),
"@images": resolve("src/assets/images"),
"@views": resolve("src/view"),
"@store": resolve("src/store"),
"@router": resolve("src/router")
}
},
module: {
rules: [
// {
// test: /\.(js|vue)$/,
// loader: "eslint-loader",
// enforce: "pre",
// include: [resolve("src"), resolve("test")],
// options: {
// formatter: require("eslint-friendly-formatter")
// }
// },
{
test: /\.vue$/,
loader: "vue-loader",
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: "babel-loader",
include: [resolve("src"), resolve("test")]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: "url-loader",
options: {
limit: 10000,
name: utils.assetsPath("img/[name].[hash:7].[ext]")
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: "url-loader",
options: {
limit: 10000,
name: utils.assetsPath("fonts/[name].[hash:7].[ext]")
}
}
]
}
};
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// 设置package.json的name与version跟随config.xml里配置 @add by evanxu 2017-06-29
// 设置版本号、时间
var exdate = require('exdate')
var fs = require('fs')
var xml2js = require('xml2js')
var parser = new xml2js.Parser({explicitArray: false})
var xml = fs.readFileSync(process.cwd() + '/config.xml', {encoding: 'utf-8'}).toString()
var versions;
parser.parseString(xml, (err, result) => {
if (err) {
throw err
}
versions = result.widget.$.version
})
var ds = new Date()
var dates = exdate.format(ds, 'yyyy-MM-dd HH:mm')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
// cheap-module-eval-source-map is faster for development
devtool: '#cheap-module-eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env,
'process.vers': JSON.stringify(versions),
'process.dates': JSON.stringify(dates)
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin()
]
})
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// 设置package.json的name与version跟随config.xml里配置 @add by evanxu 2017-06-29
// 设置版本号、时间
var exdate = require('exdate')
var fs = require('fs')
var xml2js = require('xml2js')
var parser = new xml2js.Parser({explicitArray: false})
var xml = fs.readFileSync(process.cwd() + '/config.xml', {encoding: 'utf-8'}).toString()
var versions;
parser.parseString(xml, (err, result) => {
if (err) {
throw err
}
versions = result.widget.$.version
})
var ds = new Date()
var dates = exdate.format(ds, 'yyyy-MM-dd HH:mm')
var env = config.build.env
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env,
'process.vers': JSON.stringify(versions),
'process.dates': JSON.stringify(dates)
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
var CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var ZipPlugin = require('zip-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// 设置版本号、时间
var exdate = require('exdate')
var fs = require('fs')
var xml2js = require('xml2js')
var parser = new xml2js.Parser({explicitArray: false})
var xml = fs.readFileSync(process.cwd() + '/config.xml', {encoding: 'utf-8'}).toString()
var versions;
parser.parseString(xml, (err, result) => {
if (err) {
throw err
}
versions = result.widget.$.version
})
var ds = new Date()
var dates = exdate.format(ds, 'yyyy-MM-dd HH:mm')
var env = config.prov.env
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.prov.productionSourceMap,
extract: true
})
},
devtool: config.prov.productionSourceMap ? '#source-map' : false,
output: {
path: config.prov.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env,
'process.vers': JSON.stringify(versions),
'process.dates': JSON.stringify(dates)
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.prov.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.prov.assetsSubDirectory,
ignore: ['.*']
},
// 设置文件复制粘贴
{
from: path.resolve(path.join(__dirname, '../', config.prov.appConfFile)),
to: path.resolve(path.join(config.prov.assetsRoot, config.prov.appConfFile)),
toType: 'file',
force: true,
flatten: true
}
])
]
})
if (config.prov.productionGzip) {
var CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.prov.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
// 设置压缩打包
if (config.prov.packToZip) {
webpackConfig.plugins.push(
new ZipPlugin({
path: config.prov.assetsRoot,
filename: 'vpackage.zip'
})
)
}
if (config.prov.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.jffc.vcd" version="1.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>JFFC</name>
<description>
建发房产
</description>
<author email="evanxuyi@gmail.com" href="http://cordova.io">
Core Team
</author>
<content src="index.html" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
<allow-intent href="market:*" />
<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
<application android:usesCleartextTraffic="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</edit-config>
</platform>
<platform name="ios">
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
<preference name="DisallowOverscroll" value="true" />
<preference name="BackupWebStorage" value="local" />
</platform>
<preference name="EnableViewportScale" value="true" />
<preference name="StatusBarBackgroundColor" value="#2c3e50" />
<preference name="StatusBarOverlaysWebView" value="false" />
<preference name="FadeSplashScreen" value="false" />
<preference name="SplashScreenDelay" value="1000" />
<preference name="ShowSplashScreenSpinner" value="false" />
<preference name="iosPersistentFileLocation" value="Compatibility" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
<preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />
<preference name="AndroidExtraFilesystems" value="sdcard" />
<plugin name="cordova-plugin-whitelist" spec="1" />
<plugin name="cordova-sqlite-storage" spec="~3.4.1" />
<plugin name="cordova-plugin-file" spec="^6.0.2" />
<plugin name="cordova-plugin-console" spec="^1.1.0" />
<plugin name="cordova-plugin-ble-central" spec="^1.2.4">
<variable name="BLUETOOTH_USAGE_DESCRIPTION" value=" " />
</plugin>
<plugin name="cordova-plugin-device" spec="^2.0.3" />
<plugin name="cordova-plugin-camera" spec="~4.1.0">
<variable name="ANDROID_SUPPORT_V4_VERSION" value="27.+" />
</plugin>
<plugin name="cordova-plugin-dialogs" spec="^2.0.2" />
<plugin name="cordova-plugin-splashscreen" spec="^5.0.3" />
<plugin name="cordova-plugin-statusbar" spec="^2.4.3" />
</widget>
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require("path");
module.exports = {
build: {
env: require("./prod.env"),
index: path.resolve(__dirname, "../www/index.html"),
assetsRoot: path.resolve(__dirname, "../www"),
assetsSubDirectory: "static",
assetsPublicPath: "",
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ["js", "css"],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require("./dev.env"),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: "static",
assetsPublicPath: "/",
proxyTable: {
"/api": {
target: "http://csmtest.cndrealty.com/csm/api/", //开发环境
changeOrigin: true,
ws: true,
pathRewrite: {
"^/": ""
}
}
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
},
// 2017-11-21 新增集成V+ @evanxu
prov: {
env: require("./prov.env"),
index: path.resolve(__dirname, "../dist/index.html"),
assetsRoot: path.resolve(__dirname, "../dist"),
assetsSubDirectory: "static",
assetsPublicPath: "",
productionSourceMap: false,
appConfFile: "CubeModule.json",
// eslint: true,
autoRoutes: true,
autoImportStyle: true,
friendlyErrorsPlugin: false,
packToZip: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ["js", "css"],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
/* 本地调试 */
// port: 3041,
// autoOpenBrowser: true,
// assetsSubDirectory: 'static',
// assetsPublicPath: '/',
// proxyTable: {},
// cssSourceMap: false
}
};
module.exports = {
NODE_ENV: '"production"'
}
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"provt"'
})
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
# Cordova Hooks
Cordova Hooks represent special scripts which could be added by application and plugin developers or even by your own build system to customize cordova commands. See Hooks Guide for more details: http://cordova.apache.org/docs/en/edge/guide_appdev_hooks_index.md.html#Hooks%20Guide.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,width=device-width"
/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="jf" />
<meta name="apple-mobile-web-app-title" content="contact" />
<meta name="format-detection" content="telephone=no,email=no,adress=no" />
<meta name="mobile-web-app-capable" content="jf" />
<title>建发房产</title>
<!-- <script src="cordova.js"></script> -->
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected 通过集成V+埋点 cordova.js 无需再自己添加 -->
</body>
</html>
{}
\ No newline at end of file
{
"name": "cnd-plugin",
"version": "0.0.1",
"description": "Cordova C&D Plugin",
"cordova": {
"id": "cnd-plugin",
"platforms": [
"android",
"ios"
]
}
}
\ No newline at end of file
<?xml version='1.0' encoding='utf-8'?>
<plugin id="cnd-plugin" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<name>cnd-plugin</name>
<js-module name="YFPlugin" src="www/YFPlugin.js">
<clobbers target="cordova.plugins.YFPlugin" />
</js-module>
<platform name="android">
<config-file parent="/*" target="res/xml/config.xml">
<feature name="YFPlugin">
<param name="android-package" value="com.jffc.vcd.plugin.YFPlugin" />
</feature>
</config-file>
<config-file parent="/*" target="AndroidManifest.xml" />
<source-file src="src/android/YFPlugin.java" target-dir="src/com/jffc/vcd/plugin" />
</platform>
<platform name="ios">
<config-file parent="/*" target="config.xml">
<feature name="YFPlugin">
<param name="ios-package" value="YFPlugin" />
</feature>
</config-file>
<header-file src="src/ios/YFPlugin.h" />
<source-file src="src/ios/YFPlugin.m" />
</platform>
</plugin>
\ No newline at end of file
package com.jffc.vcd.plugin;
import android.util.Base64;
import android.util.Log;
import com.jffc.vcd.util.RouterHelper;
import com.jffc.vcd.util.SPHelper;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
/**
* 获取登录用户信息插件
*/
public class YFPlugin extends CordovaPlugin {
private static final String TAG = YFPlugin.class.getSimpleName();
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(TAG,"YFPlugin Plugin execute: " + action);
if (action.equals("getUserInfo")){
this.getUserInfo(callbackContext);
return true;
}else if (action.equals("getHttpHeadValue")){
this.getHttpHeadValue(callbackContext);
return true;
}else if (action.equals("logoutSuccess")){
this.logoutSuccess();
return true;
}else if (action.equals("getHttpHost")){
this.getHttpHost(callbackContext);
return true;
}else if (action.equals("needLoadAllData")){
this.needLoadAllData(callbackContext);
return true;
}
return false;
}
/**
* 获取用户信息
* @param callbackContext
*/
private void getUserInfo(CallbackContext callbackContext){
callbackContext.success(SPHelper.getUserInfo());
}
/**
* 获取头部auth
* @param callbackContext
*/
private void getHttpHeadValue(CallbackContext callbackContext){
String userId = SPHelper.getUserId();
String password = SPHelper.getUserPassword();
StringBuilder sb = new StringBuilder();
sb.append("Basic ");
sb.append(new String(Base64.encode((userId + ":" + password).getBytes(),Base64.NO_WRAP)));
Log.d(TAG,"Authorization: " + sb.toString());
callbackContext.success(sb.toString());
}
/**
* 退出成功
*/
private void logoutSuccess(){
cordova.getActivity().finish();
SPHelper.setUserId("");
RouterHelper.gotoLogin();
}
/**
* 获取host:正式或测试
* @param callbackContext
*/
private void getHttpHost(CallbackContext callbackContext){
callbackContext.success(SPHelper.getHostApi());
}
/**
* 是否需要全量下载
* @param callbackContext
*/
private void needLoadAllData(CallbackContext callbackContext){
callbackContext.success(String.valueOf(SPHelper.isNewUser()));
}
}
//
// YFPlugin.h
// roomCheck
//
// Created by DevenChen on 2017/3/31.
//
//
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
@interface YFPlugin : CDVPlugin
-(void)sayHello:(CDVInvokedUrlCommand *)command;
/**获取用户信息 */
- (void)getUserInfo:(CDVInvokedUrlCommand *)command;
/**是否需要全量下载 */
- (void)needLoadAllData:(CDVInvokedUrlCommand *)command;
/**退出成功 */
- (void)logoutSuccess:(CDVInvokedUrlCommand *)command;
/**获取host */
- (void)getHttpHost:(CDVInvokedUrlCommand *)command;
/**获取请求头 */
- (void)getHttpHeadValue:(CDVInvokedUrlCommand *)command;
@end
//
// YFPlugin.m
// roomCheck
//
// Created by DevenChen on 2017/3/31.
//
//
#import "YFPlugin.h"
#import "GVUserDefaults+YFProperty.h"
#import "AppDelegate.h"
#import "LoginVC.h"
@implementation YFPlugin
-(void)sayHello:(CDVInvokedUrlCommand *)command
{
//接收JS传过来的值
NSDictionary *options=[command argumentAtIndex:0 withDefault:nil];
//对应键名
NSString *curValue=options[@"quality"];
UIAlertView *myAlertView=[[UIAlertView alloc]initWithTitle:@"我是小实例" message:[NSString stringWithFormat:@"当前的内容从JS传过来的值为:%@",curValue] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[myAlertView show];
//数据回调
if ([curValue isEqualToString:@"200"]) {
curValue=@"201";
}
NSDictionary *userInfoDic = @{@"username":YFDefault.username,
@"userID":YFDefault.userID,
@"fid":YFDefault.fid,
@"cell":YFDefault.cell};
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfoDic];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
/**获取用户信息 */
- (void)getUserInfo:(CDVInvokedUrlCommand *)command{
//数据回调
NSDictionary *userInfoDic = @{@"username":YFDefault.username,
@"userID":YFDefault.userID,
@"fid":YFDefault.fid,
@"cell":YFDefault.cell};
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfoDic options:NSJSONWritingPrettyPrinted error:&parseError];
NSString *userInfoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:userInfoStr];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
/**是否需要下载数据 */
- (void)needLoadAllData:(CDVInvokedUrlCommand *)command{
//数据回调
BOOL needLoadData = YFDefault.needLoadData;
CDVPluginResult *pluginResult=[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:needLoadData];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
if (YFDefault.needLoadData) {
YFDefault.needLoadData = NO;
}
}
/**退出成功 */
- (void)logoutSuccess:(CDVInvokedUrlCommand *)command{
//数据回调
CDVPluginResult *pluginResult=[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:YES];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
YFDefault.fid = nil;
YFDefault.userID = nil;
YFDefault.username = nil;
YFDefault.cell = nil;
YFDefault.needLoadData = YES;
// NSArray *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies;
// for (int i = 0; i < [cookies count]; i++) {
// NSHTTPCookie *cookie = (NSHTTPCookie *)[cookies objectAtIndex:i];
// [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
// }
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
delegate.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:LoginVC.new];
}
/**获取host */
- (void)getHttpHost:(CDVInvokedUrlCommand *)command
{
//数据回调
CDVPluginResult *pluginResult=[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:YFDefault.default_host];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
/**获取请求头 */
- (void)getHttpHeadValue:(CDVInvokedUrlCommand *)command
{
//数据回调
CDVPluginResult *pluginResult=[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:YFDefault.basicAuthCode];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end
var exec = require('cordova/exec');
var YFPlugin = {
getUserInfo:function(success, error){
exec(success, error, "YFPlugin", "getUserInfo", []);
},
getHttpHeadValue:function(success, error){
exec(success, error, "YFPlugin", "getHttpHeadValue", []);
},
logoutSuccess:function(success, error){
exec(success, error, "YFPlugin", "logoutSuccess", []);
},
getHttpHost:function(success, error){
exec(success, error, "YFPlugin", "getHttpHost", []);
},
needLoadAllData:function(success, error){
exec(success, error, "YFPlugin", "needLoadAllData", []);
}
};
module.exports = YFPlugin;
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "Default-812h@3x.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "Default-812h@3x-1.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "Default-568h@2x~iphone.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "Default-568h@2x~iphone-1.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
{
"images" : [
{
"idiom" : "iphone",
"scale" : "1x"
},
{
"idiom" : "iphone",
"filename" : "Default-667h.png",
"scale" : "2x"
},
{
"idiom" : "iphone",
"filename" : "Default-667h-1.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "Default-736h.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "Default-736h-1.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
This diff could not be displayed because it is too large.
{
"name": "jffc-frame-kesu",
"version": "1.0.1",
"description": "A VueCordova Project",
"author": "Evan Xu <evanxuyi@gmail.com>",
"private": true,
"scripts": {
"dev": "node build/dev-server.js",
"start": "node build/dev-server.js",
"build": "node build/build.js",
"lint": "eslint --ext .js,.vue src",
"android": "node build/build.js && cordova run android",
"jffc-check": "cordova requirements",
"jffc-build": "node build/build.js",
"jffc-ios": "cordova build ios",
"jffc-android": "cordova build android",
"jffc-browser": "cordova prepare browser && cross-env PORT=3004 node build/dev-server.js",
"jffc-vbuild": "node build/vt-build.js",
"jffc-save": "cordova plugin save",
"jffc-add-ios": "cordova platforms add ios",
"jffc-add-android": "cordova platforms add android",
"jffc-add-browser": "cordova platforms add browser",
"jffc-add-camera": "cordova plugin add cordova-plugin-camera",
"jffc-add-console": "cordova plugin add cordova-plugin-console",
"jffc-add-device": "cordova plugin add cordova-plugin-device",
"jffc-add-sqlite": "cordova plugin add cordova-sqlite-storage",
"jffc-add-file": "cordova plugin add cordova-plugin-file",
"jffc-add-dialogs": "cordova plugin add cordova-plugin-dialogs",
"jffc-add-splashscreen": "cordova plugin add cordova-plugin-splashscreen",
"jffc-add-statusbar": "cordova plugin add cordova-plugin-statusbar"
},
"dependencies": {
"amfe-flexible": "^2.2.1",
"axios": "^0.19.0",
"babel-polyfill": "^6.26.0",
"cordova-browser": "^6.0.0",
"core-js": "^3.1.2",
"exdate": "0.0.4",
"fastclick": "^1.0.6",
"lib-flexible": "^0.3.2",
"lodash": "^4.17.20",
"nprogress": "^0.2.0",
"vant": "^2.11.1",
"vue": "^2.3.3",
"vue-mobile-calendar": "^3.3.0",
"vue-router": "^2.3.1",
"vuex": "^2.3.1"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^4.0.0",
"@vue/eslint-config-prettier": "^5.0.0",
"@vue/eslint-config-standard": "^4.0.0",
"autoprefixer": "^6.7.2",
"babel-core": "^6.22.1",
"babel-eslint": "^7.1.1",
"babel-loader": "^6.2.10",
"babel-plugin-import": "^1.7.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.22.0",
"chalk": "^1.1.3",
"connect-history-api-fallback": "^1.3.0",
"copy-webpack-plugin": "^4.0.1",
"cordova-plugin-camera": "^4.1.0",
"cordova-plugin-file": "^6.0.2",
"cordova-plugin-file-transfer": "^1.7.1",
"cross-env": "^5.0.1",
"css-loader": "^0.28.0",
"eslint": "^3.19.0",
"eslint-config-standard": "^6.2.1",
"eslint-friendly-formatter": "^2.0.7",
"eslint-loader": "^1.7.1",
"eslint-plugin-html": "^2.0.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^2.0.1",
"eventsource-polyfill": "^0.9.6",
"express": "^4.14.1",
"extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.11.1",
"friendly-errors-webpack-plugin": "^1.1.3",
"html-webpack-plugin": "^2.28.0",
"http-proxy-middleware": "^0.17.3",
"less": "^3.0.4",
"less-loader": "^5.0.0",
"opn": "^4.0.2",
"optimize-css-assets-webpack-plugin": "^1.3.0",
"ora": "^1.2.0",
"pdfjs-dist": "^2.3.200",
"postcss-import": "^11.0.0",
"postcss-px2rem-exclude": "0.0.6",
"postcss-pxtorem": "^4.0.1",
"prettier": "^1.18.2",
"rimraf": "^2.6.0",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"url-loader": "^0.5.8",
"versiony": "^2.0.1",
"vue-loader": "^12.1.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.3.3",
"webpack": "^2.6.1",
"webpack-bundle-analyzer": "^2.2.1",
"webpack-dev-middleware": "^1.10.0",
"webpack-hot-middleware": "^2.18.0",
"webpack-merge": "^4.1.0",
"xml2js": "^0.4.19",
"zip-webpack-plugin": "^1.1.0"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8",
"ios >= 8",
"android >= 4.0"
],
"cordova": {
"platforms": [
"browser"
],
"plugins": {
"cordova-plugin-camera": {
"CAMERA_USAGE_DESCRIPTION": " ",
"PHOTOLIBRARY_USAGE_DESCRIPTION": " ",
"ANDROID_SUPPORT_V4_VERSION": "27.+"
},
"cordova-plugin-file-transfer": {},
"cordova-plugin-file": {}
}
}
}
\ No newline at end of file
# appveyor file
# http://www.appveyor.com/docs/appveyor-yml
max_jobs: 1
shallow_clone: true
init:
- git config --global core.autocrlf true
image:
- Visual Studio 2017
environment:
nodejs_version: "6"
matrix:
- PLATFORM: windows-10-store
install:
- node --version
- npm install -g github:apache/cordova-paramedic
- npm install -g cordova
build: off
test_script:
- cordova-paramedic --config pr\%PLATFORM% --plugin . --justBuild
root: true
extends: semistandard
rules:
indent:
- error
- 4
camelcase: off
padded-blocks: off
operator-linebreak: off
no-throw-literal: off
\ No newline at end of file
* text eol=lf
# source code
*.php text
*.css text
*.sass text
*.scss text
*.less text
*.styl text
*.js text
*.coffee text
*.json text
*.htm text
*.html text
*.xml text
*.svg text
*.txt text
*.ini text
*.inc text
*.pl text
*.rb text
*.py text
*.scm text
*.sql text
*.sh text
*.bat text
# templates
*.ejs text
*.hbt text
*.jade text
*.haml text
*.hbs text
*.dot text
*.tmpl text
*.phtml text
# server config
.htaccess text
# git config
.gitattributes text
.gitignore text
.gitconfig text
# code analysis config
.jshintrc text
.jscsrc text
.jshintignore text
.csslintrc text
# misc config
*.yaml text
*.yml text
.editorconfig text
# build config
*.npmignore text
*.bowerrc text
# Heroku
Procfile text
.slugignore text
# Documentation
*.md text
LICENSE text
AUTHORS text
#
## These files are binary and should be left untouched
#
# (binary is a macro for -text -diff)
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.mov binary
*.mp4 binary
*.mp3 binary
*.flv binary
*.fla binary
*.swf binary
*.gz binary
*.zip binary
*.7z binary
*.ttf binary
*.eot binary
*.woff binary
*.pyc binary
*.pdf binary
<!--
Please have a look at the issue templates you get when you click "New issue" in the GitHub UI.
We very much prefer issues created by using one of these templates.
-->
### Issue Type
<!-- Please check the boxes by putting an x in the [ ] like so: [x] -->
- [ ] Bug Report
- [ ] Feature Request
- [ ] Support Question
## Description
## Information
<!-- Include all relevant information that might help understand and reproduce the problem -->
### Command or Code
<!-- What command or code is needed to reproduce the problem? -->
### Environment, Platform, Device
<!-- In what environment, on what platform or on which device are you experiencing the issue? -->
### Version information
<!--
What are relevant versions you are using?
For example:
Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Operating System, Android Studio, Xcode etc.
-->
## Checklist
<!-- Please check the boxes by putting an `x` in the `[ ]` like so: `[x]` -->
- [ ] I searched for already existing GitHub issues about this
- [ ] I updated all Cordova tooling to their most recent version
- [ ] I included all the necessary information above
---
name: 🐛 Bug Report
about: If something isn't working as expected.
---
# Bug Report
## Problem
### What is expected to happen?
### What does actually happen?
## Information
<!-- Include all relevant information that might help understand and reproduce the problem -->
### Command or Code
<!-- What command or code is needed to reproduce the problem? -->
### Environment, Platform, Device
<!-- In what environment, on what platform or on which device are you experiencing the issue? -->
### Version information
<!--
What are relevant versions you are using?
For example:
Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Operating System, Android Studio, Xcode etc.
-->
## Checklist
<!-- Please check the boxes by putting an x in the [ ] like so: [x] -->
- [ ] I searched for existing GitHub issues
- [ ] I updated all Cordova tooling to most recent version
- [ ] I included all the necessary information above
---
name: 🚀 Feature Request
about: A suggestion for a new functionality
---
# Feature Request
## Motivation Behind Feature
<!-- Why should this feature be implemented? What problem does it solve? -->
## Feature Description
<!--
Describe your feature request in detail
Please provide any code examples or screenshots of what this feature would look like
Are there any drawbacks? Will this break anything for existing users?
-->
## Alternatives or Workarounds
<!--
Describe alternatives or workarounds you are currently using
Are there ways to do this with existing functionality?
-->
---
name: 💬 Support Question
about: If you have a question, please check out our Slack or StackOverflow!
---
<!------------^ Click "Preview" for a nicer view! -->
Apache Cordova uses GitHub Issues as a feature request and bug tracker _only_.
For usage and support questions, please check out the resources below. Thanks!
---
You can get answers to your usage and support questions about **Apache Cordova** on:
* Slack Community Chat: https://cordova.slack.com (you can sign-up at http://slack.cordova.io/)
* StackOverflow: https://stackoverflow.com/questions/tagged/cordova using the tag `cordova`
---
If you are using a tool that uses Cordova internally, like e.g. Ionic, check their support channels:
* **Ionic Framework**
* [Ionic Community Forum](https://forum.ionicframework.com/)
* [Ionic Worldwide Slack](https://ionicworldwide.herokuapp.com/)
* **PhoneGap**
* [PhoneGap Developer Community](https://forums.adobe.com/community/phonegap)
<!--
Please make sure the checklist boxes are all checked before submitting the PR. The checklist is intended as a quick reference, for complete details please see our Contributor Guidelines:
http://cordova.apache.org/contribute/contribute_guidelines.html
Thanks!
-->
### Platforms affected
### Motivation and Context
<!-- Why is this change required? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here. -->
### Description
<!-- Describe your changes in detail -->
### Testing
<!-- Please describe in detail how you tested your changes. -->
### Checklist
- [ ] I've run the tests to see all new and existing tests pass
- [ ] I added automated test coverage as appropriate for this change
- [ ] Commit is prefixed with `(platform)` if this change only applies to one platform (e.g. `(android)`)
- [ ] If this Pull Request resolves an issue, I linked to the issue in the text above (and used the correct [keyword to close issues using keywords](https://help.github.com/articles/closing-issues-using-keywords/))
- [ ] I've updated the documentation if necessary
# This Travis configuration file is built after a Cordova Paramedic
# specific template with minimal modifications and adaptations:
# https://github.com/apache/cordova-paramedic/blob/master/.travis.yml
sudo: false
addons:
jwt:
# SAUCE_ACCESS_KEY
secure: QivPLlqTVvOo3TJeHxuBOfxU6lho1I0IxQ3b68yntkEQQJko6kzleXHfgjf0a8aw8m38E3+fxaBWF1bGyucGwOLDWY8Ddt2P2xg44zdXH5EXHd9oIqAgngIdzLvUtH3Db2TbQEtIGOkrnNR2STovjqB7vHGLASQrgs4oL7r32/s=
env:
global:
- SAUCE_USERNAME=snay
- TRAVIS_NODE_VERSION=8
- ANDROID_API_LEVEL=28
- ANDROID_BUILD_TOOLS_VERSION=28.0.3
language: node_js
node_js: 8
# yaml anchor/alias: https://medium.com/@tommyvn/travis-yml-dry-with-anchors-8b6a3ac1b027
_ios: &_ios
os: osx
osx_image: xcode10.2
_android: &_android
language: android
os: linux
jdk: oraclejdk8
android:
components:
- tools
- build-tools-$ANDROID_BUILD_TOOLS_VERSION
- android-$ANDROID_API_LEVEL
licenses:
- 'android-sdk-preview-license-.+'
- 'android-sdk-license-.+'
- 'google-gdk-license-.+'
matrix:
include:
# additional tests
- env: ADDITIONAL_TESTS_DIR=./tests/ios
language: objective-c
# local tests, without saucelabs
- env: PLATFORM=local/browser
<<: *_ios
- env: PLATFORM=local/ios-10.0
<<: *_ios
# many tests with saucelabs
- env: PLATFORM=browser-chrome
- env: PLATFORM=browser-firefox
- env: PLATFORM=browser-safari
- env: PLATFORM=browser-edge
- env: PLATFORM=ios-11.3
<<: *_ios
- env: PLATFORM=ios-12.0
<<: *_ios
- env: PLATFORM=ios-12.2
<<: *_ios
- env: PLATFORM=android-5.1
<<: *_android
- env: PLATFORM=android-6.0
<<: *_android
- env: PLATFORM=android-7.0
<<: *_android
- env: PLATFORM=android-7.1
<<: *_android
- env: PLATFORM=android-8.0
<<: *_android
- env: PLATFORM=android-8.1
<<: *_android
- env: PLATFORM=android-9.0
<<: *_android
before_install:
# manually install Node for `language: android`
- if [[ "$PLATFORM" =~ android ]]; then nvm install $TRAVIS_NODE_VERSION; fi
- node --version
- if [[ "$PLATFORM" =~ android ]]; then gradle --version; fi
- if [[ "$PLATFORM" =~ ios ]]; then npm install -g ios-deploy; fi
- npm install -g cordova
# install paramedic if not running on paramedic repo
- if ! [[ "$TRAVIS_REPO_SLUG" =~ cordova-paramedic ]]; then npm install -g github:apache/cordova-paramedic; fi
install:
- npm install
before_script:
- |
if [[ "$TRAVIS_REPO_SLUG" =~ cordova-paramedic ]]; then
# when used in the cordova-paramedic repo
TEST_COMMAND="npm run eslint"
PARAMEDIC_PLUGIN_TO_TEST="./spec/testable-plugin/"
PARAMEDIC_COMMAND="node main.js"
else
# when used in any other (plugin) repo
TEST_COMMAND="npm test"
PARAMEDIC_PLUGIN_TO_TEST=$(pwd)
PARAMEDIC_COMMAND="cordova-paramedic"
fi
- PARAMEDIC_BUILDNAME=travis-$TRAVIS_REPO_SLUG-$TRAVIS_JOB_NUMBER
script:
- $TEST_COMMAND
- if [[ "$ADDITIONAL_TESTS_DIR" != "" ]];
then cd $ADDITIONAL_TESTS_DIR && npm install && npm test;
else
$PARAMEDIC_COMMAND --config ./pr/$PLATFORM --plugin $PARAMEDIC_PLUGIN_TO_TEST --buildName $PARAMEDIC_BUILDNAME;
fi
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
# Contributing to Apache Cordova
Anyone can contribute to Cordova. And we need your contributions.
There are multiple ways to contribute: report bugs, improve the docs, and
contribute code.
For instructions on this, start with the
[contribution overview](http://cordova.apache.org/contribute/).
The details are explained there, but the important items are:
- Sign and submit an Apache ICLA (Contributor License Agreement).
- Have a Jira issue open that corresponds to your contribution.
- Run the tests so your patch doesn't break existing functionality.
We look forward to your contributions!
Apache Cordova
Copyright 2012 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
{
"_from": "cordova-plugin-camera@~4.1.0",
"_id": "cordova-plugin-camera@4.1.0",
"_inBundle": false,
"_integrity": "sha512-fCLhWjWYn49q3X5xaypAPgTz6MAWSKFFQvD2Gpi5SuVlrRPRphtX2jIqR2zCBuDTBR082QVnlc+yUDXt65Mjgw==",
"_location": "/cordova-plugin-camera",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "cordova-plugin-camera@~4.1.0",
"name": "cordova-plugin-camera",
"escapedName": "cordova-plugin-camera",
"rawSpec": "~4.1.0",
"saveSpec": null,
"fetchSpec": "~4.1.0"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://repo.huaweicloud.com/repository/npm/cordova-plugin-camera/-/cordova-plugin-camera-4.1.0.tgz",
"_shasum": "6474a3e080c4662aa00fd7425705d301c693ddc0",
"_spec": "cordova-plugin-camera@~4.1.0",
"_where": "/Users/hyh/Desktop/work/建发/客诉系统/code/kesu-JFFC",
"author": {
"name": "Apache Software Foundation"
},
"bugs": {
"url": "https://github.com/apache/cordova-plugin-camera/issues"
},
"bundleDependencies": false,
"cordova": {
"id": "cordova-plugin-camera",
"platforms": [
"android",
"ios",
"browser",
"windows",
"osx"
]
},
"deprecated": false,
"description": "Cordova Camera Plugin",
"devDependencies": {
"eslint": "^4.3.0",
"eslint-config-semistandard": "^11.0.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.3.0",
"eslint-plugin-node": "^5.0.0",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1"
},
"engines": {
"cordovaDependencies": {
"3.0.0": {
"cordova-android": ">=6.3.0"
},
"4.1.0": {
"cordova": ">=7.1.0",
"cordova-android": ">=6.3.0"
},
"5.0.0": {
"cordova": ">100"
}
}
},
"homepage": "https://github.com/apache/cordova-plugin-camera#readme",
"keywords": [
"cordova",
"camera",
"ecosystem:cordova",
"cordova-android",
"cordova-ios",
"cordova-browser",
"cordova-windows",
"cordova-osx"
],
"license": "Apache-2.0",
"name": "cordova-plugin-camera",
"repository": {
"type": "git",
"url": "git+https://github.com/apache/cordova-plugin-camera.git"
},
"scripts": {
"eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests",
"test": "npm run eslint"
},
"types": "./types/index.d.ts",
"version": "4.1.0"
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="cordova-plugin-camera"
version="4.1.0">
<name>Camera</name>
<description>Cordova Camera Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,camera</keywords>
<repo>https://github.com/apache/cordova-plugin-camera</repo>
<issue>https://github.com/apache/cordova-plugin-camera/issues</issue>
<engines>
<engine name="cordova" version=">=7.1.0"/>
<engine name="cordova-android" version=">=6.3.0" />
</engines>
<js-module src="www/CameraConstants.js" name="Camera">
<clobbers target="Camera" />
</js-module>
<js-module src="www/CameraPopoverOptions.js" name="CameraPopoverOptions">
<clobbers target="CameraPopoverOptions" />
</js-module>
<js-module src="www/Camera.js" name="camera">
<clobbers target="navigator.camera" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Camera">
<param name="android-package" value="org.apache.cordova.camera.CameraLauncher"/>
</feature>
</config-file>
<config-file target="AndroidManifest.xml" parent="/*">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</config-file>
<config-file target="AndroidManifest.xml" parent="application">
<provider
android:name="org.apache.cordova.camera.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/camera_provider_paths"/>
</provider>
</config-file>
<source-file src="src/android/CameraLauncher.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/CordovaUri.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/FileHelper.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/ExifHelper.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/FileProvider.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/xml/camera_provider_paths.xml" target-dir="res/xml" />
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<preference name="ANDROID_SUPPORT_V4_VERSION" default="27.+"/>
<framework src="com.android.support:support-v4:$ANDROID_SUPPORT_V4_VERSION"/>
</platform>
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="Camera">
<param name="ios-package" value="CDVCamera" />
</feature>
<preference name="CameraUsesGeolocation" value="false" />
</config-file>
<js-module src="www/ios/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<header-file src="src/ios/UIImage+CropScaleOrientation.h" />
<source-file src="src/ios/UIImage+CropScaleOrientation.m" />
<header-file src="src/ios/CDVCamera.h" />
<source-file src="src/ios/CDVCamera.m" />
<header-file src="src/ios/CDVJpegHeaderWriter.h" />
<source-file src="src/ios/CDVJpegHeaderWriter.m" />
<header-file src="src/ios/CDVExif.h" />
<framework src="ImageIO.framework" weak="true" />
<framework src="CoreLocation.framework" />
<framework src="CoreGraphics.framework" />
<framework src="AssetsLibrary.framework" />
<framework src="MobileCoreServices.framework" />
<framework src="CoreGraphics.framework" />
<framework src="AVFoundation.framework" />
</platform>
<!-- browser -->
<platform name="browser">
<config-file target="config.xml" parent="/*">
<feature name="Camera">
<param name="browser-package" value="Camera" />
</feature>
</config-file>
<js-module src="src/browser/CameraProxy.js" name="CameraProxy">
<runs />
</js-module>
</platform>
<!-- windows -->
<platform name="windows">
<config-file target="package.appxmanifest" parent="/Package/Capabilities">
<DeviceCapability Name="webcam" />
</config-file>
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<js-module src="src/windows/CameraProxy.js" name="CameraProxy">
<runs />
</js-module>
</platform>
<!-- osx -->
<platform name="osx">
<config-file target="config.xml" parent="/*">
<feature name="Camera">
<param name="osx-package" value="CDVCamera"/>
</feature>
</config-file>
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<header-file src="src/osx/CDVCamera.h" />
<source-file src="src/osx/CDVCamera.m" />
<framework src="Quartz.framework" />
<framework src="AppKit.framework" />
</platform>
</plugin>
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import java.io.File;
/*
* This class exists because Andorid FilesProvider doesn't work on Android 4.4.4 and below and throws
* weird errors. I'm not sure why writing to shared cache directories is somehow verboten, but it is
* and this error is irritating for a Compatibility library to have.
*
*/
public class CordovaUri {
private Uri androidUri;
private String fileName;
private Uri fileUri;
/*
* We always expect a FileProvider string to be passed in for the file that we create
*
*/
CordovaUri (Uri inputUri)
{
//Determine whether the file is a content or file URI
if(inputUri.getScheme().equals("content"))
{
androidUri = inputUri;
fileName = getFileNameFromUri(androidUri);
fileUri = Uri.parse("file://" + fileName);
}
else
{
fileUri = inputUri;
fileName = FileHelper.stripFileProtocol(inputUri.toString());
}
}
public Uri getFileUri()
{
return fileUri;
}
public String getFilePath()
{
return fileName;
}
/*
* This only gets called by takePicture
*/
public Uri getCorrectUri()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
return androidUri;
else
return fileUri;
}
/*
* This is dirty, but it does the job.
*
* Since the FilesProvider doesn't really provide you a way of getting a URL from the file,
* and since we actually need the Camera to create the file for us most of the time, we don't
* actually write the file, just generate the location based on a timestamp, we need to get it
* back from the Intent.
*
* However, the FilesProvider preserves the path, so we can at least write to it from here, since
* we own the context in this case.
*/
private String getFileNameFromUri(Uri uri) {
String fullUri = uri.toString();
String partial_path = fullUri.split("external_files")[1];
File external_storage = Environment.getExternalStorageDirectory();
String path = external_storage.getAbsolutePath() + partial_path;
return path;
}
}
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.camera;
import java.io.IOException;
import android.media.ExifInterface;
public class ExifHelper {
private String aperture = null;
private String datetime = null;
private String exposureTime = null;
private String flash = null;
private String focalLength = null;
private String gpsAltitude = null;
private String gpsAltitudeRef = null;
private String gpsDateStamp = null;
private String gpsLatitude = null;
private String gpsLatitudeRef = null;
private String gpsLongitude = null;
private String gpsLongitudeRef = null;
private String gpsProcessingMethod = null;
private String gpsTimestamp = null;
private String iso = null;
private String make = null;
private String model = null;
private String orientation = null;
private String whiteBalance = null;
private ExifInterface inFile = null;
private ExifInterface outFile = null;
/**
* The file before it is compressed
*
* @param filePath
* @throws IOException
*/
public void createInFile(String filePath) throws IOException {
this.inFile = new ExifInterface(filePath);
}
/**
* The file after it has been compressed
*
* @param filePath
* @throws IOException
*/
public void createOutFile(String filePath) throws IOException {
this.outFile = new ExifInterface(filePath);
}
/**
* Reads all the EXIF data from the input file.
*/
public void readExifData() {
this.aperture = inFile.getAttribute(ExifInterface.TAG_APERTURE);
this.datetime = inFile.getAttribute(ExifInterface.TAG_DATETIME);
this.exposureTime = inFile.getAttribute(ExifInterface.TAG_EXPOSURE_TIME);
this.flash = inFile.getAttribute(ExifInterface.TAG_FLASH);
this.focalLength = inFile.getAttribute(ExifInterface.TAG_FOCAL_LENGTH);
this.gpsAltitude = inFile.getAttribute(ExifInterface.TAG_GPS_ALTITUDE);
this.gpsAltitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF);
this.gpsDateStamp = inFile.getAttribute(ExifInterface.TAG_GPS_DATESTAMP);
this.gpsLatitude = inFile.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
this.gpsLatitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
this.gpsLongitude = inFile.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
this.gpsLongitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
this.gpsProcessingMethod = inFile.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD);
this.gpsTimestamp = inFile.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP);
this.iso = inFile.getAttribute(ExifInterface.TAG_ISO);
this.make = inFile.getAttribute(ExifInterface.TAG_MAKE);
this.model = inFile.getAttribute(ExifInterface.TAG_MODEL);
this.orientation = inFile.getAttribute(ExifInterface.TAG_ORIENTATION);
this.whiteBalance = inFile.getAttribute(ExifInterface.TAG_WHITE_BALANCE);
}
/**
* Writes the previously stored EXIF data to the output file.
*
* @throws IOException
*/
public void writeExifData() throws IOException {
// Don't try to write to a null file
if (this.outFile == null) {
return;
}
if (this.aperture != null) {
this.outFile.setAttribute(ExifInterface.TAG_APERTURE, this.aperture);
}
if (this.datetime != null) {
this.outFile.setAttribute(ExifInterface.TAG_DATETIME, this.datetime);
}
if (this.exposureTime != null) {
this.outFile.setAttribute(ExifInterface.TAG_EXPOSURE_TIME, this.exposureTime);
}
if (this.flash != null) {
this.outFile.setAttribute(ExifInterface.TAG_FLASH, this.flash);
}
if (this.focalLength != null) {
this.outFile.setAttribute(ExifInterface.TAG_FOCAL_LENGTH, this.focalLength);
}
if (this.gpsAltitude != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_ALTITUDE, this.gpsAltitude);
}
if (this.gpsAltitudeRef != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF, this.gpsAltitudeRef);
}
if (this.gpsDateStamp != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, this.gpsDateStamp);
}
if (this.gpsLatitude != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE, this.gpsLatitude);
}
if (this.gpsLatitudeRef != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, this.gpsLatitudeRef);
}
if (this.gpsLongitude != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, this.gpsLongitude);
}
if (this.gpsLongitudeRef != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, this.gpsLongitudeRef);
}
if (this.gpsProcessingMethod != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, this.gpsProcessingMethod);
}
if (this.gpsTimestamp != null) {
this.outFile.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, this.gpsTimestamp);
}
if (this.iso != null) {
this.outFile.setAttribute(ExifInterface.TAG_ISO, this.iso);
}
if (this.make != null) {
this.outFile.setAttribute(ExifInterface.TAG_MAKE, this.make);
}
if (this.model != null) {
this.outFile.setAttribute(ExifInterface.TAG_MODEL, this.model);
}
if (this.orientation != null) {
this.outFile.setAttribute(ExifInterface.TAG_ORIENTATION, this.orientation);
}
if (this.whiteBalance != null) {
this.outFile.setAttribute(ExifInterface.TAG_WHITE_BALANCE, this.whiteBalance);
}
this.outFile.saveAttributes();
}
public int getOrientation() {
int o = Integer.parseInt(this.orientation);
if (o == ExifInterface.ORIENTATION_NORMAL) {
return 0;
} else if (o == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (o == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (o == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
} else {
return 0;
}
}
public void resetOrientation() {
this.orientation = "" + ExifInterface.ORIENTATION_NORMAL;
}
}
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.camera;
public class FileProvider extends android.support.v4.content.FileProvider {}
<?xml version="1.0" encoding="utf-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
\ No newline at end of file
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
function takePicture (success, error, opts) {
if (opts && opts[2] === 1) {
capture(success, error, opts);
} else {
var input = document.createElement('input');
input.style.position = 'relative';
input.style.zIndex = HIGHEST_POSSIBLE_Z_INDEX;
input.className = 'cordova-camera-select';
input.type = 'file';
input.name = 'files[]';
input.onchange = function (inputEvent) {
var reader = new FileReader(); /* eslint no-undef : 0 */
reader.onload = function (readerEvent) {
input.parentNode.removeChild(input);
var imageData = readerEvent.target.result;
return success(imageData.substr(imageData.indexOf(',') + 1));
};
reader.readAsDataURL(inputEvent.target.files[0]);
};
document.body.appendChild(input);
}
}
function capture (success, errorCallback, opts) {
var localMediaStream;
var targetWidth = opts[3];
var targetHeight = opts[4];
targetWidth = targetWidth === -1 ? 320 : targetWidth;
targetHeight = targetHeight === -1 ? 240 : targetHeight;
var video = document.createElement('video');
var button = document.createElement('button');
var parent = document.createElement('div');
parent.style.position = 'relative';
parent.style.zIndex = HIGHEST_POSSIBLE_Z_INDEX;
parent.className = 'cordova-camera-capture';
parent.appendChild(video);
parent.appendChild(button);
video.width = targetWidth;
video.height = targetHeight;
button.innerHTML = 'Capture!';
button.onclick = function () {
// create a canvas and capture a frame from video stream
var canvas = document.createElement('canvas');
canvas.width = targetWidth;
canvas.height = targetHeight;
canvas.getContext('2d').drawImage(video, 0, 0, targetWidth, targetHeight);
// convert image stored in canvas to base64 encoded image
var imageData = canvas.toDataURL('image/png');
imageData = imageData.replace('data:image/png;base64,', '');
// stop video stream, remove video and button.
// Note that MediaStream.stop() is deprecated as of Chrome 47.
if (localMediaStream.stop) {
localMediaStream.stop();
} else {
localMediaStream.getTracks().forEach(function (track) {
track.stop();
});
}
parent.parentNode.removeChild(parent);
return success(imageData);
};
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var successCallback = function (stream) {
localMediaStream = stream;
if ('srcObject' in video) {
video.srcObject = localMediaStream;
} else {
video.src = window.URL.createObjectURL(localMediaStream);
}
video.play();
document.body.appendChild(parent);
};
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true, audio: false}, successCallback, errorCallback);
} else {
alert('Browser does not support camera :(');
}
}
module.exports = {
takePicture: takePicture,
cleanup: function () {}
};
require('cordova/exec/proxy').add('Camera', module.exports);
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManager.h>
#import <Cordova/CDVPlugin.h>
enum CDVDestinationType {
DestinationTypeDataUrl = 0,
DestinationTypeFileUri,
DestinationTypeNativeUri
};
typedef NSUInteger CDVDestinationType;
enum CDVEncodingType {
EncodingTypeJPEG = 0,
EncodingTypePNG
};
typedef NSUInteger CDVEncodingType;
enum CDVMediaType {
MediaTypePicture = 0,
MediaTypeVideo,
MediaTypeAll
};
typedef NSUInteger CDVMediaType;
@interface CDVPictureOptions : NSObject
@property (strong) NSNumber* quality;
@property (assign) CDVDestinationType destinationType;
@property (assign) UIImagePickerControllerSourceType sourceType;
@property (assign) CGSize targetSize;
@property (assign) CDVEncodingType encodingType;
@property (assign) CDVMediaType mediaType;
@property (assign) BOOL allowsEditing;
@property (assign) BOOL correctOrientation;
@property (assign) BOOL saveToPhotoAlbum;
@property (strong) NSDictionary* popoverOptions;
@property (assign) UIImagePickerControllerCameraDevice cameraDirection;
@property (assign) BOOL popoverSupported;
@property (assign) BOOL usesGeolocation;
@property (assign) BOOL cropToSize;
+ (instancetype) createFromTakePictureArguments:(CDVInvokedUrlCommand*)command;
@end
@interface CDVCameraPicker : UIImagePickerController
@property (strong) CDVPictureOptions* pictureOptions;
@property (copy) NSString* callbackId;
@property (copy) NSString* postUrl;
@property (strong) UIPopoverController* pickerPopoverController;
@property (assign) BOOL cropToSize;
@property (strong) UIView* webView;
+ (instancetype) createFromPictureOptions:(CDVPictureOptions*)options;
@end
// ======================================================================= //
@interface CDVCamera : CDVPlugin <UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIPopoverControllerDelegate,
CLLocationManagerDelegate>
{}
@property (strong) CDVCameraPicker* pickerController;
@property (strong) NSMutableDictionary *metadata;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong) NSData* data;
/*
* getPicture
*
* arguments:
* 1: this is the javascript function that will be called with the results, the first parameter passed to the
* javascript function is the picture as a Base64 encoded string
* 2: this is the javascript function to be called if there was an error
* options:
* quality: integer between 1 and 100
*/
- (void)takePicture:(CDVInvokedUrlCommand*)command;
- (void)cleanup:(CDVInvokedUrlCommand*)command;
- (void)repositionPopover:(CDVInvokedUrlCommand*)command;
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info;
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary*)editingInfo;
- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker;
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
@end
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#ifndef CordovaLib_ExifData_h
#define CordovaLib_ExifData_h
// exif data types
typedef enum exifDataTypes {
EDT_UBYTE = 1, // 8 bit unsigned integer
EDT_ASCII_STRING, // 8 bits containing 7 bit ASCII code, null terminated
EDT_USHORT, // 16 bit unsigned integer
EDT_ULONG, // 32 bit unsigned integer
EDT_URATIONAL, // 2 longs, first is numerator and second is denominator
EDT_SBYTE,
EDT_UNDEFINED, // 8 bits
EDT_SSHORT,
EDT_SLONG, // 32bit signed integer (2's complement)
EDT_SRATIONAL, // 2 SLONGS, first long is numerator, second is denominator
EDT_SINGLEFLOAT,
EDT_DOUBLEFLOAT
} ExifDataTypes;
// maps integer code for exif data types to width in bytes
static const int DataTypeToWidth[] = {1,1,2,4,8,1,1,2,4,8,4,8};
static const int RECURSE_HORIZON = 8;
#endif
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <Foundation/Foundation.h>
@interface CDVJpegHeaderWriter : NSObject {
NSDictionary * SubIFDTagFormatDict;
NSDictionary * IFD0TagFormatDict;
}
- (NSData*) spliceExifBlockIntoJpeg: (NSData*) jpegdata
withExifBlock: (NSString*) exifstr;
- (NSString*) createExifAPP1 : (NSDictionary*) datadict;
- (NSString*) formattedHexStringFromDecimalNumber: (NSNumber*) numb
withPlaces: (NSNumber*) width;
- (NSString*) formatNumberWithLeadingZeroes: (NSNumber*) numb
withPlaces: (NSNumber*) places;
- (NSString*) decimalToUnsignedRational: (NSNumber*) numb
withResultNumerator: (NSNumber**) numerator
withResultDenominator: (NSNumber**) denominator;
- (void) continuedFraction: (double) val
withFractionList: (NSMutableArray*) fractionlist
withHorizon: (int) horizon;
//- (void) expandContinuedFraction: (NSArray*) fractionlist;
- (void) splitDouble: (double) val
withIntComponent: (int*) rightside
withFloatRemainder: (double*) leftside;
- (NSString*) formatRationalWithNumerator: (NSNumber*) numerator
withDenominator: (NSNumber*) denominator
asSigned: (Boolean) signedFlag;
- (NSString*) hexStringFromData : (NSData*) data;
- (NSNumber*) numericFromHexString : (NSString *) hexstring;
/*
- (void) readExifMetaData : (NSData*) imgdata;
- (void) spliceImageData : (NSData*) imgdata withExifData: (NSDictionary*) exifdata;
- (void) locateExifMetaData : (NSData*) imgdata;
- (NSString*) createExifAPP1 : (NSDictionary*) datadict;
- (void) createExifDataString : (NSDictionary*) datadict;
- (NSString*) createDataElement : (NSString*) element
withElementData: (NSString*) data
withExternalDataBlock: (NSDictionary*) memblock;
- (NSString*) hexStringFromData : (NSData*) data;
- (NSNumber*) numericFromHexString : (NSString *) hexstring;
*/
@end
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <UIKit/UIKit.h>
@interface UIImage (CropScaleOrientation)
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize;
- (UIImage*)imageCorrectedForCaptureOrientation;
- (UIImage*)imageCorrectedForCaptureOrientation:(UIImageOrientation)imageOrientation;
- (UIImage*)imageByScalingNotCroppingForSize:(CGSize)targetSize;
@end
\ No newline at end of file
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import "UIImage+CropScaleOrientation.h"
@implementation UIImage (CropScaleOrientation)
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
UIImage* sourceImage = self;
UIImage* newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor > heightFactor) {
scaleFactor = widthFactor; // scale to fit height
} else {
scaleFactor = heightFactor; // scale to fit width
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor < heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
UIGraphicsBeginImageContext(targetSize); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if (newImage == nil) {
NSLog(@"could not scale image");
}
// pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
- (UIImage*)imageCorrectedForCaptureOrientation:(UIImageOrientation)imageOrientation
{
float rotation_radians = 0;
bool perpendicular = false;
switch (imageOrientation) {
case UIImageOrientationUp :
rotation_radians = 0.0;
break;
case UIImageOrientationDown:
rotation_radians = M_PI; // don't be scared of radians, if you're reading this, you're good at math
break;
case UIImageOrientationRight:
rotation_radians = M_PI_2;
perpendicular = true;
break;
case UIImageOrientationLeft:
rotation_radians = -M_PI_2;
perpendicular = true;
break;
default:
break;
}
UIGraphicsBeginImageContext(CGSizeMake(self.size.width, self.size.height));
CGContextRef context = UIGraphicsGetCurrentContext();
// Rotate around the center point
CGContextTranslateCTM(context, self.size.width / 2, self.size.height / 2);
CGContextRotateCTM(context, rotation_radians);
CGContextScaleCTM(context, 1.0, -1.0);
float width = perpendicular ? self.size.height : self.size.width;
float height = perpendicular ? self.size.width : self.size.height;
CGContextDrawImage(context, CGRectMake(-width / 2, -height / 2, width, height), [self CGImage]);
// Move the origin back since the rotation might've change it (if its 90 degrees)
if (perpendicular) {
CGContextTranslateCTM(context, -self.size.height / 2, -self.size.width / 2);
}
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (UIImage*)imageCorrectedForCaptureOrientation
{
return [self imageCorrectedForCaptureOrientation:[self imageOrientation]];
}
- (UIImage*)imageByScalingNotCroppingForSize:(CGSize)targetSize
{
UIImage* sourceImage = self;
UIImage* newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGSize scaledSize = targetSize;
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
// opposite comparison to imageByScalingAndCroppingForSize in order to contain the image within the given bounds
if (widthFactor > heightFactor) {
scaleFactor = heightFactor; // scale to fit height
} else {
scaleFactor = widthFactor; // scale to fit width
}
scaledSize = CGSizeMake(MIN(width * scaleFactor, targetWidth), MIN(height * scaleFactor, targetHeight));
}
// If the pixels are floats, it causes a white line in iOS8 and probably other versions too
scaledSize.width = (int)scaledSize.width;
scaledSize.height = (int)scaledSize.height;
UIGraphicsBeginImageContext(scaledSize); // this will resize
[sourceImage drawInRect:CGRectMake(0, 0, scaledSize.width, scaledSize.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if (newImage == nil) {
NSLog(@"could not scale image");
}
// pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
@end
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <Quartz/Quartz.h>
#import <AppKit/AppKit.h>
#import <Cordova/CDVPlugin.h>
enum CDVDestinationType {
DestinationTypeDataUrl = 0,
DestinationTypeFileUri,
DestinationTypeNativeUri
};
typedef NSUInteger CDVDestinationType;
enum CDVSourceType {
SourceTypePhotoLibrary = 0,
SourceTypeCamera,
SourceTypePhotoAlbum
};
typedef NSUInteger CDVSourceType;
enum CDVEncodingType {
EncodingTypeJPEG = 0,
EncodingTypePNG
};
typedef NSUInteger CDVEncodingType;
enum CDVMediaType {
MediaTypePicture = 0,
MediaTypeVideo,
MediaTypeAll
};
typedef NSUInteger CDVMediaType;
// ======================================================================= //
@interface CDVPictureOptions : NSObject
@property (strong) NSNumber *quality;
@property (assign) CDVDestinationType destinationType;
@property (assign) CDVSourceType sourceType;
@property (assign) CGSize targetSize;
@property (assign) CDVEncodingType encodingType;
@property (assign) CDVMediaType mediaType;
@property (assign) BOOL allowsEditing;
@property (assign) BOOL correctOrientation;
@property (assign) BOOL saveToPhotoAlbum;
+ (instancetype) createFromTakePictureArguments:(CDVInvokedUrlCommand *)command;
@end
// ======================================================================= //
@interface CDVCamera : CDVPlugin
- (void)takePicture:(CDVInvokedUrlCommand *)command;
- (void)cleanup:(CDVInvokedUrlCommand *)command;
@end
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "container:CDVCameraTest/CDVCameraTest.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDESourceControlProjectFavoriteDictionaryKey</key>
<false/>
<key>IDESourceControlProjectIdentifier</key>
<string>6BE9AD73-1B9F-4362-98D7-DC631BEC6185</string>
<key>IDESourceControlProjectName</key>
<string>CDVCameraTest</string>
<key>IDESourceControlProjectOriginsDictionary</key>
<dict>
<key>729B5706E7BAF4E9EE7AEE3C003A08107411AB7C</key>
<string>github.com:shazron/cordova-plugin-camera.git</string>
</dict>
<key>IDESourceControlProjectPath</key>
<string>tests/ios/CDVCameraTest.xcworkspace</string>
<key>IDESourceControlProjectRelativeInstallPathDictionary</key>
<dict>
<key>729B5706E7BAF4E9EE7AEE3C003A08107411AB7C</key>
<string>../../..</string>
</dict>
<key>IDESourceControlProjectURL</key>
<string>github.com:shazron/cordova-plugin-camera.git</string>
<key>IDESourceControlProjectVersion</key>
<integer>111</integer>
<key>IDESourceControlProjectWCCIdentifier</key>
<string>729B5706E7BAF4E9EE7AEE3C003A08107411AB7C</string>
<key>IDESourceControlProjectWCConfigurations</key>
<array>
<dict>
<key>IDESourceControlRepositoryExtensionIdentifierKey</key>
<string>public.vcs.git</string>
<key>IDESourceControlWCCIdentifierKey</key>
<string>729B5706E7BAF4E9EE7AEE3C003A08107411AB7C</string>
<key>IDESourceControlWCCName</key>
<string>cordova-plugin-camera</string>
</dict>
</array>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0610"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D2AAC07D0554694100DB518D"
BuildableName = "libCordova.a"
BlueprintName = "CordovaLib"
ReferencedContainer = "container:node_modules/cordova-ios/CordovaLib/CordovaLib.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D2AAC07D0554694100DB518D"
BuildableName = "libCordova.a"
BlueprintName = "CordovaLib"
ReferencedContainer = "container:node_modules/cordova-ios/CordovaLib/CordovaLib.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D2AAC07D0554694100DB518D"
BuildableName = "libCordova.a"
BlueprintName = "CordovaLib"
ReferencedContainer = "container:node_modules/cordova-ios/CordovaLib/CordovaLib.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>org.apache.cordova.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:CDVCameraTest.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDESourceControlProjectFavoriteDictionaryKey</key>
<false/>
<key>IDESourceControlProjectIdentifier</key>
<string>6BE9AD73-1B9F-4362-98D7-DC631BEC6185</string>
<key>IDESourceControlProjectName</key>
<string>CDVCameraTest</string>
<key>IDESourceControlProjectOriginsDictionary</key>
<dict>
<key>BEF5A5D0FF64801E558286389440357A9233D7DB</key>
<string>https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git</string>
</dict>
<key>IDESourceControlProjectPath</key>
<string>tests/ios/CDVCameraTest/CDVCameraTest.xcodeproj</string>
<key>IDESourceControlProjectRelativeInstallPathDictionary</key>
<dict>
<key>BEF5A5D0FF64801E558286389440357A9233D7DB</key>
<string>../../../../..</string>
</dict>
<key>IDESourceControlProjectURL</key>
<string>https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git</string>
<key>IDESourceControlProjectVersion</key>
<integer>111</integer>
<key>IDESourceControlProjectWCCIdentifier</key>
<string>BEF5A5D0FF64801E558286389440357A9233D7DB</string>
<key>IDESourceControlProjectWCConfigurations</key>
<array>
<dict>
<key>IDESourceControlRepositoryExtensionIdentifierKey</key>
<string>public.vcs.git</string>
<key>IDESourceControlWCCIdentifierKey</key>
<string>BEF5A5D0FF64801E558286389440357A9233D7DB</string>
<key>IDESourceControlWCCName</key>
<string>cordova-plugin-camera</string>
</dict>
</array>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0610"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7E9F519419DA102000DA31AC"
BuildableName = "libCDVCameraLib.a"
BlueprintName = "CDVCameraLib"
ReferencedContainer = "container:CDVCameraTest.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7E9F519419DA102000DA31AC"
BuildableName = "libCDVCameraLib.a"
BlueprintName = "CDVCameraLib"
ReferencedContainer = "container:CDVCameraTest.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7E9F519419DA102000DA31AC"
BuildableName = "libCDVCameraLib.a"
BlueprintName = "CDVCameraLib"
ReferencedContainer = "container:CDVCameraTest.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0610"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7E9F519E19DA102000DA31AC"
BuildableName = "CDVCameraLibTests.xctest"
BlueprintName = "CDVCameraLibTests"
ReferencedContainer = "container:CDVCameraTest.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7E9F519E19DA102000DA31AC"
BuildableName = "CDVCameraLibTests.xctest"
BlueprintName = "CDVCameraLibTests"
ReferencedContainer = "container:CDVCameraTest.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7E9F519E19DA102000DA31AC"
BuildableName = "CDVCameraLibTests.xctest"
BlueprintName = "CDVCameraLibTests"
ReferencedContainer = "container:CDVCameraTest.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7E9F519E19DA102000DA31AC"
BuildableName = "CDVCameraLibTests.xctest"
BlueprintName = "CDVCameraLibTests"
ReferencedContainer = "container:CDVCameraTest.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7E9F519E19DA102000DA31AC"
BuildableName = "CDVCameraLibTests.xctest"
BlueprintName = "CDVCameraLibTests"
ReferencedContainer = "container:CDVCameraTest.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# iOS Tests for CDVCamera
You need to install `node.js` to pull in `cordova-ios`.
First install cordova-ios:
npm install
... in the current folder.
# Testing from Xcode
1. Launch the `CDVCameraTest.xcworkspace` file.
2. Choose "CDVCameraLibTests" from the scheme drop-down menu
3. Click and hold on the `Play` button, and choose the `Wrench` icon to run the tests
# Testing from the command line
npm test
{
"name": "cordova-plugin-camera-test-ios",
"version": "1.0.0",
"description": "iOS Unit Tests for Camera Plugin",
"author": "Apache Software Foundation",
"license": "Apache Version 2.0",
"dependencies": {
"cordova-ios": "*"
},
"scripts": {
"test": "xcodebuild -scheme CordovaLib && xcodebuild test -scheme CDVCameraLibTests -destination 'platform=iOS Simulator,name=iPhone 5s'"
}
}
{
"name": "cordova-plugin-camera-tests",
"version": "4.1.0",
"description": "",
"cordova": {
"id": "cordova-plugin-camera-tests",
"platforms": []
},
"keywords": [
"ecosystem:cordova"
],
"author": "",
"license": "Apache-2.0"
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:rim="http://www.blackberry.com/ns/widgets"
id="cordova-plugin-camera-tests"
version="4.1.0">
<name>Cordova Camera Plugin Tests</name>
<license>Apache 2.0</license>
<dependency id="cordova-plugin-file-transfer" />
<js-module src="tests.js" name="tests">
</js-module>
</plugin>
// Type definitions for Apache Cordova Camera plugin
// Project: https://github.com/apache/cordova-plugin-camera
// Definitions by: Microsoft Open Technologies Inc <http://msopentech.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//
// Copyright (c) Microsoft Open Technologies Inc
// Licensed under the MIT license.
interface Navigator {
/**
* This plugin provides an API for taking pictures and for choosing images from the system's image library.
*/
camera: Camera;
}
/**
* This plugin provides an API for taking pictures and for choosing images from the system's image library.
*/
interface Camera {
/**
* Removes intermediate photos taken by the camera from temporary storage.
* @param onSuccess Success callback, that called when cleanup succeeds.
* @param onError Error callback, that get an error message.
*/
cleanup(
onSuccess: () => void,
onError: (message: string) => void): void;
/**
* Takes a photo using the camera, or retrieves a photo from the device's image gallery.
* @param cameraSuccess Success callback, that get the image
* as a base64-encoded String, or as the URI for the image file.
* @param cameraError Error callback, that get an error message.
* @param cameraOptions Optional parameters to customize the camera settings.
*/
getPicture(
cameraSuccess: (data: string) => void,
cameraError: (message: string) => void,
cameraOptions?: CameraOptions): void;
// Next will work only on iOS
//getPicture(
// cameraSuccess: (data: string) => void,
// cameraError: (message: string) => void,
// cameraOptions?: CameraOptions): CameraPopoverHandle;
}
interface CameraOptions {
/** Picture quality in range 0-100. Default is 50 */
quality?: number;
/**
* Choose the format of the return value.
* Defined in navigator.camera.DestinationType. Default is FILE_URI.
* DATA_URL : 0, Return image as base64-encoded string
* FILE_URI : 1, Return image file URI
* NATIVE_URI : 2 Return image native URI
* (e.g., assets-library:// on iOS or content:// on Android)
*/
destinationType?: number;
/**
* Set the source of the picture.
* Defined in navigator.camera.PictureSourceType. Default is CAMERA.
* PHOTOLIBRARY : 0,
* CAMERA : 1,
* SAVEDPHOTOALBUM : 2
*/
sourceType?: number;
/** Allow simple editing of image before selection. */
allowEdit?: boolean;
/**
* Choose the returned image file's encoding.
* Defined in navigator.camera.EncodingType. Default is JPEG
* JPEG : 0 Return JPEG encoded image
* PNG : 1 Return PNG encoded image
*/
encodingType?: number;
/**
* Width in pixels to scale image. Must be used with targetHeight.
* Aspect ratio remains constant.
*/
targetWidth?: number;
/**
* Height in pixels to scale image. Must be used with targetWidth.
* Aspect ratio remains constant.
*/
targetHeight?: number;
/**
* Set the type of media to select from. Only works when PictureSourceType
* is PHOTOLIBRARY or SAVEDPHOTOALBUM. Defined in nagivator.camera.MediaType
* PICTURE: 0 allow selection of still pictures only. DEFAULT.
* Will return format specified via DestinationType
* VIDEO: 1 allow selection of video only, WILL ALWAYS RETURN FILE_URI
* ALLMEDIA : 2 allow selection from all media types
*/
mediaType?: number;
/** Rotate the image to correct for the orientation of the device during capture. */
correctOrientation?: boolean;
/** Save the image to the photo album on the device after capture. */
saveToPhotoAlbum?: boolean;
/**
* Choose the camera to use (front- or back-facing).
* Defined in navigator.camera.Direction. Default is BACK.
* FRONT: 0
* BACK: 1
*/
cameraDirection?: number;
/** iOS-only options that specify popover location in iPad. Defined in CameraPopoverOptions. */
popoverOptions?: CameraPopoverOptions;
}
/**
* A handle to the popover dialog created by navigator.camera.getPicture. Used on iOS only.
*/
interface CameraPopoverHandle {
/**
* Set the position of the popover.
* @param popoverOptions the CameraPopoverOptions that specify the new position.
*/
setPosition(popoverOptions: CameraPopoverOptions): void;
}
/**
* iOS-only parameters that specify the anchor element location and arrow direction
* of the popover when selecting images from an iPad's library or album.
*/
interface CameraPopoverOptions {
x: number;
y: number;
width: number;
height: number;
/**
* Direction the arrow on the popover should point. Defined in Camera.PopoverArrowDirection
* Matches iOS UIPopoverArrowDirection constants.
* ARROW_UP : 1,
* ARROW_DOWN : 2,
* ARROW_LEFT : 4,
* ARROW_RIGHT : 8,
* ARROW_ANY : 15
*/
arrowDir : number;
popoverWidth: number;
popoverHeight: number;
}
declare class CameraPopoverOptions implements CameraPopoverOptions {
constructor(x?: number, y?: number, width?: number, height?: number, arrowDir?: number);
}
declare var Camera: {
// Camera constants, defined in Camera plugin
DestinationType: {
DATA_URL: number;
FILE_URI: number;
NATIVE_URI: number
}
Direction: {
BACK: number;
FRONT: number;
}
EncodingType: {
JPEG: number;
PNG: number;
}
MediaType: {
PICTURE: number;
VIDEO: number;
ALLMEDIA: number;
}
PictureSourceType: {
PHOTOLIBRARY: number;
CAMERA: number;
SAVEDPHOTOALBUM: number;
}
// Used only on iOS
PopoverArrowDirection: {
ARROW_UP: number;
ARROW_DOWN: number;
ARROW_LEFT: number;
ARROW_RIGHT: number;
ARROW_ANY: number;
}
};
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var argscheck = require('cordova/argscheck');
var exec = require('cordova/exec');
var Camera = require('./Camera');
// XXX: commented out
// CameraPopoverHandle = require('./CameraPopoverHandle');
/**
* @namespace navigator
*/
/**
* @exports camera
*/
var cameraExport = {};
// Tack on the Camera Constants to the base camera plugin.
for (var key in Camera) {
cameraExport[key] = Camera[key];
}
/**
* Callback function that provides an error message.
* @callback module:camera.onError
* @param {string} message - The message is provided by the device's native code.
*/
/**
* Callback function that provides the image data.
* @callback module:camera.onSuccess
* @param {string} imageData - Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`]{@link module:camera.CameraOptions} in effect.
* @example
* // Show image
* //
* function cameraCallback(imageData) {
* var image = document.getElementById('myImage');
* image.src = "data:image/jpeg;base64," + imageData;
* }
*/
/**
* Optional parameters to customize the camera settings.
* * [Quirks](#CameraOptions-quirks)
* @typedef module:camera.CameraOptions
* @type {Object}
* @property {number} [quality=50] - Quality of the saved image, expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. (Note that information about the camera's resolution is unavailable.)
* @property {module:Camera.DestinationType} [destinationType=FILE_URI] - Choose the format of the return value.
* @property {module:Camera.PictureSourceType} [sourceType=CAMERA] - Set the source of the picture.
* @property {Boolean} [allowEdit=false] - Allow simple editing of image before selection.
* @property {module:Camera.EncodingType} [encodingType=JPEG] - Choose the returned image file's encoding.
* @property {number} [targetWidth] - Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant.
* @property {number} [targetHeight] - Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant.
* @property {module:Camera.MediaType} [mediaType=PICTURE] - Set the type of media to select from. Only works when `PictureSourceType` is `PHOTOLIBRARY` or `SAVEDPHOTOALBUM`.
* @property {Boolean} [correctOrientation] - Rotate the image to correct for the orientation of the device during capture.
* @property {Boolean} [saveToPhotoAlbum] - Save the image to the photo album on the device after capture.
* @property {module:CameraPopoverOptions} [popoverOptions] - iOS-only options that specify popover location in iPad.
* @property {module:Camera.Direction} [cameraDirection=BACK] - Choose the camera to use (front- or back-facing).
*/
/**
* @description Takes a photo using the camera, or retrieves a photo from the device's
* image gallery. The image is passed to the success callback as a
* Base64-encoded `String`, or as the URI for the image file.
*
* The `camera.getPicture` function opens the device's default camera
* application that allows users to snap pictures by default - this behavior occurs,
* when `Camera.sourceType` equals [`Camera.PictureSourceType.CAMERA`]{@link module:Camera.PictureSourceType}.
* Once the user snaps the photo, the camera application closes and the application is restored.
*
* If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or
* `Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays
* that allows users to select an existing image.
*
* The return value is sent to the [`cameraSuccess`]{@link module:camera.onSuccess} callback function, in
* one of the following formats, depending on the specified
* `cameraOptions`:
*
* - A `String` containing the Base64-encoded photo image.
* - A `String` representing the image file location on local storage (default).
*
* You can do whatever you want with the encoded image or URI, for
* example:
*
* - Render the image in an `<img>` tag, as in the example below
* - Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)
* - Post the data to a remote server
*
* __NOTE__: Photo resolution on newer devices is quite good. Photos
* selected from the device's gallery are not downscaled to a lower
* quality, even if a `quality` parameter is specified. To avoid common
* memory problems, set `Camera.destinationType` to `FILE_URI` rather
* than `DATA_URL`.
*
* __Supported Platforms__
*
* - Android
* - BlackBerry
* - Browser
* - Firefox
* - FireOS
* - iOS
* - Windows
* - WP8
* - Ubuntu
*
* More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks).
*
* @example
* navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
* @param {module:camera.onSuccess} successCallback
* @param {module:camera.onError} errorCallback
* @param {module:camera.CameraOptions} options CameraOptions
*/
cameraExport.getPicture = function (successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
options = options || {};
var getValue = argscheck.getValue;
var quality = getValue(options.quality, 50);
var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);
var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);
var targetWidth = getValue(options.targetWidth, -1);
var targetHeight = getValue(options.targetHeight, -1);
var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);
var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);
var allowEdit = !!options.allowEdit;
var correctOrientation = !!options.correctOrientation;
var saveToPhotoAlbum = !!options.saveToPhotoAlbum;
var popoverOptions = getValue(options.popoverOptions, null);
var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];
exec(successCallback, errorCallback, 'Camera', 'takePicture', args);
// XXX: commented out
// return new CameraPopoverHandle();
};
/**
* Removes intermediate image files that are kept in temporary storage
* after calling [`camera.getPicture`]{@link module:camera.getPicture}. Applies only when the value of
* `Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the
* `Camera.destinationType` equals `Camera.DestinationType.FILE_URI`.
*
* __Supported Platforms__
*
* - iOS
*
* @example
* navigator.camera.cleanup(onSuccess, onFail);
*
* function onSuccess() {
* console.log("Camera cleanup success.")
* }
*
* function onFail(message) {
* alert('Failed because: ' + message);
* }
*/
cameraExport.cleanup = function (successCallback, errorCallback) {
exec(successCallback, errorCallback, 'Camera', 'cleanup', []);
};
module.exports = cameraExport;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/**
* @module Camera
*/
module.exports = {
/**
* @description
* Defines the output format of `Camera.getPicture` call.
* _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with
* `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will
* disable any image modifications (resize, quality change, cropping, etc.) due
* to implementation specific.
*
* @enum {number}
*/
DestinationType: {
/** Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible */
DATA_URL: 0,
/** Return file uri (content://media/external/images/media/2 for Android) */
FILE_URI: 1,
/** Return native uri (eg. asset-library://... for iOS) */
NATIVE_URI: 2
},
/**
* @enum {number}
*/
EncodingType: {
/** Return JPEG encoded image */
JPEG: 0,
/** Return PNG encoded image */
PNG: 1
},
/**
* @enum {number}
*/
MediaType: {
/** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */
PICTURE: 0,
/** Allow selection of video only, ONLY RETURNS URL */
VIDEO: 1,
/** Allow selection from all media types */
ALLMEDIA: 2
},
/**
* @description
* Defines the output format of `Camera.getPicture` call.
* _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`
* along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality
* change, cropping, etc.) due to implementation specific.
*
* @enum {number}
*/
PictureSourceType: {
/** Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) */
PHOTOLIBRARY: 0,
/** Take picture from camera */
CAMERA: 1,
/** Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) */
SAVEDPHOTOALBUM: 2
},
/**
* Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.
* @enum {number}
*/
PopoverArrowDirection: {
ARROW_UP: 1,
ARROW_DOWN: 2,
ARROW_LEFT: 4,
ARROW_RIGHT: 8,
ARROW_ANY: 15
},
/**
* @enum {number}
*/
Direction: {
/** Use the back-facing camera */
BACK: 0,
/** Use the front-facing camera */
FRONT: 1
}
};
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment