wps.js 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188
  1. let wpsModule = {
  2. version: '2023.0427.01',
  3. createInstance(options) {
  4. var forWindowID = !!window.forWindowID
  5. ? window.forWindowID
  6. : (window.forWindowID = CreateRandomId())
  7. let wpsobj = {
  8. $$idx: {}, //对象属性
  9. slCtl: {
  10. SupportFormat: [
  11. 'wps', //wps word
  12. 'wpt',
  13. 'doc',
  14. 'docx',
  15. 'dotx',
  16. 'docm',
  17. 'dotm',
  18. 'et', //wps excel
  19. 'ett',
  20. 'xls',
  21. 'xlt',
  22. 'xlsx',
  23. 'xlsm',
  24. 'xltx',
  25. 'xltm',
  26. 'xlsb',
  27. ],
  28. forWindowID,
  29. curFileType: 'default',
  30. isFileOpen: false,
  31. isWPSInstall: false,
  32. isWPSAddonInstall: false,
  33. refurl: '',
  34. publishIndex: 0,
  35. uploadCompentInfoUrl: 'api/framework/v1/indidocx/saveIndidocxMessage',
  36. curList: [
  37. {
  38. name: 'IndiDocX',
  39. addonType: 'wps',
  40. online: 'true',
  41. url: window.location.origin + '/resource/jsplugindir/',
  42. },
  43. {
  44. name: 'IndiDocXET',
  45. addonType: 'et',
  46. online: 'true',
  47. url: window.location.origin + '/resource/jsetplugindir/',
  48. },
  49. ],
  50. localList: [],
  51. ErrorMessage: { NotSupport: 'FormatNotSupport' },
  52. checkInstall: function (argsobj) {
  53. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  54. if (window.sessionStorage && sessionStorage.getItem('isWPSAddonInstall') == 'true') {
  55. wpsobj.slCtl.isWPSAddonInstall = true
  56. startNotice()
  57. return Promise.resolve(true)
  58. }
  59. wpsobj.slCtl.curList[0].url = argsobj.WPSPluginUrl
  60. var promise = new Promise((resolve, reject) => {
  61. wpsobj.slCtl.Content.Control._inithttpCompleted = function (o) {
  62. if (wpsobj.slCtl.isWPSAddonInstall == true) {
  63. if (window.sessionStorage) sessionStorage.setItem('isWPSAddonInstall', 'true')
  64. resolve(true)
  65. } else {
  66. reject(false)
  67. }
  68. if (wpsobj.slCtl.isWPSInstall == false) {
  69. reject(false)
  70. }
  71. }
  72. wpsobj.slCtl.checkWPSInstall(5, 2000)
  73. })
  74. return promise
  75. },
  76. checkWPSInstall: function (tryCount, timeout) {
  77. var xmlReq = new createXHR()
  78. var url = 'http://127.0.0.1:58890/version'
  79. if (window.location.protocol != 'http:') url = 'https://127.0.0.1:58891/version'
  80. xmlReq.open('POST', url)
  81. xmlReq.onload = function (res) {
  82. wpsobj.slCtl.isWPSInstall = true
  83. wpsobj.slCtl.isWPSAddonInstall = false
  84. wpsobj.slCtl.CheckWPSAddonInstall(2000)
  85. //setTimeout(function () {}, 1000);
  86. }
  87. xmlReq.ontimeout = xmlReq.onerror = function (res) {
  88. if (tryCount == 1) {
  89. wpsobj.slCtl.isWPSInstall = false
  90. wpsobj.slCtl.Content.Control._inithttpCompleted(false)
  91. return
  92. }
  93. window.location.href = 'ksoWPSCloudSvr://start=RelayHttpServer'
  94. setTimeout(function () {
  95. wpsobj.slCtl.checkWPSInstall(--tryCount, 2000)
  96. }, 2000)
  97. }
  98. if (timeout == undefined) {
  99. timeout = 2000
  100. }
  101. xmlReq.timeout = timeout
  102. xmlReq.send()
  103. },
  104. CheckWPSAddonInstall: function (timeout) {
  105. var localList = []
  106. WpsAddonMgr.getAllConfig(function (e) {
  107. var elementStr = e.response
  108. if (elementStr) {
  109. localList = localList.concat(JSON.parse(elementStr))
  110. if (localList[0] != null) {
  111. for (var i = 0; i < localList.length; i++) {
  112. if (
  113. localList[i].name == 'IndiDocX' &&
  114. //localList[i].url.indexOf(location.origin) > -1 &&
  115. (localList[i].enable == 'true' || localList[i].enable == 'enable_dev')
  116. ) {
  117. wpsobj.slCtl.isWPSAddonInstall = true
  118. startNotice()
  119. wpsobj.slCtl._uploadCompentInfo(localList[i])
  120. }
  121. if (
  122. localList[i].name == 'IndiDocXET' &&
  123. // localList[i].url.indexOf(location.origin) > -1 &&
  124. (localList[i].enable == 'true' || localList[i].enable == 'enable_dev')
  125. ) {
  126. wpsobj.slCtl.isWPSAddonInstall = true
  127. }
  128. }
  129. } else {
  130. console.log('准备安装加载项')
  131. wpsobj.slCtl.isWPSAddonInstall = false
  132. wpsobj.slCtl.installWpsAddin()
  133. }
  134. }
  135. if (timeout == undefined) {
  136. timeout = 2000
  137. }
  138. setTimeout(wpsobj.slCtl.Content.Control._inithttpCompleted, timeout)
  139. })
  140. },
  141. installWpsAddin: function () {
  142. WpsAddonMgr.getAllConfig(function (e) {
  143. if (wpsobj.slCtl.curList.length > 0) {
  144. wpsobj.slCtl.installWpsAddinOne()
  145. }
  146. })
  147. },
  148. installWpsAddinOne: function () {
  149. WpsAddonMgr.enable(wpsobj.slCtl.curList[wpsobj.slCtl.publishIndex], function (e) {
  150. if (e.status) {
  151. console.log(e.msg)
  152. } else {
  153. wpsobj.slCtl.Content.Control._inithttpCompleted(true)
  154. console.log('安装成功')
  155. }
  156. wpsobj.slCtl.publishIndex++
  157. if (wpsobj.slCtl.publishIndex < wpsobj.slCtl.curList.length) {
  158. wpsobj.slCtl.installWpsAddinOne()
  159. }
  160. })
  161. },
  162. isSupport(fname) {
  163. var ext = fname.match(/\.(?<ext>\w*)$/i).groups.ext
  164. return this.SupportFormat.some((x) => ext == x)
  165. },
  166. InstallWPSAddon: function (callBack) {
  167. var localList = []
  168. WpsAddonMgr.getAllConfig(function (e) {
  169. var elementStr = e.response
  170. if (elementStr) {
  171. localList = localList.concat(JSON.parse(elementStr))
  172. for (var i = 0; i < localList.length; i++) {
  173. if (localList[i].name == 'IndiDocX' && localList[i].enable == 'false') {
  174. WpsAddonMgr.enable(localList[i], callBack)
  175. }
  176. if (localList[i].name == 'IndiDocXET' && localList[i].enable == 'false') {
  177. WpsAddonMgr.enable(localList[i], callBack)
  178. }
  179. }
  180. }
  181. })
  182. },
  183. launchBrowser: function (url, type) {
  184. return new Promise(function (resolve, reject) {
  185. _WpsInvokeExtends(
  186. 'command',
  187. { name: 'launchBrowser', data: { url, type } },
  188. function (rps) {
  189. if (rps.status == 0) {
  190. var result = JSON.parse(rps.response)
  191. resolve(result)
  192. } else {
  193. reject()
  194. }
  195. },
  196. true,
  197. 4e4
  198. )
  199. })
  200. },
  201. getRef: function (str, start, substr, seperator) {
  202. var pos
  203. var endpos
  204. pos = str.indexOf(substr, start)
  205. if (pos == -1) return ''
  206. endpos = str.indexOf(seperator, pos + 1)
  207. if (endpos == -1) return str.substring(pos + substr.length, str.length)
  208. else return str.substring(pos + substr.length, endpos)
  209. },
  210. htmldecode: function (s) {
  211. return s;
  212. // var div = document.createElement('div')
  213. // div.innerHTML = s
  214. // return div.textContent
  215. },
  216. setFileList: function (data) {
  217. var strlist = new Array()
  218. for (var i = 0; i < data.length; i++) {
  219. strlist.push(
  220. data[i].properties +
  221. '<FileServerUrl>' +
  222. fnGetFileLink(data[i].code) +
  223. '</FileServerUrl>'
  224. )
  225. }
  226. if (strlist != null && strlist != undefined) {
  227. wpsobj.slCtl.Content.Files._FileInfoString = strlist
  228. wpsobj.slCtl.Content.Files.FileList = wpsobj.slCtl.analyzeFileList(strlist) //解析filelist
  229. }
  230. },
  231. analyzeFileList: function (FileInfoString) {
  232. var arrFileMap = FileInfoString.map(function (onefile, index) {
  233. var filelink = ''
  234. if (typeof fnGetFileLink === 'function') {
  235. filelink = fnGetFileLink(
  236. wpsobj.slCtl.getRef(onefile, 0, '<file_unid>', '</file_unid>')
  237. )
  238. }
  239. return {
  240. FileName: wpsobj.slCtl.htmldecode(
  241. wpsobj.slCtl.getRef(onefile, 0, '<file_name>', '</file_name>')
  242. ),
  243. Unid: wpsobj.slCtl.getRef(onefile, 0, '<file_unid>', '</file_unid>'),
  244. CatNum: wpsobj.slCtl.getRef(onefile, 0, '<CatNum>', '</CatNum>'),
  245. Size: wpsobj.slCtl.getRef(onefile, 0, '<file_size>', '</file_size>'),
  246. FileType: wpsobj.slCtl.getRef(onefile, 0, '<filetype>', '</filetype>'),
  247. Completed: parseInt(wpsobj.slCtl.getRef(onefile, 0, '<completed>', '</completed>')),
  248. doAdd:
  249. wpsobj.slCtl.getRef(onefile, 0, '<doAdd>', '</doAdd>') == 'True' ? true : false,
  250. Type: wpsobj.slCtl.getFileType(
  251. wpsobj.slCtl.getRef(onefile, 0, '<file_name>', '</file_name>')
  252. ),
  253. CreateInfo: wpsobj.slCtl.getRef(onefile, 0, '<CreateInfo>', '</CreateInfo>'),
  254. UpdateInfo: wpsobj.slCtl.getRef(onefile, 0, '<UpdateInfo>', '</UpdateInfo>'),
  255. TaodaInfo: wpsobj.slCtl.getRef(onefile, 0, '<TaodaInfo>', '</TaodaInfo>'),
  256. NeedUpdate: wpsobj.slCtl.getRef(onefile, 0, '<NeedUpdate>', '</NeedUpdate>'),
  257. AllowPrint: false,
  258. DocUnid: wpsobj.slCtl.getRef(onefile, 0, '<doc_unid>', '</doc_unid>'),
  259. Uploading:
  260. parseInt(wpsobj.slCtl.getRef(onefile, 0, '<completed>', '</completed>')) == 0 &&
  261. wpsobj.slCtl.getRef(onefile, 0, '<doAdd>', '</doAdd>') == 'False'
  262. ? true
  263. : false,
  264. Link: filelink,
  265. }
  266. })
  267. return arrFileMap
  268. },
  269. formatParams: function (argsobj) {
  270. var $$idxtemp = {}
  271. $$idxtemp.httpserver = {}
  272. $$idxtemp.httpserver.UserName = argsobj.UserName == undefined ? 'admin' : argsobj.UserName
  273. $$idxtemp.httpserver.UploadParam =
  274. argsobj.UploadParam == undefined ? '' : argsobj.UploadParam
  275. $$idxtemp.httpserver.UploadUrl = argsobj.UploadUrl == undefined ? '' : argsobj.UploadUrl
  276. $$idxtemp.httpserver.cookie = argsobj.cookie == undefined ? '' : argsobj.cookie
  277. $$idxtemp.httpserver.refresh_token =
  278. argsobj.refresh_token == undefined ? '' : argsobj.refresh_token
  279. return $$idxtemp
  280. },
  281. //参数规范化
  282. fileParamsNormalized: function (fileparam) {
  283. var result = Object.assign({}, fileparam);
  284. if (fileparam.hasOwnProperty('IsMaximization'))
  285. result.IsMaximization = getBoolean(fileparam.IsMaximization, true);
  286. return result;
  287. },
  288. // V6控件打开附件
  289. fnV6OpenFile: function (fname, fileparam) {
  290. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  291. var promise = new Promise((resolve, reject) => {
  292. if (!wpsobj.slCtl.isSupport(fname)) {
  293. reject(wpsobj.slCtl.ErrorMessage.NotSupport)
  294. return
  295. }
  296. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  297. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  298. if (userfile == null) {
  299. userfile = {}
  300. userfile.Unid = fname
  301. usefileinfostring = fname
  302. userfile.Link = fileparam.FileServerUrl
  303. }
  304. registerEvent(userfile, resolve)
  305. if (
  306. wpsobj.slCtl.getFileType(fname).toLocaleLowerCase() == '.xls' ||
  307. wpsobj.slCtl.getFileType(fname).toLocaleLowerCase() == '.xlsx' ||
  308. wpsobj.slCtl.getFileType(fname).toLocaleLowerCase() == '.et'
  309. ) {
  310. _WpsInvokeET(
  311. [
  312. {
  313. OpenDoc: {
  314. uploadPath: wpsobj.slCtl.$$idx.httpserver.UploadUrl, // 保存文档上传路径
  315. cookie: wpsobj.slCtl.Base64.encode(
  316. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  317. ),
  318. refresh_token: wpsobj.slCtl.Base64.encode(
  319. wpsobj.slCtl.$$idx.httpserver.refresh_token
  320. ),
  321. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  322. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  323. fileName: userfile.Link,
  324. fileparam: fileparam,
  325. uploadFieldName: 'file',
  326. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  327. openType: {
  328. //文档打开方式
  329. // 文档保护类型,-1:不启用保护模式,0:只允许对现有内容进行修订,
  330. // 1:只允许添加批注,2:只允许修改窗体域(禁止拷贝功能),3:只读
  331. protectType: Number.parseInt(fileparam.Status),
  332. },
  333. },
  334. },
  335. ],
  336. reject
  337. )
  338. } else {
  339. var protectType = Number.parseInt(fileparam.Status)
  340. if (protectType == 4) protectType = 1
  341. _WpsInvoke(
  342. [
  343. {
  344. OpenDoc: {
  345. uploadPath: wpsobj.slCtl.$$idx.httpserver.UploadUrl, // 保存文档上传路径
  346. cookie: wpsobj.slCtl.Base64.encode(
  347. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  348. ),
  349. refresh_token: wpsobj.slCtl.Base64.encode(
  350. wpsobj.slCtl.$$idx.httpserver.refresh_token
  351. ),
  352. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  353. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  354. fileName: userfile.Link,
  355. fileparam: fileparam,
  356. uploadFieldName: 'file',
  357. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  358. openType: {
  359. //文档打开方式
  360. // 文档保护类型,-1:不启用保护模式,0:只允许对现有内容进行修订,
  361. // 1:只允许添加批注,2:只允许修改窗体域(禁止拷贝功能),3:只读
  362. protectType,
  363. },
  364. },
  365. },
  366. ],
  367. reject
  368. )
  369. }
  370. }).catch(function (reason) {
  371. wpsobj.slCtl.isFileOpen = false
  372. return Promise.reject(reason)
  373. })
  374. return promise
  375. },
  376. CreateTrackFileName: function (sourcename) {
  377. var count = 1
  378. var tmp = null
  379. var files = wpsobj.slCtl.Content.Files
  380. for (var i = 0; i < files.FileList.length; i++) {
  381. var userFile = files.FileList[i]
  382. var filename = userFile.FileName
  383. if (filename.indexOf('痕迹稿') != -1 && filename.indexOf('_' + sourcename) != -1) {
  384. count++
  385. }
  386. }
  387. tmp = '痕迹稿' + count + '_' + sourcename //痕迹1_正文.doc
  388. return tmp
  389. },
  390. /**
  391. * 获取用户信息的扩展接口,如果项目需要,可以自行覆盖实现方法
  392. * 默认是基于产品的实现
  393. * @returns Object{id,account,name,access_token}
  394. */
  395. getUserInfo: function () {
  396. var state = JSON.parse(sessionStorage.getItem('vuex'))
  397. // var userinfo = state?.sd?.common?.userInfo?.default || {}
  398. if (!!state && !!state.sd.login && state.sd.login.tokens) {
  399. var info = {}
  400. info.access_token = state.sd.login.tokens.access_token
  401. if (
  402. !!state.sd.common &&
  403. !!state.sd.common.userInfo &&
  404. !!state.sd.common.userInfo.default
  405. ) {
  406. var dft = state.sd.common.userInfo.default
  407. info.id = dft.id
  408. info.account = dft.account
  409. info.name = dft.name
  410. return info
  411. } else return undefined
  412. }
  413. return undefined
  414. },
  415. _uploadCompentInfo: function (serverinfo) {
  416. var userinfo = wpsobj.slCtl.getUserInfo()
  417. if (userinfo === undefined) return
  418. var data = {
  419. userId: userinfo.id,
  420. userAccount: userinfo.account,
  421. userName: userinfo.name,
  422. updateDate: Date.now(), //当前日期的毫秒值
  423. controlType: 'wps加载项',
  424. // browsername: navigator.userAgent,
  425. // equipmentName: serverinfo.HostName,
  426. indidocxVersion: serverinfo.version, //inididoc版本
  427. }
  428. var ajax = createXHR()
  429. ajax.open('POST', wpsobj.slCtl.uploadCompentInfoUrl)
  430. ajax.onreadystatechange = function () {
  431. if (ajax.readyState == 4 && ajax.status == 200) {
  432. console.log('上传组件信息成功')
  433. }
  434. }
  435. ajax.setRequestHeader('Cache-Control', 'no-cache')
  436. ajax.setRequestHeader('Content-type', 'application/json;charset=utf-8')
  437. ajax.setRequestHeader('Authorization', userinfo.access_token)
  438. ajax.send(JSON.stringify(data))
  439. },
  440. _download:function(url,fname){
  441. return new Promise(function(resolve,reject){
  442. var ajax = createXHR();
  443. ajax.onload=function(){
  444. if(ajax.status == 200)
  445. resolve(ajax.response);
  446. else reject()
  447. };
  448. ajax.onerror=function(){
  449. reject()
  450. }
  451. ajax.responseType = "blob";
  452. var userinfo=wpsobj.slCtl.getUserInfo()||{};
  453. ajax.open('GET',url);
  454. ajax.setRequestHeader('Authorization', userinfo.access_token)
  455. ajax.send();
  456. }).then(function(data){
  457. if ('msSaveOrOpenBlob' in window.navigator) {
  458. // 兼容IE
  459. window.navigator.msSaveOrOpenBlob(data, fname)
  460. return
  461. }
  462. const blobUrl = URL.createObjectURL(data)
  463. const a = document.createElement('a')
  464. a.href = blobUrl
  465. a.download = fname
  466. // 不用a.click()因为52的firefox不允许
  467. var evt = document.createEvent('MouseEvents')
  468. evt.initEvent('click', true, true)
  469. a.dispatchEvent(evt)
  470. URL.revokeObjectURL(blobUrl)
  471. })
  472. },
  473. Content: {
  474. Files: {
  475. FileList: [],
  476. _FileInfoString: [],
  477. },
  478. Control: {
  479. //页面打印回调
  480. _PrintDocumented: function (o) { },
  481. _inithttpCompleted: function (o) { },
  482. getFileByName: function (fname) {
  483. var userfile = null
  484. wpsobj.slCtl.Content.Files.FileList.map(function (onefile, index) {
  485. if (onefile.Unid == fname || onefile.FileName == fname) {
  486. userfile = onefile
  487. }
  488. })
  489. return userfile
  490. },
  491. getFileByUnid: function (fname) {
  492. return wpsobj.slCtl.Content.Control.getFileByName(fname)
  493. },
  494. _getFileInfoByName: function (fname) {
  495. var usefileinfostring = null
  496. wpsobj.slCtl.Content.Files._FileInfoString.map(function (onefile, index) {
  497. if (
  498. wpsobj.slCtl.getRef(onefile, 0, '<file_unid>', '</file_unid>') == fname ||
  499. wpsobj.slCtl.htmldecode(
  500. wpsobj.slCtl.getRef(onefile, 0, '<file_name>', '</file_name>')
  501. ) == fname
  502. ) {
  503. usefileinfostring = onefile
  504. }
  505. })
  506. return usefileinfostring
  507. },
  508. //编辑
  509. EditFile: function (fname, fileparam, argsobj) {
  510. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  511. return wpsobj.slCtl.fnV6OpenFile(fname, fileparam)
  512. },
  513. //清稿
  514. QingGao: function (fname, fileparam, argsobj) {
  515. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  516. var promise = new Promise((resolve, reject) => {
  517. if (!wpsobj.slCtl.isSupport(fname)) {
  518. reject(wpsobj.slCtl.ErrorMessage.NotSupport)
  519. return
  520. }
  521. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  522. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  523. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  524. if (userfile == null) {
  525. userfile = {}
  526. userfile.Unid = fname
  527. usefileinfostring = fname
  528. userfile.Link = fileparam.FileServerUrl
  529. }
  530. registerEvent(userfile, resolve)
  531. _WpsInvoke(
  532. [
  533. {
  534. QingGao: {
  535. uploadPath: wpsobj.slCtl.$$idx.httpserver.UploadUrl, // 保存文档上传路径
  536. cookie: wpsobj.slCtl.Base64.encode(
  537. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  538. ),
  539. refresh_token: wpsobj.slCtl.Base64.encode(
  540. wpsobj.slCtl.$$idx.httpserver.refresh_token
  541. ),
  542. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  543. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  544. fileName: userfile.Link,
  545. uploadFieldName: 'file',
  546. fileparam: fileparam,
  547. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  548. trackFileName: wpsobj.slCtl.CreateTrackFileName(fname),
  549. action: 'qinggao',
  550. openType: {
  551. //文档打开方式
  552. // 文档保护类型,-1:不启用保护模式,0:只允许对现有内容进行修订,
  553. // 1:只允许添加批注,2:只允许修改窗体域(禁止拷贝功能),3:只读
  554. protectType: Number.parseInt(fileparam.Status),
  555. },
  556. },
  557. },
  558. ],
  559. reject
  560. )
  561. }).catch(function (reason) {
  562. wpsobj.slCtl.isFileOpen = false
  563. return Promise.reject(reason)
  564. })
  565. return promise
  566. },
  567. //套打
  568. TaoDa: function (
  569. ModelUrl,
  570. ContentFieldName,
  571. fname,
  572. fileparam,
  573. OldDocName,
  574. values,
  575. taodainfo,
  576. argsobj
  577. ) {
  578. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  579. var promise = new Promise((resolve, reject) => {
  580. if (!wpsobj.slCtl.isSupport(fname)) {
  581. reject(wpsobj.slCtl.ErrorMessage.NotSupport)
  582. return
  583. }
  584. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  585. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  586. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  587. if (userfile == null) {
  588. userfile = {}
  589. userfile.Unid = fname
  590. usefileinfostring = fname
  591. userfile.Link = fileparam.FileServerUrl
  592. } else {
  593. var infoarr = usefileinfostring.split('<TaodaInfo>')
  594. usefileinfostring =
  595. infoarr[0] +
  596. '<TaodaInfo>' +
  597. taodainfo +
  598. '</TaodaInfo>' +
  599. infoarr[1].split('</TaodaInfo>')[1]
  600. //更新taodainfo
  601. for (var i = 0; i < wpsobj.slCtl.Content.Files._FileInfoString.length; i++) {
  602. if (
  603. wpsobj.slCtl.getRef(
  604. wpsobj.slCtl.Content.Files._FileInfoString[i],
  605. 0,
  606. '<file_unid>',
  607. '</file_unid>'
  608. ) == fname ||
  609. wpsobj.slCtl.getRef(
  610. wpsobj.slCtl.Content.Files._FileInfoString[i],
  611. 0,
  612. '<file_name>',
  613. '</file_name>'
  614. ) == fname
  615. ) {
  616. wpsobj.slCtl.Content.Files._FileInfoString.splice(i, 1, usefileinfostring)
  617. }
  618. }
  619. }
  620. registerEvent(userfile, resolve)
  621. _WpsInvoke(
  622. [
  623. {
  624. TaoDa: {
  625. uploadPath: wpsobj.slCtl.$$idx.httpserver.UploadUrl, // 保存文档上传路径
  626. cookie: wpsobj.slCtl.Base64.encode(
  627. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  628. ),
  629. refresh_token: wpsobj.slCtl.Base64.encode(
  630. wpsobj.slCtl.$$idx.httpserver.refresh_token
  631. ),
  632. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  633. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  634. fileName: userfile.Link,
  635. uploadFieldName: 'file',
  636. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  637. ModelUrl: ModelUrl,
  638. fileparam: fileparam,
  639. ContentFieldName: ContentFieldName,
  640. values: values,
  641. action: 'taoda',
  642. openType: {
  643. //文档打开方式
  644. // 文档保护类型,-1:不启用保护模式,0:只允许对现有内容进行修订,
  645. // 1:只允许添加批注,2:只允许修改窗体域(禁止拷贝功能),3:只读
  646. protectType: Number.parseInt(fileparam.Status),
  647. },
  648. },
  649. },
  650. ],
  651. reject
  652. )
  653. }).catch(function (reason) {
  654. wpsobj.slCtl.isFileOpen = false
  655. return Promise.reject(reason)
  656. })
  657. return promise
  658. },
  659. //盖章
  660. GaiZhang: function (
  661. ModelUrl,
  662. ContentFieldName,
  663. fname,
  664. fileparam,
  665. OldDocName,
  666. values,
  667. argsobj
  668. ) {
  669. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  670. var promise = new Promise((resolve, reject) => {
  671. if (!wpsobj.slCtl.isSupport(fname)) {
  672. reject(wpsobj.slCtl.ErrorMessage.NotSupport)
  673. return
  674. }
  675. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  676. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  677. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  678. if (userfile == null) {
  679. userfile = {}
  680. userfile.Unid = fname
  681. usefileinfostring = fname
  682. userfile.Link = fileparam.FileServerUrl
  683. }
  684. registerEvent(userfile, resolve)
  685. _WpsInvoke(
  686. [
  687. {
  688. GaiZhang: {
  689. uploadPath: wpsobj.slCtl.$$idx.httpserver.UploadUrl, // 保存文档上传路径
  690. cookie: wpsobj.slCtl.Base64.encode(
  691. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  692. ),
  693. refresh_token: wpsobj.slCtl.Base64.encode(
  694. wpsobj.slCtl.$$idx.httpserver.refresh_token
  695. ),
  696. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  697. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  698. fileName: userfile.Link,
  699. uploadFieldName: 'file',
  700. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  701. ModelUrl: ModelUrl,
  702. fileparam: fileparam,
  703. ContentFieldName: ContentFieldName,
  704. action: 'gaizhang',
  705. openType: {
  706. //文档打开方式
  707. // 文档保护类型,-1:不启用保护模式,0:只允许对现有内容进行修订,
  708. // 1:只允许添加批注,2:只允许修改窗体域(禁止拷贝功能),3:只读
  709. protectType: Number.parseInt(fileparam.Status),
  710. },
  711. },
  712. },
  713. ],
  714. reject
  715. )
  716. }).catch(function (reason) {
  717. wpsobj.slCtl.isFileOpen = false
  718. return Promise.reject(reason)
  719. })
  720. return promise
  721. },
  722. //更新正文
  723. UpdateRegion: function (fname, values, picvalues, fileparam, argsobj) {
  724. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  725. var promise = new Promise((resolve, reject) => {
  726. if (!wpsobj.slCtl.isSupport(fname)) {
  727. reject(wpsobj.slCtl.ErrorMessage.NotSupport)
  728. return
  729. }
  730. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  731. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  732. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  733. if (userfile == null) {
  734. userfile = {}
  735. userfile.Unid = fname
  736. usefileinfostring = fname
  737. userfile.Link = fileparam.FileServerUrl
  738. }
  739. registerEvent(userfile, resolve)
  740. //if(!slCtl.isString(values)){
  741. //values=values.join("|")
  742. // }
  743. _WpsInvoke(
  744. [
  745. {
  746. UpdateRegion: {
  747. uploadPath: wpsobj.slCtl.$$idx.httpserver.UploadUrl, // 保存文档上传路径
  748. cookie: wpsobj.slCtl.Base64.encode(
  749. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  750. ),
  751. refresh_token: wpsobj.slCtl.Base64.encode(
  752. wpsobj.slCtl.$$idx.httpserver.refresh_token
  753. ),
  754. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  755. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  756. fileName: userfile.Link,
  757. uploadFieldName: 'file',
  758. values: values,
  759. fileparam: fileparam,
  760. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  761. action: 'updateregion',
  762. openType: {
  763. //文档打开方式
  764. // 文档保护类型,-1:不启用保护模式,0:只允许对现有内容进行修订,
  765. // 1:只允许添加批注,2:只允许修改窗体域(禁止拷贝功能),3:只读
  766. protectType: Number.parseInt(fileparam.Status),
  767. },
  768. },
  769. },
  770. ],
  771. reject
  772. )
  773. }).catch(function (reason) {
  774. wpsobj.slCtl.isFileOpen = false
  775. return Promise.reject(reason)
  776. })
  777. return promise
  778. },
  779. //文档打印
  780. PrintDocument: function (fname, fileparam, values, argsobj) {
  781. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  782. var promise = new Promise((resolve, reject) => {
  783. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  784. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  785. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  786. if (userfile == null) {
  787. userfile = {}
  788. userfile.Unid = fname
  789. usefileinfostring = fname
  790. userfile.Link = fileparam.FileServerUrl
  791. }
  792. registerEvent(userfile, resolve)
  793. _WpsInvoke(
  794. [
  795. {
  796. PrintDocument: {
  797. cookie: wpsobj.slCtl.Base64.encode(
  798. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  799. ),
  800. refresh_token: wpsobj.slCtl.Base64.encode(
  801. wpsobj.slCtl.$$idx.httpserver.refresh_token
  802. ),
  803. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  804. fileparam: fileparam,
  805. values: values,
  806. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  807. fileName: userfile.Link,
  808. uploadFieldName: 'file',
  809. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  810. action: 'printdocument',
  811. },
  812. },
  813. ],
  814. reject
  815. )
  816. }).catch(function (reason) {
  817. wpsobj.slCtl.isFileOpen = false
  818. return Promise.reject(reason)
  819. })
  820. return promise
  821. },
  822. //转换pdf
  823. DOCConvertToPDF: function (fname, fileparam, argsobj) {
  824. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  825. var promise = new Promise((resolve, reject) => {
  826. if (!wpsobj.slCtl.isSupport(fname)) {
  827. reject(wpsobj.slCtl.ErrorMessage.NotSupport)
  828. return
  829. }
  830. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  831. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  832. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  833. if (userfile == null) {
  834. userfile = {}
  835. userfile.Unid = fname
  836. usefileinfostring = fname
  837. userfile.Link = fileparam.FileServerUrl
  838. }
  839. fileparam.IsMaximization = false //启用静默
  840. registerEvent(userfile, resolve)
  841. _WpsInvoke(
  842. [
  843. {
  844. DOCConvertToPDF: {
  845. uploadPath: wpsobj.slCtl.$$idx.httpserver.UploadUrl, // 保存文档上传路径
  846. cookie: wpsobj.slCtl.Base64.encode(
  847. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  848. ),
  849. refresh_token: wpsobj.slCtl.Base64.encode(
  850. wpsobj.slCtl.$$idx.httpserver.refresh_token
  851. ),
  852. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  853. fileparam: fileparam,
  854. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  855. fileName: userfile.Link,
  856. uploadFieldName: 'file',
  857. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  858. action: 'convertpdf',
  859. },
  860. },
  861. ],
  862. reject
  863. )
  864. }).catch(function (reason) {
  865. wpsobj.slCtl.isFileOpen = false
  866. return Promise.reject(reason)
  867. })
  868. return promise
  869. },
  870. DOCConvertToOFD: function (fname, fileparam, argsobj) {
  871. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  872. var promise = new Promise((resolve, reject) => {
  873. if (!wpsobj.slCtl.isSupport(fname)) {
  874. reject(wpsobj.slCtl.ErrorMessage.NotSupport)
  875. return
  876. }
  877. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  878. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  879. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  880. if (userfile == null) {
  881. userfile = {}
  882. userfile.Unid = fname
  883. usefileinfostring = fname
  884. userfile.Link = fileparam.FileServerUrl
  885. }
  886. fileparam.IsMaximization = false //启用静默
  887. registerEvent(userfile, resolve)
  888. _WpsInvoke(
  889. [
  890. {
  891. DOCConvertToOFD: {
  892. uploadPath: wpsobj.slCtl.$$idx.httpserver.UploadUrl, // 保存文档上传路径
  893. cookie: wpsobj.slCtl.Base64.encode(
  894. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  895. ),
  896. refresh_token: wpsobj.slCtl.Base64.encode(
  897. wpsobj.slCtl.$$idx.httpserver.refresh_token
  898. ),
  899. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  900. fileparam: fileparam,
  901. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  902. fileName: userfile.Link,
  903. uploadFieldName: 'file',
  904. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  905. action: 'convertofd',
  906. },
  907. },
  908. ],
  909. reject
  910. )
  911. }).catch(function (reason) {
  912. wpsobj.slCtl.isFileOpen = false
  913. return Promise.reject(reason)
  914. })
  915. return promise
  916. },
  917. SaveFileToLocal: function (fname, fileparam, argsobj) {
  918. fileparam = wpsobj.slCtl.fileParamsNormalized(fileparam);
  919. var userfile = wpsobj.slCtl.Content.Control.getFileByName(fname)
  920. var promise = new Promise((resolve, reject) => {
  921. if (!wpsobj.slCtl.isSupport(fname)) {
  922. //reject(wpsobj.slCtl.ErrorMessage.NotSupport)
  923. wpsobj.slCtl._download(userfile.Link,fname).then(function(){
  924. resolve()
  925. }).catch(_=>resolve())
  926. }else{
  927. wpsobj.slCtl.$$idx = wpsobj.slCtl.formatParams(argsobj)
  928. var usefileinfostring = wpsobj.slCtl.Content.Control._getFileInfoByName(fname)
  929. if (userfile == null) {
  930. userfile = {}
  931. userfile.Unid = fname
  932. usefileinfostring = fname
  933. userfile.Link = fileparam.FileServerUrl
  934. }
  935. var openType = { protectType: Number.parseInt(fileparam.Status) }
  936. //处理indidox兼容
  937. if (fileparam.Status === 'qinggao') {
  938. openType.protectType = -1
  939. fileparam.AutoAcceptRevisions = true
  940. }
  941. registerEvent(userfile, resolve)
  942. if (
  943. wpsobj.slCtl.getFileType(fname).toLocaleLowerCase() == '.xls' ||
  944. wpsobj.slCtl.getFileType(fname).toLocaleLowerCase() == '.xlsx' ||
  945. wpsobj.slCtl.getFileType(fname).toLocaleLowerCase() == '.et'
  946. )
  947. _WpsInvokeET(
  948. [{
  949. SaveFileToLocal: {
  950. cookie: wpsobj.slCtl.Base64.encode(
  951. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  952. ),
  953. refresh_token: wpsobj.slCtl.Base64.encode(
  954. wpsobj.slCtl.$$idx.httpserver.refresh_token
  955. ),
  956. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  957. fileparam: fileparam,
  958. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  959. fileName: userfile.Link,
  960. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  961. action: 'saveAs',
  962. openType,
  963. },
  964. }]
  965. )
  966. else
  967. _WpsInvoke(
  968. [
  969. {
  970. SaveFileToLocal: {
  971. cookie: wpsobj.slCtl.Base64.encode(
  972. wpsobj.slCtl.$$idx.httpserver.cookie.replace('Authorization=', '')
  973. ),
  974. refresh_token: wpsobj.slCtl.Base64.encode(
  975. wpsobj.slCtl.$$idx.httpserver.refresh_token
  976. ),
  977. uploadParam: wpsobj.slCtl.$$idx.httpserver.UploadParam,
  978. fileparam: fileparam,
  979. fileInfo: usefileinfostring.split('<FileServerUrl>')[0],
  980. fileName: userfile.Link,
  981. userName: wpsobj.slCtl.$$idx.httpserver.UserName,
  982. action: 'saveAs',
  983. openType,
  984. },
  985. },
  986. ],
  987. reject
  988. )
  989. }
  990. }).catch(function (reason) {
  991. wpsobj.slCtl.isFileOpen = false
  992. return Promise.reject(reason)
  993. })
  994. return promise
  995. },
  996. SaveMultiFiles: function (strFiles, fileparam, argsobj) {
  997. var opts = {};
  998. argsobj.UploadParam.split('|').forEach(function(v){
  999. var item = v.split('=');
  1000. opts[item[0]]=item[1];
  1001. });
  1002. return new Promise((resolve, reject) => {
  1003. var arrFileNames = strFiles.split('|');
  1004. var fileName = arrFileNames[0];
  1005. var codes =arrFileNames.map(v=>wpsobj.slCtl.Content.Control.getFileByName(v)).filter(Boolean);
  1006. wpsobj.slCtl._download(
  1007. `api/framework/v1/attachment-extend/attachments-download/multi?groupId=${
  1008. opts.groupId
  1009. }&codes=${codes.map(x=>x.Unid)}`,
  1010. `${fileName}等${codes.length}个附件.zip`
  1011. ).then(_=>resolve()).catch(_=>resolve());
  1012. })
  1013. }
  1014. },
  1015. },
  1016. getFileType: function (strFileName) {
  1017. var arrtmp = strFileName.split('.')
  1018. return '.' + arrtmp.pop().toLowerCase()
  1019. },
  1020. isString: function (str) {
  1021. return typeof str == 'string' && str.constructor == String
  1022. },
  1023. Base64: {
  1024. base64EncodeChars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
  1025. base64DecodeChars: new Array(
  1026. -1,
  1027. -1,
  1028. -1,
  1029. -1,
  1030. -1,
  1031. -1,
  1032. -1,
  1033. -1,
  1034. -1,
  1035. -1,
  1036. -1,
  1037. -1,
  1038. -1,
  1039. -1,
  1040. -1,
  1041. -1,
  1042. -1,
  1043. -1,
  1044. -1,
  1045. -1,
  1046. -1,
  1047. -1,
  1048. -1,
  1049. -1,
  1050. -1,
  1051. -1,
  1052. -1,
  1053. -1,
  1054. -1,
  1055. -1,
  1056. -1,
  1057. -1,
  1058. -1,
  1059. -1,
  1060. -1,
  1061. -1,
  1062. -1,
  1063. -1,
  1064. -1,
  1065. -1,
  1066. -1,
  1067. -1,
  1068. -1,
  1069. 62,
  1070. -1,
  1071. -1,
  1072. -1,
  1073. 63,
  1074. 52,
  1075. 53,
  1076. 54,
  1077. 55,
  1078. 56,
  1079. 57,
  1080. 58,
  1081. 59,
  1082. 60,
  1083. 61,
  1084. -1,
  1085. -1,
  1086. -1,
  1087. -1,
  1088. -1,
  1089. -1,
  1090. -1,
  1091. 0,
  1092. 1,
  1093. 2,
  1094. 3,
  1095. 4,
  1096. 5,
  1097. 6,
  1098. 7,
  1099. 8,
  1100. 9,
  1101. 10,
  1102. 11,
  1103. 12,
  1104. 13,
  1105. 14,
  1106. 15,
  1107. 16,
  1108. 17,
  1109. 18,
  1110. 19,
  1111. 20,
  1112. 21,
  1113. 22,
  1114. 23,
  1115. 24,
  1116. 25,
  1117. -1,
  1118. -1,
  1119. -1,
  1120. -1,
  1121. -1,
  1122. -1,
  1123. 26,
  1124. 27,
  1125. 28,
  1126. 29,
  1127. 30,
  1128. 31,
  1129. 32,
  1130. 33,
  1131. 34,
  1132. 35,
  1133. 36,
  1134. 37,
  1135. 38,
  1136. 39,
  1137. 40,
  1138. 41,
  1139. 42,
  1140. 43,
  1141. 44,
  1142. 45,
  1143. 46,
  1144. 47,
  1145. 48,
  1146. 49,
  1147. 50,
  1148. 51,
  1149. -1,
  1150. -1,
  1151. -1,
  1152. -1,
  1153. -1
  1154. ),
  1155. base64encode: function (str) {
  1156. var out, i, len
  1157. var c1, c2, c3
  1158. len = str.length
  1159. i = 0
  1160. out = ''
  1161. while (i < len) {
  1162. c1 = str.charCodeAt(i++) & 0xff
  1163. if (i == len) {
  1164. out += this.base64EncodeChars.charAt(c1 >> 2)
  1165. out += this.base64EncodeChars.charAt((c1 & 0x3) << 4)
  1166. out += '=='
  1167. break
  1168. }
  1169. c2 = str.charCodeAt(i++)
  1170. if (i == len) {
  1171. out += this.base64EncodeChars.charAt(c1 >> 2)
  1172. out += this.base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4))
  1173. out += this.base64EncodeChars.charAt((c2 & 0xf) << 2)
  1174. out += '='
  1175. break
  1176. }
  1177. c3 = str.charCodeAt(i++)
  1178. out += this.base64EncodeChars.charAt(c1 >> 2)
  1179. out += this.base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4))
  1180. out += this.base64EncodeChars.charAt(((c2 & 0xf) << 2) | ((c3 & 0xc0) >> 6))
  1181. out += this.base64EncodeChars.charAt(c3 & 0x3f)
  1182. }
  1183. return out
  1184. },
  1185. base64decode: function (str) {
  1186. var c1, c2, c3, c4
  1187. var i, len, out
  1188. len = str.length
  1189. i = 0
  1190. out = ''
  1191. while (i < len) {
  1192. do {
  1193. c1 = this.base64DecodeChars[str.charCodeAt(i++) & 0xff]
  1194. } while (i < len && c1 == -1)
  1195. if (c1 == -1) break
  1196. do {
  1197. c2 = this.base64DecodeChars[str.charCodeAt(i++) & 0xff]
  1198. } while (i < len && c2 == -1)
  1199. if (c2 == -1) break
  1200. out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4))
  1201. do {
  1202. c3 = str.charCodeAt(i++) & 0xff
  1203. if (c3 == 61) return out
  1204. c3 = this.base64DecodeChars[c3]
  1205. } while (i < len && c3 == -1)
  1206. if (c3 == -1) break
  1207. out += String.fromCharCode(((c2 & 0xf) << 4) | ((c3 & 0x3c) >> 2))
  1208. do {
  1209. c4 = str.charCodeAt(i++) & 0xff
  1210. if (c4 == 61) return out
  1211. c4 = this.base64DecodeChars[c4]
  1212. } while (i < len && c4 == -1)
  1213. if (c4 == -1) break
  1214. out += String.fromCharCode(((c3 & 0x03) << 6) | c4)
  1215. }
  1216. return out
  1217. },
  1218. utf16to8: function (str) {
  1219. var out, i, len, c
  1220. out = ''
  1221. len = str.length
  1222. for (i = 0; i < len; i++) {
  1223. c = str.charCodeAt(i)
  1224. if (c >= 0x0001 && c <= 0x007f) {
  1225. out += str.charAt(i)
  1226. } else if (c > 0x07ff) {
  1227. out += String.fromCharCode(0xe0 | ((c >> 12) & 0x0f))
  1228. out += String.fromCharCode(0x80 | ((c >> 6) & 0x3f))
  1229. out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f))
  1230. } else {
  1231. out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1f))
  1232. out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f))
  1233. }
  1234. }
  1235. return out
  1236. },
  1237. utf8to16: function (str) {
  1238. var out, i, len, c
  1239. var char2, char3
  1240. out = ''
  1241. len = str.length
  1242. i = 0
  1243. while (i < len) {
  1244. c = str.charCodeAt(i++)
  1245. switch (c >> 4) {
  1246. case 0:
  1247. case 1:
  1248. case 2:
  1249. case 3:
  1250. case 4:
  1251. case 5:
  1252. case 6:
  1253. case 7:
  1254. // 0xxxxxxx
  1255. out += str.charAt(i - 1)
  1256. break
  1257. case 12:
  1258. case 13:
  1259. // 110x xxxx 10xx xxxx
  1260. char2 = str.charCodeAt(i++)
  1261. out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f))
  1262. break
  1263. case 14:
  1264. // 1110 xxxx 10xx xxxx 10xx xxxx
  1265. char2 = str.charCodeAt(i++)
  1266. char3 = str.charCodeAt(i++)
  1267. out += String.fromCharCode(
  1268. ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
  1269. )
  1270. break
  1271. }
  1272. }
  1273. return out
  1274. }, //end
  1275. encode: function (input) {
  1276. return this.base64encode(this.utf16to8(input))
  1277. },
  1278. decode: function (str) {
  1279. return this.utf8to16(this.base64decode(str))
  1280. },
  1281. },
  1282. },
  1283. }
  1284. var getEventName = function (fname) {
  1285. return wpsobj.slCtl.forWindowID + '_' + fname
  1286. }
  1287. /**
  1288. * 只有操作文件的时候才会注册心跳
  1289. * @param {*} userfile
  1290. * @param {*} resolve
  1291. */
  1292. var registerEvent = function (userfile, resolve) {
  1293. window.curPromise[getEventName(userfile.FileName || userfile.Unid)] = resolve
  1294. var extend = userfile.Type || '.' + userfile.Unid.match(/\.(?<ext>\w*)$/i).groups.ext
  1295. var clientType =
  1296. ['.xls', '.xlsx', '.et'].indexOf(extend.toLocaleLowerCase()) > -1
  1297. ? WpsInvoke.ClientType.et
  1298. : WpsInvoke.ClientType.wps
  1299. // RegisterHeart(clientType, { uuid: userfile.Unid, name: userfile.FileName })
  1300. // delayHeart()
  1301. }
  1302. var triggerEvent = function (msg, value) {
  1303. var func = window.curPromise[getEventName(msg)]
  1304. if (!!func) func(value === undefined ? true : value)
  1305. else console.warn('not found handler ' + getEventName(msg))
  1306. }
  1307. var handleEvent = function (message) {
  1308. var reg = /^{.*}$/;
  1309. if (reg.test(message)) {
  1310. var data = JSON.parse(message)
  1311. if (data.cmd == '$reconnect') {
  1312. RegisterHeart(data.type, { uuid: data.uuid, name: data.name })
  1313. heart(true) //强制启动心跳
  1314. } else if (data.cmd == '$disconnect') {
  1315. logoutHeart(data.type, { uuid: data.uuid, name: data.name })
  1316. triggerEvent(data.name)
  1317. } else {
  1318. triggerEvent(data.name, reg.test(data.msg) ? JSON.parse(data.msg) : data.msg);
  1319. }
  1320. } else {
  1321. triggerEvent(message)
  1322. }
  1323. }
  1324. var startNotice = function () {
  1325. if (!!window.$$__wpsNotice) return
  1326. window.$$__wpsNotice = true
  1327. WpsInvoke.RegWebNotify(WpsInvoke.ClientType.wps, 'IndiDocX', handleEvent)
  1328. WpsInvoke.RegWebNotify(WpsInvoke.ClientType.et, 'IndiDocXET', handleEvent)
  1329. startHeart()
  1330. }
  1331. return wpsobj
  1332. },
  1333. }
  1334. /*
  1335. *******************
  1336. *
  1337. * 心跳 功能
  1338. *
  1339. *******************
  1340. */
  1341. var bUseHttps = false
  1342. var heartTimeout = 2e3 //2秒
  1343. var heart_active_key = 'heart_active'
  1344. var heart_active_clientid = 'heart_active_clientid'
  1345. var heart_time_handler = null
  1346. var heart_delay = false
  1347. /**
  1348. * 注册心跳检查
  1349. * @param {*} clientType
  1350. * @param {number} active 0为不激活,大于0为激活 默认值为1
  1351. */
  1352. function RegisterHeart(clientType, info) {
  1353. // var instancekey = `${window.forWindowID}_${clientType}`
  1354. var instancekey = clientType
  1355. var cfg = JSON.parse(sessionStorage.getItem(heart_active_key) || '{}')
  1356. var obj = cfg[instancekey] || {}
  1357. obj[info.uuid] = info
  1358. cfg[instancekey] = obj
  1359. sessionStorage.setItem(heart_active_key, JSON.stringify(cfg))
  1360. // 这里为了是立即设定心跳,但是这个动作可以做到wps加载项中,有通讯加标识已经激活
  1361. // if (active > 0) {
  1362. // //新注册事件,立即激活心跳
  1363. // clearTimeout(heart_time_handler)
  1364. // heart()
  1365. // }
  1366. }
  1367. function logoutHeart(clientType, info) {
  1368. delayHeart(2e3)
  1369. // var instancekey = `${window.forWindowID}_${clientType}`
  1370. var instancekey = clientType
  1371. var cfg = JSON.parse(sessionStorage.getItem(heart_active_key) || '{}')
  1372. var obj = cfg[instancekey] || {}
  1373. delete obj[info.uuid]
  1374. if (Object.keys(obj).length > 0) {
  1375. cfg[instancekey] = obj
  1376. } else {
  1377. delete cfg[instancekey]
  1378. }
  1379. sessionStorage.setItem(heart_active_key, JSON.stringify(cfg))
  1380. }
  1381. function delayHeart(time) {
  1382. heart_delay = true
  1383. if (heart_time_handler) {
  1384. clearTimeout(heart_time_handler)
  1385. heart_time_handler = setTimeout(heart, time || heartTimeout * 3)
  1386. heart_delay = false
  1387. }
  1388. }
  1389. /**
  1390. * 启动心跳
  1391. *
  1392. */
  1393. function startHeart() {
  1394. //确保每个window只有一个心跳不管多少个控件
  1395. if (!!window.$$heartid) {
  1396. return
  1397. } else {
  1398. window.$$heartid = CreateRandomId()
  1399. }
  1400. window.addEventListener('unload', function () {
  1401. var val = localStorage.getItem(heart_active_clientid)
  1402. if (val && window.$$heartid === val) {
  1403. localStorage.removeItem(heart_active_clientid)
  1404. }
  1405. //清理心跳项目
  1406. // var cfg = JSON.parse(localStorage.getItem(heart_active_key) || '{}')
  1407. // delete cfg[`${window.forWindowID}_${WpsInvoke.ClientType.wps}`]
  1408. // delete cfg[`${window.forWindowID}_${WpsInvoke.ClientType.et}`]
  1409. // console.log(cfg)
  1410. // localStorage.setItem(heart_active_key, JSON.stringify(cfg))
  1411. })
  1412. localStorage.removeItem(heart_active_clientid)
  1413. heart()
  1414. }
  1415. /**
  1416. * 心跳
  1417. * 1.强制启动出现在第一次加载组件,用于重连客户端;
  1418. * 2.但是由于wps客户端通信的时候不支持静默模式,
  1419. * 所以改变思路,加载项检测到过期之后主动请求重连
  1420. * @param {boolean} force 默认false
  1421. */
  1422. function heart(force = false) {
  1423. if (force && !!heart_time_handler) {
  1424. //强制启动会取消掉之前的循环
  1425. clearTimeout(heart_time_handler)
  1426. }
  1427. var val = localStorage.getItem(heart_active_clientid) || window.$$heartid
  1428. //确保这个浏览器只有一个心跳链接
  1429. if (window.$$heartid === val) {
  1430. localStorage.setItem(heart_active_clientid, val)
  1431. //默认唤醒
  1432. var cfg = JSON.parse(sessionStorage.getItem(heart_active_key) || '{}')
  1433. var wps = Object.keys(cfg).some((x) => x.endsWith(WpsInvoke.ClientType.wps))
  1434. var table = Object.keys(cfg).some((x) => x.endsWith(WpsInvoke.ClientType.et))
  1435. if (wps && !heart_delay) heart_invoke(WpsInvoke.ClientType.wps, 'IndiDocX')
  1436. if (table && !heart_delay) heart_invoke(WpsInvoke.ClientType.et, 'IndiDocXET')
  1437. }
  1438. heart_time_handler = setTimeout(heart, heartTimeout)
  1439. }
  1440. function heart_invoke(clientType, pluginName) {
  1441. var func = bUseHttps ? WpsInvoke.InvokeAsHttps : WpsInvoke.InvokeAsHttp
  1442. func(
  1443. clientType, // 组件类型
  1444. pluginName, // 插件名,与wps客户端加载的加载的插件名对应
  1445. 'heart', // 插件方法入口,与wps客户端加载的加载的插件代码对应,详细见插件代码
  1446. null,
  1447. function (result) {
  1448. //这里是同步请求
  1449. // if (result.status === 0 && /^{.*}/i.test(result.response)) {
  1450. // var docs = JSON.parse(result.response).docs
  1451. // var count = docs.length
  1452. // RegisterHeart(clientType, count, true)
  1453. // }
  1454. },
  1455. false,
  1456. null,
  1457. false,
  1458. 2e3,
  1459. null,
  1460. 1
  1461. )
  1462. }
  1463. function createXHR() {
  1464. if (typeof XMLHttpRequest != 'undefined') {
  1465. //兼容高版本浏览器
  1466. return new XMLHttpRequest()
  1467. } else if (typeof ActiveXObject != 'undefined') {
  1468. //IE6 采用 ActiveXObject, 兼容IE6
  1469. var versions = [
  1470. //由于MSXML库有3个版本,因此都要考虑
  1471. 'MSXML2.XMLHttp.6.0',
  1472. 'MSXML2.XMLHttp.3.0',
  1473. 'MSXML2.XMLHttp',
  1474. ]
  1475. for (var i = 0; i < versions.length; i++) {
  1476. try {
  1477. return new ActiveXObject(versions[i])
  1478. } catch (e) {
  1479. //跳过
  1480. }
  1481. }
  1482. } else {
  1483. throw new Error('您的浏览器不支持XHR对象')
  1484. }
  1485. }
  1486. /**
  1487. * 获取随机字符串
  1488. * @returns 随机ID字符串
  1489. */
  1490. function CreateRandomId() {
  1491. return Number(
  1492. Math.random()
  1493. .toString()
  1494. .substr(3, 3) + Date.now()
  1495. ).toString(36)
  1496. }
  1497. /**
  1498. * 此方法是根据wps_sdk.js做的调用方法封装
  1499. * 可参照此定义
  1500. * @param {*} funcs 这是在WPS加载项内部定义的方法,采用JSON格式(先方法名,再参数)
  1501. */
  1502. function _WpsInvoke(funcs, reject) {
  1503. var silentmode = IsSilentMode(funcs)
  1504. console.log('silentmode:' + silentmode + ':' + typeof (silentmode))
  1505. var info = { funcs: funcs }
  1506. var func = bUseHttps ? WpsInvoke.InvokeAsHttps : WpsInvoke.InvokeAsHttp
  1507. func(
  1508. WpsInvoke.ClientType.wps, // 组件类型
  1509. 'IndiDocX', // 插件名,与wps客户端加载的加载的插件名对应
  1510. 'dispatcher', // 插件方法入口,与wps客户端加载的加载的插件代码对应,详细见插件代码
  1511. info, // 传递给插件的数据
  1512. function (result) {
  1513. // 调用回调,status为0为成功,其他是错误
  1514. if (result.status) {
  1515. reject(result.message || result.response)
  1516. if (bUseHttps && result.status == 100) {
  1517. WpsInvoke.AuthHttpesCert('请在稍后打开的网页中,点击"高级" => "继续前往",完成授权。')
  1518. return
  1519. }
  1520. alert(result.message)
  1521. } else {
  1522. console.log(result.response)
  1523. !silentmode && funcs.length > 0 && _WpsInvoke([]) //麒麟系统弹出wps问题修复
  1524. }
  1525. },
  1526. !silentmode,
  1527. undefined,
  1528. silentmode,
  1529. 1e4, //10秒
  1530. null,
  1531. 4
  1532. )
  1533. }
  1534. function _WpsInvokeET(funcs, reject) {
  1535. var info = {}
  1536. info.funcs = funcs
  1537. var func = bUseHttps ? WpsInvoke.InvokeAsHttps : WpsInvoke.InvokeAsHttp
  1538. func(
  1539. WpsInvoke.ClientType.et, // 组件类型
  1540. 'IndiDocXET', // 插件名,与wps客户端加载的加载的插件名对应
  1541. 'dispatcher', // 插件方法入口,与wps客户端加载的加载的插件代码对应,详细见插件代码
  1542. info, // 传递给插件的数据
  1543. function (result) {
  1544. // 调用回调,status为0为成功,其他是错误
  1545. if (result.status) {
  1546. reject(result.message || result.response)
  1547. if (bUseHttps && result.status == 100) {
  1548. WpsInvoke.AuthHttpesCert('请在稍后打开的网页中,点击"高级" => "继续前往",完成授权。')
  1549. return
  1550. }
  1551. // alert(result.message)
  1552. } else {
  1553. if (result.response) {
  1554. console.log(result.response)
  1555. }
  1556. }
  1557. }
  1558. )
  1559. }
  1560. function _WpsInvokeExtends(enter, params, callback, silentmode, tiemout) {
  1561. var func = bUseHttps ? WpsInvoke.InvokeAsHttps : WpsInvoke.InvokeAsHttp
  1562. func(
  1563. WpsInvoke.ClientType.wps, // 组件类型
  1564. 'IndiDocX', // 插件名,与wps客户端加载的加载的插件名对应
  1565. enter, // 插件方法入口,与wps客户端加载的加载的插件代码对应,详细见插件代码
  1566. params, // 传递给插件的数据
  1567. callback,
  1568. !silentmode,
  1569. undefined,
  1570. silentmode,
  1571. tiemout || 1e5 //10秒
  1572. )
  1573. }
  1574. /**
  1575. * 判断是否使用静默启动
  1576. * @param {Array}} info
  1577. */
  1578. function IsSilentMode(funcs) {
  1579. for (const iterator of funcs) {
  1580. for (const key in iterator) {
  1581. if (Object.hasOwnProperty.call(iterator, key)) {
  1582. const item = iterator[key]
  1583. if (item.fileparam.IsMaximization == false) return true
  1584. }
  1585. }
  1586. }
  1587. return false
  1588. }
  1589. function getBoolean(str, defaultValue) {
  1590. console.log('get str:' + str + ':' + typeof (str));
  1591. if (typeof str === 'string') return str.toLocaleLowerCase() === 'true'
  1592. else if (typeof str === 'boolean') return str
  1593. else if (typeof str === 'number') return !!str
  1594. else if (str === undefined) return defaultValue
  1595. else return !!str
  1596. }
  1597. /**
  1598. * 处理WPS加载项的方法返回值
  1599. *
  1600. * @param {*} resultData
  1601. */
  1602. function showresult(resultData) {
  1603. var json = eval('(' + resultData + ')')
  1604. switch (json.message) {
  1605. case 'GetDocStatus': {
  1606. var docstatus = json.docstatus
  1607. if (typeof docstatus != 'undefined') {
  1608. var str =
  1609. '文档保存状态:' +
  1610. docstatus.saved +
  1611. '\n文档字数:' +
  1612. docstatus.words +
  1613. '\n文档页数:' +
  1614. docstatus.pages
  1615. alert(str)
  1616. }
  1617. }
  1618. }
  1619. }
  1620. /**
  1621. * 这是页面中针对代码显示的变量定义,开发者无需关心
  1622. */
  1623. var _wps = {}
  1624. /**
  1625. * 检查操作系统
  1626. *
  1627. * @returns Win10 | Win7 | WinVista | Win2003 | WinXP | Win2000 | Linux | Unix | Mac
  1628. */
  1629. function detectOS() {
  1630. var sUserAgent = navigator.userAgent
  1631. var isWin = navigator.platform == 'Win32' || navigator.platform == 'Windows'
  1632. var isMac =
  1633. navigator.platform == 'Mac68K' ||
  1634. navigator.platform == 'MacPPC' ||
  1635. navigator.platform == 'Macintosh' ||
  1636. navigator.platform == 'MacIntel'
  1637. if (isMac) return 'Mac'
  1638. var isUnix = navigator.platform == 'X11' && !isWin && !isMac
  1639. if (isUnix) return 'Unix'
  1640. var isLinux = String(navigator.platform).indexOf('Linux') > -1
  1641. if (isLinux) return 'Linux'
  1642. if (isWin) {
  1643. var isWin2K =
  1644. sUserAgent.indexOf('Windows NT 5.0') > -1 || sUserAgent.indexOf('Windows 2000') > -1
  1645. if (isWin2K) return 'Win2000'
  1646. var isWinXP = sUserAgent.indexOf('Windows NT 5.1') > -1 || sUserAgent.indexOf('Windows XP') > -1
  1647. if (isWinXP) return 'WinXP'
  1648. var isWin2003 =
  1649. sUserAgent.indexOf('Windows NT 5.2') > -1 || sUserAgent.indexOf('Windows 2003') > -1
  1650. if (isWin2003) return 'Win2003'
  1651. var isWinVista =
  1652. sUserAgent.indexOf('Windows NT 6.0') > -1 || sUserAgent.indexOf('Windows Vista') > -1
  1653. if (isWinVista) return 'WinVista'
  1654. var isWin7 = sUserAgent.indexOf('Windows NT 6.1') > -1 || sUserAgent.indexOf('Windows 7') > -1
  1655. if (isWin7) return 'Win7'
  1656. var isWin10 = sUserAgent.indexOf('Windows NT 6.1') > -1 || sUserAgent.indexOf('Windows 10') > -1
  1657. if (isWin10) return 'Win10'
  1658. }
  1659. return 'other'
  1660. }
  1661. window.curPromise = {}
  1662. /**
  1663. * 这是浏览器与WPS通信的SDK,是WPS提供的SDK
  1664. * 无需修改
  1665. * 直接引用到业务系统前端调用即可
  1666. * 可覆盖如下使用场景:
  1667. * 1. 通过浏览器中的页面直接启动WPS
  1668. * 2. 浏览器与WPS双向通信,WPS发消息,浏览器前端页面可接受并解析
  1669. */
  1670. ; (function (global, factory) {
  1671. 'use strict'
  1672. if (typeof module === 'object' && typeof module.exports === 'object') {
  1673. module.exports = factory(global, true)
  1674. } else {
  1675. factory(global)
  1676. }
  1677. })(typeof window !== 'undefined' ? window : this, function (window, noGlobal) {
  1678. 'use strict'
  1679. var bFinished = true
  1680. /**
  1681. * 兼容IE低版本的创建httpobj对象的方法
  1682. * @returns httpobj,可用于进行数据传输的http的对象
  1683. */
  1684. function getHttpObj() {
  1685. var httpobj = null
  1686. if (IEVersion() < 10) {
  1687. try {
  1688. httpobj = new XDomainRequest()
  1689. } catch (e1) {
  1690. httpobj = new createXHR()
  1691. }
  1692. } else {
  1693. httpobj = new createXHR()
  1694. }
  1695. return httpobj
  1696. }
  1697. //兼容IE低版本的创建xmlhttprequest对象的方法
  1698. /**
  1699. * 兼容IE低版本的创建xmlhttprequest对象的方法
  1700. * @returns xmlhttprequest对象,兼容低版本IE
  1701. */
  1702. function createXHR() {
  1703. if (typeof XMLHttpRequest != 'undefined') {
  1704. //兼容高版本浏览器
  1705. return new XMLHttpRequest()
  1706. } else if (typeof ActiveXObject != 'undefined') {
  1707. //IE6 采用 ActiveXObject, 兼容IE6
  1708. var versions = [
  1709. //由于MSXML库有3个版本,因此都要考虑
  1710. 'MSXML2.XMLHttp.6.0',
  1711. 'MSXML2.XMLHttp.3.0',
  1712. 'MSXML2.XMLHttp',
  1713. ]
  1714. for (var i = 0; i < versions.length; i++) {
  1715. try {
  1716. return new ActiveXObject(versions[i])
  1717. } catch (e) {
  1718. //跳过
  1719. }
  1720. }
  1721. } else {
  1722. throw new Error('您的浏览器不支持XHR对象')
  1723. }
  1724. }
  1725. /**
  1726. * 加载项本地服务返回的错误信息,统一为data : message的json格式
  1727. * 如果有新增错误信息,添加到下面
  1728. * 也可以通过请求状态码返回错误信息
  1729. */
  1730. var errorMsg = [
  1731. '{"data": "Failed to send message to WPS."}',
  1732. '{"data": "Json parse failed."}',
  1733. '{"error": "Json parse failed."}',
  1734. ]
  1735. /**
  1736. * 通过该接口给服务器发请求
  1737. * @param {*} options 参数对象,具体包含的参数如下:
  1738. * @param {*} url 网页路径,传输地址
  1739. * @param {*} type 传输类型,POST / GET / PUT
  1740. * @param {*} sendData 传输的数据
  1741. * @param {*} callback 回调函数
  1742. * @param {*} tryCount 请求失败后的尝试次数
  1743. * @param {*} bPop 是否弹出浏览器提示对话框
  1744. * @param {*} timeout 请求等待响应的时间,超过时间请求实效
  1745. * @param {*} concurrent 请求是否同步发送
  1746. * @param {*} wpsclient wpsclient对象
  1747. * @returns NULL
  1748. */
  1749. function startWps(options) {
  1750. if (!bFinished && !options.concurrent) {
  1751. if (options.callback)
  1752. options.callback({
  1753. status: 1,
  1754. message: '上一次请求没有完成',
  1755. })
  1756. return
  1757. }
  1758. if (!options.concurrent) bFinished = false
  1759. else options.bFinished = false
  1760. function startWpsInnder(tryCount) {
  1761. if (tryCount <= 0) {
  1762. if (!options.concurrent) {
  1763. if (bFinished) return
  1764. bFinished = true
  1765. } else {
  1766. if (options.bFinished) {
  1767. return
  1768. }
  1769. options.bFinished = true
  1770. }
  1771. if (options.callback)
  1772. options.callback({
  1773. status: 2,
  1774. message: '请允许浏览器打开WPS Office',
  1775. })
  1776. return
  1777. }
  1778. var xmlReq = getHttpObj()
  1779. //WPS客户端提供的接收参数的本地服务,HTTP服务端口为58890,HTTPS服务端口为58891
  1780. //这俩配置,取一即可,不可同时启用
  1781. xmlReq.open('POST', options.url)
  1782. xmlReq.onload = function (res) {
  1783. var responseStr = IEVersion() < 10 ? xmlReq.responseText : res.target.response
  1784. var respStatus = IEVersion() < 10 ? xmlReq.status : res.target.status
  1785. if (!options.concurrent) bFinished = true
  1786. else options.bFinished = true
  1787. if (options.callback) {
  1788. if (respStatus != 200 || errorMsg.indexOf(responseStr) != -1) {
  1789. var errorMessage = JSON.parse(responseStr)
  1790. options.callback({
  1791. status: 1,
  1792. message: errorMessage.data,
  1793. })
  1794. if (
  1795. errorMessage.data == 'Subserver not available.' &&
  1796. tryCount == options.tryCount &&
  1797. options.bPop
  1798. ) {
  1799. InitWpsCloudSvr()
  1800. setTimeout(function () {
  1801. startWpsInnder(tryCount - 1)
  1802. }, 3000)
  1803. }
  1804. } else {
  1805. options.callback({
  1806. status: 0,
  1807. response: responseStr,
  1808. })
  1809. }
  1810. }
  1811. }
  1812. xmlReq.ontimeout = xmlReq.onerror = function (res) {
  1813. xmlReq.bTimeout = true
  1814. if (tryCount == options.tryCount && options.bPop) {
  1815. //打开wps并传参
  1816. InitWpsCloudSvr()
  1817. }
  1818. setTimeout(function () {
  1819. startWpsInnder(tryCount - 1)
  1820. }, 1000)
  1821. }
  1822. if (IEVersion() < 10) {
  1823. xmlReq.onreadystatechange = function () {
  1824. if (xmlReq.readyState != 4) return
  1825. if (xmlReq.bTimeout) {
  1826. return
  1827. }
  1828. if (xmlReq.status === 200) xmlReq.onload()
  1829. else xmlReq.onerror()
  1830. }
  1831. }
  1832. xmlReq.timeout = options.timeout
  1833. xmlReq.send(options.sendData)
  1834. }
  1835. startWpsInnder(options.tryCount)
  1836. return
  1837. }
  1838. var fromCharCode = String.fromCharCode
  1839. // encoder stuff
  1840. var cb_utob = function (c) {
  1841. if (c.length < 2) {
  1842. var cc = c.charCodeAt(0)
  1843. return cc < 0x80
  1844. ? c
  1845. : cc < 0x800
  1846. ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))
  1847. : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) +
  1848. fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
  1849. fromCharCode(0x80 | (cc & 0x3f))
  1850. } else {
  1851. var cc = 0x10000 + (c.charCodeAt(0) - 0xd800) * 0x400 + (c.charCodeAt(1) - 0xdc00)
  1852. return (
  1853. fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) +
  1854. fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) +
  1855. fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
  1856. fromCharCode(0x80 | (cc & 0x3f))
  1857. )
  1858. }
  1859. }
  1860. var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g
  1861. var utob = function (u) {
  1862. return u.replace(re_utob, cb_utob)
  1863. }
  1864. var _encode = function (u) {
  1865. var isUint8Array = Object.prototype.toString.call(u) === '[object Uint8Array]'
  1866. if (isUint8Array) return u.toString('base64')
  1867. else return btoa(utob(String(u)))
  1868. }
  1869. if (typeof window.btoa !== 'function') window.btoa = func_btoa
  1870. function func_btoa(input) {
  1871. var str = String(input)
  1872. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  1873. for (
  1874. // initialize result and counter
  1875. var block, charCode, idx = 0, map = chars, output = '';
  1876. // if the next str index does not exist:
  1877. // change the mapping table to "="
  1878. // check if d has no fractional digits
  1879. str.charAt(idx | 0) || ((map = '='), idx % 1);
  1880. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  1881. output += map.charAt(63 & (block >> (8 - (idx % 1) * 8)))
  1882. ) {
  1883. charCode = str.charCodeAt((idx += 3 / 4))
  1884. if (charCode > 0xff) {
  1885. throw new InvalidCharacterError(
  1886. "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."
  1887. )
  1888. }
  1889. block = (block << 8) | charCode
  1890. }
  1891. return output
  1892. }
  1893. if (typeof window.atob !== 'function') window.atob = func_atob
  1894. function func_atob(input) {
  1895. output = input.replace(/[\s\S]{1,4}/g, cb_decode)
  1896. return output
  1897. }
  1898. function cb_decode(cccc) {
  1899. var len = cccc.length,
  1900. padlen = len % 4,
  1901. n =
  1902. (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) |
  1903. (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) |
  1904. (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) |
  1905. (len > 3 ? b64tab[cccc.charAt(3)] : 0),
  1906. chars = [fromCharCode(n >>> 16), fromCharCode((n >>> 8) & 0xff), fromCharCode(n & 0xff)]
  1907. chars.length -= [0, 0, 2, 1][padlen]
  1908. return chars.join('')
  1909. }
  1910. function btou(b) {
  1911. return b.replace(re_btou, cb_btou)
  1912. }
  1913. // decoder stuff
  1914. var re_btou = new RegExp(
  1915. ['[\xC0-\xDF][\x80-\xBF]', '[\xE0-\xEF][\x80-\xBF]{2}', '[\xF0-\xF7][\x80-\xBF]{3}'].join('|'),
  1916. 'g'
  1917. )
  1918. function cb_btou(cccc) {
  1919. switch (cccc.length) {
  1920. case 4:
  1921. var cp =
  1922. ((0x07 & cccc.charCodeAt(0)) << 18) |
  1923. ((0x3f & cccc.charCodeAt(1)) << 12) |
  1924. ((0x3f & cccc.charCodeAt(2)) << 6) |
  1925. (0x3f & cccc.charCodeAt(3)),
  1926. offset = cp - 0x10000
  1927. return fromCharCode((offset >>> 10) + 0xd800) + fromCharCode((offset & 0x3ff) + 0xdc00)
  1928. case 3:
  1929. return fromCharCode(
  1930. ((0x0f & cccc.charCodeAt(0)) << 12) |
  1931. ((0x3f & cccc.charCodeAt(1)) << 6) |
  1932. (0x3f & cccc.charCodeAt(2))
  1933. )
  1934. default:
  1935. return fromCharCode(((0x1f & cccc.charCodeAt(0)) << 6) | (0x3f & cccc.charCodeAt(1)))
  1936. }
  1937. }
  1938. /**
  1939. * 将字符串进行Base64编码
  1940. * @param {*} u 需要编码的数据
  1941. * @param {*} urisafe 返回值,编码后的数据
  1942. * @returns urisafe
  1943. */
  1944. var encode = function (u, urisafe) {
  1945. return !urisafe
  1946. ? _encode(u)
  1947. : _encode(String(u))
  1948. .replace(/[+\/]/g, function (m0) {
  1949. return m0 == '+' ? '-' : '_'
  1950. })
  1951. .replace(/=/g, '')
  1952. }
  1953. var decode = function (u) {
  1954. return btou(atob(String(u)))
  1955. }
  1956. /**
  1957. * 获取IE浏览器版本
  1958. * @returns IE浏览器版本
  1959. */
  1960. function IEVersion() {
  1961. var userAgent = navigator.userAgent //取得浏览器的userAgent字符串
  1962. var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 //判断是否IE<11浏览器
  1963. var isEdge = userAgent.indexOf('Edge') > -1 && !isIE //判断是否IE的Edge浏览器
  1964. var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1
  1965. if (isIE) {
  1966. var reIE = new RegExp('MSIE (\\d+\\.\\d+);')
  1967. reIE.test(userAgent)
  1968. var fIEVersion = parseFloat(RegExp['$1'])
  1969. if (fIEVersion == 7) {
  1970. return 7
  1971. } else if (fIEVersion == 8) {
  1972. return 8
  1973. } else if (fIEVersion == 9) {
  1974. return 9
  1975. } else if (fIEVersion == 10) {
  1976. return 10
  1977. } else {
  1978. return 6 //IE版本<=7
  1979. }
  1980. } else if (isEdge) {
  1981. return 20 //edge
  1982. } else if (isIE11) {
  1983. return 11 //IE11
  1984. } else {
  1985. return 30 //不是ie浏览器
  1986. }
  1987. }
  1988. /**
  1989. * 启动wps客户端,加载项执行操作,无返回值
  1990. * @param {*} options 参数对象,详情见下:
  1991. * @param {*} clientType 加载项类型, wps / wpp / et
  1992. * @param {*} name 加载项名称
  1993. * @param {*} func 客户端加载项要执行的方法
  1994. * @param {*} param 客户端家乡执行方法的参数
  1995. * @param {*} urlBase 网页路径前缀
  1996. * @param {*} callback 回调函数
  1997. * @param {*} tryCount 请求失败后的尝试次数
  1998. * @param {*} bPop 是否弹出浏览器提示对话框
  1999. * @param {*} wpsclient wpsclient对象
  2000. */
  2001. function WpsStart(options) {
  2002. var startInfo = {
  2003. name: options.name,
  2004. function: options.func,
  2005. info: options.param.param,
  2006. jsPluginsXml: options.param.jsPluginsXml,
  2007. }
  2008. var strData = JSON.stringify(startInfo)
  2009. if (IEVersion() < 10) {
  2010. try {
  2011. eval("strData = '" + JSON.stringify(startInfo) + "';")
  2012. } catch (err) { }
  2013. }
  2014. var baseData = encode(strData)
  2015. var url = options.urlBase + '/' + options.clientType + '/runParams'
  2016. var data = 'ksowebstartup' + options.clientType + '://' + baseData
  2017. startWps({
  2018. url: url,
  2019. sendData: data,
  2020. callback: options.callback,
  2021. tryCount: options.tryCount,
  2022. bPop: options.bPop,
  2023. timeout: 5000,
  2024. concurrent: false,
  2025. wpsclient: options.wpsclient,
  2026. })
  2027. }
  2028. /**
  2029. * 服务端版本为空时,通过该接口启动wps
  2030. * @param {*} options 参数对象,详情见下:
  2031. * @param {*} clientType 加载项类型, wps / wpp / et
  2032. * @param {*} name 加载项名称
  2033. * @param {*} func 客户端加载项要执行的方法
  2034. * @param {*} param 客户端家乡执行方法的参数
  2035. * @param {*} urlBase 网页路径前缀
  2036. * @param {*} callback 回调函数
  2037. * @param {*} wpsclient wpsclient对象
  2038. * @param {*} concurrent 请求是否同步发送
  2039. */
  2040. function WpsStartWrap(options) {
  2041. WpsStart({
  2042. clientType: options.clientType,
  2043. name: options.name,
  2044. func: options.func,
  2045. param: options.param,
  2046. urlBase: options.urlBase,
  2047. callback: options.callback,
  2048. tryCount: 4,
  2049. bPop: true,
  2050. wpsclient: options.wpsclient,
  2051. })
  2052. }
  2053. /**
  2054. * 支持浏览器触发,WPS有返回值的启动
  2055. *
  2056. * @param {*} clientType 组件类型
  2057. * @param {*} name WPS加载项名称
  2058. * @param {*} func WPS加载项入口方法
  2059. * @param {*} param 参数:包括WPS加载项内部定义的方法,参数等
  2060. * @param {*} callback 回调函数
  2061. * @param {*} tryCount 重试次数
  2062. * @param {*} bPop 是否弹出浏览器提示对话框
  2063. */
  2064. function WpsStartWrapExInner(options) {
  2065. var infocontent = options.param.param
  2066. var cmdId = guid()
  2067. if (!options.wpsclient || options.wpsclient.single) {
  2068. infocontent = JSON.stringify(options.param.param)
  2069. var rspUrl = options.urlBase + '/transferEcho/runParams'
  2070. var funcEx = 'var res = ' + options.func
  2071. var cbCode =
  2072. "var xhr = new XMLHttpRequest();xhr.open('POST', '" +
  2073. rspUrl +
  2074. "');xhr.send(JSON.stringify({id: '" +
  2075. cmdId +
  2076. "', response: res}));" //res 为func执行返回值
  2077. var infoEx = infocontent + ');' + cbCode + 'void(0'
  2078. options.func = funcEx
  2079. infocontent = infoEx
  2080. }
  2081. var startInfo = {
  2082. name: options.name,
  2083. function: options.func,
  2084. info: infocontent,
  2085. showToFront: options.param.showToFront,
  2086. jsPluginsXml: options.param.jsPluginsXml,
  2087. }
  2088. var strData = JSON.stringify(startInfo)
  2089. if (IEVersion() < 10) {
  2090. try {
  2091. eval("strData = '" + JSON.stringify(startInfo) + "';")
  2092. } catch (err) { }
  2093. }
  2094. var baseData = encode(strData)
  2095. var wrapper
  2096. if (!options.wpsclient || options.wpsclient.single) {
  2097. var url = options.urlBase + '/transfer/runParams'
  2098. var data = 'ksowebstartup' + options.clientType + '://' + baseData
  2099. wrapper = {
  2100. id: cmdId,
  2101. app: options.clientType,
  2102. data: data,
  2103. serverId: serverId,
  2104. mode: options.silentMode ? true : false,
  2105. }
  2106. } else {
  2107. var url = options.urlBase + '/transferEx/runParams'
  2108. wrapper = {
  2109. id: options.wpsclient.clientId,
  2110. app: options.clientType,
  2111. data: baseData,
  2112. mode: options.wpsclient.silentMode ? 'true' : 'false',
  2113. serverId: serverId,
  2114. }
  2115. }
  2116. wrapper = JSON.stringify(wrapper)
  2117. startWps({
  2118. url: url,
  2119. sendData: wrapper,
  2120. callback: options.callback,
  2121. tryCount: options.tryCount,
  2122. bPop: options.bPop,
  2123. timeout: 0,
  2124. concurrent: options.concurrent,
  2125. wpsclient: options.wpsclient,
  2126. })
  2127. }
  2128. var serverVersion = 'wait'
  2129. /**
  2130. * 获取服务端版本号的接口
  2131. * @param {*} options 参数对象,详情见下:
  2132. * @param {*} clientType 加载项类型, wps / wpp / et
  2133. * @param {*} name 加载项名称
  2134. * @param {*} func 客户端加载项要执行的方法
  2135. * @param {*} param 客户端家乡执行方法的参数
  2136. * @param {*} urlBase 网页路径前缀
  2137. * @param {*} callback 回调函数
  2138. * @param {*} wpsclient wpsclient对象
  2139. * @param {*} concurrent 请求是否同步发送
  2140. */
  2141. function WpsStartWrapVersionInner(options) {
  2142. if (serverVersion == 'wait') {
  2143. if (g_isSdkInited == true) {
  2144. InitWpsCloudSvr()
  2145. }
  2146. startWps({
  2147. url: options.urlBase + '/version',
  2148. sendData: JSON.stringify({ serverId: serverId }),
  2149. callback: function (res) {
  2150. if (res.status !== 0) {
  2151. options.callback(res)
  2152. return
  2153. }
  2154. serverVersion = res.response
  2155. options.tryCount = 1
  2156. options.bPop = false
  2157. if (serverVersion === '') {
  2158. WpsStart(options)
  2159. } else if (serverVersion < '1.0.1' && options.wpsclient) {
  2160. options.wpsclient.single = true
  2161. WpsStartWrapExInner(options)
  2162. } else {
  2163. WpsStartWrapExInner(options)
  2164. }
  2165. },
  2166. tryCount: 4,
  2167. bPop: !g_isSdkInited,
  2168. timeout: 5000,
  2169. concurrent: options.concurrent,
  2170. })
  2171. } else {
  2172. options.tryCount = 4
  2173. options.bPop = true
  2174. if (serverVersion === '') {
  2175. WpsStartWrap(options)
  2176. } else if (serverVersion < '1.0.1' && options.wpsclient) {
  2177. options.wpsclient.single = true
  2178. WpsStartWrapExInner(options)
  2179. } else {
  2180. WpsStartWrapExInner(options)
  2181. }
  2182. }
  2183. }
  2184. var HeartBeatCode =
  2185. 'function getHttpObj() {\n' +
  2186. ' var httpobj = null;\n' +
  2187. ' if (IEVersion() < 10) {\n' +
  2188. ' try {\n' +
  2189. ' httpobj = new XDomainRequest();\n' +
  2190. ' } catch (e1) {\n' +
  2191. ' httpobj = new createXHR();\n' +
  2192. ' }\n' +
  2193. ' } else {\n' +
  2194. ' httpobj = new createXHR();\n' +
  2195. ' }\n' +
  2196. ' return httpobj;\n' +
  2197. ' }\n' +
  2198. ' \n' +
  2199. ' function createXHR() {\n' +
  2200. " if (typeof XMLHttpRequest != 'undefined') {\n" +
  2201. ' return new XMLHttpRequest();\n' +
  2202. " } else if (typeof ActiveXObject != 'undefined') {\n" +
  2203. ' var versions = [\n' +
  2204. " 'MSXML2.XMLHttp.6.0',\n" +
  2205. " 'MSXML2.XMLHttp.3.0',\n" +
  2206. " 'MSXML2.XMLHttp'\n" +
  2207. ' ];\n' +
  2208. ' \n' +
  2209. ' for (var i = 0; i < versions.length; i++) {\n' +
  2210. ' try {\n' +
  2211. ' return new ActiveXObject(versions[i]);\n' +
  2212. ' } catch (e) {\n' +
  2213. ' \n' +
  2214. ' }\n' +
  2215. ' }\n' +
  2216. ' } else {\n' +
  2217. " throw new Error('您的浏览器不支持XHR对象');\n" +
  2218. ' }\n' +
  2219. ' }\n' +
  2220. ' \n' +
  2221. ' function IEVersion() {\n' +
  2222. ' var userAgent = navigator.userAgent; \n' +
  2223. " var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1;\n" +
  2224. " var isEdge = userAgent.indexOf('Edge') > -1 && !isIE; \n" +
  2225. " var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;\n" +
  2226. ' if (isIE) {\n' +
  2227. " var reIE = new RegExp('MSIE (\\d+\\.\\d+);');\n" +
  2228. ' reIE.test(userAgent);\n' +
  2229. " var fIEVersion = parseFloat(RegExp['$1']);\n" +
  2230. ' if (fIEVersion == 7) {\n' +
  2231. ' return 7;\n' +
  2232. ' } else if (fIEVersion == 8) {\n' +
  2233. ' return 8;\n' +
  2234. ' } else if (fIEVersion == 9) {\n' +
  2235. ' return 9;\n' +
  2236. ' } else if (fIEVersion == 10) {\n' +
  2237. ' return 10;\n' +
  2238. ' } else {\n' +
  2239. ' return 6; \n' +
  2240. ' }\n' +
  2241. ' } else if (isEdge) {\n' +
  2242. ' return 20; \n' +
  2243. ' } else if (isIE11) {\n' +
  2244. ' return 11; \n' +
  2245. ' } else {\n' +
  2246. ' return 30; \n' +
  2247. ' }\n' +
  2248. ' }\n' +
  2249. ' var heartBeatStart = false;\n' +
  2250. ' function checkLastRegTime() {\n' +
  2251. ' var now = new Date().valueOf();\n' +
  2252. ' var TimeGap = now - LastRegTime;\n' +
  2253. ' if (TimeGap > 5000 && !heartBeatStart) {\n' +
  2254. ' HeartBeat();\n' +
  2255. ' heartBeatStart = true;\n' +
  2256. ' }\n' +
  2257. ' }\n' +
  2258. ' \n' +
  2259. ' function HeartBeat() {\n' +
  2260. ' var heartBeatItem = function () {\n' +
  2261. ' var xhr = getHttpObj();\n' +
  2262. ' xhr.onload = function (e) {\n' +
  2263. ' self.setTimeout(heartBeatItem, 5000);\n' +
  2264. ' }\n' +
  2265. ' xhr.onerror = function (e) {\n' +
  2266. ' self.setTimeout(heartBeatItem, 5000);\n' +
  2267. ' }\n' +
  2268. ' xhr.ontimeout = function (e) {\n' +
  2269. ' self.setTimeout(heartBeatItem, 5000);\n' +
  2270. ' }\n' +
  2271. " xhr.open('POST', 'http://127.0.0.1:58890/askwebnotify', true);\n" +
  2272. ' xhr.timeout = 2000;\n' +
  2273. ' xhr.send(JSON.stringify(paramStr));\n' +
  2274. ' }\n' +
  2275. ' heartBeatItem();\n' +
  2276. ' }\n' +
  2277. ' \n' +
  2278. ' var paramStr;\n' +
  2279. ' var startCheck = false;\n' +
  2280. " self.addEventListener('message', function (event) {\n" +
  2281. ' var data = event.data;\n' +
  2282. ' paramStr = data.param\n' +
  2283. ' paramStr.heartBeat = true\n' +
  2284. ' LastRegTime = data.LastRegTime;\n' +
  2285. ' if (!startCheck) {\n' +
  2286. ' startCheck = true;\n' +
  2287. ' self.setInterval(checkLastRegTime, 5000)\n' +
  2288. ' }\n' +
  2289. ' }, false);\n'
  2290. /**
  2291. * 生成guid的接口
  2292. * @returns guid
  2293. */
  2294. function guid() {
  2295. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2296. var r = (Math.random() * 16) | 0,
  2297. v = c == 'x' ? r : (r & 0x3) | 0x8
  2298. return v.toString(16)
  2299. })
  2300. }
  2301. /**
  2302. * 开启多用户的接口
  2303. */
  2304. var serverId = undefined
  2305. function EnableMultiUser() {
  2306. serverId = getServerId()
  2307. InitSdk(true)
  2308. }
  2309. /**
  2310. * 自定义协议启动服务端
  2311. * 默认不带参数serverId,linux未升级之前不要使用多用户
  2312. */
  2313. function InitWpsCloudSvr() {
  2314. if (serverId == undefined) window.location.href = 'ksoWPSCloudSvr://start=RelayHttpServer'
  2315. //是否启动wps弹框
  2316. else window.location.href = 'ksoWPSCloudSvr://start=RelayHttpServer' + '&serverId=' + serverId //是否启动wps弹框
  2317. }
  2318. /**
  2319. * 获取serverId的接口
  2320. * @returns serverId
  2321. */
  2322. function getServerId() {
  2323. if (window.localStorage) {
  2324. if (localStorage.getItem('serverId')) {
  2325. //
  2326. } else {
  2327. localStorage.setItem('serverId', guid())
  2328. }
  2329. return localStorage.getItem('serverId')
  2330. } else {
  2331. return guid()
  2332. }
  2333. }
  2334. /**
  2335. * 将字符串转成二进制,这里用来将字符串化后的js代码转成二进制文件
  2336. * @param {*} code
  2337. * @returns js文件对象的url
  2338. */
  2339. function codeToBlob(code) {
  2340. var blob = new Blob([code], { type: 'text/javascript' }) // 生成js文件对象
  2341. var objectURL = window.URL.createObjectURL(blob) // 生成js文件的url
  2342. return objectURL
  2343. }
  2344. var RegWebNotifyMap = { wps: {}, wpp: {}, et: {} }
  2345. var bWebNotifyUseTimeout = true
  2346. function WebNotifyUseTimeout(value) {
  2347. bWebNotifyUseTimeout = value ? true : false
  2348. }
  2349. var g_businessId = Number(
  2350. Math.random()
  2351. .toString()
  2352. .substr(3, 5) + Date.parse(new Date())
  2353. ).toString(36)
  2354. var HeartBeatWorker
  2355. if (window.Worker) {
  2356. try {
  2357. HeartBeatWorker = new Worker(codeToBlob(HeartBeatCode))
  2358. } catch (error) {
  2359. //
  2360. }
  2361. }
  2362. var g_LastRegTime
  2363. /**
  2364. * 注册一个前端页面接收WPS传来消息的方法
  2365. * @param {*} clientType wps | et | wpp
  2366. * @param {*} name WPS加载项的名称
  2367. * @param {*} callback 回调函数
  2368. * @param {*} wpsclient wpsclient对象
  2369. */
  2370. function RegWebNotify(clientType, name, callback, wpsclient) {
  2371. if (clientType != 'wps' && clientType != 'wpp' && clientType != 'et') return
  2372. var paramStr = {}
  2373. if (wpsclient) {
  2374. if (wpsclient.notifyRegsitered == true) {
  2375. return
  2376. }
  2377. wpsclient.notifyRegsitered = true
  2378. paramStr = {
  2379. clientId: wpsclient.clientId,
  2380. name: name,
  2381. type: clientType,
  2382. serverId: serverId,
  2383. }
  2384. if (HeartBeatWorker) paramStr.businessId = g_businessId
  2385. } else {
  2386. if (typeof callback != 'function') return
  2387. if (RegWebNotifyMap[clientType][name]) {
  2388. RegWebNotifyMap[clientType][name] = callback
  2389. return
  2390. }
  2391. var RegWebNotifyID = new Date().valueOf() + ''
  2392. paramStr = {
  2393. id: RegWebNotifyID,
  2394. name: name,
  2395. type: clientType,
  2396. serverId: serverId,
  2397. }
  2398. if (HeartBeatWorker) paramStr.businessId = g_businessId
  2399. RegWebNotifyMap[clientType][name] = callback
  2400. }
  2401. var askItem = function () {
  2402. var xhr = getHttpObj()
  2403. xhr.onload = function (e) {
  2404. if (xhr.responseText == 'WPSInnerMessage_quit' || xhr.status != 200) {
  2405. if (!wpsclient || wpsclient.single) {
  2406. window.setTimeout(askItem, 2000)
  2407. }
  2408. return
  2409. }
  2410. window.setTimeout(askItem, 300)
  2411. try {
  2412. if (!HeartBeatWorker) throw new Error()
  2413. var resText = JSON.parse(xhr.responseText)
  2414. paramStr.messageId = resText.msgId
  2415. if (wpsclient) {
  2416. if (resText.data != undefined && paramStr.messageId != undefined)
  2417. if (typeof resText.data == 'object')
  2418. // 如果发的数据是字符串化后的json对象,这里的resText.data就是一个json对象,可以输出自己想要的json数据
  2419. wpsclient.OnRegWebNotify(JSON.stringify(resText.data))
  2420. else wpsclient.OnRegWebNotify(resText.data)
  2421. else wpsclient.OnRegWebNotify(xhr.responseText)
  2422. } else {
  2423. var func = RegWebNotifyMap[clientType][name]
  2424. if (resText.data != undefined && paramStr.messageId != undefined)
  2425. if (typeof resText.data == 'object')
  2426. // 如果发的数据是字符串化后的json对象,这里的resText.data就是一个json对象,可以输出自己想要的json数据
  2427. func(JSON.stringify(resText.data))
  2428. else func(resText.data)
  2429. else func(xhr.responseText)
  2430. }
  2431. } catch (e) {
  2432. // 这里做一个容错,即使json解析失败,也要把msgId提取出来,发回给服务端,避免消息清不掉一直重复发送
  2433. // 同时把data也取出来,但是格式无法保证
  2434. var data
  2435. var str = xhr.responseText
  2436. var idx1 = str.indexOf('"msgId"')
  2437. var idx2
  2438. var idx3
  2439. var idx4
  2440. var data
  2441. if (idx1 != -1) {
  2442. idx1 = idx1 + 8
  2443. idx2 = str.indexOf('"data"') - 2
  2444. paramStr.messageId = parseInt(str.substring(idx1, idx2))
  2445. idx3 = str.indexOf('"data"') + 7
  2446. idx4 = str.length - 1
  2447. data = str.substring(idx3, idx4)
  2448. if (/^\".*\"$/.test(data)) {
  2449. data = data.substring(1, data.length - 1)
  2450. }
  2451. }
  2452. if (wpsclient) {
  2453. if (paramStr.messageId !== undefined && data != undefined)
  2454. wpsclient.OnRegWebNotify(data)
  2455. else wpsclient.OnRegWebNotify(xhr.responseText)
  2456. } else {
  2457. var func = RegWebNotifyMap[clientType][name]
  2458. if (paramStr.messageId !== undefined && data != undefined) func(data)
  2459. else func(xhr.responseText)
  2460. }
  2461. }
  2462. }
  2463. xhr.onerror = function (e) {
  2464. if (bWebNotifyUseTimeout) window.setTimeout(askItem, 1000)
  2465. else window.setTimeout(askItem, 10000)
  2466. }
  2467. xhr.ontimeout = function (e) {
  2468. if (bWebNotifyUseTimeout) window.setTimeout(askItem, 300)
  2469. else window.setTimeout(askItem, 10000)
  2470. }
  2471. if (IEVersion() < 10) {
  2472. xhr.onreadystatechange = function () {
  2473. if (xhr.readyState != 4) return
  2474. if (xhr.bTimeout) {
  2475. return
  2476. }
  2477. if (xhr.status === 200) xhr.onload()
  2478. else xhr.onerror()
  2479. }
  2480. }
  2481. xhr.open('POST', GetUrlBase() + '/askwebnotify', true)
  2482. if (bWebNotifyUseTimeout) xhr.timeout = 2000
  2483. if (HeartBeatWorker) {
  2484. g_LastRegTime = new Date().valueOf()
  2485. var param = {
  2486. param: {
  2487. name: name,
  2488. type: clientType,
  2489. businessId: g_businessId,
  2490. serverId: serverId,
  2491. },
  2492. LastRegTime: g_LastRegTime,
  2493. }
  2494. HeartBeatWorker.postMessage(param)
  2495. }
  2496. xhr.send(JSON.stringify(paramStr))
  2497. }
  2498. askItem()
  2499. }
  2500. /**
  2501. * 获取网页路径前缀
  2502. * @returns url前缀
  2503. */
  2504. function GetUrlBase() {
  2505. if (location.protocol == 'https:') return 'https://127.0.0.1:58891'
  2506. return 'http://127.0.0.1:58890'
  2507. }
  2508. /**
  2509. * 获取服务端版本号的接口,这里主要是初始化一些参数
  2510. * @param {*} clientType 加载项类型, wps / wpp / et
  2511. * @param {*} name 加载项名称
  2512. * @param {*} func 客户端加载项要执行的方法
  2513. * @param {*} param 客户端加载项执行方法的参数
  2514. * @param {*} callback 回调函数
  2515. * @param {*} showToFront 设置客户端是否显示到前面
  2516. * @param {*} jsPluginsXml 设置加载项路径
  2517. * @param {*} silentMode 是否是静默启动
  2518. */
  2519. function WpsStartWrapVersion(
  2520. clientType,
  2521. name,
  2522. func,
  2523. param,
  2524. callback,
  2525. showToFront,
  2526. jsPluginsXml,
  2527. silentMode
  2528. ) {
  2529. var paramEx = {
  2530. jsPluginsXml: jsPluginsXml ? jsPluginsXml : '',
  2531. showToFront: typeof showToFront == 'boolean' ? showToFront : true,
  2532. param: typeof param == 'object' ? param : JSON.parse(param),
  2533. }
  2534. var options = {
  2535. clientType: clientType,
  2536. name: name,
  2537. func: func,
  2538. param: paramEx,
  2539. urlBase: GetUrlBase(),
  2540. callback: callback,
  2541. wpsclient: undefined,
  2542. concurrent: true,
  2543. silentMode: silentMode,
  2544. }
  2545. WpsStartWrapVersionInner(options)
  2546. }
  2547. //从外部浏览器远程调用 WPS 加载项中的方法
  2548. var WpsInvoke = {
  2549. InvokeAsHttp: WpsStartWrapVersion,
  2550. InvokeAsHttps: WpsStartWrapVersion,
  2551. RegWebNotify: RegWebNotify,
  2552. ClientType: {
  2553. wps: 'wps',
  2554. et: 'et',
  2555. wpp: 'wpp',
  2556. },
  2557. CreateXHR: getHttpObj,
  2558. IsClientRunning: IsClientRunning,
  2559. }
  2560. /**
  2561. * @constructor WpsClient wps客户端
  2562. * @param {string} clientType 必传参数,加载项类型,有效值为"wps","wpp","et";分别表示文字,演示,电子表格
  2563. */
  2564. function WpsClient(clientType) {
  2565. /**
  2566. * 设置RegWebNotify的回调函数,加载项给业务端发消息通过该函数
  2567. * @memberof WpsClient
  2568. * @member onMessage
  2569. */
  2570. this.onMessage
  2571. /**
  2572. * 设置加载项路径
  2573. * @memberof WpsClient
  2574. * @member jsPluginsXml
  2575. */
  2576. this.jsPluginsXml
  2577. /**
  2578. * 内部成员,外部无需调用
  2579. */
  2580. this.notifyRegsitered = false
  2581. this.clientId = ''
  2582. this.concurrent = true
  2583. this.clientType = clientType
  2584. /**
  2585. * 内部函数,外部无需调用
  2586. * @param {*} options
  2587. */
  2588. this.initWpsClient = function (options) {
  2589. options.clientType = this.clientType
  2590. options.wpsclient = this
  2591. options.concurrent = this.concurrent
  2592. WpsStartWrapVersionInner(options)
  2593. }
  2594. /**
  2595. * 以http启动
  2596. * @param {string} name 加载项名称
  2597. * @param {string} func 要调用的加载项中的函数行
  2598. * @param {string} param 在加载项中执行函数func要传递的数据
  2599. * @param {function({int, string})} callback 回调函数,status = 0 表示成功,失败请查看message信息
  2600. * @param {bool} showToFront 设置wps是否显示到前面来
  2601. * @return {string} "Failed to send message to WPS." 发送消息失败,客户端已关闭;
  2602. * "WPS Addon is not response." 加载项阻塞,函数执行失败
  2603. */
  2604. this.InvokeAsHttp = function (name, func, param, callback, showToFront) {
  2605. function clientCallback(res) {
  2606. //this不是WpsClient,是options对象
  2607. if (res.status !== 0 || serverVersion < '1.0.1' || this.wpsclient.single == true) {
  2608. if (callback) callback(res)
  2609. if (serverVersion < '1.0.1' || this.wpsclient.single == true)
  2610. RegWebNotify(clientType, name, this.wpsclient.onMessage)
  2611. return
  2612. }
  2613. if (serverVersion < '1.0.3') {
  2614. try {
  2615. var resObject = JSON.parse(res.response)
  2616. if (this.wpsclient.clientId == '') {
  2617. this.wpsclient.clientId = resObject.clientId
  2618. }
  2619. if (typeof resObject.data == 'object') res.response = JSON.stringify(resObject.data)
  2620. else res.response = resObject.data
  2621. } catch (e) {
  2622. var str = res.response
  2623. var idx1 = str.indexOf('"clientId":"{')
  2624. var idx2
  2625. var idx3
  2626. var idx4
  2627. if (idx1 != -1) {
  2628. idx1 = idx1 + '"clientId":"{'.length - 1
  2629. idx2 = str.indexOf('"data":') - 3
  2630. if (this.wpsclient.clientId == '') {
  2631. this.wpsclient.clientId = str.substring(idx1, idx2)
  2632. }
  2633. idx3 = str.indexOf('"data":') + '"data":'.length
  2634. idx4 = str.length - 1
  2635. if (idx3 < idx4) res.response = str.substring(idx3, idx4)
  2636. else res.response = ''
  2637. }
  2638. }
  2639. } else {
  2640. var resObject = JSON.parse(res.response)
  2641. if (this.wpsclient.clientId == '') {
  2642. this.wpsclient.clientId = resObject.clientId
  2643. }
  2644. res.response = decode(resObject.data)
  2645. }
  2646. if (IEVersion() < 10) eval(" res.response = '" + res.response + "';")
  2647. if (callback) callback(res)
  2648. this.wpsclient.RegWebNotify(name)
  2649. }
  2650. var paramEx = {
  2651. jsPluginsXml: this.jsPluginsXml ? this.jsPluginsXml : '',
  2652. showToFront: typeof showToFront == 'boolean' ? showToFront : true,
  2653. param: typeof param == 'object' ? param : JSON.parse(param),
  2654. }
  2655. this.initWpsClient({
  2656. name: name,
  2657. func: func,
  2658. param: paramEx,
  2659. urlBase: GetUrlBase(),
  2660. callback: clientCallback,
  2661. })
  2662. }
  2663. /**
  2664. * 以https启动
  2665. * @param {string} name 加载项名称
  2666. * @param {string} func 要调用的加载项中的函数行
  2667. * @param {string} param 在加载项中执行函数func要传递的数据
  2668. * @param {function({int, string})} callback 回调函数,status = 0 表示成功,失败请查看message信息
  2669. * @param {bool} showToFront 设置wps是否显示到前面来
  2670. */
  2671. this.InvokeAsHttps = function (name, func, param, callback, showToFront) {
  2672. var paramEx = {
  2673. jsPluginsXml: this.jsPluginsXml ? this.jsPluginsXml : '',
  2674. showToFront: typeof showToFront == 'boolean' ? showToFront : true,
  2675. param: typeof param == 'object' ? param : JSON.parse(param),
  2676. }
  2677. this.initWpsClient({
  2678. name: name,
  2679. func: func,
  2680. param: paramEx,
  2681. urlBase: GetUrlBase(),
  2682. callback: callback,
  2683. })
  2684. }
  2685. /**
  2686. * 内部函数,外部无需调用
  2687. * @param {*} name
  2688. */
  2689. this.RegWebNotify = function (name) {
  2690. RegWebNotify(this.clientType, name, null, this)
  2691. }
  2692. /**
  2693. * 消息注册函数的回调函数
  2694. * @param {*} message 客户端发来的消息
  2695. */
  2696. this.OnRegWebNotify = function (message) {
  2697. if (this.onMessage) this.onMessage(message)
  2698. }
  2699. /**
  2700. * 以静默模式启动客户端
  2701. * @param {string} name 必传参数,加载项名称
  2702. * @param {function({int, string})} [callback] 回调函数,status = 0 表示成功,失败请查看message信息
  2703. */
  2704. this.StartWpsInSilentMode = function (name, callback) {
  2705. function initCallback(res) {
  2706. //this不是WpsClient,是options对象
  2707. if (res.status !== 0 || serverVersion < '1.0.1' || this.wpsclient.single == true) {
  2708. if (callback) callback(res)
  2709. if (serverVersion < '1.0.1' || this.wpsclient.single == true)
  2710. RegWebNotify(clientType, name, this.wpsclient.onMessage)
  2711. return
  2712. }
  2713. var jsonObj = JSON.parse(res.response)
  2714. if (this.wpsclient.clientId == '') {
  2715. this.wpsclient.clientId = jsonObj.clientId
  2716. }
  2717. if (serverVersion < '1.0.3') {
  2718. res.response = JSON.stringify(jsonObj.data)
  2719. } else {
  2720. res.response = decode(jsonObj.data)
  2721. }
  2722. if (callback) {
  2723. callback(res)
  2724. }
  2725. this.wpsclient.RegWebNotify(name)
  2726. }
  2727. var paramEx = {
  2728. jsPluginsXml: this.jsPluginsXml,
  2729. showToFront: false,
  2730. param: { status: 'InitInSilentMode' },
  2731. }
  2732. this.silentMode = true
  2733. this.initWpsClient({
  2734. name: name,
  2735. func: '',
  2736. param: paramEx,
  2737. urlBase: GetUrlBase(),
  2738. callback: initCallback,
  2739. })
  2740. }
  2741. /**
  2742. * 显示客户端到最前面
  2743. * @param {string} name 必传参数,加载项名称
  2744. * @param {function({int, string})} [callback] 回调函数
  2745. */
  2746. this.ShowToFront = function (name, callback) {
  2747. if (serverVersion < '1.0.1') {
  2748. if (callback) {
  2749. callback({
  2750. status: 4,
  2751. message: '当前客户端不支持,请升级客户端',
  2752. })
  2753. return
  2754. }
  2755. return
  2756. }
  2757. if (this.clientId == '') {
  2758. if (callback)
  2759. callback({
  2760. status: 3,
  2761. message: '没有静默启动客户端',
  2762. })
  2763. return
  2764. }
  2765. var paramEx = {
  2766. jsPluginsXml: '',
  2767. showToFront: true,
  2768. param: { status: 'ShowToFront' },
  2769. }
  2770. this.initWpsClient({
  2771. name: name,
  2772. func: '',
  2773. param: paramEx,
  2774. urlBase: GetUrlBase(),
  2775. callback: callback,
  2776. })
  2777. }
  2778. /**
  2779. * 关闭未显示出来的静默启动客户端
  2780. * @param {string} name 必传参数,加载项名称
  2781. * @param {function({int, string})} [callback] 回调函数
  2782. */
  2783. this.CloseSilentClient = function (name, callback) {
  2784. if (serverVersion < '1.0.1') {
  2785. if (callback) {
  2786. callback({
  2787. status: 4,
  2788. message: '当前客户端不支持,请升级客户端',
  2789. })
  2790. return
  2791. }
  2792. return
  2793. }
  2794. if (this.clientId == '') {
  2795. if (callback)
  2796. callback({
  2797. status: 3,
  2798. message: '没有静默启动客户端',
  2799. })
  2800. return
  2801. }
  2802. var paramEx = {
  2803. jsPluginsXml: '',
  2804. showToFront: false,
  2805. param: undefined,
  2806. }
  2807. var func
  2808. if (this.clientType == 'wps') func = 'wps.WpsApplication().Quit'
  2809. else if (this.clientType == 'et') func = 'wps.EtApplication().Quit'
  2810. else if (this.clientType == 'wpp') func = 'wps.WppApplication().Quit'
  2811. function closeSilentClient(res) {
  2812. if (res.status == 0) this.wpsclient.clientId = ''
  2813. if (callback) callback(res)
  2814. return
  2815. }
  2816. this.initWpsClient({
  2817. name: name,
  2818. func: func,
  2819. param: paramEx,
  2820. urlBase: GetUrlBase(),
  2821. callback: closeSilentClient,
  2822. })
  2823. }
  2824. /**
  2825. * 当前客户端是否在运行,使用WpsClient.IsClientRunning()进行调用
  2826. * @param {function({int, string})} [callback] 回调函数,"Client is running." 客户端正在运行
  2827. * "Client is not running." 客户端没有运行
  2828. */
  2829. this.IsClientRunning = function (callback) {
  2830. if (serverVersion < '1.0.1') {
  2831. if (callback) {
  2832. callback({
  2833. status: 4,
  2834. message: '当前客户端不支持,请升级客户端',
  2835. })
  2836. return
  2837. }
  2838. return
  2839. }
  2840. IsClientRunning(this.clientType, callback, this)
  2841. }
  2842. }
  2843. /**
  2844. * 初始化sdk,用来减少在服务进程启动时自定义协议弹框出现的次数
  2845. */
  2846. var g_isSdkInited = false
  2847. function InitSdk(bMultiUser) {
  2848. g_isSdkInited = false
  2849. var url = GetUrlBase() + '/version'
  2850. startWps({
  2851. url: url,
  2852. sendData: JSON.stringify({ serverId: serverId }),
  2853. callback: function (res) {
  2854. if ((!serverId && !bMultiUser) || bMultiUser) g_isSdkInited = true
  2855. if (res.status !== 0 && res.message !== 'Subserver not available.') {
  2856. serverVersion = 'wait'
  2857. return
  2858. }
  2859. if (res.response && serverVersion == 'wait') serverVersion = res.response
  2860. },
  2861. tryCount: 1,
  2862. bPop: false,
  2863. concurrent: true,
  2864. timeout: 1000,
  2865. })
  2866. }
  2867. InitSdk(false)
  2868. if (typeof noGlobal === 'undefined') {
  2869. window.WpsInvoke = WpsInvoke
  2870. window.WpsClient = WpsClient
  2871. window.WebNotifyUseTimeout = WebNotifyUseTimeout
  2872. window.EnableMultiUser = EnableMultiUser
  2873. }
  2874. /**
  2875. * 当前客户端是否在运行,使用WpsInvoke.IsClientRunning()进行调用
  2876. * @param {string} clientType 加载项类型
  2877. * @param {function} [callback] 回调函数,"Client is running." 客户端正在运行
  2878. * "Client is not running." 客户端没有运行
  2879. */
  2880. function IsClientRunning(clientType, callback, wpsclient) {
  2881. var url = GetUrlBase() + '/isRunning'
  2882. var wrapper = {
  2883. id: wpsclient == undefined ? undefined : wpsclient.clientId,
  2884. app: clientType,
  2885. serverId: serverId,
  2886. }
  2887. wrapper = JSON.stringify(wrapper)
  2888. startWps({
  2889. url: url,
  2890. sendData: wrapper,
  2891. callback: callback,
  2892. tryCount: 1,
  2893. bPop: false,
  2894. timeout: 2000,
  2895. concurrent: true,
  2896. wpsclient: wpsclient,
  2897. })
  2898. }
  2899. /**
  2900. * 获取publish.xml的内容
  2901. * @param {*} callBack 回调函数
  2902. */
  2903. function WpsAddonGetAllConfig(callBack) {
  2904. var baseData = JSON.stringify({ serverId: serverId })
  2905. startWps({
  2906. url: GetUrlBase() + '/publishlist',
  2907. type: 'POST',
  2908. sendData: baseData,
  2909. callback: callBack,
  2910. tryCount: 3,
  2911. bPop: true,
  2912. timeout: 5000,
  2913. concurrent: true,
  2914. })
  2915. }
  2916. /**
  2917. * 检查ribbon.xml文件是否有效
  2918. * @param {*} element 参数对象
  2919. * @param {*} callBack 回调函数
  2920. */
  2921. function WpsAddonVerifyStatus(element, callBack) {
  2922. var xmlReq = getHttpObj()
  2923. var offline = element.online === 'false'
  2924. var url = offline ? element.url : element.url + 'ribbon.xml'
  2925. xmlReq.open('POST', GetUrlBase() + '/redirect/runParams')
  2926. xmlReq.onload = function (res) {
  2927. if (offline && !res.target.response.startsWith('7z')) {
  2928. callBack({ status: 1, msg: '不是有效的7z格式' + url })
  2929. } else if (!offline && !res.target.response.startsWith('<customUI')) {
  2930. callBack({ status: 1, msg: '不是有效的ribbon.xml, ' + url })
  2931. } else {
  2932. callBack({ status: 0, msg: 'OK' })
  2933. }
  2934. }
  2935. xmlReq.onerror = function (res) {
  2936. xmlReq.bTimeout = true
  2937. callBack({
  2938. status: 2,
  2939. msg: '网页路径不可访问,如果是跨域问题,不影响使用' + url,
  2940. })
  2941. }
  2942. xmlReq.ontimeout = function (res) {
  2943. xmlReq.bTimeout = true
  2944. callBack({ status: 3, msg: '访问超时' + url })
  2945. }
  2946. if (IEVersion() < 10) {
  2947. xmlReq.onreadystatechange = function () {
  2948. if (xmlReq.readyState != 4) return
  2949. if (xmlReq.bTimeout) {
  2950. return
  2951. }
  2952. if (xmlReq.status === 200) xmlReq.onload()
  2953. else xmlReq.onerror()
  2954. }
  2955. }
  2956. xmlReq.timeout = 5000
  2957. var data = {
  2958. method: 'get',
  2959. url: url,
  2960. data: '',
  2961. }
  2962. var sendData = FormatSendData(data)
  2963. xmlReq.send(sendData)
  2964. }
  2965. /**
  2966. * 部署加载项,包括启动enable / disable禁用 / disableall禁用所有
  2967. * @param {*} element 参数对象
  2968. * @param {*} cmd 具体操作,enable / disable / disableall
  2969. * @param {*} callBack 回调函数
  2970. */
  2971. function WpsAddonHandleEx(element, cmd, callBack) {
  2972. var data = FormatData(element, cmd)
  2973. startWps({
  2974. url: GetUrlBase() + '/deployaddons/runParams',
  2975. type: 'POST',
  2976. sendData: data,
  2977. callback: callBack,
  2978. tryCount: 3,
  2979. bPop: true,
  2980. timeout: 0,
  2981. concurrent: true,
  2982. })
  2983. }
  2984. /**
  2985. * 启用加载项
  2986. * @param {*} element 参数对象
  2987. * @param {*} callBack 回调函数
  2988. */
  2989. function WpsAddonEnable(element, callBack) {
  2990. WpsAddonHandleEx(element, 'enable', callBack)
  2991. }
  2992. /**
  2993. * 禁用加载项
  2994. * @param {*} element 参数对象
  2995. * @param {*} callBack 回调函数
  2996. */
  2997. function WpsAddonDisable(element, callBack) {
  2998. WpsAddonHandleEx(element, 'disable', callBack)
  2999. }
  3000. /**
  3001. * 禁用所有加载项
  3002. * @param {*} element
  3003. * @param {*} callBack
  3004. */
  3005. function WpsAddonDisableAll(element, callBack) {
  3006. WpsAddonHandleEx(element, 'disableall', callBack)
  3007. }
  3008. /**
  3009. * 生成json格式的数据
  3010. * @param {*} element 参数对象
  3011. * @param {*} cmd 具体操作,enable / disable / disableall
  3012. * @returns base64编码后的数据
  3013. */
  3014. function FormatData(element, cmd) {
  3015. var data = {
  3016. cmd: cmd, //"enable", 启用, "disable", 禁用, "disableall", 禁用所有
  3017. name: element.name,
  3018. url: element.url,
  3019. addonType: element.addonType,
  3020. online: element.online,
  3021. version: element.version,
  3022. time: new Date().getTime(),
  3023. }
  3024. return FormatSendData(data)
  3025. }
  3026. /**
  3027. * 将json格式的数据字符串化,并进行base64编码
  3028. * @param {*} data 数据
  3029. * @returns base64编码后的数据
  3030. */
  3031. function FormatSendData(data) {
  3032. var strData = JSON.stringify(data)
  3033. if (IEVersion() < 10) eval("strData = '" + JSON.stringify(strData) + "';")
  3034. if (serverVersion >= '1.0.2' && serverId != undefined) {
  3035. var base64Data = encode(strData)
  3036. return JSON.stringify({
  3037. serverId: serverId,
  3038. data: base64Data,
  3039. })
  3040. } else {
  3041. return encode(strData)
  3042. }
  3043. }
  3044. //管理 WPS 加载项
  3045. var WpsAddonMgr = {
  3046. getAllConfig: WpsAddonGetAllConfig,
  3047. verifyStatus: WpsAddonVerifyStatus,
  3048. enable: WpsAddonEnable,
  3049. disable: WpsAddonDisable,
  3050. disableall: WpsAddonDisableAll,
  3051. }
  3052. if (typeof noGlobal === 'undefined') {
  3053. window.WpsAddonMgr = WpsAddonMgr
  3054. }
  3055. return { WpsInvoke: WpsInvoke, WpsAddonMgr: WpsAddonMgr, version: '1.0.31' }
  3056. })
  3057. export default wpsModule