I have created a frontend app with Vue js on the Quasar framework, it works very well on the browser. But when I run it on android by using Cordova it does not work properly when it loads an MS word file from a remote server to fill it with some data. For templating I am using docxtemplater. And I take the following error:
Error: InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').
In addition, I have used the Django framework as a server with Nginx, Gunicorn on Ubuntu 20.04.2 LTS.
the site works via https
Cordova 11.0.0
Android 10.0 (Q) API level 29
Django settings:
"""
Django settings for tuberculosis project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
from corsheaders.defaults import default_headers
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'some-key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '75.119.133.43', 'www.tub-aspergillosis.uz', 'tub-aspergillosis.uz']
# Application definition
INSTALLED_APPS = [
'home.apps.HomeConfig',
'patientapp.apps.PatientappConfig',
'ai.apps.AIConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'rest_framework_simplejwt.token_blacklist'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
# **Dont forget to add your client's address to the CORS whitelist. This will make sure the server accepts request from
# the specified source only
CORS_ALLOWED_ORIGINS = [
'http://localhost:8000', 'http://75.119.133.43:8000', 'http://tub-aspergillosis.uz', 'https://tub-aspergillosis.uz'
]
# allow all requests containing any of the default headers(as in django docs) or content-type header
CORS_ALLOW_HEADERS = default_headers + (
'contenttype',
)
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
CORS_REPLACE_HTTPS_REFERER = True
ROOT_URLCONF = 'tuberculosis.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR + '/templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'tuberculosis.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'app',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = str(os.path.join(BASE_DIR, 'staticfiles'))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR.replace('\\', '/') + STATIC_URL,
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
# Localizing date and time => day-month-year
DATE_INPUT_FORMATS = ['%d-%m-%Y']
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=1440),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
Related
I am new to app building and I started using nuxt and capacitor to develop both an ios and android app. I was having trouble integrating push notifications with my app. I am using the #capacitor/push-notifications package. Is there any direction on how to integrate push notifications with nuxt and capacitor using this package. It would help if someone could walk through this step by step.
This is my nuxt.config.json file
import colors from 'vuetify/es5/util/colors'
export default {
// Disable server-side rendering (https://go.nuxtjs.dev/ssr-mode)
ssr: false,
// Target (https://go.nuxtjs.dev/config-target)
target: 'static',
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
titleTemplate: '%s - title',
title: 'title',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content:"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" },
{ hid: 'description', name: 'description', content: '' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
},
// Global CSS (https://go.nuxtjs.dev/config-css)
css: [],
// Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
plugins: [
'#/plugins/parse',
'#/plugins/axios',
{ src: '~plugins/leaflet.js', src: '~plugins/vuesocial.js', ssr: false },
],
// Auto import components (https://go.nuxtjs.dev/config-components)
components: true,
// Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
buildModules: [
// https://go.nuxtjs.dev/eslint
// '#nuxtjs/eslint-module',
// https://go.nuxtjs.dev/vuetify
'#nuxtjs/vuetify',
'#nuxtjs/moment',
],
// Modules (https://go.nuxtjs.dev/config-modules)
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/toast',
//nuxt-leaflet
'nuxt-leaflet',
['nuxt-stripe-module', {publishableKey:'...',}],
],
// Axios module configuration (https://go.nuxtjs.dev/config-axios)
axios: {},
toast: {
position: 'bottom-left',
duration: 3000,
},
// Vuetify module configuration (https://go.nuxtjs.dev/config-vuetify)
vuetify: {
customVariables: ['~/assets/variables.scss'],
theme: {
dark: false,
themes: {
dark: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3,
},
},
},
},
// Build Configuration (https://go.nuxtjs.dev/config-build)
build: {
transpile: ['parse', 'axios'],
},
}
This is my capacitor.config.json
{
"appId":"com.undefined.mobile",
"appName":"undefined",
"bundledWebRuntime":false,
"npmClient": "yarn",
"webDir":"dist",
"plugins": {
"SplashScreen": {
"launchShowDuration": 0
}
},
"cordova": {},
"server": {
"iosScheme": "nuxtmobile"
}
}
This is my Podfile
platform :ios, '13.0'
use_frameworks!
# workaround to avoid Xcode caching of Pods that requires
# Product -> Clean Build Folder after new Cordova plugins installed
# Requires CocoaPods 1.6 or newer
install! 'cocoapods', :disable_input_output_paths => true
def capacitor_pods
pod 'Capacitor', :path => '../../node_modules/#capacitor/ios'
pod 'CapacitorCordova', :path => '../../node_modules/#capacitor/ios'
pod 'CapacitorClipboard', :path => '../../node_modules/#capacitor/clipboard'
pod 'CapacitorGeolocation', :path => '../../node_modules/#capacitor/geolocation'
end
target 'App' do
capacitor_pods
# Add your Pods here
end
I have an app in IONIC and in browser the call to API works but when I run on android device it shows this error:
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://192.168.1.***:8080/api/auth/login", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://192.168.1.***:8080/api/auth/login: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://192.168.1.***:8080/api/auth/login"
__proto__: HttpResponseBase
In IONIC I send like API_URL = 'http://192.168.1.***:8080/api/'; to use HttpClient, and in Laravel I run php artisan serve --host 192.168.1.*** --port 8080
Please, someone knows what I should do to work?
The issue is related to CORS. You don't have to do anything to your IONIC app. You can enable CORS request by adding required headers for that you can create your own middleware in Laravel to handle cors, A sample middleware would be:
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
}
}
Then use it, by editing app\Http\Kernel.php
protected $middlewareGroups = [
'web' => [
// middleware for your web routes
],
'api' => [
'throttle:60,1',
'bindings',
'cors',
],
]
protected $routeMiddleware = [
// other middleware code
'cors' => \EuroKids\Http\Middleware\Cors::class,
]
You can customize the above middleware as required.
However, if you don't want to do create your own middleware you can use this library:
https://github.com/barryvdh/laravel-cors
I am planning to upload an APK to hockey app through Jenkins Pipeline. My upload is failing.
Can anyone help me on this issue
Trying to upload android APK with an error.
def DEV_APK_PATH="APP/build/outputs/apk/mobileDevelopment/release/*.apk"
def DEV_MAPPING="APP/build/outputs/mapping/mobileDevelopment/release/mapping.txt"
pipeline {
agent { label 'ABC' }
stages {
stage('Upload To HockeyApp') {
when {
expression { return params.UPLOAD_HOCKEYAPP }
}
steps {
// Build Android
archiveArtifacts DEV_APK_PATH
hockeyApp applications: [
[
apiToken: 'HOCKEY_APP_TOKEN',
downloadAllowed: true,
filePath: DEV_APK_PATH,
dsymPath: DEV_MAPPING
releaseNotesMethod: changelog('true'),
uploadMethod: versionCreation('app-id')
]
], debugMode: false, failGracefully: false
}
}
} // stages
} // pipeline
Error Log:
Running in Durability level: MAX_SURVIVABILITY org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:enter code here WorkflowScript: 44: expecting '}', found ':' # line 44, column 39.
hockeyApp applications: [
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.ErrorCollector.addFatalError(ErrorCollector.java:150)
at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:120)
at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:132)
at org.codehaus.groovy.control.SourceUnit.addError(SourceUnit.java:350)
at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:144)
at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(AntlrParserPlugin.java:110)
at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:234)
at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:168)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:943)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:605)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:320)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
New S3 item triggers lambda function. I'd like to somehow extract it's URL and pass it to sns as a link or something that can be opened from notification on Android phone. I can send notifications to phone at the moment but need to pass new element from S3. Does anyone have any ideas and is it possible to achieve like that?
Here's the code from my lambda function. It's in mess since i've been trying different combinations to attempt this:
import logging
import boto3
sns = boto3.client('sns')
s3 = boto3.client('s3')
# Change topic, qos and payload
def lambda_handler(event, context):
# retrieve bucket name and file_key from the S3 event
bucket_name = event['Records'][0]['s3']['bucket']['name']
file_key = event['Records'][0]['s3']['object']['key']
#logger.info('Reading {} from {}'.format(file_key, bucket_name))
presigned_url = s3.genereate_presigned_url(
'get_object',
Params = {'Bucket': bucket_name, 'Key': file_key}
)
sns.publish(
TargetArn='arn:aws:sns:eu...',
Message=presigned_url
)
error:
Response:
{
"errorMessage": "'S3' object has no attribute
'genereate_presigned_url'",
"errorType": "AttributeError",
"stackTrace": [
[
"/var/task/lambda_function.py",
14,
"lambda_handler",
"presigned_url = s3.genereate_presigned_url("
],
[
"/var/runtime/botocore/client.py",
555,
"__getattr__",
"self.__class__.__name__, item)"
]
]
}
Thanks to dpwrussell, I was able to extract url from test function and learned more about lambda and AWS. Below is updated version of the code and lambda trigger test.
from __future__ import print_function
import logging
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
sns = boto3.client('sns')
s3 = boto3.client('s3')
# Change topic, qos and payload
def lambda_handler(event, context):
# retrieve bucket name and file_key from the S3 event
bucket_name = event['Records'][0]['s3']['bucket']['name']
print(bucket_name)
file_key = event['Records'][0]['s3']['object']['key']
#logger.info('Reading {} from {}'.format(file_key, bucket_name))
print('this will also show up in cloud watch')
logger.info('got event{}'.format(bucket_name))
logger.info('got event{}'.format(file_key))
generate_presigned_url = s3.genereate_presigned_url(
'get_object',
Params = {'Bucket': bucket_name, 'Key': file_key}
)
sns.publish(
TargetArn='arn.........',
Message=generate_presigned_url
)
Test event:
{
"Records": [
{
"s3": {
"bucket": {
"name": "mybucket"
}
},
"object": {
"key": "Example.json.gz"
}
}
]
}
That's not the interface to generate_presigned_url.
It's:
presigned_url = s3.generate_presigned_url(
'get_object',
Params = {'Bucket': bucket_name, 'Key': file_key}
)
You also have a problem with your input. Your input needs to have a structure like this. Otherwise your lambda function will fail with that KeyError that your getting when trying to read these parameters from the event.
{
"Records": [
"s3": {
"bucket": {
"name: "mybucketname"
},
"object": {
"key": "mybucketkey"
}
}
]
}
Thank you #Marszal and #dpwrussell.
I am new to python and this post helped me to get the desired output. I am using Python 3.8 Runtime and was getting error with generate_presigned_url. Error looks like:
[ERROR] AttributeError: 'S3' object has no attribute 'genereate_presigned_url'
Also, I had to fetch file size. So I tried this simple approach to get the final URL and it is working.
import boto3
import logging
import json
sns = boto3.client('sns')
s3 = boto3.client('s3')
def lambda_handler(event, context):
# retrieve bucket name, file_key and size from the S3 event
bucket_name = event['Records'][0]['s3']['bucket']['name']
print("Bucket Name: "+bucket_name)
file_key = event['Records'][0]['s3']['object']['key']
print("File Key: "+file_key)
file_size = event['Records'][0]['s3']['object']['size']
print("File Size: "+str(file_size)+"kb")
s3url = "s3://"+bucket_name+"/"+file_key
print("S3 URL: "+s3url)
Error Appear when i build android using ionic build android command
ngc: Error: Error encountered resolving symbol values statically. Reference to a local (non-exported) symbol 'dictionary'. Consider exporting the symbol (position 14:8 in the original .ts file), resolving symbol TRANSLATION_PROVIDERS
My code in translation.ts file
export const TRANSLATIONS = new OpaqueToken('translations');
// all traslations
const dictionary : any = {
[LANG_EN_NAME]: LANG_EN_TRANS,
[LANG_AR_NAME]: LANG_AR_TRANS,
[LANG_FR_NAME]: LANG_FR_TRANS
};
// providers
export const TRANSLATION_PROVIDERS : any = [
{ provide: TRANSLATIONS, useValue: dictionary},
];
My app.module.ts code
import {TRANSLATION_PROVIDERS,TranslatePipe,TranslateService} from './translate';
#NgModule({
declarations: [
MyApp,
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
],
providers: [TRANSLATION_PROVIDERS,TranslateService ]
})
export class AppModule {}
any suggestions about this issue, by the way when im using ionic serve command my project work 100% with transaltion
I found a workaround for that.
you don't have to export your dictionary object, just change the keys to static values.
This worked for me:
// all translations
const dictionary = {
"en": LANG_EN_TRANS,
"ar": LANG_AR_TRANS,
"fr": LANG_FR_TRANS
};
// providers
export const TRANSLATION_PROVIDERS = [
{ provide: TRANSLATIONS, useValue: dictionary },
];
Yes exactly as said by #welefish in his answer, no need to export your dictionary object, you just have to change to keys to static value.
PS:- another method (Posting as answer because #welefish method is not working for me)
let en = LANG_EN_NAME;
let er = LANG_AR_NAME;
let fr = LANG_FR_NAME;
const dictionary : any = {
en: LANG_EN_TRANS,
er: LANG_AR_TRANS,
fr: LANG_FR_TRANS
};
// providers
export const TRANSLATION_PROVIDERS = [
{ provide: TRANSLATIONS, useValue: dictionary },
];
Well, do what the compiler says :). Export your dictionary:
export const dictionary : any = {
[LANG_EN_NAME]: LANG_EN_TRANS,
[LANG_AR_NAME]: LANG_AR_TRANS,
[LANG_FR_NAME]: LANG_FR_TRANS
};
Declare the type of [LANG_EN_NAME]:
export const LANG_EN_NAME : string = 'en';
Worked for me.