UNPKG

imobile_for_reactnative

Version:

iMobile for ReactNative,是SuperMap iMobile推出的一款基于React-Native框架的移动应用开发工具。基于该开发工具,用户可以使用JavaScript开发语言,开发出在Android和IOS操作系统下运行的原生移动GIS应用,入门门槛低,一次开发,处处运行。

1,656 lines (1,559 loc) 44.7 kB
/** * 云服务相关接口 * * @author yangsl */ import { EmitterSubscription, NativeEventEmitter, NativeModules, Platform } from 'react-native' import RNFetchBlob from 'rn-fetch-blob' import { request } from '../utils' import { QueryParamToStr, SetUrlParams } from './UrlUtils' import * as URL from './url' import { ApplyToGroupParams, CheckGroupApplyParams, CreateGroupResponse, DeleteGroupResourseParams, GetApplyParams, GetGroupApplyParams, GetInviteParams, GroupInfo, GroupMembersParams, GroupType, HttpRequest, HttpResponse, InviteToGroupParams, OnlineData, OnlineRouteAnalyzeParam, POISearchParamOnline, POISearchResultOnline, Person, QuaryGroupMessageParams, QuaryGroupResourseParams, QueryParam, ReplyInviteParams, ResourceDetail, ResourceType, ResultData, ResultDataBase, ShareParams, ShareServiceParams, TOnlineDataType, UrlHeader, } from './types' import { RNFS } from 'imobile_for_reactnative' import { RouteAnalyzeResult } from '../navigation/SNavigation' import { EventConst } from 'imobile_for_reactnative/NativeModule/constains' import { Point2D } from '../data/SData' import { DownloadBeginCallbackResult, DownloadProgressCallbackResult } from 'imobile_for_reactnative/NativeModule/utility/FS.common' const SIPortalService = NativeModules.SIPortalService const SOnlineService = NativeModules.SOnlineService const onlineServiceEvt = new NativeEventEmitter(SOnlineService) const SOnline = NativeModules.SOnline /** * 游客用户 * */ const PROBATION_USER = 'probation_user' /** * 普通用户 * */ const COMMON_USER = 'common_user' /** * iPortal用户 * */ const IPORTAL_COMMON_USER = 'iPortal_common_user' /** * online 日本站点用户 */ const COMMON_USER_JP = 'COMMON_USER_JP' /** 正式用户类型 */ export type TLoginUserType = typeof COMMON_USER | typeof IPORTAL_COMMON_USER | typeof COMMON_USER_JP /** 用户类型,游客 和 正式用户 */ export type TUserType = typeof PROBATION_USER | TLoginUserType /** 用户信息 */ export interface UserInfo { /** * 用户名,用户注册后不可改变 * iportal为注册时使用的字符串 * online为系统分配的数字的字符串,即id */ userName: string, /** 昵称,用户可修改 */ nickname: string, /** 邮箱地址,用户可修改 */ email: string, /** 电话号码,用户可修改 */ phoneNumber: number, /** 密码 */ password?: string, /** 用户类型,详见UserType */ userType: TUserType, /** 用户角色 */ roles?: string[], /** iportal用户所使用的服务器地址 */ serverUrl?: string, /** @deprecated 同userName */ userId?: string, /** @deprecated 是否为邮箱登录 */ isEmail?: string, } /** 用户信息 */ export interface CommonUserInfo { /** 缩略图 */ thumbnail: string | null, /** 拥有者角色数组 eg: ["PORTAL_USER", "NOPASSWORD", "DATA_CENTER"] */ ownRoles: string[], /** 用户角色,同ownRoles */ roles: string[] | null, /** 加入时间 */ joinTime: number | null, /** 所属部门ID */ departmentId: string | null, /** 用户描述 */ description: string, /** 用户类型 "CREATOR" */ type: string, /** */ userGroups: any[], /** 密码 */ password: string | null, /** 电话号码 */ phoneNumber: string, /** */ extendAttrs: any[] | null, /** */ expirationTime: number | null, /** 是否被锁定 */ isLocked: boolean, /** 用户显示昵称 */ nickname: string, /** 用户名 */ name: string, /** 密码问题 */ passwordQuestion: { /** 密码答案 */ pwdAnswer: string | null, /** 密码问题 */ pwdQuestion: string, } | null, /** 用户ID */ id: string | null, /** 密码修改时间 */ passwordLastModified: { /** 日期 */ date: number, /** 日期 */ time: number /** 时 */ hours: number, /** 秒 */ seconds: number, /** 月 */ month: number, /** 年 */ year: number, /** 分 */ minutes: number, } | null, /** 邮箱 */ email: string | null, /** 部门名字 */ departmentNames: string[] | null /** iportal或online用户 */ userType: TLoginUserType, userId: string, } // interface OnlineUserInfo { // userId: string, // nickname: string, // phoneNumber: string, // email: string | null // } // /** online 服务参数 */ // export interface OnlineServiceParams { // /** online云服务地址 */ // url: string, // /** online 单点登录地址 */ // ssoUrl: string, // } // /** iportal 服务参数 */ // export interface IPortalServiceParams { // /** iportal云服务地址 */ // url: string, // } /** 获取数据请求参数 */ export interface RequestDataParams extends HttpRequest { /** 数据所有者的id */ userName?: string, /** 文件名 */ fileName?: string, /** 数据类型,与types相斥 */ type?: TOnlineDataType, /** 数据类型数组,与type相斥 */ types?: TOnlineDataType[], } /** TODO 数据信息 */ export interface DataInfo { /** 最后修改时间 */ lastModfiedTime: number, /** 数据名 */ fileName: string, /** 缩略图 */ thumbnail: string, dataItemServices: any[], dataCheckResult: any, /** 服务发布信息 */ publishInfo: any, authorizeSetting: any[], /** 数据描述 */ description: any, /** 上传数据的用户名 */ userName: string, /** 上传数据的类型 */ type: TOnlineDataType, /** 数据标签 */ tags: string[], coordType: any, /** 数据大小 */ size: number, /** 创建时间 */ createTime: number, /** 服务状态 */ serviceStatus: string //UNPUBLISHED, nickname: string, /** 数据ID */ id: number, /** 服务ID */ serviceId: any, /** 下载次数 */ downloadCount: number, storageId: string, /** 状态 */ status: string, /** 校验码 */ MD5: string, } /** 文件上传/下载回调 */ export interface FileCallBack { /** 开始回调 */ begin?: (res: DownloadBeginCallbackResult) => void; /** 进度回调 */ progress?: (res: DownloadProgressCallbackResult) => void; } /** 私有云服务类型 */ const IPORTAL = 'iportal' /** 云服务类型 */ const ONLINE = 'online' /** 云服务类型 */ export type ServiceType = 'iportal' | 'online' | 'OnlineJP' /** 服务类型 */ let serverType: ServiceType = 'online' /** 服务地址 */ let serverUrl: string = '' /** sso单点登录地址 */ let ssoUrl: string = '' /** 许可地址 */ let licenseUrl: string = '' /** 请求异常结果 */ const HttpResponseException = { succeed: false, } /** 数据请求异常结果 */ const ResultDataException = { total: 0, content: [], } function timeout(sec: number): Promise<'timeout'> { return new Promise(resolve => { setTimeout(() => { resolve('timeout') }, 1000 * sec) }) } /** * 检验是否是URL * @param str 检验的字符串 * @returns */ function isUrl(str: string): boolean { const v = new RegExp('^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$', 'i'); return v.test(str); } /** * 设置服务地址 * * 若有url不为空或者与online服务不相同,且没有ssoUrl则视为使用iPortal服务 * * 若有url为空或者与online服务相同,则视为使用Online服务,会自动补上ssoUrl * * 若有ssoUrl,则视为使用Online服务 * 云服务地址 eg: https://www.supermapol.com/web * @param url 服务地址 * @param ssoUrl 单点登录地址 * @returns 返回是否设置服务成功 */ export function setServerUrl(params: { url: string, ssoUrl?: string, licenseUrl?: string, }): Promise<boolean> { if (params.url && params.url !== URL.ONLINE_URL && !params.ssoUrl) { serverType = IPORTAL serverUrl = params.url ssoUrl = '' return SOnline.setService({ url: params.url }) } else { serverType = ONLINE // 若无许可地址,默认设置为'' if (!params.ssoUrl) { // ssoUrl = URL.SSO_URL ssoUrl = '' } else { ssoUrl = params.ssoUrl } // 若无许可地址,默认设置Online许可地址 if (!params.licenseUrl) { licenseUrl = URL.LICENSE_URL } else { licenseUrl = params.licenseUrl } serverUrl = params.url SOnlineService.init() return SOnline.setService({ url: params.url.replace('/web', ''), ssoUrl, licenseUrl }) } } /** * 获取服务地址 * @returns 返回服务地址 */ export function getServerUrl(): string { return serverUrl } /** * 获取SSO地址 * @returns 返回SSO地址 */ export function getSSOUrl(): string { return ssoUrl } /** * 获取许可地址 * @returns 返回许可地址 */ export function getLicenseUrl(): string { return licenseUrl } /** * 获取服务地址 Android Only * @returns 返回服务地址 */ export async function getCookie(): Promise<string> { if (Platform.OS === 'ios') { return '' } if (serverType === IPORTAL) { return await SIPortalService.getIPortalCookie() } else { return await SOnlineService.getSessionID() } } /** * 移除所有cookies * @description Online Only */ export function removeCookie(): void { SOnlineService.removeCookie() } /*********************************** 用户相关接口 *************************************/ /** * 用户登录 * @param userName 用户名 * @param password 密码 * @returns 返回是否登录成功 */ export async function login(userName: string, password: string): Promise<boolean> { if (userName === undefined || password === undefined) { return false } if (serverType === IPORTAL) { return await SIPortalService.login(serverUrl, userName, password, true) } else { removeCookie() return await SOnlineService.login(userName, password) } } /** * 退出登录 * @returns 返回是否退出登录成功 */ export function logout(): Promise<boolean> { if (serverType === IPORTAL) { return SIPortalService.logout() } else { return SOnlineService.logout() } } /** * 检测连接是否正常 */ export async function checkConnection() { let url = serverUrl + '/login.rjson' if (serverUrl.indexOf('http') !== 0) { url = 'http://' + url } let status = undefined try { const response: any = await Promise.race([ fetch(url), new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('request timeout')) }, 10000) }), ]) status = response.status } catch (error) { // console.log(error) } // iportal: 405, online: 200 return status === 405 || status === 200 } export function _getUserType(): TLoginUserType { switch (serverType) { case 'iportal': return IPORTAL_COMMON_USER // TODO 移除 OnlineJP case 'OnlineJP': return COMMON_USER_JP case 'online': default: return COMMON_USER } } /** * 获取当前登录用户的详细信息 * @returns 返回用户信息 */ export async function getMyAccount(): Promise<CommonUserInfo | null> { try { let url = serverUrl + URL.GetMyAccount[0] let headers = {} const cookie = await getCookie() if (cookie) { headers = { Cookie: cookie, } } url = encodeURI(url) // const response = await RNFetchBlob.config({ trusty: true }).fetch(URL.GetMyAccount[1], url, headers) // let result = await Promise.race([response, timeout(10)]) // if (result === 'timeout') { // return null // } const result = await request(url, URL.GetMyAccount[1], { headers: headers, }) if (result) { return { ...result, userId: result.name, userType: _getUserType(), } } else { return null } // if (result.respInfo.status === 200) { // const info = await result.json() // return { // ...info, // userId: info.name, // userType: _getUserType(), // } // } else { // return null // } } catch { return null } } /** * 根据用户昵称搜索用户 * @param nickname 用户昵称 * @returns 返回用户信息数组 */ export async function searchUser(params: { email: string } | { tel: string } | { nickname: string }): Promise<CommonUserInfo | {userId: string, nickname: string} | null> { try { // if (!nickname) { // throw new Error('nickname not be found') // } let url, method if (getServerUrl() === URL.ONLINE_URL) { url = getServerUrl() + URL.SearchUser[0] + QueryParamToStr(params) method = URL.SearchUser[1] } else { url = getServerUrl() + URL.SearchUserPortal[0] + QueryParamToStr(params) method = URL.SearchUserPortal[1] } url = encodeURI(url) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } const result = await request(url, method, { headers: headers, }) // 若查找失败,返回 // { // "succeed": false, // "error": { // "code": 404, // "errorMsg": "resource is not exist" // } // } if (!result || result.succeed === false || result.code === 400 || result.des !== 'success') { return null } else if (typeof result === 'object'){ return result.data } else { return result } } catch (e) { return null } } /*********************************** 数据相关接口 *************************************/ /** * 查询数据 * @param params 查询数据参数 */ export async function getData(params: RequestDataParams): Promise<ResultDataBase<DataInfo>> { let url = serverUrl + URL.GetData[0] + QueryParamToStr(params) let headers = {} const cookie = await getCookie() if (cookie) { headers = { Cookie: cookie, } } url = encodeURI(url) const result = await request(url, URL.GetData[1], { headers: headers, }) return result } /** * 获取服务器 我的数据 中查找数据 * @param params 查询数据参数 * @returns 返回数据,若没有,则返回null */ export async function getMyData(params: RequestDataParams): Promise<ResultDataBase<DataInfo>> { let url = serverUrl + URL.GetMyAccountData[0] + QueryParamToStr(params) let headers = {} const cookie = await getCookie() if (cookie) { headers = { Cookie: cookie, } } url = encodeURI(url) const result = await request(url, URL.GetMyAccountData[1], { headers: headers, }) return result } /** * 查询数据 * * 为新接口,与getData获取的数据内容不一样 * @param params 查询数据参数 */ export async function getOnlineData(params: RequestDataParams): Promise<ResultDataBase<OnlineData>> { let url = serverUrl + URL.GetOnlineData[0] + QueryParamToStr(params) url = encodeURI(url) const cookie = await getCookie() let headers = {} if (cookie) { headers = { Cookie: cookie, } } const result = await request(url, URL.GetData[1], { headers, }) return result } /** * 删除指定ID的数据 * @param ID 要删除的数据ID * TODO 删除结果验证 * @returns 返回删除结果 */ export async function deleteData(ID: number): Promise<boolean> { let url = SetUrlParams(serverUrl + URL.DeleteData[0], [ID]) url = encodeURI(url) const cookie = await getCookie() let headers = {} if (cookie) { headers = { Cookie: cookie, } } const result = await request(url, URL.DeleteData[1], { headers, }) return result.succeed } /** * 设置数据公开私有 * @param id 数据id * @param isPublic 是否公开 * @returns 返回是否设置成功 */ export async function setDatasShareConfig(id: number, isPublic: boolean): Promise<boolean> { try { let url = serverUrl + URL.ShareData[0] let headers = {} const cookie = await getCookie() if (cookie) { headers = { Cookie: cookie, Accept: 'application/json', 'Content-Type': 'application/json', } } let entities: any[] if (isPublic) { entities = [ { entityType: 'USER', entityName: 'GUEST', dataPermissionType: 'DOWNLOAD', }, ] } else { entities = [] } url = encodeURI(url) const response = await RNFetchBlob.config({ trusty: true }).fetch(URL.ShareData[1], url, headers, JSON.stringify({ ids: [id], entities: entities, })) const result = await response.json() return result.succeed } catch (e) { return false } } /** * 获取云存储空间,上传前先检查下空间是否足够 * @returns 返回可用空间大小和最大空间大小 */ export async function getMyDataCapacity(): Promise<{ usedCapacity: number, maxCapacity: number } | undefined> { try { const url = serverUrl + URL.GetMyDataCapacity[0] let headers = {} const cookie = await getCookie() if (cookie) { headers = { Cookie: cookie, } } const response = RNFetchBlob.config({ trusty: true }).fetch(URL.GetMyDataCapacity[1], url, headers) const result = await Promise.race([response, timeout(10)]) if (result === 'timeout') { return undefined } if (result.respInfo.status === 200) { const info: { usedCapacity: number, maxCapacity: number } = await result.json() return info } else { return undefined } } catch (e) { return undefined } } /** * 根据文件名和类型获取上传id * @param fileName 数据名称 * @param fileType 数据类型 */ async function _getUploadId(fileName: string, fileType: TOnlineDataType): Promise<string> { try { let url = serverUrl + URL.GetMyAccountUploadID[0] let headers = {} let cookie = await getCookie() if (cookie) { headers = { Cookie: cookie, } } url = encodeURI(url) let response = await RNFetchBlob.config({ trusty: true }).fetch(URL.GetMyAccountUploadID[1], url, headers, JSON.stringify({ fileName: fileName, type: fileType, })) let result = await response.json() if (result.childID) { return result.childID } else { return '' } } catch (error) { return '' } } /** * 上传文件 * @param filePath 文件绝对路径 * @param fileType 上传文件到服务器的类型,常用WORKSPACE, PHOTOS, VIDEO, UDB等 * @param fileName 上传后的文件名 * @param callback 上传开始 和 上传中的回调 * @returns 返回上传文件ID则成功,返回0则表示空间不足,返回false则失败 */ export async function uploadFile(filePath: string, fileType: TOnlineDataType, fileName?: string, callback?: FileCallBack): Promise<number | boolean> { try { // 上传文件前检查空间是否足够 const capacity = await getMyDataCapacity() if (capacity) { const stat = await RNFetchBlob.fs.stat(filePath) const isEnough = stat.size + capacity.usedCapacity < capacity.maxCapacity if (!isEnough) { return 0 } } fileName = fileName || filePath.substring(filePath.lastIndexOf('/') + 1) const id = await _getUploadId(fileName, fileType) if (id) { let url = SetUrlParams(serverUrl + URL.UploadData[0], [id]) let headers = {} const cookie = await getCookie() if (cookie) { headers = { Cookie: cookie, } } url = encodeURI(url) const uploadParams = { toUrl: url, headers: headers, files: [ { name: fileName, filename: fileName, filepath: filePath, filetype: '', }, ], background: true, method: URL.UploadData[1], begin: (res: any) => { if (callback && typeof callback.onBegin === 'function') { callback.onBegin(res) } }, progress: (res: any) => { try { if (callback && typeof callback.onProgress === 'function') { const progress = res.totalBytesSent / res.totalBytesExpectedToSend callback.onProgress(progress * 100) } } catch { /*** */ } }, } const result = await RNFS.uploadFiles(uploadParams).promise const body = JSON.parse(result.body) return parseInt(body.childID) } return false } catch (e) { return false } } /** * 更新服务器已有的文件 * @param fileId 要更新的文件在服务器上的ID * @param filePath 文件绝对路径(路径最后的文件名与要更新的文件名保持一致) * @param dataType 上传文件到服务器的类型,常用WORKSPACE, PHOTOS, VIDEO, UDB等 * @param callback 上传开始 和 上传中的回调 * @returns 返回上传文件ID,-1为失败 */ export async function updateFile(fileId: number, filePath: string, dataType: TOnlineDataType, callback?: FileCallBack): Promise<number> { try { // 更新文件前检查空间是否足够 const capacity = await getMyDataCapacity() if (capacity) { const stat = await RNFetchBlob.fs.stat(filePath) const isEnough = stat.size + capacity.usedCapacity < capacity.maxCapacity if (!isEnough) { return -1 } } if (fileId) { const fileName = filePath.substring(filePath.lastIndexOf('/') + 1) let url = SetUrlParams(serverUrl + URL.UpdateData[0], [fileId]) + QueryParamToStr({ fileName, dataType, }) let headers = {} const cookie = await getCookie() if (cookie) { headers = { Cookie: cookie, } } url = encodeURI(url) const uploadParams = { toUrl: url, headers: headers, files: [ { name: fileName, filename: fileName, filepath: filePath, filetype: '', }, ], background: true, method: URL.UpdateData[1], begin: (res: any) => { if (callback && typeof callback.onBegin === 'function') { callback.onBegin(res) } }, progress: (res: any) => { try { if (callback && typeof callback.onProgress === 'function') { const progress = res.totalBytesSent / res.totalBytesExpectedToSend callback.onProgress(progress * 100) } } catch { /*** */ } }, } const result = await RNFS.uploadFiles(uploadParams).promise const body = JSON.parse(result.body) return body.childID } else { return -1 } } catch (error) { return -1 } } /** * 下载文件 * @param from 服务器上文件url或ID * @param toPath 下载到指定位置,完整路径(含文件名和后缀) * @param callback 文件下载开始 和 下载中 的回调 * @returns 返回下载结果,失败返回null */ export async function downloadFile(from: string, toPath: string, callback?: FileCallBack): Promise<RNFS.DownloadResult | null> { try { let url = '' if (isUrl(from)) { url = encodeURI(from) } else { url = SetUrlParams(serverUrl + URL.downloadData[0], [from]) } const downloadOptions: RNFS.DownloadFileOptions = { ...Platform.select({ android: { headers: { Cookie: await getCookie() || '', }, }, }), fromUrl: url, toFile: toPath || '', background: true, ...callback, } const result = RNFS.downloadFile(downloadOptions).promise return result } catch (e) { return null } } /*********************************** 群组相关接口 *************************************/ /** * 获取所有群组 * @param params 查询参数 * @returns 返回数据结果 */ export async function getGroupInfos(params: QueryParam): Promise<ResultData> { try { const url = getServerUrl() + URL.GetGroup[0] + QueryParamToStr(params) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } const result = await request(url, URL.GetGroup[1], { headers: headers, body: {}, }) return result } catch (e) { return ResultDataException } } /** * 获取我的群组 * @param params 查询参数 * @returns 返回数据结果 */ export async function getMyGroupInfos(params: QueryParam): Promise<ResultData> { try { const url = getServerUrl() + URL.GetMyGroup[0] + QueryParamToStr(params) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } const result = await request(url, URL.GetMyGroup[1], { headers: headers, body: {}, }) return result } catch (error) { return ResultDataException } } /** * 获取我的群组 * @param id 群组ID * @returns 返回群组成员,群组资源,群组信息 */ export async function getGroupInfo(id: number): Promise<{ groupMembers: ResultDataBase<Person>, groupResources: ResultDataBase<any>, basicInfo: GroupType, } | null> { try { const url = SetUrlParams(getServerUrl() + URL.GetGroupInfo[0], [id]) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } const result = await request(url, URL.GetGroupInfo[1], { headers: headers, body: {}, }) return result } catch (error) { return null } } /** * 创建群组 * @param params 创建群组信息 * @returns 返回创建结果 */ export async function createGroup(params: GroupInfo): Promise<CreateGroupResponse> { try { const url = getServerUrl() + URL.CreateGroup[0] const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.CreateGroup[1], { headers: headers, body: params, }) } catch (e) { return HttpResponseException } } /** * 修改群组信息 * @param params 修改群组信息 * @returns 返回修改结果 */ export async function modifyGroup(params: GroupInfo): Promise<CreateGroupResponse> { try { const url = SetUrlParams(getServerUrl() + URL.ModifyGroup[0], [params.id + '']) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.ModifyGroup[1], { headers: headers, body: params, }) } catch (e) { return HttpResponseException } } /** * 解散群组 * @param params 解散群组的ID数组 * @returns 返回解散结果 */ export async function deleteGroup(params: Array<number>): Promise<HttpResponse> { try { const _params = { ids: params, } const url = getServerUrl() + URL.DeleteGroup[0] + QueryParamToStr(_params) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.DeleteGroup[1], { headers: headers, body: params, }) } catch (e) { return HttpResponseException } } /** * 退出群组 * @param params 退出群组的ID数组 * @returns 返回退出结果 */ export async function existGroup(params: Array<number>): Promise<HttpResponse> { try { const _params = { ids: params, } const url = getServerUrl() + URL.DeleteGroup[0] + QueryParamToStr(_params) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.DeleteGroup[1], { headers: headers, body: params, }) } catch (e) { return HttpResponseException } } /** * 邀请加入群组 * @param params 邀请加入群组的信息 * @returns 返回邀请结果 */ export async function inviteToGroup(params: InviteToGroupParams): Promise<HttpResponse> { try { if (!params.groupId) { throw new Error('groupId not be found') } const url = SetUrlParams(getServerUrl() + URL.InviteToGroup[0], [params.groupId]) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.InviteToGroup[1], { headers: headers, body: params, }) } catch (e) { return HttpResponseException } } /** * 申请加入群组 * @param params 申请加入群组的信息 * @returns 返回申请结果 */ export async function applyToGroup(params: ApplyToGroupParams): Promise<HttpResponse> { try { if (!params.groupIds || params.groupIds.length === 0) { throw new Error('groupIds not be found') } const url = getServerUrl() + URL.ApplyToGroup[0] const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.ApplyToGroup[1], { headers: headers, body: params, }) } catch (e) { return HttpResponseException } } /** * 获取当前群组中的申请列表信息。包括申请的,审核过的,有权限审核的。 * @param params 群组查询信息 * @returns 返回申请列表信息 */ export async function getGroupApply(params: GetGroupApplyParams): Promise<ResultData> { try { if (!params.groupId) { throw new Error('groupId not be found') } const url = SetUrlParams(getServerUrl() + URL.GetGroupApply[0] + QueryParamToStr(params), [params.groupId]) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.GetGroupApply[1], { headers: headers, }) } catch (e) { return ResultDataException } } /** * 获取我的群组授权/申请 * @param params 群组查询信息 * @returns 返回群组授权/申请信息 */ export async function getApply(params: GetApplyParams): Promise<ResultData> { try { const url = getServerUrl() + URL.GetApply[0] + QueryParamToStr(params) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.GetApply[1], { headers: headers, }) } catch (e) { return ResultDataException } } /** * 获取邀请消息 * @param params 群组查询信息 * @returns 返回群组授权/申请信息 */ export async function getInvite(params: GetInviteParams): Promise<HttpResponse> { try { const url = getServerUrl() + URL.GetInvite[0] + QueryParamToStr(params) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.GetInvite[1], { headers: headers, }) } catch (e) { return HttpResponseException } } /** * 回复邀请消息 * @param params 回复成员和信息 * @returns 返回回复结果 */ export async function replyInvite(params: ReplyInviteParams): Promise<HttpResponse> { try { const url = getServerUrl() + URL.PutInvite[0] const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.PutInvite[1], { headers: headers, body: params, }) } catch (e) { return HttpResponseException } } /** * 批量审核当前群组中的申请,支持根据申请 id 审核指定的申请。 * @param params 审核入群申请信息 * @returns 返回审核结果 */ export async function checkGroupApply(params: CheckGroupApplyParams): Promise<HttpResponse> { try { if (!params.groupId) { throw new Error('groupId not be found') } if (!params.userIds || params.userIds.length === 0) { throw new Error('userIds not be found') } const _params = { ids: params.userIds, checkInfo: 'REFUSED', checkStatus: 'REFUSED', } if (params.isAccepted) { _params.checkInfo = 'ACCEPTED' _params.checkStatus = 'ACCEPTED' } const url = SetUrlParams(getServerUrl() + URL.CheckGroupApply[0], [params.groupId]) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.CheckGroupApply[1], { headers: headers, body: _params, }) } catch (e) { return HttpResponseException } } /** * 获取组员 * @param params 获取组员信息 * @returns 返回审核结果 */ export async function getGroupMembers(params: GroupMembersParams): Promise<ResultData> { try { if (!params.groupId) { throw new Error('groupId not be found') } const url = SetUrlParams(getServerUrl() + URL.GetGroupMembers[0] + QueryParamToStr(params), [params.groupId]) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.GetGroupMembers[1], { headers: headers, }) } catch (e) { return ResultDataException } } /** * 批量删除组员 * @param params 删除组员信息 * @returns 返回删除结果 */ export async function deleteGroupMembers(params: GroupMembersParams): Promise<HttpResponse> { try { if (!params.groupId) { throw new Error('groupId not be found') } if (!params.userIds || params.userIds.length === 0) { throw new Error('userIds not be found') } const _params = { userNames: params.userIds, } const url = SetUrlParams(getServerUrl() + URL.DeleteGroupMembers[0] + QueryParamToStr(_params), [params.groupId]) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.DeleteGroupMembers[1], { headers: headers, }) } catch (e) { return HttpResponseException } } /** * 分享数据到群组 * @param params 分享数据信息 * @returns 返回分享结果 */ export async function shareDataToGroup(params: ShareParams): Promise<HttpResponse> { try { if (!params.groupId) { throw new Error('groupId not be found') } if (!params.ids || params.ids.length === 0) { throw new Error('ids not be found') } const _params = { ids: params.ids, entities: [{ entityId: params.groupId, entityType: 'IPORTALGROUP', dataPermissionType: 'DOWNLOAD', }], } const url = getServerUrl() + URL.ShareData[0] const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.ShareData[1], { headers: headers, body: _params, }) } catch (e) { return HttpResponseException } } /** * 分享服务到群组 * @param params 分享服务信息 * @returns 返回分享结果 */ export async function shareServiceToGroup(params: ShareServiceParams): Promise<HttpResponse> { try { if (params.ids.length === 0) { throw new Error('ids not be found') } const url = getServerUrl() + URL.ShareService[0] const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.ShareService[1], { headers: headers, body: params, }) } catch (e) { return HttpResponseException } } /** * 查看群组的数据资源 * @param params 查询群组资源参数 * @returns 返回群组资源 */ export async function getGroupResources(params: QuaryGroupResourseParams): Promise<ResultDataBase<ResourceType>> { try { if (!params.groupId) { throw new Error('groupId not be found') } let _params: Partial<QuaryGroupResourseParams> if (!params.groupResourceType) { _params = Object.assign({ groupResourceType: "DATA" }, params) } else { _params = Object.assign({}, params) } _params.groupId && delete _params.groupId const url = SetUrlParams(getServerUrl() + URL.GetGroupResources[0] + QueryParamToStr(_params), [params.groupId]) + `&t=${new Date().getTime()}` const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.GetGroupResources[1], { headers: headers, }) } catch (e) { return ResultDataException } } /** * 获取资源详情 * @param id 资源ID * @returns 返回资源信息,若查询失败,返回null */ export async function getResourceDetail(id: string): Promise<ResourceDetail | null> { try { if (!id) { throw new Error('id not be found') } const url = SetUrlParams(getServerUrl() + URL.DataDetail[0], [id]) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.DataDetail[1], { headers: headers, }) } catch (e) { return null } } /** * 删除群组的数据资源 * @param params 群组ID,资源IDs,数据类型参数 * @returns 返回删除群组的数据资源结果 */ export async function deleteGroupResources(params: DeleteGroupResourseParams): Promise<HttpResponse> { try { if (!params.resourceIds) { throw new Error('groupId not be found') } let _params: Partial<DeleteGroupResourseParams> if (!params.groupResourceType) { _params = Object.assign({ groupResourceType: "DATA" }, params) } else { _params = Object.assign({}, params) } _params.groupId && delete _params.groupId const _url = getServerUrl() + URL.DeleteGroupResources[0] + `?deleteResourceSetting=${JSON.stringify(_params)}` + `&t=${new Date().getTime()}` const url = SetUrlParams(_url, [params.groupId]) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.DeleteGroupResources[1], { headers: headers, }) } catch (e) { return HttpResponseException } } /** * 查询用户消息 * @param params 查询参数 * @returns 返回删除群组的数据资源结果 */ export async function getGroupMessage(params: QuaryGroupMessageParams): Promise<Array<ResultData>> { try { const url = getServerUrl() + URL.GetMessage[0] + QueryParamToStr(params) const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.GetMessage[1], { headers: headers, }) } catch (e) { return [] } } /** * 获取共享群组信息 * @param params * @returns 返回共享群组数组 */ export async function getShareGroups(params?: HttpRequest): Promise<ResultData[]> { try { const url = getServerUrl() + URL.ShareGroups[0] + (params ? QueryParamToStr(params) : '') const headers: UrlHeader = {} const cookie = await getCookie() if (cookie) { headers.cookie = cookie } return request(url, URL.ShareGroups[1], { headers: headers, }) } catch (e) { return [] } } /*********************************** online 公共服务api *************************************/ /** * poi 在线搜索 * Online Only * @param params 参数 * @returns 返回搜索结果,失败返回null */ export async function searchPoi(params: POISearchParamOnline): Promise<POISearchResultOnline | null> { try { let url = 'https://www.supermapol.com/iserver/services/localsearch/rest/searchdatas/China/poiinfos.json' url += QueryParamToStr(params) + '&key=tY5A7zRBvPY0fTHDmKkDjjlr' const response = await fetch(url) if (response.status === 200) { const result = await response.json() if ('error' in result) { // AppLog.error(result) return null } else { return result } } return null } catch (e) { // AppLog.error(e) return null } } /** * 在线路径分析 * Online Only * @param params 在线路径分析参数 * @returns 返回分析结果,失败返回null */ export async function routeAnalyze(params: OnlineRouteAnalyzeParam): Promise<RouteAnalyzeResult | null> { try { let url = 'https://www.supermapol.com/iserver/services/navigation/rest/navigationanalyst/China/pathanalystresults.json' url += QueryParamToStr({ pathAnalystParameters: [params] }) + '&key=fvV2osxwuZWlY0wJb8FEb2i5' const response = await fetch(url) if (response.status === 200) { const result = await response.json() if ('error' in result) { // AppLog.error(result) return null } else if (result.length > 0) { return result[0] } else { return null } } return null } catch (e) { // AppLog.error(e) return null } } let reverseGeocodingListener: EmitterSubscription | null | undefined /** * 根据坐标查询位置名称 * Online Only * @param point 经纬度坐标 * @param handler 查询结果回调 * @returns 返回方法是否调用成功 */ export function reverseGeocoding (point: Point2D, handler: { onResult: (result: string) => void, }) { reverseGeocodingListener && reverseGeocodingListener.remove() if (typeof handler.onResult === 'function' && handler) { reverseGeocodingListener = onlineServiceEvt.addListener(EventConst.ONLINE_SERVICE_REVERSEGEOCODING, function (result) { handler.onResult(result) }) } return SOnlineService.reverseGeocoding(point.x, point.y) } /** * 同步Android cookie * Online Only, 仅支持android * @returns 返回是否同步成功 * @deprecated 待销毁,暂无替代 */ export async function _syncAndroidCookie(): Promise<boolean> { if (Platform.OS === 'android') { return SOnlineService.syncCookie('https://www.supermapol.com/') } return true } /** * 带参数的登录 * Online Only * @param url 服务器url * @param cookie 登录cookie * @param params 参数json字符串 * *params = { loginType: '', username: userName, password: password, lt: $('input[name=lt]').attr()?.value, execution: $('input[name=execution]').attr()?.value, _eventId: $('input[name=_eventId]').attr()?.value, // submit: '登录', } * @returns 返回是否登录成功 * @deprecated 待销毁,暂无替代 */ export function _loginWithParam (url: string, cookie: string | undefined, params: string): Promise<boolean> { if(Platform.OS === 'android') { if(!cookie) { cookie = '' } return SOnlineService.loginWithParam(url, cookie, params) } else { return SOnlineService.loginWithParam(url, params) } }