# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2021 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
QA fetch module
@yutiansut
QAFetch is Under [QAStandard#[email protected]] Protocol
"""
from QUANTAXIS.QAFetch import QAWind as QAWind
from QUANTAXIS.QAFetch import QATushare as QATushare
from QUANTAXIS.QAFetch import QATdx as QATdx
from QUANTAXIS.QAFetch import QAThs as QAThs
from QUANTAXIS.QAFetch import QACrawler as QACL
from QUANTAXIS.QAFetch import QAEastMoney as QAEM
from QUANTAXIS.QAFetch import QAHexun as QAHexun
from QUANTAXIS.QAFetch import QAfinancial
from QUANTAXIS.QAFetch.base import get_stock_market
from QUANTAXIS.QAFetch import QAQAWEB as QAWEB
from QUANTAXIS.QAFetch import QAKQ as QAKQ
def use(package):
if package in ['wind']:
try:
from WindPy import w
# w.start()
return QAWind
except ModuleNotFoundError:
print('NO WIND CLIENT FOUND')
elif package in ['tushare', 'ts']:
return QATushare
elif package in ['tdx', 'pytdx']:
return QATdx
elif package in ['ths', 'THS']:
return QAThs
elif package in ['HEXUN', 'Hexun', 'hexun']:
return QAHexun
elif package in ['QA']:
return QAWEB
def QA_fetch_get_stock_day(package, code, start, end, if_fq='00', level='day', type_='pd'):
Engine = use(package)
if package in ['ths', 'THS', 'wind']:
return Engine.QA_fetch_get_stock_day(code, start, end, if_fq)
elif package in ['ts', 'tushare']:
return Engine.QA_fetch_get_stock_day(code, start, end, if_fq, type_)
elif package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_stock_day(code, start, end, if_fq, level)
else:
return Engine.QA_fetch_get_stock_day(code, start, end)
def QA_fetch_get_stock_realtime(package, code):
Engine = use(package)
return Engine.QA_fetch_get_stock_realtime(code)
def QA_fetch_get_stock_indicator(package, code, start, end):
Engine = use(package)
return Engine.QA_fetch_get_stock_indicator(code, start, end)
def QA_fetch_get_trade_date(package, end, exchange):
Engine = use(package)
return Engine.QA_fetch_get_trade_date(end, exchange)
def QA_fetch_get_stock_min(package, code, start, end, level='1min'):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_stock_min(code, start, end, level)
else:
return 'Unsupport packages'
def QA_fetch_get_stock_transaction(package, code, start, end, retry=2):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_stock_transaction(code, start, end, retry)
else:
return 'Unsupport packages'
def QA_fetch_get_index_transaction(package, code, start, end, retry=2):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_index_transaction(code, start, end, retry)
else:
return 'Unsupport packages'
def QA_fetch_get_stock_transaction_realtime(package, code):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_stock_transaction_realtime(code)
else:
return 'Unsupport packages'
def QA_fetch_get_stock_xdxr(package, code):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_stock_xdxr(code)
else:
return 'Unsupport packages'
def QA_fetch_get_index_day(package, code, start, end, level='day'):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_index_day(code, start, end, level)
else:
return 'Unsupport packages'
def QA_fetch_get_index_min(package, code, start, end, level='1min'):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_index_min(code, start, end, level)
else:
return 'Unsupport packages'
def QA_fetch_get_index_realtime(package, code):
Engine = use(package)
return Engine.QA_fetch_get_index_realtime(code)
def QA_fetch_get_bond_day(package, code, start, end, level='day'):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_bond_day(code, start, end, level)
else:
return 'Unsupport packages'
def QA_fetch_get_bond_min(package, code, start, end, level='1min'):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_bond_min(code, start, end, level)
else:
return 'Unsupport packages'
def QA_fetch_get_bond_realtime(package, code):
Engine = use(package)
return Engine.QA_fetch_get_bond_realtime(code)
def QA_fetch_get_stock_block(package):
Engine = use(package)
if package in ['tdx', 'pytdx', 'ths', 'tushare', 'QA']:
return Engine.QA_fetch_get_stock_block()
else:
return 'Unsupport packages'
def QA_fetch_get_stock_info(package, code):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_stock_info(code)
else:
return 'Unsupport packages'
# LIST
def QA_fetch_get_stock_list(package, type_='stock'):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_stock_list(type_)
else:
return 'Unsupport packages'
def QA_fetch_get_bond_list(package):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_bond_list()
else:
return 'Unsupport packages'
def QA_fetch_get_index_list(package):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_index_list()
else:
return 'Unsupport packages'
def QA_fetch_get_future_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_future_list()
else:
return 'Unsupport packages'
def QA_fetch_get_option_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_option_list()
else:
return 'Unsupport packages'
def QA_fetch_get_globalfuture_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_globalfuture_list()
else:
return 'Unsupport packages'
def QA_fetch_get_hkstock_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_hkstock_list()
else:
return 'Unsupport packages'
def QA_fetch_get_hkfund_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_hkfund_list()
else:
return 'Unsupport packages'
def QA_fetch_get_hkindex_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_hkindex_list()
else:
return 'Unsupport packages'
def QA_fetch_get_usstock_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_usstock_list()
else:
return 'Unsupport packages'
def QA_fetch_get_macroindex_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_macroindex_list()
else:
return 'Unsupport packages'
def QA_fetch_get_globalindex_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_globalindex_list()
else:
return 'Unsupport packages'
def QA_fetch_get_exchangerate_list(package,):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_exchangerate_list()
else:
return 'Unsupport packages'
#######################
def QA_fetch_get_security_bars(code, _type, lens):
return QATdx.QA_fetch_get_security_bars(code, _type, lens)
def QA_fetch_get_future_transaction(package, code, start, end):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_future_transaction(code, start, end)
else:
return 'Unsupport packages'
def QA_fetch_get_future_transaction_realtime(package, code):
"""
æè´§å®æ¶tick
"""
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_future_transaction_realtime(code)
else:
return 'Unsupport packages'
def QA_fetch_get_future_domain():
return QAKQ.QA_fetch_get_future_domain()
def QA_fetch_get_future_realtime(package, code):
Engine = use(package)
return Engine.QA_fetch_get_future_realtime(code)
def QA_fetch_get_future_day(package, code, start, end, frequence='day'):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_future_day(code, start, end, frequence=frequence)
else:
return 'Unsupport packages'
def QA_fetch_get_future_min(package, code, start, end, frequence='1min'):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_future_min(code, start, end, frequence=frequence)
else:
return 'Unsupport packages'
def QA_fetch_get_chibor(package, frequence):
Engine = use(package)
if package in ['Hexun', 'hexun']:
return Engine.QA_fetch_get_chibor(frequence)
else:
return 'Unsupport packages'
QA_fetch_get_option_day = QA_fetch_get_future_day
QA_fetch_get_option_min = QA_fetch_get_future_min
QA_fetch_get_hkstock_day = QA_fetch_get_future_day
QA_fetch_get_hkstock_min = QA_fetch_get_future_min
QA_fetch_get_hkfund_day = QA_fetch_get_future_day
QA_fetch_get_hkfund_min = QA_fetch_get_future_min
QA_fetch_get_hkindex_day = QA_fetch_get_future_day
QA_fetch_get_hkindex_min = QA_fetch_get_future_min
QA_fetch_get_usstock_day = QA_fetch_get_future_day
QA_fetch_get_usstock_min = QA_fetch_get_future_min
QA_fetch_get_option_day = QA_fetch_get_future_day
QA_fetch_get_option_min = QA_fetch_get_future_min
QA_fetch_get_globalfuture_day = QA_fetch_get_future_day
QA_fetch_get_globalfuture_min = QA_fetch_get_future_min
QA_fetch_get_exchangerate_day = QA_fetch_get_future_day
QA_fetch_get_exchangerate_min = QA_fetch_get_future_min
QA_fetch_get_macroindex_day = QA_fetch_get_future_day
QA_fetch_get_macroindex_min = QA_fetch_get_future_min
QA_fetch_get_globalindex_day = QA_fetch_get_future_day
QA_fetch_get_globalindex_min = QA_fetch_get_future_min
# stdlib
import urlparse
import hashlib
import logging
# local
import const
# external
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Make requests stop logging so much. I love you but you need to shut
# up.
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING)
# Disable warning when making non-verified HTTPS requests
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
USER_AGENT = "Edgemanage v2 (https://github.com/equalitie/edgemanage)"
class FetchFailed(Exception):
def __init__(self, edgetest, fetch_host, fetch_object, reason):
message = "Failed to fetch %s/%s from %s: %s" % (fetch_host, fetch_object,
edgetest.edgename, reason)
super(FetchFailed, self).__init__(message)
self.edgename = edgetest.edgename
self.local_sum = edgetest.local_sum
self.fetch_host = fetch_host
self.fetch_object = fetch_object
class VerifyFailed(Exception):
def __init__(self, edgetest, fetch_host, fetch_object, reason):
message = "Failed to verify %s/%s from %s: %s != %s" % (
fetch_host, fetch_object, edgetest.edgename,
edgetest.local_sum, reason)
super(VerifyFailed, self).__init__(message)
self.edgename = edgetest.edgename
self.local_sum = edgetest.local_sum
self.fetch_host = fetch_host
self.fetch_object = fetch_object
class EdgeTest(object):
def __init__(self, edgename, local_sum):
"""
edgename: FQDN string of the edge to be tested
local_sum: the pre-computed known checksum of the object to be fetched
"""
self.edgename = edgename
self.local_sum = local_sum
def make_request(self, fetch_host, fetch_object, proto, port, verify):
request_url = urlparse.urljoin(proto + "://" + self.edgename + ":" + str(port),
fetch_object)
return requests.get(request_url, verify=verify, timeout=const.FETCH_TIMEOUT,
headers={"Host": fetch_host, "User-Agent": USER_AGENT})
pass
def fetch(self, fetch_host, fetch_object, proto="https", port=80, verify=False):
"""
fetch_host: The Host header to use when fetching
fetch_object: The path to the object to be fetched
"""
try:
response = self.make_request(fetch_host, fetch_object, proto, port, verify)
except requests.exceptions.Timeout as e:
# Just assume it took the maximum amount of time
return const.FETCH_TIMEOUT
except requests.exceptions.ConnectionError as e:
logging.error("Connection error when fetching from %s: %s", self.edgename, str(e))
for i in range(const.FETCH_RETRY-1):
logging.warning("Retrying connection to %s", self.edgename)
try:
response = self.make_request(fetch_host, fetch_object, proto, port, verify)
# Request was successful, stop retrying and
# continue
break
except requests.exceptions.ConnectionError as e:
continue
else:
logging.error("Failed to connect to %s after retrying %d times",
self.edgename, const.FETCH_RETRY)
# The loop finished without a break - we got more
# connection errors. Let's bail and return the maximum
# amount of time. for/else is weird.
return const.FETCH_TIMEOUT
if not response.ok:
logging.error("Object fetch failed on %s:%s", self.edgename, port)
raise FetchFailed(self, fetch_host, fetch_object, response.text)
remote_hash = hashlib.md5(response.content).hexdigest()
if remote_hash != self.local_sum:
logging.error("Failed to verify hash on %s!!", self.edgename)
raise VerifyFailed(self, fetch_host, fetch_object, remote_hash)
return response.elapsed.total_seconds()
const EmployeeActionTypes = {
// For fetching single employee by id
FETCH_EMPLOYEE_START: 'FETCH_EMPLOYEE_START',
FETCH_EMPLOYEE_SUCCESS: 'FETCH_EMPLOYEE_SUCCESS',
FETCH_EMPLOYEE_FAILURE: 'FETCH_EMPLOYEE_FAILURE',
// For fetching latest employee
FETCH_NEWLY_HIRED_EMPLOYEE_START: 'FETCH_NEWLY_HIRED_EMPLOYEE_START',
FETCH_NEWLY_HIRED_EMPLOYEE_SUCCESS: 'FETCH_NEWLY_HIRED_EMPLOYEE_SUCCESS',
FETCH_NEWLY_HIRED_EMPLOYEE_FAILURE: 'FETCH_NEWLY_HIRED_EMPLOYEE_FAILURE',
// For searching
FETCH_EMPLOYEES_BY_KEYWORD_START: 'FETCH_EMPLOYEES_BY_KEYWORD_START',
FETCH_EMPLOYEES_BY_KEYWORD_SUCCESS: 'FETCH_EMPLOYEES_BY_KEYWORD_SUCCESS',
FETCH_EMPLOYEES_BY_KEYWORD_FALURE: 'FETCH_EMPLOYEES_BY_KEYWORD_FALURE',
FETCH_EMPLOYEES_BY_KEYWORD_CANCELLED: 'FETCH_EMPLOYEES_BY_KEYWORD_CANCELLED',
// For pagination
FETCH_INITIAL_PAGE_EMPLOYEES_START: 'FETCH_INITIAL_PAGE_EMPLOYEES_START',
FETCH_INITIAL_PAGE_EMPLOYEES_SUCCESS: 'FETCH_INITIAL_PAGE_EMPLOYEES_SUCCESS',
FETCH_PREVIOUS_PAGE_EMPLOYEES_START: 'FETCH_PREVIOUS_PAGE_EMPLOYEES_START',
FETCH_PREVIOUS_PAGE_EMPLOYEES_SUCCESS: 'FETCH_PREVIOUS_PAGE_EMPLOYEES_SUCCESS',
FETCH_NEXT_PAGE_EMPLOYEES_START: 'FETCH_NEXT_PAGE_EMPLOYEES_START',
FETCH_NEXT_PAGE_EMPLOYEES_SUCCESS: 'FETCH_NEXT_PAGE_EMPLOYEES_SUCCESS',
FETCH_PAGE_EMPLOYEES_FAILURE: 'FETCH_PAGE_EMPLOYEES_FAILURE'
};
const fetchEmployeeStart = (id) => ({
type: EmployeeActionTypes.FETCH_EMPLOYEE_START,
payload: id
});
const fetchNewlyHiredEmployeeStart = () => ({
type: EmployeeActionTypes.FETCH_NEWLY_HIRED_EMPLOYEE_START
});
const fetchEmployeesByKeywordStart = (keyword, pageKey, isActive, sortBy) => ({
type: EmployeeActionTypes.FETCH_EMPLOYEES_BY_KEYWORD_START,
payload: { keyword, pageKey, isActive, sortBy }
});
const fetchInitialPageEmployeesStart = (pageKey, isActive, sortBy) => ({
type: EmployeeActionTypes.FETCH_INITIAL_PAGE_EMPLOYEES_START,
payload: { pageKey, isActive, sortBy }
});
const fetchPreviousPageEmployeesStart = (pageKey, isActive, sortBy) => ({
type: EmployeeActionTypes.FETCH_PREVIOUS_PAGE_EMPLOYEES_START,
payload: { pageKey, isActive, sortBy }
});
const fetchNextPageEmployeesStart = (pageKey, isActive, sortBy) => ({
type: EmployeeActionTypes.FETCH_NEXT_PAGE_EMPLOYEES_START,
payload: { pageKey, isActive, sortBy }
});
const fetchEmployeeSuccess = (employee) => ({
type: EmployeeActionTypes.FETCH_EMPLOYEE_SUCCESS,
payload: employee
});
const fetchNewlyHiredEmployeeSuccess = (employee) => ({
type: EmployeeActionTypes.FETCH_NEWLY_HIRED_EMPLOYEE_SUCCESS,
payload: employee
});
const fetchEmployeesByKeywordSuccess = (employees) => ({
type: EmployeeActionTypes.FETCH_EMPLOYEES_BY_KEYWORD_SUCCESS,
payload: employees
});
const fetchInitialPageEmployeesSuccess = (employees, collectionSize) => ({
type: EmployeeActionTypes.FETCH_INITIAL_PAGE_EMPLOYEES_SUCCESS,
payload: { employees, collectionSize }
});
const fetchPreviousPageEmployeesSuccess = (employees, pageIndex) => ({
type: EmployeeActionTypes.FETCH_PREVIOUS_PAGE_EMPLOYEES_SUCCESS,
payload: { employees, pageIndex }
});
const fetchNextPageEmployeesSuccess = (employees, pageIndex) => ({
type: EmployeeActionTypes.FETCH_NEXT_PAGE_EMPLOYEES_SUCCESS,
payload: { employees, pageIndex }
});
const fetchEmployeeFailure = () => ({
type: EmployeeActionTypes.FETCH_EMPLOYEE_FAILURE
});
const fetchNewlyHiredEmployeeFailure = () => ({
type: EmployeeActionTypes.FETCH_NEWLY_HIRED_EMPLOYEE_FAILURE
});
const fetchEmployeesByKeywordFailure = () => ({
type: EmployeeActionTypes.FETCH_EMPLOYEES_BY_KEYWORD_FALURE
});
const fetchEmployeesByKeywordCancelled = () => ({
type: EmployeeActionTypes.FETCH_EMPLOYEES_BY_KEYWORD_CANCELLED
});
const fetchPageEmployeesFailure = () => ({
type: EmployeeActionTypes.FETCH_PAGE_EMPLOYEES_FAILURE
});
export {
EmployeeActionTypes,
fetchEmployeeStart,
fetchNewlyHiredEmployeeStart,
fetchEmployeesByKeywordStart,
fetchInitialPageEmployeesStart,
fetchPreviousPageEmployeesStart,
fetchNextPageEmployeesStart,
fetchEmployeeSuccess,
fetchNewlyHiredEmployeeSuccess,
fetchEmployeesByKeywordSuccess,
fetchInitialPageEmployeesSuccess,
fetchPreviousPageEmployeesSuccess,
fetchNextPageEmployeesSuccess,
fetchEmployeeFailure,
fetchNewlyHiredEmployeeFailure,
fetchEmployeesByKeywordFailure,
fetchEmployeesByKeywordCancelled,
fetchPageEmployeesFailure
};
// Fetch data
// Races
export const FETCH_RACES_REQUEST = 'FETCH_RACES_REQUEST';
export const FETCH_RACES_SUCCESS = 'FETCH_RACES_SUCCESS';
export const FETCH_RACES_ERROR = 'FETCH_RACES_ERROR';
// Classes
export const FETCH_CLASSES_REQUEST = 'FETCH_CLASSES_REQUEST';
export const FETCH_CLASSES_SUCCESS = 'FETCH_CLASSES_SUCCESS';
export const FETCH_CLASSES_ERROR = 'FETCH_CLASSES_ERROR';
// Realms
export const FETCH_REALMS_REQUEST = 'FETCH_REALMS_REQUEST';
export const FETCH_REALMS_SUCCESS = 'FETCH_REALMS_SUCCESS';
export const FETCH_REALMS_ERROR = 'FETCH_REALMS_ERROR';
// Talents
export const FETCH_TALENTS_REQUEST = 'FETCH_TALENTS_REQUEST';
export const FETCH_TALENTS_SUCCESS = 'FETCH_TALENTS_SUCCESS';
export const FETCH_TALENTS_ERROR = 'FETCH_TALENTS_ERROR';
// Item Types
export const FETCH_ITEM_TYPES_REQUEST = 'FETCH_ITEM_TYPES_REQUEST';
export const FETCH_ITEM_TYPES_SUCCESS = 'FETCH_ITEM_TYPES_SUCCESS';
export const FETCH_ITEM_TYPES_ERROR = 'FETCH_ITEM_TYPES_ERROR';
// Character related
export const FETCH_CHARACTER_REQUEST = 'FETCH_CHARACTER_REQUEST';
export const FETCH_CHARACTER_SUCCESS = 'FETCH_CHARACTER_SUCCESS';
export const FETCH_CHARACTER_ERROR = 'FETCH_CHARACTER_ERROR';
export const SWITCH_CHARACTER = 'SWITCH_CHARACTER';
export const MOVE_CHARACTER = 'MOVE_CHARACTER';
export const REMOVE_CHARACTER = 'REMOVE_CHARACTER';
// ITEMS
export const FETCH_ITEM_REQUEST = 'FETCH_ITEM_REQUEST';
export const FETCH_ITEM_SUCCESS = 'FETCH_ITEM_SUCCESS';
export const FETCH_ITEM_FAILURE = 'FETCH_ITEM_FAILURE';
export const FETCH_INFO_ITEM_REQUEST = 'FETCH_INFO_ITEM_REQUEST';
export const FETCH_INFO_ITEM_SUCCESS = 'FETCH_INFO_ITEM_SUCCESS';
export const FETCH_INFO_ITEM_FAILURE = 'FETCH_INFO_ITEM_FAILURE';
export const FETCH_ITEMSET_ITEM_REQUEST = 'FETCH_ITEMSET_ITEM_REQUEST';
export const FETCH_ITEMSET_ITEM_SUCCESS = 'FETCH_ITEMSET_ITEM_SUCCESS';
export const FETCH_ITEMSET_ITEM_FAILURE = 'FETCH_ITEMSET_ITEM_FAILURE';
export const UPDATE_ITEMSET_ITEM = 'UPDATE_ITEMSET_ITEM';
export const FETCH_TRANSMOG_ITEM_REQUEST = 'FETCH_TRANSMOG_ITEM_REQUEST';
export const FETCH_TRANSMOG_ITEM_SUCCESS = 'FETCH_TRANSMOG_ITEM_SUCCESS';
export const FETCH_TRANSMOG_ITEM_FAILURE = 'FETCH_TRANSMOG_ITEM_FAILURE';
export const UNSELECT_ITEM = 'UNSELECT_ITEM';
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["commonStoreForAll-VX"],{
/***/ "./resources/js/store/commonStoreForAll.js":
/*!*************************************************!*\
!*** ./resources/js/store/commonStoreForAll.js ***!
\*************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
var commonStoreForAll = {
namespaced: true,
state: function state() {
return {
//accessable from any where
authUser: {},
authPermissions: {},
systemSettings: {},
adminRoles: {},
branches: {},
chartOfAccountHeads: {},
allLanguages: {},
allCurrencies: {},
allDepertments: {},
autoSearchDepartments: {},
userStatus: {},
//get data from user_status table
AllStatus: {},
//get status for order, payment, purchase, porduct
jobTitles: {},
Countries: {},
Divisions: {},
Districts: {},
Dist_Zones: {},
AllAttributes: {},
AllAttributeValues: {},
AllBrands: {},
allBrandShops: {},
AllCategory: {},
autoSearchCategories: {},
autoSearchSuppliers: {},
AllSpecifications: {},
allCustomerGroups: {},
allCustomerMemberships: {},
allUnits: {}
};
},
/*end state*/
getters: {//userStatus: state => { return state.userStatus },
},
/*end getters*/
mutations: {
//commit from resources/js/components/admin/AdminWrapper.vue
AUTH_USER: function AUTH_USER(state, data) {
return state.authUser = data;
},
AUTH_PERMISSIONS: function AUTH_PERMISSIONS(state, data) {
return state.authPermissions = data;
},
SYSTEM_SETTINGS: function SYSTEM_SETTINGS(state, data) {
return state.systemSettings = data;
},
//End Commit
//get from action
FETCH_ROLES: function FETCH_ROLES(state, data) {
return state.adminRoles = data;
},
FETCH_BRANCHES: function FETCH_BRANCHES(state, data) {
return state.branches = data;
},
FETCH_CHART_OF_ACCOUNT_HEADS: function FETCH_CHART_OF_ACCOUNT_HEADS(state, data) {
return state.chartOfAccountHeads = data;
},
FETCH_LANGUAGES: function FETCH_LANGUAGES(state, data) {
return state.allLanguages = data;
},
FETCH_CURRENCIES: function FETCH_CURRENCIES(state, data) {
return state.allCurrencies = data;
},
FETCH_DEPARTMENTS: function FETCH_DEPARTMENTS(state, data) {
return state.allDepertments = data;
},
FETCH_JOB_TITLE: function FETCH_JOB_TITLE(state, data) {
return state.jobTitles = data;
},
FETCH_USER_STATUS: function FETCH_USER_STATUS(state, data) {
return state.userStatus = data;
},
FETCH_ALL_STATUS: function FETCH_ALL_STATUS(state, data) {
return state.AllStatus = data;
},
FETCH_COUNTRY_DATA: function FETCH_COUNTRY_DATA(state, Countries) {
return state.Countries = Countries;
},
FETCH_DIVISION_DATA: function FETCH_DIVISION_DATA(state, Divisions) {
return state.Divisions = Divisions;
},
FETCH_DISTRICT_DATA: function FETCH_DISTRICT_DATA(state, Districts) {
return state.Districts = Districts;
},
FETCH_DISTRICT_ZONE_DATA: function FETCH_DISTRICT_ZONE_DATA(state, Dist_Zones) {
return state.Dist_Zones = Dist_Zones;
},
FETCH_ATTRIBUTE_DATA: function FETCH_ATTRIBUTE_DATA(state, data) {
return state.AllAttributes = data;
},
FETCH_ATTRIBUTE_VALUE_DATA: function FETCH_ATTRIBUTE_VALUE_DATA(state, data) {
return state.AllAttributeValues = data;
},
FETCH_BRAND_DATA: function FETCH_BRAND_DATA(state, data) {
return state.AllBrands = data;
},
FETCH_BRAND_SHOP_DATA: function FETCH_BRAND_SHOP_DATA(state, data) {
return state.allBrandShops = data;
},
FETCH_CATEGORY_DATA: function FETCH_CATEGORY_DATA(state, data) {
return state.AllCategory = data;
},
FETCH_SPECIFICATION_DATA: function FETCH_SPECIFICATION_DATA(state, data) {
return state.AllSpecifications = data;
},
FETCH_CUSTOMER_GROUPS_DATA: function FETCH_CUSTOMER_GROUPS_DATA(state, data) {
return state.allCustomerGroups = data;
},
FETCH_CUSTOMER_MEMBERSHIP_DATA: function FETCH_CUSTOMER_MEMBERSHIP_DATA(state, data) {
return state.allCustomerMemberships = data;
},
FETCH_UNITS_DATA: function FETCH_UNITS_DATA(state, data) {
return state.allUnits = data;
},
//#####################################Search ###########################################
AUTO_COMPLETE_DATA_FOR_DEPARTMENTS: function AUTO_COMPLETE_DATA_FOR_DEPARTMENTS(state, data) {
return state.autoSearchDepartments = data;
},
AUTO_COMPLETE_DATA_FOR_CATEGORIES: function AUTO_COMPLETE_DATA_FOR_CATEGORIES(state, data) {
return state.autoSearchCategories = data;
},
AUTO_COMPLETE_DATA_FOR_SUPPLIERS: function AUTO_COMPLETE_DATA_FOR_SUPPLIERS(state, data) {
return state.autoSearchSuppliers = data;
}
},
/*end Mutations*/
actions: {
userStatus: function userStatus(context) {
axios.get('/spa/user-status-info').then(function (response) {
context.commit('FETCH_USER_STATUS', response.data);
})["catch"](function () {});
},
AllStatus: function AllStatus(context, payload) {
var query = payload;
axios.get('/spa/StatusMaster-Info/getAllStatus?&q=' + query).then(function (response) {
context.commit('FETCH_ALL_STATUS', response.data);
})["catch"](function () {});
},
fetchJobTitles: function fetchJobTitles(context) {
axios.get('/spa/JobTitle-Info/GetJobTitles').then(function (response) {
context.commit('FETCH_JOB_TITLE', response.data); //use for only show data
})["catch"](function () {});
},
fetchRoles: function fetchRoles(context) {
//return role 1 to 6
axios.get('/spa/Role-Info/GetRoles').then(function (response) {
context.commit('FETCH_ROLES', response.data); //use for only show data
})["catch"](function () {});
},
fetchBranches: function fetchBranches(context) {
axios.get('/spa/Branch-Info/getBranches').then(function (response) {
context.commit('FETCH_BRANCHES', response.data); //use for only show data
})["catch"](function () {});
},
fetchChartOfAccountHeads: function fetchChartOfAccountHeads(context) {
axios.get('/spa/AccountHeads-Info/getChartOfAccountHeads').then(function (response) {
context.commit('FETCH_CHART_OF_ACCOUNT_HEADS', response.data); //use for only show data
})["catch"](function () {});
},
fetchLanguages: function fetchLanguages(context) {
axios.get('/spa/Language-Info/getLanguages').then(function (response) {
context.commit('FETCH_LANGUAGES', response.data); //use for only show data
})["catch"](function () {});
},
fetchCurrencies: function fetchCurrencies(context) {
axios.get('/spa/Currency-Info/getCurrencies').then(function (response) {
context.commit('FETCH_CURRENCIES', response.data); //use for only show data
})["catch"](function () {});
},
fetchDepartments: function fetchDepartments(context) {
axios.get('/spa/Department-Info/getDetartments').then(function (response) {
context.commit('FETCH_DEPARTMENTS', response.data); //use for only show data
})["catch"](function () {});
},
fetchCountryList: function fetchCountryList(context) {
axios.get('/spa/Country-Info/GetCountry').then(function (response) {
context.commit('FETCH_COUNTRY_DATA', response.data); //use for only show data
})["catch"](function () {});
},
// fetchDivisionList(context){
// axios.get('/spa/Division-Info/GetDivision')
// .then( (response) => {
// context.commit('FETCH_DIVISION_DATA', response.data); //use for only show data
// }).catch( () => { })
// },
fetchDivisionList: function fetchDivisionList(context, payload) {
axios.get('/spa/Division-Info/GetDivision?&id=' + payload).then(function (response) {
context.commit('FETCH_DIVISION_DATA', response.data); //use for only show data
})["catch"](function () {});
},
fetchDistrictList: function fetchDistrictList(context, payload) {
axios.get('/spa/District-Info/GetDistrict?&id=' + payload).then(function (response) {
context.commit('FETCH_DISTRICT_DATA', response.data); //use for only show data
})["catch"](function () {});
},
fetchDistrictZoneList: function fetchDistrictZoneList(context, payload) {
axios.get('/spa/DistrictZone-Info/GetDistrictZone?&id=' + payload).then(function (response) {
context.commit('FETCH_DISTRICT_ZONE_DATA', response.data); //use for only show data
})["catch"](function () {});
},
fetchAttributeList: function fetchAttributeList(context) {
axios.get('/spa/Attribute-Info/GetAttributes').then(function (response) {
context.commit('FETCH_ATTRIBUTE_DATA', response.data);
})["catch"](function () {});
},
fetchAttributeValue: function fetchAttributeValue(context, payload) {
var query = payload;
axios.get('/spa/AttributeValue-Info/GetAttributeValue?&q=' + query).then(function (response) {
context.commit('FETCH_ATTRIBUTE_VALUE_DATA', response.data);
})["catch"](function () {});
},
fetchBrands: function fetchBrands(context) {
axios.get('/spa/Brand-Info/getBrands').then(function (response) {
context.commit('FETCH_BRAND_DATA', response.data);
})["catch"](function () {});
},
fetchBrandShops: function fetchBrandShops(context) {
axios.get('/spa/BrandShop-Info/getBrandShops').then(function (response) {
context.commit('FETCH_BRAND_SHOP_DATA', response.data);
})["catch"](function () {});
},
fetchCategory: function fetchCategory(context) {
axios.get('/spa/CategoryMaster-Info/getCategory').then(function (response) {
context.commit('FETCH_CATEGORY_DATA', response.data); //use for only show data
})["catch"](function () {});
},
fetchSpecifications: function fetchSpecifications(context) {
axios.get('/spa/Specification-Info/getSpecification').then(function (response) {
context.commit('FETCH_SPECIFICATION_DATA', response.data);
})["catch"](function () {});
},
fetchCustomerGroups: function fetchCustomerGroups(context) {
axios.get('/spa/customerGroup-Info/getCustomerGroup').then(function (response) {
context.commit('FETCH_CUSTOMER_GROUPS_DATA', response.data);
})["catch"](function () {});
},
fetchCustomerMemberships: function fetchCustomerMemberships(context) {
axios.get('/spa/customerMembership-Info/getCustomerMembership').then(function (response) {
context.commit('FETCH_CUSTOMER_MEMBERSHIP_DATA', response.data);
})["catch"](function () {});
},
fetchUnits: function fetchUnits(context) {
axios.get('/spa/UnitsMaster-Info/getAllUnits').then(function (response) {
context.commit('FETCH_UNITS_DATA', response.data);
})["catch"](function () {});
},
//############################################# Search ############################################
AutoCompleteSearchForDepartment: function AutoCompleteSearchForDepartment(context, payload) {
var query = payload;
axios.get('/spa/searchDepartmentData?&q=' + query).then(function (response) {
context.commit('AUTO_COMPLETE_DATA_FOR_DEPARTMENTS', response.data);
})["catch"](function () {});
},
AutoCompleteSearchForCategory: function AutoCompleteSearchForCategory(context, payload) {
var query = payload;
axios.get('/spa/AutoCompleteCategoryData?&q=' + query).then(function (response) {
context.commit('AUTO_COMPLETE_DATA_FOR_CATEGORIES', response.data);
})["catch"](function () {});
},
AutoCompleteSearchForSuppliers: function AutoCompleteSearchForSuppliers(context, payload) {
var query = payload;
axios.get('/spa/AutoCompleteSupplierData?&q=' + query).then(function (response) {
context.commit('AUTO_COMPLETE_DATA_FOR_SUPPLIERS', response.data);
})["catch"](function () {});
}
}
/*end actions*/
};
/* harmony default export */ __webpack_exports__["default"] = (commonStoreForAll);
/***/ })
}]);
var Fetch = {
attr_t_offset_requestMethod: 0,
attr_t_offset_userData: 32,
attr_t_offset_onsuccess: 36,
attr_t_offset_onerror: 40,
attr_t_offset_onprogress: 44,
attr_t_offset_attributes: 48,
attr_t_offset_timeoutMSecs: 52,
attr_t_offset_withCredentials: 56,
attr_t_offset_destinationPath: 60,
attr_t_offset_userName: 64,
attr_t_offset_password: 68,
attr_t_offset_requestHeaders: 72,
attr_t_offset_overriddenMimeType: 76,
attr_t_offset_requestData: 80,
attr_t_offset_requestDataSize: 84,
fetch_t_offset_id: 0,
fetch_t_offset_userData: 4,
fetch_t_offset_url: 8,
fetch_t_offset_data: 12,
fetch_t_offset_numBytes: 16,
fetch_t_offset_dataOffset: 24,
fetch_t_offset_totalBytes: 32,
fetch_t_offset_readyState: 40,
fetch_t_offset_status: 42,
fetch_t_offset_statusText: 44,
fetch_t_offset___proxyState: 108,
fetch_t_offset___attributes: 112,
xhrs: [],
// The web worker that runs proxied file I/O requests.
worker: undefined,
// Specifies an instance to the IndexedDB database. The database is opened
// as a preload step before the Emscripten application starts.
dbInstance: undefined,
setu64: function(addr, val) {
HEAPU32[addr >> 2] = val;
HEAPU32[addr + 4 >> 2] = (val / 4294967296)|0;
},
openDatabase: function(dbname, dbversion, onsuccess, onerror) {
try {
#if FETCH_DEBUG
console.log('fetch: indexedDB.open(dbname="' + dbname + '", dbversion="' + dbversion + '");');
#endif
var openRequest = indexedDB.open(dbname, dbversion);
} catch (e) { return onerror(e); }
openRequest.onupgradeneeded = function(event) {
#if FETCH_DEBUG
console.log('fetch: IndexedDB upgrade needed. Clearing database.');
#endif
var db = event.target.result;
if (db.objectStoreNames.contains('FILES')) {
db.deleteObjectStore('FILES');
}
db.createObjectStore('FILES');
};
openRequest.onsuccess = function(event) { onsuccess(event.target.result); };
openRequest.onerror = function(error) { onerror(error); };
},
initFetchWorker: function() {
var stackSize = 128*1024;
var stack = allocate(stackSize>>2, "i32*", ALLOC_DYNAMIC);
Fetch.worker.postMessage({cmd: 'init', TOTAL_MEMORY: TOTAL_MEMORY, DYNAMICTOP_PTR: DYNAMICTOP_PTR, STACKTOP: stack, STACK_MAX: stack + stackSize, queuePtr: _fetch_work_queue, buffer: HEAPU8.buffer}, [HEAPU8.buffer]);
},
staticInit: function() {
#if USE_PTHREADS
var isMainThread = (typeof ENVIRONMENT_IS_FETCH_WORKER === 'undefined' && !ENVIRONMENT_IS_PTHREAD);
#else
var isMainThread = (typeof ENVIRONMENT_IS_FETCH_WORKER === 'undefined');
#endif
var onsuccess = function(db) {
#if FETCH_DEBUG
console.log('fetch: IndexedDB successfully opened.');
#endif
Fetch.dbInstance = db;
#if USE_PTHREADS
if (isMainThread) {
if (typeof SharedArrayBuffer !== 'undefined') Fetch.initFetchWorker();
removeRunDependency('library_fetch_init');
}
#else
if (typeof ENVIRONMENT_IS_FETCH_WORKER === 'undefined' || !ENVIRONMENT_IS_FETCH_WORKER) removeRunDependency('library_fetch_init');
#endif
};
var onerror = function() {
#if FETCH_DEBUG
console.error('fetch: IndexedDB open failed.');
#endif
Fetch.dbInstance = false;
#if USE_PTHREADS
if (isMainThread) {
if (typeof SharedArrayBuffer !== 'undefined') Fetch.initFetchWorker();
removeRunDependency('library_fetch_init');
}
#endif
};
Fetch.openDatabase('emscripten_filesystem', 1, onsuccess, onerror);
#if USE_PTHREADS
if (isMainThread) {
addRunDependency('library_fetch_init');
var fetchJs = 'fetch-worker.js';
// Allow HTML module to configure the location where the 'pthread-main.js' file will be loaded from,
// either via Module.locateFile() function, or via Module.pthreadMainPrefixURL string. If neither
// of these are passed, then the default URL 'pthread-main.js' relative to the main html file is loaded.
if (typeof Module['locateFile'] === 'function') fetchJs = Module['locateFile'](fetchJs);
else if (Module['pthreadMainPrefixURL']) fetchJs = Module['pthreadMainPrefixURL'] + fetchJs;
Fetch.worker = new Worker(fetchJs);
Fetch.worker.onmessage = function(e) {
Module['print']('fetch-worker sent a message: ' + e.filename + ':' + e.lineno + ': ' + e.message);
};
Fetch.worker.onerror = function(e) {
Module['printErr']('fetch-worker sent an error! ' + e.filename + ':' + e.lineno + ': ' + e.message);
};
}
#else
if (typeof ENVIRONMENT_IS_FETCH_WORKER === 'undefined' || !ENVIRONMENT_IS_FETCH_WORKER) addRunDependency('library_fetch_init');
#endif
}
}
function __emscripten_fetch_delete_cached_data(db, fetch, onsuccess, onerror) {
if (!db) {
#if FETCH_DEBUG
console.error('fetch: IndexedDB not available!');
#endif
onerror(fetch, 0, 'IndexedDB not available!');
return;
}
var fetch_attr = fetch + Fetch.fetch_t_offset___attributes;
var path = HEAPU32[fetch_attr + Fetch.attr_t_offset_destinationPath >> 2];
if (!path) path = HEAPU32[fetch + Fetch.fetch_t_offset_url >> 2];
var pathStr = Pointer_stringify(path);
try {
var transaction = db.transaction(['FILES'], 'readwrite');
var packages = transaction.objectStore('FILES');
var request = packages.delete(pathStr);
request.onsuccess = function(event) {
var value = event.target.result;
#if FETCH_DEBUG
console.log('fetch: Deleted file ' + pathStr + ' from IndexedDB');
#endif
HEAPU32[fetch + Fetch.fetch_t_offset_data >> 2] = 0;
Fetch.setu64(fetch + Fetch.fetch_t_offset_numBytes, 0);
Fetch.setu64(fetch + Fetch.fetch_t_offset_dataOffset, 0);
Fetch.setu64(fetch + Fetch.fetch_t_offset_dataOffset, 0);
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = 4; // Mimic XHR readyState 4 === 'DONE: The operation is complete'
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = 200; // Mimic XHR HTTP status code 200 "OK"
onsuccess(fetch, 0, value);
};
request.onerror = function(error) {
#if FETCH_DEBUG
console.error('fetch: Failed to delete file ' + pathStr + ' from IndexedDB! error: ' + error);
#endif
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = 4; // Mimic XHR readyState 4 === 'DONE: The operation is complete'
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = 404; // Mimic XHR HTTP status code 404 "Not Found"
onerror(fetch, 0, error);
};
} catch(e) {
#if FETCH_DEBUG
console.error('fetch: Failed to load file ' + pathStr + ' from IndexedDB! Got exception ' + e);
#endif
onerror(fetch, 0, e);
}
}
function __emscripten_fetch_load_cached_data(db, fetch, onsuccess, onerror) {
if (!db) {
#if FETCH_DEBUG
console.error('fetch: IndexedDB not available!');
#endif
onerror(fetch, 0, 'IndexedDB not available!');
return;
}
var fetch_attr = fetch + Fetch.fetch_t_offset___attributes;
var path = HEAPU32[fetch_attr + Fetch.attr_t_offset_destinationPath >> 2];
if (!path) path = HEAPU32[fetch + Fetch.fetch_t_offset_url >> 2];
var pathStr = Pointer_stringify(path);
try {
var transaction = db.transaction(['FILES'], 'readonly');
var packages = transaction.objectStore('FILES');
var getRequest = packages.get(pathStr);
getRequest.onsuccess = function(event) {
if (event.target.result) {
var value = event.target.result;
var len = value.byteLength || value.length;
#if FETCH_DEBUG
console.log('fetch: Loaded file ' + pathStr + ' from IndexedDB, length: ' + len);
#endif
// The data pointer malloc()ed here has the same lifetime as the emscripten_fetch_t structure itself has, and is
// freed when emscripten_fetch_close() is called.
var ptr = _malloc(len);
HEAPU8.set(new Uint8Array(value), ptr);
HEAPU32[fetch + Fetch.fetch_t_offset_data >> 2] = ptr;
Fetch.setu64(fetch + Fetch.fetch_t_offset_numBytes, len);
Fetch.setu64(fetch + Fetch.fetch_t_offset_dataOffset, 0);
Fetch.setu64(fetch + Fetch.fetch_t_offset_totalBytes, len);
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = 4; // Mimic XHR readyState 4 === 'DONE: The operation is complete'
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = 200; // Mimic XHR HTTP status code 200 "OK"
onsuccess(fetch, 0, value);
} else {
// Succeeded to load, but the load came back with the value of undefined, treat that as an error since we never store undefined in db.
#if FETCH_DEBUG
console.error('fetch: File ' + pathStr + ' not found in IndexedDB');
#endif
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = 4; // Mimic XHR readyState 4 === 'DONE: The operation is complete'
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = 404; // Mimic XHR HTTP status code 404 "Not Found"
onerror(fetch, 0, 'no data');
}
};
getRequest.onerror = function(error) {
#if FETCH_DEBUG
console.error('fetch: Failed to load file ' + pathStr + ' from IndexedDB!');
#endif
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = 4; // Mimic XHR readyState 4 === 'DONE: The operation is complete'
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = 404; // Mimic XHR HTTP status code 404 "Not Found"
onerror(fetch, 0, error);
};
} catch(e) {
#if FETCH_DEBUG
console.error('fetch: Failed to load file ' + pathStr + ' from IndexedDB! Got exception ' + e);
#endif
onerror(fetch, 0, e);
}
}
function __emscripten_fetch_cache_data(db, fetch, data, onsuccess, onerror) {
if (!db) {
#if FETCH_DEBUG
console.error('fetch: IndexedDB not available!');
#endif
onerror(fetch, 0, 'IndexedDB not available!');
return;
}
var fetch_attr = fetch + Fetch.fetch_t_offset___attributes;
var destinationPath = HEAPU32[fetch_attr + Fetch.attr_t_offset_destinationPath >> 2];
if (!destinationPath) destinationPath = HEAPU32[fetch + Fetch.fetch_t_offset_url >> 2];
var destinationPathStr = Pointer_stringify(destinationPath);
try {
var transaction = db.transaction(['FILES'], 'readwrite');
var packages = transaction.objectStore('FILES');
var putRequest = packages.put(data, destinationPathStr);
putRequest.onsuccess = function(event) {
#if FETCH_DEBUG
console.log('fetch: Stored file "' + destinationPathStr + '" to IndexedDB cache.');
#endif
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = 4; // Mimic XHR readyState 4 === 'DONE: The operation is complete'
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = 200; // Mimic XHR HTTP status code 200 "OK"
onsuccess(fetch, 0, destinationPathStr);
};
putRequest.onerror = function(error) {
#if FETCH_DEBUG
console.error('fetch: Failed to store file "' + destinationPathStr + '" to IndexedDB cache!');
#endif
// Most likely we got an error if IndexedDB is unwilling to store any more data for this page.
// TODO: Can we identify and break down different IndexedDB-provided errors and convert those
// to more HTTP status codes for more information?
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = 4; // Mimic XHR readyState 4 === 'DONE: The operation is complete'
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = 413; // Mimic XHR HTTP status code 413 "Payload Too Large"
onerror(fetch, 0, error);
};
} catch(e) {
#if FETCH_DEBUG
console.error('fetch: Failed to store file "' + destinationPathStr + '" to IndexedDB cache! Exception: ' + e);
#endif
onerror(fetch, 0, e);
}
}
function __emscripten_fetch_xhr(fetch, onsuccess, onerror, onprogress) {
var url = HEAPU32[fetch + Fetch.fetch_t_offset_url >> 2];
if (!url) {
#if FETCH_DEBUG
console.error('fetch: XHR failed, no URL specified!');
#endif
onerror(fetch, 0, 'no url specified!');
return;
}
var url_ = Pointer_stringify(url);
var fetch_attr = fetch + Fetch.fetch_t_offset___attributes;
var requestMethod = Pointer_stringify(fetch_attr);
if (!requestMethod) requestMethod = 'GET';
var userData = HEAPU32[fetch_attr + Fetch.attr_t_offset_userData >> 2];
var fetchAttributes = HEAPU32[fetch_attr + Fetch.attr_t_offset_attributes >> 2];
var timeoutMsecs = HEAPU32[fetch_attr + Fetch.attr_t_offset_timeoutMSecs >> 2];
var withCredentials = !!HEAPU32[fetch_attr + Fetch.attr_t_offset_withCredentials >> 2];
var destinationPath = HEAPU32[fetch_attr + Fetch.attr_t_offset_destinationPath >> 2];
var userName = HEAPU32[fetch_attr + Fetch.attr_t_offset_userName >> 2];
var password = HEAPU32[fetch_attr + Fetch.attr_t_offset_password >> 2];
var requestHeaders = HEAPU32[fetch_attr + Fetch.attr_t_offset_requestHeaders >> 2];
var overriddenMimeType = HEAPU32[fetch_attr + Fetch.attr_t_offset_overriddenMimeType >> 2];
var fetchAttrLoadToMemory = !!(fetchAttributes & 1/*EMSCRIPTEN_FETCH_LOAD_TO_MEMORY*/);
var fetchAttrStreamData = !!(fetchAttributes & 2/*EMSCRIPTEN_FETCH_STREAM_DATA*/);
var fetchAttrPersistFile = !!(fetchAttributes & 4/*EMSCRIPTEN_FETCH_PERSIST_FILE*/);
var fetchAttrAppend = !!(fetchAttributes & 8/*EMSCRIPTEN_FETCH_APPEND*/);
var fetchAttrReplace = !!(fetchAttributes & 16/*EMSCRIPTEN_FETCH_REPLACE*/);
var fetchAttrNoDownload = !!(fetchAttributes & 32/*EMSCRIPTEN_FETCH_NO_DOWNLOAD*/);
var fetchAttrSynchronous = !!(fetchAttributes & 64/*EMSCRIPTEN_FETCH_SYNCHRONOUS*/);
var fetchAttrWaitable = !!(fetchAttributes & 128/*EMSCRIPTEN_FETCH_WAITABLE*/);
var userNameStr = userName ? Pointer_stringify(userName) : undefined;
var passwordStr = password ? Pointer_stringify(password) : undefined;
var overriddenMimeTypeStr = overriddenMimeType ? Pointer_stringify(overriddenMimeType) : undefined;
var xhr = new XMLHttpRequest();
xhr.withCredentials = withCredentials;
#if FETCH_DEBUG
console.log('fetch: xhr.timeout: ' + xhr.timeout + ', xhr.withCredentials: ' + xhr.withCredentials);
console.log('fetch: xhr.open(requestMethod="' + requestMethod + '", url: "' + url_ +'", userName: ' + userNameStr + ', password: ' + passwordStr + ');');
#endif
xhr.open(requestMethod, url_, !fetchAttrSynchronous, userNameStr, passwordStr);
if (!fetchAttrSynchronous) xhr.timeout = timeoutMsecs; // XHR timeout field is only accessible in async XHRs, and must be set after .open() but before .send().
xhr.url_ = url_; // Save the url for debugging purposes (and for comparing to the responseURL that server side advertised)
xhr.responseType = fetchAttrStreamData ? 'moz-chunked-arraybuffer' : 'arraybuffer';
if (overriddenMimeType) {
#if FETCH_DEBUG
console.log('fetch: xhr.overrideMimeType("' + overriddenMimeTypeStr + '");');
#endif
xhr.overrideMimeType(overriddenMimeTypeStr);
}
if (requestHeaders) {
for(;;) {
var key = HEAPU32[requestHeaders >> 2];
if (!key) break;
var value = HEAPU32[requestHeaders + 4 >> 2];
if (!value) break;
requestHeaders += 8;
var keyStr = Pointer_stringify(key);
var valueStr = Pointer_stringify(value);
#if FETCH_DEBUG
console.log('fetch: xhr.setRequestHeader("' + keyStr + '", "' + valueStr + '");');
#endif
xhr.setRequestHeader(keyStr, valueStr);
}
}
Fetch.xhrs.push(xhr);
var id = Fetch.xhrs.length;
HEAPU32[fetch + Fetch.fetch_t_offset_id >> 2] = id;
var data = null; // TODO: Support user to pass data to request.
// TODO: Support specifying custom headers to the request.
xhr.onload = function(e) {
var len = xhr.response ? xhr.response.byteLength : 0;
var ptr = 0;
var ptrLen = 0;
if (fetchAttrLoadToMemory && !fetchAttrStreamData) {
ptrLen = len;
#if FETCH_DEBUG
console.log('fetch: allocating ' + ptrLen + ' bytes in Emscripten heap for xhr data');
#endif
// The data pointer malloc()ed here has the same lifetime as the emscripten_fetch_t structure itself has, and is
// freed when emscripten_fetch_close() is called.
ptr = _malloc(ptrLen);
HEAPU8.set(new Uint8Array(xhr.response), ptr);
}
HEAPU32[fetch + Fetch.fetch_t_offset_data >> 2] = ptr;
Fetch.setu64(fetch + Fetch.fetch_t_offset_numBytes, ptrLen);
Fetch.setu64(fetch + Fetch.fetch_t_offset_dataOffset, 0);
if (len) {
// If the final XHR.onload handler receives the bytedata to compute total length, report that,
// otherwise don't write anything out here, which will retain the latest byte size reported in
// the most recent XHR.onprogress handler.
Fetch.setu64(fetch + Fetch.fetch_t_offset_totalBytes, len);
}
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = xhr.readyState;
if (xhr.readyState === 4 && xhr.status === 0) {
if (len > 0) xhr.status = 200; // If loading files from a source that does not give HTTP status code, assume success if we got data bytes.
else xhr.status = 404; // Conversely, no data bytes is 404.
}
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = xhr.status;
// if (xhr.statusText) stringToUTF8(fetch + Fetch.fetch_t_offset_statusText, xhr.statusText, 64);
if (xhr.status == 200) {
#if FETCH_DEBUG
console.log('fetch: xhr of URL "' + xhr.url_ + '" / responseURL "' + xhr.responseURL + '" succeeded with status 200');
#endif
if (onsuccess) onsuccess(fetch, xhr, e);
} else {
#if FETCH_DEBUG
console.error('fetch: xhr of URL "' + xhr.url_ + '" / responseURL "' + xhr.responseURL + '" failed with status ' + xhr.status);
#endif
if (onerror) onerror(fetch, xhr, e);
}
}
xhr.onerror = function(e) {
var status = xhr.status; // XXX TODO: Overwriting xhr.status doesn't work here, so don't override anywhere else either.
if (xhr.readyState == 4 && status == 0) status = 404; // If no error recorded, pretend it was 404 Not Found.
#if FETCH_DEBUG
console.error('fetch: xhr of URL "' + xhr.url_ + '" / responseURL "' + xhr.responseURL + '" finished with error, readyState ' + xhr.readyState + ' and status ' + status);
#endif
HEAPU32[fetch + Fetch.fetch_t_offset_data >> 2] = 0;
Fetch.setu64(fetch + Fetch.fetch_t_offset_numBytes, 0);
Fetch.setu64(fetch + Fetch.fetch_t_offset_dataOffset, 0);
Fetch.setu64(fetch + Fetch.fetch_t_offset_totalBytes, 0);
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = xhr.readyState;
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = status;
if (onerror) onerror(fetch, xhr, e);
}
xhr.ontimeout = function(e) {
#if FETCH_DEBUG
console.error('fetch: xhr of URL "' + xhr.url_ + '" / responseURL "' + xhr.responseURL + '" timed out, readyState ' + xhr.readyState + ' and status ' + xhr.status);
#endif
if (onerror) onerror(fetch, xhr, e);
}
xhr.onprogress = function(e) {
var ptrLen = (fetchAttrLoadToMemory && fetchAttrStreamData && xhr.response) ? xhr.response.byteLength : 0;
var ptr = 0;
if (fetchAttrLoadToMemory && fetchAttrStreamData) {
#if FETCH_DEBUG
console.log('fetch: allocating ' + ptrLen + ' bytes in Emscripten heap for xhr data');
#endif
// The data pointer malloc()ed here has the same lifetime as the emscripten_fetch_t structure itself has, and is
// freed when emscripten_fetch_close() is called.
ptr = _malloc(ptrLen);
HEAPU8.set(new Uint8Array(xhr.response), ptr);
}
HEAPU32[fetch + Fetch.fetch_t_offset_data >> 2] = ptr;
Fetch.setu64(fetch + Fetch.fetch_t_offset_numBytes, ptrLen);
Fetch.setu64(fetch + Fetch.fetch_t_offset_dataOffset, e.loaded - ptrLen);
Fetch.setu64(fetch + Fetch.fetch_t_offset_totalBytes, e.total);
HEAPU16[fetch + Fetch.fetch_t_offset_readyState >> 1] = xhr.readyState;
if (xhr.readyState >= 3 && xhr.status === 0 && e.loaded > 0) xhr.status = 200; // If loading files from a source that does not give HTTP status code, assume success if we get data bytes
HEAPU16[fetch + Fetch.fetch_t_offset_status >> 1] = xhr.status;
if (xhr.statusText) stringToUTF8(fetch + Fetch.fetch_t_offset_statusText, xhr.statusText, 64);
if (onprogress) onprogress(fetch, xhr, e);
}
#if FETCH_DEBUG
console.log('fetch: xhr.send(data=' + data + ')');
#endif
try {
xhr.send(data);
} catch(e) {
#if FETCH_DEBUG
console.error('fetch: xhr failed with exception: ' + e);
#endif
if (onerror) onerror(fetch, xhr, e);
}
}
function emscripten_start_fetch(fetch, successcb, errorcb, progresscb) {
if (typeof Module !== 'undefined') Module['noExitRuntime'] = true; // If we are the main Emscripten runtime, we should not be closing down.
var fetch_attr = fetch + Fetch.fetch_t_offset___attributes;
var requestMethod = Pointer_stringify(fetch_attr);
var onsuccess = HEAPU32[fetch_attr + Fetch.attr_t_offset_onsuccess >> 2];
var onerror = HEAPU32[fetch_attr + Fetch.attr_t_offset_onerror >> 2];
var onprogress = HEAPU32[fetch_attr + Fetch.attr_t_offset_onprogress >> 2];
var fetchAttributes = HEAPU32[fetch_attr + Fetch.attr_t_offset_attributes >> 2];
var fetchAttrLoadToMemory = !!(fetchAttributes & 1/*EMSCRIPTEN_FETCH_LOAD_TO_MEMORY*/);
var fetchAttrStreamData = !!(fetchAttributes & 2/*EMSCRIPTEN_FETCH_STREAM_DATA*/);
var fetchAttrPersistFile = !!(fetchAttributes & 4/*EMSCRIPTEN_FETCH_PERSIST_FILE*/);
var fetchAttrAppend = !!(fetchAttributes & 8/*EMSCRIPTEN_FETCH_APPEND*/);
var fetchAttrReplace = !!(fetchAttributes & 16/*EMSCRIPTEN_FETCH_REPLACE*/);
var fetchAttrNoDownload = !!(fetchAttributes & 32/*EMSCRIPTEN_FETCH_NO_DOWNLOAD*/);
var reportSuccess = function(fetch, xhr, e) {
#if FETCH_DEBUG
console.log('fetch: operation success. e: ' + e);
#endif
if (onsuccess && Runtime.dynCall) Module['dynCall_vi'](onsuccess, fetch);
else if (successcb) successcb(fetch);
};
var cacheResultAndReportSuccess = function(fetch, xhr, e) {
#if FETCH_DEBUG
console.log('fetch: operation success. Caching result.. e: ' + e);
#endif
var storeSuccess = function() {
#if FETCH_DEBUG
console.log('fetch: IndexedDB store succeeded.');
#endif
};
var storeError = function() {
#if FETCH_DEBUG
console.error('fetch: IndexedDB store failed.');
#endif
};
__emscripten_fetch_cache_data(Fetch.dbInstance, fetch, xhr.response, storeSuccess, storeError);
if (onsuccess && Runtime.dynCall) Module['dynCall_vi'](onsuccess, fetch);
else if (successcb) successcb(fetch);
};
var reportProgress = function(fetch, xhr, e) {
if (onprogress && Runtime.dynCall) Module['dynCall_vi'](onprogress, fetch);
else if (progresscb) progresscb(fetch);
};
var reportError = function(fetch, xhr, e) {
#if FETCH_DEBUG
console.error('fetch: operation failed: ' + e);
#endif
if (onerror && Runtime.dynCall) Module['dynCall_vi'](onerror, fetch);
else if (errorcb) errorcb(fetch);
};
var performUncachedXhr = function(fetch, xhr, e) {
#if FETCH_DEBUG
console.error('fetch: starting (uncached) XHR: ' + e);
#endif
__emscripten_fetch_xhr(fetch, reportSuccess, reportError, reportProgress);
};
var performCachedXhr = function(fetch, xhr, e) {
#if FETCH_DEBUG
console.error('fetch: starting (cached) XHR: ' + e);
#endif
__emscripten_fetch_xhr(fetch, cacheResultAndReportSuccess, reportError, reportProgress);
};
// Should we try IndexedDB first?
if (!fetchAttrReplace || requestMethod === 'EM_IDB_STORE' || requestMethod === 'EM_IDB_DELETE') {
if (!Fetch.dbInstance) {
#if FETCH_DEBUG
console.error('fetch: failed to read IndexedDB! Database is not open.');
#endif
reportError(fetch, 0, 'IndexedDB is not open');
return 0; // todo: free
}
if (requestMethod === 'EM_IDB_STORE') {
var dataPtr = HEAPU32[fetch_attr + Fetch.attr_t_offset_requestData >> 2];
var dataLength = HEAPU32[fetch_attr + Fetch.attr_t_offset_requestDataSize >> 2];
var data = HEAPU8.slice(dataPtr, dataPtr + dataLength); // TODO(?): Here we perform a clone of the data, because storing shared typed arrays to IndexedDB does not seem to be allowed.
__emscripten_fetch_cache_data(Fetch.dbInstance, fetch, data, reportSuccess, reportError);
} else if (requestMethod === 'EM_IDB_DELETE') {
__emscripten_fetch_delete_cached_data(Fetch.dbInstance, fetch, reportSuccess, reportError);
} else if (fetchAttrNoDownload) {
__emscripten_fetch_load_cached_data(Fetch.dbInstance, fetch, reportSuccess, reportError);
} else if (fetchAttrPersistFile) {
__emscripten_fetch_load_cached_data(Fetch.dbInstance, fetch, reportSuccess, performCachedXhr);
} else {
__emscripten_fetch_load_cached_data(Fetch.dbInstance, fetch, reportSuccess, performUncachedXhr);
}
} else if (!fetchAttrNoDownload) {
if (fetchAttrPersistFile) {
__emscripten_fetch_xhr(fetch, cacheResultAndReportSuccess, reportError, reportProgress);
} else {
__emscripten_fetch_xhr(fetch, reportSuccess, reportError, reportProgress);
}
} else {
#if FETCH_DEBUG
console.error('fetch: Invalid combination of flags passed.');
#endif
return 0; // todo: free
}
return fetch;
}
Accelerate Your Automation Test Cycles With LambdaTest
Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.