• 平台功能
  • 功能介绍
    • 配置文件
    • 系统函数
    • 组态图形
    • 页面集成
    • 功能扩展
    • SSL TLS
  • 本地部署
    • 数据库备份与还原
  • 协议处理
    • WebSocket
    • 国标协议
    • JT808协议
    • MQTT协议
    • OPC网关
    • 自定义协议(my)
    • 自定义协议(di)
    • 平台主动发给终端
    • 串口功能
    • 客户端功能
  • 完整案例演示
  • 系统函数源代码
  • 简洁的Ajax代码
    没有发现主题
文档主题
https://twuyun.com/help/doc/0/index?id=5f689a1ba5a79a8ba43ef2bc
功能
模板管理图形管理脚本测试文档管理系统日志
0

系统函数源代码

  1. switch (v)
  2. {
  3. case "dllmethods":
  4. return () =>
  5. {
  6. return DllMethods.Keys.ToArray();
  7. };
  8. case "timeout":
  9. return () =>
  10. {
  11. MyTimeout = p[0]._Int();
  12. return null;
  13. };
  14. case "publishs":
  15. return () =>
  16. {
  17. if (TempGet == null)
  18. {
  19. return null;
  20. }
  21. return TempGet();
  22. };
  23. //case "actions":
  24. // return () =>
  25. // {
  26. // return this.GetAllServerActions();
  27. // };
  28. #region XML操作
  29. case "xml.parse":
  30. return () =>
  31. {
  32. XmlDocument xmldoc = new XmlDocument();
  33. xmldoc.LoadXml(p[0]._Str());
  34. return xmldoc;
  35. };
  36. #endregion
  37. #region 数据库操作
  38. case "dbindex.query":
  39. return () =>
  40. {
  41. string tid = p[0]._Str();//模板
  42. tid = HttpUtility.UrlDecode(tid);
  43. if (tid.StartsWith("/"))
  44. {
  45. tid = tid._Path(this.GetSource());
  46. }
  47. if (string.IsNullOrEmpty(this.UserId))
  48. {
  49. throw new NoSecurityException("没有登录");
  50. }
  51. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  52. var index = tid.IndexOf('.');
  53. var property = "";
  54. if (index != -1)
  55. {
  56. property = tid.Substring(index);
  57. tid = tid.Substring(0, index);
  58. }
  59. tid = this.GetTemplateId(tid);
  60. if (string.IsNullOrEmpty(tid))
  61. {
  62. throw new NotExistException("模板不存在:" + p[0]._Str());
  63. }
  64. var tdoc = this.GetTemplateNode(tid);
  65. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  66. //=======================================================
  67. //q = Query.And(q, Query.EQ(TemplateFlag, tid));
  68. var collection = DataCollection + "_" + tid;
  69. return this.dbHelper.QueryIndex(collection);
  70. };
  71. case "dbindex.create":
  72. return () =>
  73. {
  74. string tid = p[0]._Str();//模板
  75. tid = HttpUtility.UrlDecode(tid);
  76. if (tid.StartsWith("/"))
  77. {
  78. tid = tid._Path(this.GetSource());
  79. }
  80. if (string.IsNullOrEmpty(this.UserId))
  81. {
  82. throw new NoSecurityException("没有登录");
  83. }
  84. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  85. var index = tid.IndexOf('.');
  86. var property = "";
  87. if (index != -1)
  88. {
  89. property = tid.Substring(index);
  90. tid = tid.Substring(0, index);
  91. }
  92. tid = this.GetTemplateId(tid);
  93. if (string.IsNullOrEmpty(tid))
  94. {
  95. throw new NotExistException("模板不存在:" + p[0]._Str());
  96. }
  97. var tdoc = this.GetTemplateNode(tid);
  98. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  99. //=======================================================
  100. //q = Query.And(q, Query.EQ(TemplateFlag, tid));
  101. var collection = DataCollection + "_" + tid;
  102. this.dbHelper.SetIndex(collection, p[1]._Str(), p[2] as Dictionary<string, object>, p[3]._Bool());
  103. return this.dbHelper.QueryIndex(collection);
  104. };
  105. #endregion
  106. #region 图片相关
  107. case "compressimage":
  108. return () =>
  109. {
  110. byte[] bytes = (byte[])p[0];
  111. int size = p[1]._Int(300);
  112. var result = CommonFunction.CompressImage(bytes, 90, size);
  113. return result;
  114. };
  115. case "checkidcard":
  116. return () =>
  117. {
  118. return CommonFunction.CheckIDCard(p[0]._Str());
  119. };
  120. case "qr"://(内容,级别,版本,比例, bitmap)
  121. return () =>
  122. {
  123. var content = p[0]._Str();
  124. var level = p[1]._Int(1);
  125. var size = p[2]._Int(20);
  126. var format = p[3]._Str();
  127. var drawQuietZones = p[4]._Bool();
  128. ImageFormat imagetype = ImageFormat.Jpeg;
  129. if (!string.IsNullOrEmpty(format))
  130. {
  131. switch (format.ToLower())
  132. {
  133. case "gif":
  134. imagetype = ImageFormat.Gif;
  135. break;
  136. case "jpeg":
  137. imagetype = ImageFormat.Jpeg;
  138. break;
  139. case "png":
  140. imagetype = ImageFormat.Png;
  141. break;
  142. case "tiff":
  143. imagetype = ImageFormat.Tiff;
  144. break;
  145. }
  146. }
  147. QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level);
  148. QRCodeGenerator qrGenerator = new QRCodeGenerator();
  149. QRCodeData qrCodeData = qrGenerator.CreateQrCode(content, eccLevel);
  150. QRCode qrCode = new QRCode(qrCodeData);
  151. Bitmap qrCodeImage = qrCode.GetGraphic(size, Color.Black, Color.White, drawQuietZones);
  152. MemoryStream stream = new MemoryStream();
  153. qrCodeImage.Save(stream, imagetype);
  154. return CommonFunction.StreamToBytes(stream);
  155. //Base64QRCode.ImageType imagetype = Base64QRCode.ImageType.Jpeg;
  156. //if (!string.IsNullOrEmpty(format))
  157. //{
  158. // switch (format.ToLower())
  159. // {
  160. // case "gif":
  161. // imagetype = Base64QRCode.ImageType.Gif;
  162. // break;
  163. // case "jpeg":
  164. // imagetype = Base64QRCode.ImageType.Jpeg;
  165. // break;
  166. // case "png":
  167. // imagetype = Base64QRCode.ImageType.Png;
  168. // break;
  169. // }
  170. //}
  171. //QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level);
  172. ////QRCodeGenerator qrGenerator = new QRCodeGenerator();
  173. ////QRCodeData qrCodeData = qrGenerator.CreateQrCode(content, eccLevel);
  174. //QRCodeGenerator qrGenerator = new QRCodeGenerator();
  175. //QRCodeData qrCodeData = qrGenerator.CreateQrCode(content, eccLevel);
  176. //Base64QRCode qrCode = new Base64QRCode(qrCodeData);
  177. //string qrCodeImageAsBase64 = qrCode.GetGraphic(20, Color.Black, Color.White, false, imagetype);
  178. //return Base64Helper.FromBase64String(qrCodeImageAsBase64);
  179. };
  180. #endregion
  181. #region Business
  182. //case "actions":
  183. // return () =>
  184. // {
  185. // return this.GetAllServerActions();
  186. // };
  187. case "send":
  188. return () =>
  189. {
  190. var serverid = p[0]._Str();
  191. var clientid = p[1]._Str();
  192. var data = (byte[])p[2];
  193. var result = RunMethodOnAllServers((client) =>
  194. {
  195. return client.SendBytes(serverid, clientid, data);
  196. });
  197. return result;
  198. };
  199. case "token":
  200. return () =>
  201. {
  202. return NewToken(this.UserId ?? NewId);
  203. };
  204. case "rest.get":
  205. return () =>
  206. {
  207. string url = p[0]._Str();
  208. SSClient client = new SSClient();
  209. string ct;
  210. byte[] r = client.Get(out ct, url, p[1] as Dictionary<string, object>, p[2]._Bool(), p[3]._Int(30000));
  211. string contenttype;
  212. string charset;
  213. this.GetContentType(ct, out contenttype, out charset);
  214. if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase))
  215. {
  216. var str = CommonFunction.BytesToString(r, charset);
  217. Dictionary<string, object> data;
  218. if (str._IsJson(out data))
  219. {
  220. return data;
  221. }
  222. }
  223. return r;
  224. };
  225. case "rest.post":
  226. return () =>
  227. {
  228. string url = p[0]._Str();
  229. var target = p[5];
  230. if (target != null)
  231. {
  232. var server = DataClient.GetServer(target._Str());
  233. if (server == null)
  234. {
  235. throw new Exception("指定的服务器不存在:" + target._Str());
  236. }
  237. var client = ServiceHelpler.GetBPClient1(server);
  238. var result = client.Rest(url, p[1] as Dictionary<string, object>, p[2] as Dictionary<string, object>, "post", p[3]._Bool(), p[4]._Int(30000), p[6]._Bool());
  239. var r = (byte[])result["r"];
  240. var ct = result["ct"].ToString();
  241. string contenttype;
  242. string charset;
  243. this.GetContentType(ct, out contenttype, out charset);
  244. var str = CommonFunction.BytesToString(r, charset);
  245. Dictionary<string, object> data;
  246. if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase) && str._IsJson(out data))
  247. {
  248. return data;
  249. }
  250. return str;
  251. }
  252. else
  253. {
  254. SSClient client = new SSClient();
  255. string ct;
  256. byte[] r = client.Post(out ct, url, p[1] as Dictionary<string, object>, p[2] as Dictionary<string, object>, p[3]._Bool(), p[4]._Int(30000), p[6]._Bool());
  257. string contenttype;
  258. string charset;
  259. this.GetContentType(ct, out contenttype, out charset);
  260. var str = CommonFunction.BytesToString(r, charset);
  261. Dictionary<string, object> data;
  262. if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase) && str._IsJson(out data))
  263. {
  264. return data;
  265. }
  266. return str;
  267. }
  268. };
  269. case "rest.put":
  270. return () =>
  271. {
  272. string url = p[0]._Str();
  273. SSClient client = new SSClient();
  274. string ct;
  275. var r = client.Put(out ct, url, p[1] as Dictionary<string, object>, p[2] as Dictionary<string, object>, p[3]._Bool(), p[4]._Int(30000));
  276. string contenttype;
  277. string charset;
  278. this.GetContentType(ct, out contenttype, out charset);
  279. var str = CommonFunction.BytesToString(r, charset);
  280. Dictionary<string, object> data;
  281. if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase) && str._IsJson(out data))
  282. {
  283. return data;
  284. }
  285. return str;
  286. };
  287. case "rest.delete":
  288. return () =>
  289. {
  290. string url = p[0]._Str();
  291. SSClient client = new SSClient();
  292. string ct;
  293. byte[] r = client.Delete(out ct, url, p[1] as Dictionary<string, object>, p[2]._Bool(), p[3]._Int(30000));
  294. string contenttype;
  295. string charset;
  296. this.GetContentType(ct, out contenttype, out charset);
  297. var str = CommonFunction.BytesToString(r, charset);
  298. Dictionary<string, object> data;
  299. if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase) && str._IsJson(out data))
  300. {
  301. return data;
  302. }
  303. return str;
  304. };
  305. #endregion
  306. #region 类型转换
  307. case "substring2":
  308. return () =>
  309. {
  310. return CommonFunction.GetSubString(p[0]._Str(), p[1]._Int(), p[2]._Int());
  311. };
  312. case "length2":
  313. return () =>
  314. {
  315. return CommonFunction.GetLength(p[0]._Str());
  316. };
  317. case "rsa.encrypewithprivate":
  318. return () =>
  319. {
  320. return DataAccess.bc.rsa.EncryptWithPrivate(p[0]._Str(), p[1]._Str());
  321. };
  322. case "hash":
  323. return () =>
  324. {
  325. var bytes = (byte[])p[0];
  326. string hash = HashHelper.ComputeMD5(bytes);
  327. return hash;
  328. };
  329. case "random":
  330. return () =>
  331. {
  332. int rv = myrandom.Next(p[0]._Int(), p[1]._Int());
  333. return rv;
  334. };
  335. case "id":
  336. return () =>
  337. {
  338. return NewId;
  339. };
  340. case "md":
  341. return () =>
  342. {
  343. MarkdownSharp.Markdown md = new MarkdownSharp.Markdown();
  344. var html = md.Transform(p[0]._Str());
  345. return html;
  346. };
  347. case "json":
  348. return () =>
  349. {
  350. var para = p[0];
  351. return para._Json();
  352. };
  353. case "obj":
  354. return () =>
  355. {
  356. //var obj = script.RunScript("=" + p[0]._Str());
  357. //return obj;
  358. var obj = this.RunScript("=" + p[0]._Str(), vget, functions, timeout);
  359. return obj;
  360. };
  361. case "script.run":
  362. case "test":
  363. return () =>
  364. {
  365. var obj = this.RunScript(p[0]._Str(), vget, functions, timeout);
  366. return obj;
  367. };
  368. case "int":
  369. return () =>
  370. {
  371. return Support.Int(p[0]);
  372. };
  373. case "int64":
  374. return () =>
  375. {
  376. return Support.Int64(p[0]);
  377. };
  378. case "string":
  379. return () =>
  380. {
  381. bool base64 = true;
  382. if (p.Count > 1)
  383. {
  384. base64 = p[1]._Bool();
  385. }
  386. return p[0]._Str(base64: base64);
  387. };
  388. case "number":
  389. return () =>
  390. {
  391. return Support.Number(p[0]);
  392. };
  393. case "localtime":
  394. return () =>
  395. {
  396. DateTime dt = (DateTime)p[0];
  397. return dt.ToLocalTime();
  398. };
  399. case "dateformat":
  400. return () =>
  401. {
  402. DateTime dt = (DateTime)p[0];
  403. return dt.ToString(p[1]._Str());
  404. };
  405. case "bytes":
  406. return () =>
  407. {
  408. bool base64 = true;
  409. if (p.Count > 1)
  410. {
  411. base64 = p[1]._Bool();
  412. }
  413. return p[0]._ObjBytes(base64);
  414. };
  415. case "byte":
  416. return () =>
  417. {
  418. var data = Support.Int(p[0]);
  419. return (byte)data;
  420. };
  421. case "timestamp":
  422. return () =>
  423. {
  424. var time = p[0]._Time();
  425. System.DateTime startTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
  426. long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
  427. return t;
  428. };
  429. #endregion
  430. #region 字符串函数
  431. case "string.encode":
  432. return () =>
  433. {
  434. return encode(p[0]._Str());
  435. };
  436. case "string.decode":
  437. return () =>
  438. {
  439. return decode(p[0]._Str());
  440. };
  441. #endregion
  442. #region Object Function
  443. case "share":
  444. return () =>
  445. {
  446. var name = p[0]._Str();
  447. var value = p[1]._Str();
  448. var sec = p[2]._Str();
  449. string ctype;
  450. var id = this.CheckAndGetObjectId(name, out ctype);
  451. var values = new BsonDocument();
  452. values[ShareFlag] = value ?? "0";
  453. //values[SecurityFlag] = sec ?? "0";
  454. this.dbHelper.Update(ctype, id, values, nobackup: true);
  455. var doc = this.FindDocumentById(ctype, id, new string[] { ShareFlag });
  456. return doc.GetString(ShareFlag);
  457. };
  458. case "sync":
  459. return () =>
  460. {
  461. byte[] vbytes = p[0]._ObjBytes();
  462. Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
  463. Zip.Unzip(vbytes, (name, value) =>
  464. {
  465. files[name] = value;
  466. });
  467. byte[] licensebytes;
  468. if (!files.TryGetValue("admin/license", out licensebytes))
  469. {
  470. throw new NoSecurityException("没有发现license文件");
  471. }
  472. var license = CommonFunction.BytesToString(licensebytes);
  473. var ls = DatabaseHelper.GetLicenseFeatures(license);
  474. var user = ls["user"].ToString();
  475. var type = ls["type"].ToString();
  476. if (type != "sync")
  477. {
  478. throw new NoSecurityException("license类型不对");
  479. }
  480. if (DataClient.licenseuser != user)
  481. {
  482. throw new NoSecurityException(string.Format("license用户 {1} 不对,需要用户:{0}", DataClient.licenseuser, user));
  483. }
  484. var pkg1 = ls["pkg1"].ToString();
  485. var hash1 = ls["hash1"].ToString();
  486. byte[] zipfiles;
  487. if (!files.TryGetValue(pkg1, out zipfiles))
  488. {
  489. throw new NoSecurityException("没有发现同步的文件");
  490. }
  491. var pkg2 = ls["pkg2"].ToString();
  492. var hash2 = ls["hash2"].ToString();
  493. byte[] ziptemplates;
  494. if (!files.TryGetValue(pkg2, out ziptemplates))
  495. {
  496. throw new NoSecurityException("没有发现同步的模板");
  497. }
  498. string filehash = HashHelper.ComputeMD5(zipfiles);
  499. if (filehash != hash1)
  500. {
  501. throw new NoSecurityException("文件hash不对");
  502. }
  503. string templatehash = HashHelper.ComputeMD5(ziptemplates);
  504. if (templatehash != hash2)
  505. {
  506. throw new NoSecurityException("模板hash不对");
  507. }
  508. Zip.Unzip(zipfiles, (name, value) =>
  509. {
  510. string path;
  511. string description = string.Empty;
  512. var myname = name;
  513. int index = myname.IndexOf("/admin/");
  514. if (index == -1)
  515. {
  516. myname = "/admin/" + name;
  517. }
  518. else
  519. {
  520. myname = name.Substring(index);
  521. }
  522. this.UploadFileByName(out path, myname, value, DataOperations.Upsert, description, true, fornew: false, min: false, oid: null, team: null);
  523. });
  524. Zip.Unzip(ziptemplates, (name, value) =>
  525. {
  526. string path = null;
  527. string description = string.Empty;
  528. var myname = name;
  529. int index = myname.IndexOf("/admin/");
  530. if (index == -1)
  531. {
  532. myname = "/admin/" + name;
  533. }
  534. else
  535. {
  536. myname = name.Substring(index);
  537. }
  538. this.PublishTemplate(ref path, myname, description, string.Empty, value._Str(false), upsert: true, fornew: false, oid: null, team: null);
  539. });
  540. return true;
  541. };
  542. case "zip":
  543. return () =>
  544. {
  545. Dictionary<string, object> list = p[0] as Dictionary<string, object>;
  546. Dictionary<string, byte[]> bytes = new Dictionary<string, byte[]>();
  547. foreach (var kv in list)
  548. {
  549. bytes[kv.Key] = (byte[])kv.Value;
  550. }
  551. return Zip.ToBytes(bytes);
  552. };
  553. case "zip.add":
  554. return () =>
  555. {
  556. byte[] values = (byte[])p[0];
  557. var files = p[1];
  558. Dictionary<string, object> list = null;
  559. if (files is Dictionary<string, object>)
  560. {
  561. list = (Dictionary<string, object>)p[1];
  562. }
  563. else if (files is byte[])
  564. {
  565. list = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  566. Zip.Unzip((byte[])files, (name, value) =>
  567. {
  568. list[name] = value;
  569. });
  570. }
  571. else
  572. {
  573. return values;
  574. }
  575. Dictionary<string, byte[]> bytes = new Dictionary<string, byte[]>();
  576. foreach (var kv in list)
  577. {
  578. bytes[kv.Key] = (byte[])kv.Value;
  579. }
  580. return Zip.AddBytes(values, bytes);
  581. };
  582. case "object.get":
  583. return () =>
  584. {
  585. var collection = p[0]._Str();
  586. var id = p[1]._Str();
  587. var query = p[2]._Str();
  588. var sortby = p[3] as Dictionary<string, object>;
  589. BsonDocument doc3 = this.FindDocumentById(collection, id, new string[] { NameFlag, DescriptionFlag, UserFlag });
  590. if (doc3 == null)
  591. {
  592. throw new NotExistException("不存在:" + id);
  593. }
  594. this.CheckTeamSecurity(doc3);
  595. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  596. r["id"] = doc3[IDFlag].ToString();
  597. r["name"] = doc3[NameFlag].ToString();
  598. return r;
  599. };
  600. case "object.query":
  601. return () =>
  602. {
  603. var collection = p[0]._Str();
  604. if (string.IsNullOrEmpty(collection))
  605. {
  606. collection = "f";
  607. }
  608. switch (collection.ToLower().First())
  609. {
  610. case 't':
  611. collection = CollectionType.Template.ToString();
  612. break;
  613. case 'i':
  614. collection = CollectionType.Instance.ToString();
  615. break;
  616. default:
  617. collection = CollectionType.File.ToString();
  618. break;
  619. }
  620. var group = p[1]._Str();
  621. var query = p[2]._Str();
  622. var sortby = p[3] as Dictionary<string, object>;
  623. bool nofolder = p[4]._Bool();
  624. bool relative = p[5]._Bool();
  625. string team = p[6]._Str();
  626. return this.GetObjectsInfoByQuery(collection, group, query, sortby, nofolder, relative, vget, team);
  627. };
  628. case "object.rename":
  629. return () =>
  630. {
  631. var collection = p[0]._Str();
  632. var id = p[1]._Str();
  633. var name = p[2]._Str();
  634. return this.RenameObject(collection, id, name, false, false);
  635. };
  636. case "object.desc":
  637. return () =>
  638. {
  639. var collection = p[0]._Str();
  640. var id = p[1]._Str();
  641. var desc = p[2]._Str();
  642. CollectionType objcollection = CollectionType.File;
  643. switch (collection.ToLower().First())
  644. {
  645. case 'f':
  646. objcollection = CollectionType.File;
  647. break;
  648. case 't':
  649. objcollection = CollectionType.Template;
  650. break;
  651. case 'i':
  652. objcollection = CollectionType.Instance;
  653. break;
  654. }
  655. this.CheckSecurity(id, objcollection, SecurityType.Write);
  656. var values = new BsonDocument();
  657. values[DescriptionFlag] = desc;
  658. this.dbHelper.Update(objcollection.ToString(), id, values);
  659. return true;
  660. };
  661. case "object.delete":
  662. return () =>
  663. {
  664. var collection = p[0]._Str();
  665. var id = p[1]._Str();
  666. var name = p[2]._Str();
  667. return this.RenameObject(collection, id, name, false, true);
  668. };
  669. case "object.namecheck":
  670. return () =>
  671. {
  672. var name = p[0]._Str();
  673. this.CheckName(name, false, 30, true);
  674. return true;
  675. };
  676. case "object.copy":
  677. return () =>
  678. {
  679. var collection = p[0]._Str();
  680. var id = p[1]._Str();
  681. var name = p[2]._Str();
  682. return this.RenameObject(collection, id, name, true, false);
  683. };
  684. case "object.move":
  685. return () =>
  686. {
  687. var collection = p[0]._Str();
  688. var oid = p[1]._Str();
  689. var did = p[2]._Str();
  690. var mode = p[3]._Str();
  691. string name = string.Empty;
  692. if (oid.StartsWith("_"))
  693. {
  694. name = decode(oid);//admin/a/b
  695. }
  696. else
  697. {
  698. name = this.GetFileName(oid);//admin/a/1.html
  699. }
  700. string folder = decode(did);//admin/c/d
  701. int index = name.LastIndexOf('/');
  702. string filename = name.Substring(index + 1);
  703. folder = folder + "/" + filename;
  704. return this.RenameObject(collection, oid, "/" + folder, mode == "copy", false);
  705. };
  706. case "object.folders":
  707. return () =>
  708. {
  709. var collection = p[0]._Str();
  710. var group = p[1]._Str();
  711. var query = p[2]._Str();
  712. var sortby = p[3] as Dictionary<string, object>;
  713. return this.GetGroupStructure(collection, group, query, sortby, vget: vget);
  714. };
  715. case "object.add":
  716. return () =>
  717. {
  718. var collection = p[0]._Str();
  719. var name = p[1]._Str();
  720. var vp = p[2];
  721. byte[] value;
  722. if (vp is byte[])
  723. {
  724. value = (byte[])p[2];
  725. }
  726. else
  727. {
  728. value = p[2]._ObjBytes(false);
  729. }
  730. var description = p[3]._Str();
  731. bool isoverride = p[4]._Bool();
  732. return this.CreateObject(collection, name, value, description, isoverride);
  733. };
  734. case "history.zip":
  735. return () =>
  736. {
  737. string hid = p[0]._Str();
  738. string type = p[1]._Str();
  739. if (string.IsNullOrEmpty(type))
  740. {
  741. type = "f";
  742. }
  743. char t = type.ToLower().First();
  744. string valuefield = string.Empty;
  745. string collection = "FileHistory";
  746. CollectionType objcollection = CollectionType.File;
  747. switch (t)
  748. {
  749. case 'f':
  750. type = "file";
  751. collection = "FileHistory";
  752. objcollection = CollectionType.File;
  753. valuefield = "doc._value";
  754. break;
  755. case 't':
  756. type = "template";
  757. collection = "TemplateHistory";
  758. objcollection = CollectionType.Template;
  759. valuefield = "doc._value_";
  760. break;
  761. case 'i':
  762. type = "instance";
  763. collection = "InstanceHistory";
  764. objcollection = CollectionType.Instance;
  765. valuefield = "doc";
  766. break;
  767. }
  768. List<string> fields = new List<string>() { valuefield, UserFlag, "id", "name", "desc", "tag" };
  769. if (t == 'f')
  770. {
  771. fields.Add("doc._gz");
  772. }
  773. BsonDocument doc = this.dbHelper.FindDocumentByQuery(collection, Query.EQ(IDFlag, hid), fields.ToArray());
  774. if (doc == null)
  775. {
  776. throw new NotExistException("不存在:" + hid);
  777. }
  778. var id = doc.GetString("id");
  779. this.CheckSecurity(id, objcollection, SecurityType.Read);
  780. var name = doc.GetString("name") + ".$." + id;
  781. Dictionary<string, byte[]> result = new Dictionary<string, byte[]>();
  782. switch (t)
  783. {
  784. case 'f':
  785. type = "file";
  786. bool gz = doc.GetBool("doc._gz");
  787. byte[] vvv = doc.Value(valuefield).AsByteArray;
  788. if (gz)
  789. {
  790. vvv = CommonFunction.Decompress(vvv);
  791. }
  792. result[name] = vvv;
  793. break;
  794. case 't':
  795. type = "template";
  796. result[name] = doc.Value(valuefield).AsString._Bytes(false);
  797. break;
  798. case 'i':
  799. type = "instance";
  800. result[name] = doc.Value(valuefield)._Json()._Bytes(false);
  801. break;
  802. }
  803. return Zip.ToBytes(result);
  804. };
  805. case "history":
  806. case "history.delete":
  807. return () =>
  808. {
  809. string type = "file";
  810. string filename = p[0]._Str().Trim('/');
  811. string hid = p[1]._Str();
  812. bool deleted = p[2]._Bool();
  813. var count = p[3]._Int();
  814. var team = p[4]._Str();
  815. string[] fs = filename.Split('?');
  816. filename = fs[0];
  817. if (fs.Length > 1)
  818. {
  819. type = fs[1];
  820. }
  821. //this.CheckMyFileName(filename);
  822. string valuefield = string.Empty;
  823. string collection = "FileHistory";
  824. CollectionType objcollection = CollectionType.File;
  825. switch (type.ToLower().First())
  826. {
  827. case 'f':
  828. type = "file";
  829. collection = "FileHistory";
  830. objcollection = CollectionType.File;
  831. valuefield = "doc._value";
  832. break;
  833. case 't':
  834. type = "template";
  835. collection = "TemplateHistory";
  836. objcollection = CollectionType.Template;
  837. valuefield = "doc._value_";
  838. break;
  839. case 'i':
  840. type = "instance";
  841. collection = "InstanceHistory";
  842. objcollection = CollectionType.Instance;
  843. valuefield = "doc";
  844. break;
  845. }
  846. if (v == "history.delete")
  847. {
  848. BsonDocument dochistory = this.dbHelper.FindDocumentByQuery(collection, Query.EQ(IDFlag, hid), new string[] { UserFlag });
  849. if (dochistory == null)
  850. {
  851. throw new NotExistException("记录不存在");
  852. }
  853. if (dochistory[UserFlag].ToString() != this.UserId)
  854. {
  855. throw new NoSecurityException("没有权限", hid);
  856. }
  857. this.dbHelper.Remove(collection, Query.EQ(IDFlag, hid), true);
  858. return true;
  859. }
  860. IMongoQuery q = null;
  861. if (string.IsNullOrEmpty(hid))
  862. {
  863. if (filename.Contains('/'))
  864. {
  865. //q = Query.Matches("lname", new BsonRegularExpression(filename.ToLower()));
  866. q = Query.EQ("lname", filename.ToLower());
  867. }
  868. else
  869. {
  870. q = Query.EQ("id", filename);
  871. }
  872. }
  873. if (deleted)
  874. {
  875. if (string.IsNullOrEmpty(hid))
  876. {
  877. var q2 = Query.EQ(UserFlag, this.UserId);
  878. IMongoQuery searchquery = Query.Matches("lname", new BsonRegularExpression("/.*" + filename.ToLower() + ".*/"));
  879. q = Query.And(searchquery, Query.EQ("flag", "delete"), q2);
  880. }
  881. }
  882. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  883. if (string.IsNullOrEmpty(hid))
  884. {
  885. List<BsonDocument> docs = this.dbHelper.Find(collection, q, new List<string> { IDFlag, "desc", "time", "user", "name", "size", "flag", "muser", "tag" }, sortby: new SortByDocument("time", -1), limit: count);//
  886. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  887. foreach (var doc in docs)
  888. {
  889. Dictionary<string, object> obj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  890. obj["id"] = doc[IDFlag].ToString();
  891. obj["desc"] = doc.Value("desc").Value();
  892. obj["time"] = doc.Value("time").Value();
  893. obj["user"] = doc.Value("user").Value();
  894. obj["name"] = doc.Value("name").Value();
  895. obj["size"] = doc.Value("size").Value();
  896. obj["flag"] = doc.Value("flag").Value();
  897. obj["muser"] = doc.Value("muser").Value();
  898. obj["tag"] = doc.Value("tag").Value();
  899. list.Add(obj);
  900. }
  901. result["count"] = list.Count;
  902. result["data"] = list;
  903. return result;
  904. }
  905. else
  906. {
  907. List<string> fields = new List<string>() { valuefield, UserFlag, "id", "name", "desc", "tag" };
  908. if (type.ToLower().First() == 'f')
  909. {
  910. fields.Add("doc._gz");
  911. }
  912. BsonDocument doc = this.dbHelper.FindDocumentByQuery(collection, Query.EQ(IDFlag, hid), fields.ToArray());
  913. if (doc == null)
  914. {
  915. throw new NotExistException("不存在:" + hid);
  916. }
  917. var id = doc.GetString("id");
  918. this.CheckSecurity(id, objcollection, SecurityType.Read);
  919. switch (type.ToLower().First())
  920. {
  921. case 'f':
  922. type = "file";
  923. bool gz = doc.GetBool("doc._gz");
  924. byte[] vvv = doc.Value(valuefield).AsByteArray;
  925. if (gz)
  926. {
  927. vvv = CommonFunction.Decompress(vvv);
  928. }
  929. result["value"] = vvv._Str(false);
  930. break;
  931. case 't':
  932. type = "template";
  933. result["value"] = doc.Value(valuefield).AsString;
  934. break;
  935. case 'i':
  936. type = "instance";
  937. result["value"] = doc.Value(valuefield)._Json();
  938. break;
  939. }
  940. if (deleted)
  941. {
  942. filename = doc.GetString("name");
  943. result["id"] = doc.GetString("id");
  944. result["desc"] = doc.GetString("desc");
  945. result["tag"] = doc.GetString("tag");
  946. }
  947. result["name"] = filename;
  948. result["t"] = type;
  949. return result;
  950. }
  951. };
  952. case "history.restore":
  953. return () =>
  954. {
  955. string type = "file";
  956. string filename = p[0]._Str().Trim('/');
  957. string[] fs = filename.Split('?');
  958. filename = fs[0];
  959. if (fs.Length > 1)
  960. {
  961. type = fs[1];
  962. }
  963. //this.CheckMyFileName(filename);
  964. string valuefield = string.Empty;
  965. string collection = "FileHistory";
  966. switch (type.ToLower().First())
  967. {
  968. case 'f':
  969. type = "file";
  970. collection = "FileHistory";
  971. valuefield = "doc._value";
  972. break;
  973. case 't':
  974. type = "template";
  975. collection = "TemplateHistory";
  976. valuefield = "doc._value_";
  977. break;
  978. case 'i':
  979. type = "instance";
  980. collection = "InstanceHistory";
  981. valuefield = "doc";
  982. break;
  983. }
  984. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  985. IMongoQuery searchquery = Query.Matches("lname", new BsonRegularExpression("/.*" + filename.ToLower() + ".*/"));
  986. q = Query.And(q, searchquery);
  987. q = Query.And(q, Query.EQ("flag", "delete"));
  988. List<BsonDocument> docs = this.dbHelper.Find(collection, q, new List<string> { IDFlag, "name" });//
  989. Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
  990. foreach (var doc in docs)
  991. {
  992. Dictionary<string, object> obj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  993. var id = doc[IDFlag].ToString();
  994. var name = doc.GetString("name");
  995. List<string> fields = new List<string>() { valuefield };
  996. if (type.ToLower().First() == 'f')
  997. {
  998. fields.Add("doc._gz");
  999. }
  1000. BsonDocument valuedoc = this.dbHelper.FindDocumentByQuery(collection, Query.EQ(IDFlag, id), fields.ToArray());
  1001. if (valuedoc == null)
  1002. {
  1003. continue;
  1004. }
  1005. byte[] vvv = null;
  1006. switch (type.ToLower().First())
  1007. {
  1008. case 'f':
  1009. type = "file";
  1010. bool gz = valuedoc.GetBool("doc._gz");
  1011. vvv = valuedoc.Value(valuefield).AsByteArray;
  1012. if (gz)
  1013. {
  1014. vvv = CommonFunction.Decompress(vvv);
  1015. }
  1016. //result["value"] = vvv._Str(false);
  1017. break;
  1018. case 't':
  1019. type = "template";
  1020. vvv = valuedoc.Value(valuefield).AsString._Bytes(false);
  1021. break;
  1022. case 'i':
  1023. type = "instance";
  1024. vvv = valuedoc.Value(valuefield)._Json()._Bytes(false);
  1025. break;
  1026. }
  1027. files[name] = vvv;
  1028. }
  1029. var values = Zip.ToBytes(files);
  1030. return values;
  1031. };
  1032. case "mymessages":
  1033. return () =>
  1034. {
  1035. var collection = InstanceHistoryCollection;
  1036. var query = p[0]._Str();
  1037. var page = p[1]._Int(1);
  1038. var pagesize = p[2]._Int(100);
  1039. var sortby = p[3] as Dictionary<string, object>;
  1040. if (string.IsNullOrEmpty(this.UserId))
  1041. {
  1042. throw new NoSecurityException("没有登录");
  1043. }
  1044. IMongoQuery q = Query.And(Query.EQ(UserFlag, this.UserId));
  1045. if (!string.IsNullOrEmpty(query))
  1046. {
  1047. q = Query.And(q, this.GetMyQuery(query, (name) =>
  1048. {
  1049. return name;
  1050. }, (name, value) =>
  1051. {
  1052. return BsonTypeMapper.MapToBsonValue(value);
  1053. }, vget));
  1054. }
  1055. List<string> fs = new List<string> { "doc" };
  1056. SortByDocument sdoc = null;
  1057. if (sortby != null)
  1058. {
  1059. sdoc = new SortByDocument(sortby);
  1060. }
  1061. Func<List<BsonDocument>, List<Dictionary<string, object>>> mapping = (ds) =>
  1062. {
  1063. List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
  1064. foreach (var doc in ds)
  1065. {
  1066. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1067. result["id"] = doc.GetString("_id");
  1068. result["nodename"] = doc.GetString("doc._name");
  1069. string userid = doc.GetString("doc._muser");
  1070. result["username"] = this.GetUserName(userid);
  1071. result["time"] = doc.GetDateTime("doc._time");
  1072. result["value"] = doc.Value("doc._value").Value();
  1073. result["type"] = result["value"].GetType().Name;
  1074. results.Add(result);
  1075. }
  1076. return results;
  1077. };
  1078. var docs = this.dbHelper.FindPage(collection, q, page, pagesize, fs, sdoc, mapping);
  1079. return docs;
  1080. };
  1081. case "mymessage":
  1082. return () =>
  1083. {
  1084. //string userid = this.UserId;
  1085. string name = p[0]._Str();
  1086. var page = p[2]._Int();
  1087. var pagesize = p[3]._Int();
  1088. string clientname = name;
  1089. string tempId = null;
  1090. string userId = null;
  1091. BsonDocument instDoc = null;
  1092. BsonDocument tempDoc = null;
  1093. string keyBase = null;
  1094. string keyFlag = null;
  1095. string instRoot = null;
  1096. this.GetInstanceInformation(name, out instRoot, out userId, out keyBase, out keyFlag, out instDoc, out tempDoc, out clientname, out tempId, SecurityType.Read);
  1097. List<BsonDocument> docs = new List<BsonDocument>();
  1098. var count = 0;
  1099. if (tempDoc.GetBool(HistoryFlag))
  1100. {
  1101. IMongoQuery q1 = Query.EQ("doc.id", clientname);
  1102. IMongoQuery q3 = Query.Or(Query.EQ("doc." + Definitions.ToFlag, "*"), Query.EQ("doc." + Definitions.ToFlag, this.UserId));
  1103. IMongoQuery q = Query.And(q1, q3);
  1104. string search = p[1]._Str();
  1105. if (!string.IsNullOrEmpty(search))
  1106. {
  1107. IMongoQuery searchquery = Query.Matches("doc._value", new BsonRegularExpression("/.*" + search + ".*/"));
  1108. q = Query.And(q, searchquery);
  1109. }
  1110. //var docs2 = this.dbHelper.FindPage(InstanceHistoryCollection, q, page, pagesize, new List<string> { "doc" }, new SortByDocument("time", -1), null);
  1111. int skip = -1;
  1112. int limit = -1;
  1113. if (page > 0 && pagesize > 0)
  1114. {
  1115. skip = (page - 1) * pagesize;
  1116. limit = pagesize;
  1117. }
  1118. var docs2 = this.dbHelper.Find(out count, InstanceHistoryCollection, q, new List<string> { "doc" }, sortby: new SortByDocument("time", -1), limit: limit, skip: skip);
  1119. foreach (var doc in docs2)
  1120. {
  1121. instDoc = doc["doc"] as BsonDocument;
  1122. instDoc["id"] = doc[IDFlag].ToString();
  1123. docs.Add(instDoc);
  1124. }
  1125. }
  1126. else
  1127. {
  1128. instDoc.Add("id", instDoc[IDFlag].ToString());
  1129. IList to = instDoc.GetList(Definitions.ToFlag);
  1130. if (to == null)
  1131. {
  1132. docs.Add(instDoc);
  1133. }
  1134. if (to.Contains("*") || to.Contains(this.UserId))
  1135. {
  1136. docs.Add(instDoc);
  1137. }
  1138. count = docs.Count;
  1139. }
  1140. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1141. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  1142. foreach (var doc in docs)
  1143. {
  1144. Dictionary<string, object> obj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1145. obj["id"] = doc["id"].ToString();
  1146. string _from = doc.GetString(Definitions.FromFlag);
  1147. obj["from"] = this.GetUserName(_from);
  1148. obj["value"] = doc.GetString("_value");
  1149. obj["time"] = doc.GetDateTime("_time");
  1150. BsonValue cp;
  1151. if (doc.TryGetValue(Definitions.CpFlag, out cp))
  1152. {
  1153. var mycp = (cp as BsonDocument).ToDictionary();
  1154. if (mycp != null)
  1155. {
  1156. obj["cp"] = mycp;
  1157. }
  1158. }
  1159. list.Add(obj);
  1160. }
  1161. result["count"] = count;
  1162. result["rows"] = list;
  1163. return result;
  1164. };
  1165. case "template.info":
  1166. return () =>
  1167. {
  1168. string filename = p[0]._Str();
  1169. filename = System.Web.HttpUtility.UrlDecode(filename);
  1170. string collection = TemplateCollection;
  1171. BsonDocument doc = this.FindDocumentByName(collection, filename, new string[] { NameFlag, DescriptionFlag, UserFlag, ShareFlag, CreatedFlag, ModifiedFlag });
  1172. if (doc == null)
  1173. {
  1174. return null;
  1175. //throw new NotExistException("不存在:" + filename);
  1176. }
  1177. //this.CheckSecurity(ct, doc, SecurityType.Read);
  1178. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1179. string id = doc[IDFlag].ToString();
  1180. string name = doc[NameFlag].ToString();
  1181. string desc = doc[DescriptionFlag].ToString();
  1182. result["path"] = name;
  1183. result["id"] = id;
  1184. int index = name.LastIndexOf('/');
  1185. result["name"] = name.Substring(index + 1);
  1186. result["desc"] = desc;
  1187. result["share"] = doc.Value(ShareFlag);
  1188. result["uid"] = doc.Value(UserFlag);
  1189. result["created"] = doc.Value(CreatedFlag);
  1190. result["updated"] = doc.Value(ModifiedFlag);
  1191. return result;
  1192. };
  1193. case "object.info":
  1194. return () =>
  1195. {
  1196. string filename = p[0]._Str();
  1197. filename = System.Web.HttpUtility.UrlDecode(filename);
  1198. char t = 'f';
  1199. string str = p[1]._Str()._Trim();
  1200. if (!string.IsNullOrEmpty(str))
  1201. {
  1202. t = str.ToLower().First();
  1203. }
  1204. string collection = FileCollection;
  1205. //CollectionType ct = CollectionType.File;
  1206. switch (t)
  1207. {
  1208. case 't':
  1209. collection = TemplateCollection;
  1210. //ct = CollectionType.Template;
  1211. break;
  1212. case 'i':
  1213. collection = InstanceCollection;
  1214. //ct = CollectionType.Instance;
  1215. break;
  1216. }
  1217. BsonDocument doc = this.FindDocumentByName(collection, filename, new string[] { NameFlag, DescriptionFlag, UserFlag, TypeFlag, ShareFlag, CreatedFlag, ModifiedFlag });
  1218. if (doc == null)
  1219. {
  1220. return null;
  1221. //throw new NotExistException("不存在:" + filename);
  1222. }
  1223. //this.CheckSecurity(ct, doc, SecurityType.Read);
  1224. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1225. string id = doc[IDFlag].ToString();
  1226. string name = doc[NameFlag].ToString();
  1227. string desc = doc[DescriptionFlag].ToString();
  1228. result["path"] = name;
  1229. result["type"] = doc.GetString(TypeFlag);
  1230. result["id"] = id;
  1231. int index = name.LastIndexOf('/');
  1232. result["name"] = name.Substring(index + 1);
  1233. result["desc"] = desc;
  1234. result["share"] = doc.Value(ShareFlag);
  1235. result["uid"] = doc.Value(UserFlag);
  1236. result["created"] = doc.Value(CreatedFlag);
  1237. result["updated"] = doc.Value(ModifiedFlag);
  1238. return result;
  1239. };
  1240. case "objects":
  1241. return () =>
  1242. {
  1243. char t = 'f';
  1244. string type = "file";
  1245. string str = p[0]._Str()._Trim();
  1246. if (!string.IsNullOrEmpty(str))
  1247. {
  1248. t = str.ToLower().First();
  1249. }
  1250. string group = p[1]._Str();
  1251. string action = p[2]._Str();
  1252. string search = p[3]._Str();
  1253. string team = p[4]._Str();
  1254. var sort = p[5] as Dictionary<string, object>;
  1255. SortByDocument sortby = null;
  1256. if (sort != null)
  1257. {
  1258. sortby = new SortByDocument(sort);
  1259. }
  1260. string collection = FileCollection;
  1261. switch (t)
  1262. {
  1263. case 't':
  1264. type = "template";
  1265. collection = TemplateCollection;
  1266. break;
  1267. case 'i':
  1268. type = "instance";
  1269. collection = InstanceCollection;
  1270. break;
  1271. }
  1272. List<string> fields = new List<string> { IDFlag, UserFlag, NameFlag, DescriptionFlag, GroupFlag, TemplateFlag, SizeFlag };
  1273. if (group.StartsWith("/"))
  1274. {
  1275. string g = group.TrimStart('/') + "/";
  1276. int i = g.IndexOf('/');
  1277. group = g.Remove(0, i);
  1278. group = group.Trim('/').Trim();
  1279. }
  1280. var r = this.GetDocs(collection, group, fields, null, search, team, sortby);
  1281. //if (!string.IsNullOrEmpty(action))
  1282. //{
  1283. // action = "return " + action + ";" + script;
  1284. //}
  1285. var nodes = this.ConvertTree3(r, type, group, action, functions, team);
  1286. return nodes;
  1287. };
  1288. case "updatefilename":
  1289. return () =>
  1290. {
  1291. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1292. r["err"] = string.Empty;
  1293. string oldname = p[0]._Str();
  1294. string type = "file";
  1295. string[] fs = oldname.Split('?');
  1296. oldname = fs[0];
  1297. if (fs.Length > 1)
  1298. {
  1299. type = fs[1];
  1300. }
  1301. string newname = p[1]._Str();
  1302. var team = p[2]._Str();
  1303. oldname = WebUtility.UrlDecode(oldname);
  1304. newname = WebUtility.UrlDecode(newname);
  1305. newname = newname._Path();
  1306. r["name"] = newname;
  1307. switch (type.ToLower().First())
  1308. {
  1309. case 'f':
  1310. var doc = this.FindDocumentByName(FileCollection, oldname, new string[] { IDFlag });
  1311. if (doc == null)
  1312. {
  1313. throw new NotExistException(oldname + " 不存在");//ServerException.FileNotExist(oldname);
  1314. }
  1315. string fileid = doc[IDFlag].ToString();
  1316. this.UploadFile(ref fileid, newname, null, null, null, false, true, team: team);
  1317. break;
  1318. case 't':
  1319. this.UpdateTemplateName(oldname, newname, team);
  1320. break;
  1321. case 'i':
  1322. this.UpdateInstanceName(oldname, newname, team);
  1323. break;
  1324. }
  1325. r["path"] = oldname;
  1326. r["type"] = type;
  1327. r["filename"] = newname;
  1328. return r;
  1329. };
  1330. case "file.update2"://不备份
  1331. return () =>
  1332. {
  1333. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1334. r["err"] = string.Empty;
  1335. string filename = p[0]._Str();
  1336. filename = filename._Path(this.ClientInfo.PageSource);
  1337. string filevalue = p[1]._Str();
  1338. string nodeid = p[2]._Str();
  1339. var ddoc = this.FindDocumentByName(FileCollection, filename, new string[] { IDFlag });
  1340. string fileid = null;
  1341. if (ddoc != null)
  1342. {
  1343. fileid = ddoc[IDFlag].AsString;
  1344. }
  1345. UploadFile(ref fileid, filename, null, null,
  1346. filevalue._Bytes(false), false, false, onlycontent: true, nodeid: nodeid, nobackup: true);
  1347. r["path"] = filename;
  1348. r["type"] = "file";
  1349. r["filename"] = filename;
  1350. return r;
  1351. };
  1352. case "file.update":
  1353. return () =>
  1354. {
  1355. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1356. r["err"] = string.Empty;
  1357. string filename = p[0]._Str();
  1358. filename = filename._Path(this.ClientInfo.PageSource);
  1359. string filevalue = p[1]._Str();
  1360. string nodeid = p[2]._Str();
  1361. bool nominhtml = p[3]._Bool();
  1362. bool nobackup = p[4]._Bool();
  1363. var ddoc = this.FindDocumentByName(FileCollection, filename, new string[] { IDFlag });
  1364. string fileid = null;
  1365. if (ddoc != null)
  1366. {
  1367. fileid = ddoc[IDFlag].AsString;
  1368. }
  1369. UploadFile(ref fileid, filename, null, null,
  1370. filevalue._Bytes(false), false, false, onlycontent: true, nodeid: nodeid, nominhtml: nominhtml, nobackup: nobackup);
  1371. r["path"] = filename;
  1372. r["type"] = "file";
  1373. r["filename"] = filename;
  1374. return r;
  1375. };
  1376. case "group.update":
  1377. return () =>
  1378. {
  1379. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1380. r["err"] = string.Empty;
  1381. r["msg"] = string.Empty;
  1382. string oldname = p[0]._Str();
  1383. string type = "file";
  1384. string[] fs = oldname.Split('?');
  1385. oldname = fs[0];
  1386. if (fs.Length > 1)
  1387. {
  1388. type = fs[1];
  1389. }
  1390. string newname = p[1]._Str();
  1391. string team = p[2]._Str();
  1392. oldname = WebUtility.UrlDecode(oldname).Trim('/').Trim();
  1393. newname = WebUtility.UrlDecode(newname).Trim('/').Trim();
  1394. newname = newname._Path();
  1395. r["name"] = newname;
  1396. string olduser = this.GetFirstName(oldname);
  1397. string newuser = this.GetFirstName(newname);
  1398. //if (!olduser.Equals(newuser, StringComparison.OrdinalIgnoreCase))
  1399. //{
  1400. // throw new NoSecurityException("没有权限", oldname);//(oldname, this.UserName);
  1401. //}
  1402. if (!newuser.Equals(olduser, StringComparison.OrdinalIgnoreCase))
  1403. {
  1404. throw new InvalidNameException(newname + " 不合法");//ServerException.InvalidName(newname);
  1405. }
  1406. if (Regex.Match(newname, @"[\\:\*\?""<>\|]", RegexOptions.IgnoreCase).Success)
  1407. {
  1408. throw new InvalidNameException("不合法的名称:" + newname); //ServerException.InvalidName(newname);
  1409. }
  1410. IMongoQuery q = GetQuery(oldname, team);
  1411. string collection = FileCollection;
  1412. switch (type.ToLower().First())
  1413. {
  1414. case 'i':
  1415. collection = InstanceCollection;
  1416. break;
  1417. case 't':
  1418. collection = TemplateCollection;
  1419. break;
  1420. }
  1421. var docs = this.dbHelper.Find(collection, q, new List<string> { IDFlag, NameFlag });
  1422. foreach (var doc in docs)
  1423. {
  1424. string id = doc[IDFlag].ToString();
  1425. string name = doc[NameFlag].ToString();
  1426. string objName = newname + "/" + name.Remove(0, oldname.Length);
  1427. string user = string.Empty;
  1428. string groupName = string.Empty;
  1429. CheckNameAndGroup(id, collection, ref objName, ref groupName, ref user);
  1430. this.GetRealName(ref objName, ref groupName, user);
  1431. BsonDocument values = new BsonDocument();
  1432. string lname = objName.ToLower();
  1433. string lgroup = GetLGroup(groupName);
  1434. this.AddNameMapping(lname, ref values);
  1435. values.Add(LNameFlag, lname);
  1436. values.Add(NameFlag, objName);
  1437. values.Add(GroupFlag, groupName);
  1438. values.Add(LGroupFlag, lgroup);
  1439. this.dbHelper.Update(collection, id, values);
  1440. }
  1441. r["msg"] = "updated: " + docs.Count;
  1442. return r;
  1443. };
  1444. case "symbol.cps":
  1445. return () =>
  1446. {
  1447. var symbolname = p[0]._Str();
  1448. if (string.IsNullOrEmpty(symbolname))
  1449. {
  1450. return null;
  1451. }
  1452. var doc = this.FindDocumentByName(FileCollection, symbolname, new string[] { Definitions.ValueFlag, DescriptionFlag, NameFlag });
  1453. if (doc == null)
  1454. {
  1455. throw new NotExistException("图形不存在:" + symbolname);
  1456. }
  1457. var vv = doc[Definitions.ValueFlag].AsByteArray._Str(false);
  1458. XmlDocument xmldoc = new XmlDocument();
  1459. xmldoc.LoadXml(vv);
  1460. var nodes = xmldoc.GetElementsByTagName("customproperty");
  1461. Dictionary<string, object> data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1462. foreach (var node in nodes)
  1463. {
  1464. var e = node as XmlElement;
  1465. var name = e.GetAttribute("name");
  1466. var id = e.GetAttribute("id");
  1467. var value = e.GetAttribute("value");
  1468. var type = e.GetAttribute("type");
  1469. var description = e.GetAttribute("description");
  1470. Dictionary<string, object> prop = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1471. prop["_value"] = value;
  1472. switch (type)
  1473. {
  1474. case "bool":
  1475. prop["_type"] = ItemDataType.Boolean;
  1476. break;
  1477. case "string":
  1478. prop["_type"] = ItemDataType.String;
  1479. break;
  1480. case "number":
  1481. prop["_type"] = ItemDataType.Decimal;
  1482. break;
  1483. }
  1484. prop["_desc"] = description;
  1485. prop["_change"] = "";
  1486. prop["_rid"] = "";
  1487. prop["_array"] = false;
  1488. prop["_ro"] = false;
  1489. prop["_history"] = false;
  1490. prop["_id"] = id;
  1491. data[name] = prop;
  1492. }
  1493. return data;
  1494. };
  1495. case "symbol.getimg":
  1496. return () =>
  1497. {
  1498. var name = p[0]._Str();
  1499. var value = p[1]._Str();
  1500. string ctype;
  1501. var id = this.CheckAndGetObjectId(name, out ctype);
  1502. var doc = this.FindDocumentById(ctype, id, new string[] { "_img" });
  1503. var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1504. result["id"] = doc.GetString(IDFlag);
  1505. result["img"] = doc.GetString("_img") ?? "";
  1506. return result;
  1507. };
  1508. case "symbol.saveimg":
  1509. return () =>
  1510. {
  1511. var name = p[0]._Str();
  1512. var value = p[1]._Str();
  1513. if (string.IsNullOrEmpty(value))
  1514. {
  1515. return false;
  1516. }
  1517. string ctype;
  1518. var id = this.CheckAndGetObjectId(name, out ctype);
  1519. var values = new BsonDocument();
  1520. values["_img"] = value;
  1521. values["_img2"] = "1";
  1522. this.dbHelper.Update(ctype, id, values, nobackup: true);
  1523. return true;
  1524. };
  1525. case "symbol.embeddedlist":
  1526. return () =>
  1527. {
  1528. var list = p[0]._StrList();
  1529. var sec = p[1]._Bool();
  1530. var dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1531. foreach (var name in list)
  1532. {
  1533. if (dic.ContainsKey(name))
  1534. {
  1535. continue;
  1536. }
  1537. var parents = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1538. this.GetEmbeddedList(name, dic, this.UserId, parents, sec);
  1539. }
  1540. return dic;
  1541. };
  1542. case "symbol.template":
  1543. return () =>
  1544. {
  1545. var symbolname = p[0]._Str();
  1546. var doc = this.FindDocumentByName(FileCollection, symbolname, new string[] { Definitions.ValueFlag, DescriptionFlag, NameFlag });
  1547. var vv = doc[Definitions.ValueFlag].AsByteArray._Str(false);
  1548. XmlDocument xmldoc = new XmlDocument();
  1549. xmldoc.LoadXml(vv);
  1550. var nodes = xmldoc.GetElementsByTagName("customproperty");
  1551. Dictionary<string, object> dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1552. Dictionary<string, object> data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1553. string me = this.GetLastName(doc[NameFlag].ToString());
  1554. dic[me] = data;
  1555. data["_symbol"] = symbolname;
  1556. data["_value"] = "";
  1557. data["_desc"] = doc.GetString(DescriptionFlag);
  1558. data["_change"] = "";
  1559. data["_rid"] = "";
  1560. data["_array"] = false;
  1561. data["_ro"] = false;
  1562. data["_history"] = false;
  1563. foreach (var node in nodes)
  1564. {
  1565. var e = node as XmlElement;
  1566. var name = e.GetAttribute("name");
  1567. var value = e.GetAttribute("value");
  1568. var type = e.GetAttribute("type");
  1569. var description = e.GetAttribute("description");
  1570. Dictionary<string, object> prop = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1571. prop["_value"] = value;
  1572. switch (type)
  1573. {
  1574. case "bool":
  1575. prop["_type"] = ItemDataType.Boolean;
  1576. break;
  1577. case "string":
  1578. prop["_type"] = ItemDataType.String;
  1579. break;
  1580. case "number":
  1581. prop["_type"] = ItemDataType.Decimal;
  1582. break;
  1583. }
  1584. prop["_desc"] = description;
  1585. prop["_change"] = "";
  1586. prop["_rid"] = "";
  1587. prop["_array"] = false;
  1588. prop["_ro"] = false;
  1589. prop["_history"] = false;
  1590. data[name] = prop;
  1591. }
  1592. return dic;
  1593. };
  1594. case "template.changeprop":
  1595. return () =>
  1596. {
  1597. //changeprop(tid, prop, value
  1598. var fullname = p[0]._Str();
  1599. var prop = p[1]._Str();
  1600. var value = p[2]._Str();
  1601. var tid = fullname;
  1602. var property = string.Empty;
  1603. int index = fullname.IndexOf('.');
  1604. if (index != -1)
  1605. {
  1606. tid = fullname.Substring(0, index);
  1607. property = fullname.Substring(index + 1);
  1608. }
  1609. BsonDocument tempDoc = this.FindDocumentById(TemplateCollection, tid, new string[] { Definitions.ValueFlag, UserFlag, NameFlag });
  1610. if (tempDoc == null)
  1611. {
  1612. throw new NotExistException("模板不存在:" + tid);
  1613. }
  1614. this.CheckSecurity(CollectionType.Template, tempDoc, SecurityType.Read);
  1615. tid = tempDoc.GetString(IDFlag);
  1616. tempDoc = tempDoc[Definitions.ValueFlag] as BsonDocument;
  1617. var ps = property.Split(".".ToArray(), StringSplitOptions.RemoveEmptyEntries);
  1618. var doc = tempDoc;
  1619. foreach (var pp in ps)
  1620. {
  1621. var e = doc.Find(pp);
  1622. doc = e.Value as BsonDocument;
  1623. }
  1624. if (value == null)
  1625. {
  1626. doc.Remove(prop);
  1627. }
  1628. else
  1629. {
  1630. doc[prop] = value;
  1631. }
  1632. this.PublishTemplate(ref tid, null, null, null, tempDoc.ToString(), true);
  1633. return true;
  1634. };
  1635. case "instance.templateid":
  1636. return () =>
  1637. {
  1638. string inst = p[0]._Str();
  1639. var tdoc = this.FindDocumentByName(InstanceCollection, inst, new string[] { TemplateFlag });
  1640. if (tdoc == null)
  1641. {
  1642. throw new NotExistException("实例不存在:" + inst);
  1643. }
  1644. return tdoc.GetString(TemplateFlag);
  1645. };
  1646. case "instance.template":
  1647. return () =>
  1648. {
  1649. var iname = p[0].ToString();
  1650. var tempnode = this.GetNodeForInstance(iname);
  1651. //foreach (var t in tempnode.Elements.ToList())
  1652. //{
  1653. // if (t.Value is BsonDocument)
  1654. // {
  1655. // tempnode.Remove(t.Name);
  1656. // }
  1657. //}
  1658. return tempnode.ToDictionary();
  1659. };
  1660. case "template.reference":
  1661. return () =>
  1662. {
  1663. var rid = p[0].ToString();
  1664. if (string.IsNullOrEmpty(rid))
  1665. {
  1666. return null;
  1667. }
  1668. var tempnode = this.GetTemplateNode(rid);
  1669. foreach (var t in tempnode.Elements.ToList())
  1670. {
  1671. if (t.Value is BsonDocument)
  1672. {
  1673. tempnode.Remove(t.Name);
  1674. }
  1675. }
  1676. return tempnode.ToDictionary();
  1677. };
  1678. case "instance.removeevent":
  1679. return () =>
  1680. {
  1681. var iid = p[0]._Str();
  1682. var id = p[2]._Str();
  1683. this.RemoveInstanceEvent(iid, id);
  1684. return null;
  1685. };
  1686. case "instance.setevent":
  1687. return () =>
  1688. {
  1689. var iid = p[0]._Str();
  1690. var e = p[1]._Str();
  1691. var id = p[2]._Str();
  1692. if (string.IsNullOrEmpty(e))
  1693. {
  1694. this.RemoveInstanceEvent(iid, id);
  1695. return null;
  1696. }
  1697. this.SetInstanceEvent(iid, e, id);
  1698. var dic = this.GetMyInstanceValue(iid, this.UserId, null, null);
  1699. TokenObject tokenObj = this.CopyToken();
  1700. Dictionary<string, object> data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1701. Dictionary<string, object> inputs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1702. inputs["id"] = dic.GetString("id");
  1703. inputs["value"] = this.myInstanceModels;
  1704. data["data()"] = inputs;
  1705. data["this"] = dic.GetString("id");
  1706. this.RunWorkflow(tokenObj, e, data);
  1707. return dic;
  1708. };
  1709. case "instance.binding":
  1710. return () =>
  1711. {
  1712. var iid = p[0]._Str();
  1713. var id = p[1]._Str();
  1714. var remove = p[2]._Bool();
  1715. if (remove)
  1716. {
  1717. this.RemoveInstanceEvent(iid, id);
  1718. return null;
  1719. }
  1720. var e = id + "=this";
  1721. this.SetInstanceEvent(iid, e, id);
  1722. var dic = this.GetMyInstanceValue(iid, this.UserId, null, null);
  1723. TokenObject tokenObj = this.CopyToken();
  1724. Dictionary<string, object> data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1725. Dictionary<string, object> inputs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1726. inputs["id"] = dic.GetString("id");
  1727. inputs["value"] = this.myInstanceModels;
  1728. data["data()"] = inputs;
  1729. data["this"] = dic.GetString("id");
  1730. this.RunWorkflow(tokenObj, e, data);
  1731. return dic;
  1732. };
  1733. case "instance.get":
  1734. return () =>
  1735. {
  1736. var dic = this.GetMyInstanceValue(p[0]._Str(), this.UserId, null, null);
  1737. return dic;
  1738. };
  1739. //case "instance.time":
  1740. // return () =>
  1741. // {
  1742. // return null;
  1743. // };
  1744. case "instance.symbol":
  1745. return () =>
  1746. {
  1747. Dictionary<string, object> cp = p[1] as Dictionary<string, object>;
  1748. Dictionary<string, object> size = p[2] as Dictionary<string, object>;
  1749. string clientname;
  1750. string username;
  1751. var symbolname = this.GetInstanceSymbol(p[0]._Str(), out clientname, out username);
  1752. var sn = symbolname.Trim('/');
  1753. if (sn.StartsWith("this/", StringComparison.OrdinalIgnoreCase))
  1754. {
  1755. symbolname = username + "/" + sn.Remove(0, 5);
  1756. }
  1757. var doc = this.FindDocumentByName(FileCollection, symbolname, new string[] { Definitions.ValueFlag });
  1758. if (doc == null)
  1759. {
  1760. throw new NotExistException("图形不存在:" + symbolname);
  1761. }
  1762. var value = doc[Definitions.ValueFlag].AsByteArray._Str(false);
  1763. XmlDocument xmldoc = new XmlDocument();
  1764. xmldoc.LoadXml(value);
  1765. if (cp != null)
  1766. {
  1767. var nodes = xmldoc.GetElementsByTagName("customproperty");
  1768. foreach (var node in nodes)
  1769. {
  1770. var e = node as XmlElement;
  1771. var name = e.GetAttribute("name");
  1772. object obj;
  1773. if (cp != null && cp.TryGetValue(name, out obj))
  1774. {
  1775. e.SetAttribute("value", obj._Str());
  1776. }
  1777. }
  1778. }
  1779. if (size != null)
  1780. {
  1781. var nodes = xmldoc.GetElementsByTagName("mxGraphModel");
  1782. foreach (var node in nodes)
  1783. {
  1784. var e = node as XmlElement;
  1785. object obj;
  1786. if (size != null)
  1787. {
  1788. if (size.TryGetValue("width", out obj))
  1789. {
  1790. e.SetAttribute("pageWidth", obj._Str());
  1791. }
  1792. if (size.TryGetValue("height", out obj))
  1793. {
  1794. e.SetAttribute("pageHeight", obj._Str());
  1795. }
  1796. }
  1797. }
  1798. }
  1799. return xmldoc.InnerXml;
  1800. };
  1801. case "file.exist":
  1802. return () =>
  1803. {
  1804. string filename = p[0]._Str();
  1805. string collection = FileCollection;
  1806. return this.FileExist(filename, collection);
  1807. };
  1808. case "template.exist":
  1809. return () =>
  1810. {
  1811. string filename = p[0]._Str();
  1812. string collection = TemplateCollection;
  1813. return this.FileExist(filename, collection);
  1814. };
  1815. case "instance.exist":
  1816. return () =>
  1817. {
  1818. string filename = p[0]._Str();
  1819. string collection = InstanceCollection;
  1820. return this.FileExist(filename, collection);
  1821. };
  1822. case "setteam":
  1823. return () =>
  1824. {
  1825. this.SetTeam(p[0]._Str(), p[1]._Str());
  1826. return true;
  1827. };
  1828. case "file":
  1829. case "template":
  1830. return () =>
  1831. {
  1832. if (p[0] is Dictionary<string, object>)
  1833. {
  1834. var pd = (Dictionary<string, object>)p[0];
  1835. var a = new ArrayList();
  1836. a.Add(pd._Value("name"));
  1837. a.Add(pd._Value("value"));
  1838. a.Add(pd._Value("desc"));
  1839. a.Add(pd._Value("ispkg"));
  1840. a.Add(pd._Value("ignoreexist"));
  1841. a.Add(pd._Value("isnew"));
  1842. a.Add(pd._Value("min"));
  1843. a.Add(pd._Value("id"));
  1844. a.Add(pd._Value("team"));
  1845. a.Add(pd._Value("tag"));
  1846. ParameterModel pm = new ParameterModel();
  1847. pm.AddRange(a);
  1848. p = pm;
  1849. }
  1850. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  1851. string path = string.Empty;
  1852. string filename = p[0]._Str();
  1853. string type = v;
  1854. r["err"] = string.Empty;
  1855. //try
  1856. //{
  1857. filename = filename._Path(this.ClientInfo.PageSource);
  1858. r["name"] = filename;
  1859. string[] fs222 = filename.Split('|');
  1860. string newname = null;
  1861. if (fs222.Length > 1)
  1862. {
  1863. filename = fs222[0];
  1864. newname = fs222[1];
  1865. newname = newname._Path(this.ClientInfo.PageSource);
  1866. r["name"] = newname;
  1867. }
  1868. string[] fs = filename.Split('?');
  1869. filename = fs[0];
  1870. this.CheckName(ref filename);
  1871. if (fs.Length > 1)
  1872. {
  1873. type = fs[1].ToLower();
  1874. }
  1875. if (filename.EndsWith("/"))
  1876. {
  1877. throw new InvalidNameException("文件名不合法");
  1878. }
  1879. if (p.Count == 1)
  1880. {
  1881. switch (type)
  1882. {
  1883. case "instance":
  1884. BsonDocument doc3 = this.FindDocumentByName(InstanceCollection, filename, new string[] { NameFlag, DescriptionFlag, TemplateFlag, UserFlag });
  1885. if (doc3 == null)
  1886. {
  1887. throw new NotExistException("不存在:" + filename);// ServerException.NotExist(filename);
  1888. }
  1889. filename = doc3[NameFlag].ToString();
  1890. this.CheckTeamSecurity(doc3);
  1891. doc3.Remove(UserFlag);
  1892. string vs3 = this.GetInstance(filename);
  1893. r["value"] = vs3;
  1894. r["property"] = doc3.ToDictionary();
  1895. return r;
  1896. case "template":
  1897. BsonDocument doc2 = this.FindDocumentByName(TemplateCollection, filename, new string[] { NameFlag, DescriptionFlag, UserFlag, "_value", "_value_" });
  1898. if (doc2 == null)
  1899. {
  1900. throw new NotExistException("不存在:" + filename);//ServerException.NotExist(filename);
  1901. }
  1902. filename = doc2[NameFlag].ToString();
  1903. this.CheckTeamSecurity(doc2);
  1904. doc2.Remove(UserFlag);
  1905. string vs2 = null;
  1906. BsonValue bv;
  1907. if (doc2.TryGetValue("_value_", out bv))
  1908. {
  1909. doc2.Remove("_value_");
  1910. vs2 = bv.AsString;
  1911. }
  1912. if (doc2.TryGetValue("_value", out bv))
  1913. {
  1914. doc2.Remove("_value");
  1915. if (vs2 == null)
  1916. {
  1917. vs2 = bv._Json();
  1918. }
  1919. }
  1920. r["value"] = vs2;
  1921. r["property"] = doc2.ToDictionary();
  1922. return r;
  1923. default:
  1924. BsonDocument doc = this.FindDocumentByName(FileCollection, filename, new string[] { NameFlag, DescriptionFlag, UserFlag, SizeFlag });
  1925. if (doc == null)
  1926. {
  1927. throw new NotExistException(filename + " 不存在");//ServerException.FileNotExist(filename);
  1928. }
  1929. filename = doc[NameFlag].ToString();
  1930. this.CheckTeamSecurity(doc);
  1931. doc.Remove(UserFlag);
  1932. //doc.Remove(TeamFlag);
  1933. //string fileExt = Path.GetExtension(filename);
  1934. byte[] vs = null;
  1935. int size = 0;
  1936. if (doc.TryGetValue(SizeFlag, out bv))
  1937. {
  1938. size = bv.AsInt32;
  1939. }
  1940. if (size < 10000 * 1000)
  1941. {
  1942. vs = this.GetFileContent(filename);
  1943. }
  1944. if (doc == null)
  1945. {
  1946. throw new NotExistException(filename + " 不存在");
  1947. }
  1948. r["value"] = vs._Str(false);
  1949. r["property"] = doc.ToDictionary();
  1950. return r;
  1951. }
  1952. }
  1953. byte[] vbytes = null;
  1954. if (p[1] != null)
  1955. {
  1956. if (p[1] is byte[])
  1957. {
  1958. vbytes = (byte[])p[1];
  1959. }
  1960. else
  1961. {
  1962. string vstr = p[1]._Str();
  1963. vbytes = vstr._ObjBytes(false);
  1964. }
  1965. }
  1966. bool content = true;
  1967. if (p.Count > 2)
  1968. {
  1969. content = false;
  1970. }
  1971. string description = p[2]._Str();
  1972. bool ispkg = p[3]._Bool();
  1973. bool ignoreexist = p[4]._Bool();
  1974. bool isnew = p[5]._Bool();
  1975. bool min = p[6]._Bool();
  1976. string id = p[7]._Str();
  1977. if (id == "null" || id == "undefined")
  1978. {
  1979. id = null;
  1980. }
  1981. string team = p[8]._Str();
  1982. string tag = p[9]._Str();
  1983. string objid = null;
  1984. script.MyScriptTimeout = () =>
  1985. {
  1986. return 60000 * 10;
  1987. };
  1988. Action<byte[], string, string, string, string, bool> uploadAction = null;
  1989. Action<byte[], string, string> unzipAction = (mybytes, mygroup, mytype) =>
  1990. {
  1991. Zip.Unzip(mybytes, (name, value) =>
  1992. {
  1993. uploadAction(value, mygroup, mytype, name, null, true);
  1994. });
  1995. };
  1996. uploadAction = (myvalue, mygroup, mytype, myname, mynewname, mycontent) =>
  1997. {
  1998. if (myname.EndsWith(".$template$.zip"))
  1999. {
  2000. if (string.IsNullOrEmpty(mygroup))
  2001. {
  2002. int lastindex = myname.LastIndexOf('/');
  2003. if (lastindex > 0)
  2004. {
  2005. mygroup = myname.Substring(0, lastindex);
  2006. }
  2007. }
  2008. unzipAction(myvalue, mygroup, "template");
  2009. return;
  2010. }
  2011. if (!string.IsNullOrEmpty(mygroup))
  2012. {
  2013. myname = mygroup + "/" + myname;
  2014. }
  2015. if (ignoreexist && FileExist(myname))
  2016. {
  2017. return;
  2018. }
  2019. path = null;
  2020. switch (mytype)
  2021. {
  2022. case "instance":
  2023. var values = myvalue._Str(false)._Dic();
  2024. TemplateModel tm = new TemplateModel();
  2025. tm.Cons = ConditionModel.Create(values, string.Empty);
  2026. this.PublishInstance(ref path, myname, description, string.Empty, null, DataOperations.Upsert, tm, newname: mynewname, fornew: isnew, oid: id, team: team);
  2027. objid = path;
  2028. break;
  2029. case "template":
  2030. this.PublishTemplate(ref path, myname, description, string.Empty, myvalue._Str(false), upsert: true, newname: mynewname, fornew: isnew, oid: id, team: team, tag: tag);
  2031. objid = path;
  2032. break;
  2033. default:
  2034. objid = UploadFileByName(out path, myname, myvalue, DataOperations.Upsert, description, mycontent, newname: mynewname, fornew: isnew, min: min, oid: id, team: team, tag: tag);
  2035. path = objid;
  2036. break;
  2037. }
  2038. };
  2039. if (ispkg)
  2040. {
  2041. string group = string.Empty;
  2042. int lastindex = filename.LastIndexOf('/');
  2043. if (lastindex > 0)
  2044. {
  2045. group = filename.Substring(0, lastindex);
  2046. }
  2047. if (vbytes != null && vbytes.Length > 0)
  2048. {
  2049. unzipAction(vbytes, group, type);
  2050. }
  2051. }
  2052. else
  2053. {
  2054. if (!filename.Contains('/'))
  2055. {
  2056. string collection = FileCollection;
  2057. switch (type)
  2058. {
  2059. case "instance":
  2060. collection = InstanceCollection;
  2061. break;
  2062. case "template":
  2063. collection = TemplateCollection;
  2064. break;
  2065. default:
  2066. collection = FileCollection;
  2067. break;
  2068. }
  2069. var doc = this.FindDocumentById(collection, filename, new string[] { NameFlag });
  2070. if (doc == null)
  2071. {
  2072. throw new NotExistException("不存在:" + filename);
  2073. }
  2074. filename = doc.GetString(NameFlag);
  2075. path = doc.GetString(IDFlag);
  2076. }
  2077. if (filename.Equals(newname, StringComparison.OrdinalIgnoreCase))
  2078. {
  2079. newname = null;
  2080. }
  2081. uploadAction(vbytes, null, type, filename, newname, content);
  2082. //switch (type)
  2083. //{
  2084. // case "instance":
  2085. // var values = p[1]._Str(false)._Dic();
  2086. // TemplateModel tm = new TemplateModel();
  2087. // tm.Cons = ConditionModel.Create(values, string.Empty);
  2088. // this.PublishInstance(ref path, filename, description, string.Empty, null, DataOperations.Upsert, tm, newname: newname, fornew: isnew, oid: id, team: team);
  2089. // objid = path;
  2090. // break;
  2091. // case "template":
  2092. // this.PublishTemplate(ref path, filename, description, string.Empty, p[1]._Str(false), upsert: true, newname: newname, fornew: isnew, oid: id, team: team, tag: tag);
  2093. // objid = path;
  2094. // break;
  2095. // default:
  2096. // objid = UploadFileByName(out path, filename, vbytes, DataOperations.Upsert, description, content, newname: newname, fornew: isnew, min: min, oid: id, team: team, tag: tag);
  2097. // break;
  2098. //}
  2099. }
  2100. //SendResultMessage("Save " + type + ": " + filename + "; path: " + path);
  2101. //}
  2102. //catch (Exception ex)
  2103. //{
  2104. // throw ex;
  2105. // //SendResultMessage("Save " + type + ": " + ex._msg());
  2106. // //r["err"] = ex._msg();
  2107. //}
  2108. r["id"] = objid;
  2109. r["path"] = path;
  2110. r["type"] = type;
  2111. r["filename"] = filename;
  2112. script.MyScriptTimeout = null;
  2113. return r;
  2114. };
  2115. case "file.bytes":
  2116. return () =>
  2117. {
  2118. try
  2119. {
  2120. string filename = p[0]._Str();
  2121. byte[] vs = this.GetFileContent(filename);
  2122. return vs;
  2123. }
  2124. catch (Exception ex)
  2125. {
  2126. Log.LogMessage("Error", ex.Message);
  2127. //SendResultMessage("file.bytes: " + ex._msg());
  2128. return null;
  2129. }
  2130. };
  2131. case "group.copy":
  2132. return () =>
  2133. {
  2134. if (string.IsNullOrEmpty(this.UserId))
  2135. {
  2136. throw new NoSecurityException("需要登录");
  2137. }
  2138. bool fornew = p[2]._Bool();
  2139. string group = p[0]._Str().Trim('/').Trim();
  2140. group = WebUtility.UrlDecode(group);
  2141. string copygroup = p[1]._Str().Trim('/').Trim();
  2142. copygroup = WebUtility.UrlDecode(copygroup);
  2143. string type = "file";
  2144. var wenhao = group.IndexOf('?');
  2145. if (wenhao != -1)
  2146. {
  2147. type = group.Substring(wenhao + 1);
  2148. group = group.Substring(0, wenhao);
  2149. }
  2150. string collection = FileCollection;
  2151. if (!string.IsNullOrEmpty(type))
  2152. {
  2153. switch (type.ToLower())
  2154. {
  2155. case "instance":
  2156. collection = InstanceCollection;
  2157. break;
  2158. case "template":
  2159. collection = TemplateCollection;
  2160. break;
  2161. }
  2162. }
  2163. var q = GetQuery(group, null);
  2164. var c = this.dbHelper.Sum(collection, q);
  2165. int limit = DataClient.GetMyLimit(this.UserId, "Download")._Int();
  2166. if (limit > 0 && c > limit)
  2167. {
  2168. string msg = "文件数量太大:" + c + ">" + limit;
  2169. this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + msg, new List<string> { this.UserId }, null);
  2170. throw new OverLimitException(msg);
  2171. }
  2172. var docs = this.dbHelper.Find(collection, q, new List<string> { NameFlag, SizeFlag });
  2173. int grouplength = group.Length;
  2174. foreach (var d in docs)
  2175. {
  2176. string name = d[NameFlag].AsString;
  2177. string othername = name.Remove(0, grouplength);
  2178. string newfilename = copygroup + othername;
  2179. string path = null;
  2180. switch (type)
  2181. {
  2182. case "instance":
  2183. var vvv = this.FindDocumentById(collection, d[IDFlag].ToString(), new string[] { TemplateFlag, Definitions.ValueFlag });
  2184. var value = vvv[Definitions.ValueFlag] as BsonDocument;
  2185. TemplateModel tm = new TemplateModel();
  2186. tm.Cons = ConditionModel.Create(value.ToDictionary(), string.Empty);
  2187. this.PublishInstance(ref path, newfilename, string.Empty, string.Empty, vvv[TemplateFlag].ToString(), DataOperations.Upsert, tm, fornew: fornew);
  2188. break;
  2189. case "template":
  2190. vvv = this.FindDocumentById(collection, d["_id"].ToString(), new string[] { Definitions.ValueFlag });
  2191. var resultstring = vvv[Definitions.ValueFlag].ToString();
  2192. this.PublishTemplate(ref path, newfilename, string.Empty, string.Empty, resultstring, fornew: fornew);
  2193. break;
  2194. default:
  2195. byte[] result = this.GetValueResult(d, collection);
  2196. UploadFileByName(out path, newfilename, result, DataOperations.Upsert, string.Empty, false, fornew: fornew);
  2197. break;
  2198. }
  2199. }
  2200. return null;
  2201. };
  2202. case "group.export":
  2203. case "group.clone":
  2204. //script.
  2205. return () =>
  2206. {
  2207. try
  2208. {
  2209. if (string.IsNullOrEmpty(this.UserId))
  2210. {
  2211. throw new NoSecurityException("需要登录");
  2212. }
  2213. //var userdoc = this.FindDocumentById(UserCollection, this.UserId, new string[] { "_exporttime" });
  2214. //BsonValue bv;
  2215. //if (userdoc.TryGetValue("_exporttime", out bv))
  2216. //{
  2217. // var t = bv.ToUniversalTime();
  2218. // var diff = DateTime.UtcNow - t;
  2219. // if (diff.TotalMinutes < 1)
  2220. // {
  2221. // throw new TimeLimitException("间隔时间需要大于1分钟");
  2222. // }
  2223. //}
  2224. string group = p[0]._Str().Trim('/').Trim();
  2225. group = WebUtility.UrlDecode(group);
  2226. string team = p[3]._Str();
  2227. string type = p[1]._Str();
  2228. var wenhao = group.IndexOf('?');
  2229. if (wenhao != -1)
  2230. {
  2231. type = group.Substring(wenhao + 1);
  2232. group = group.Substring(0, wenhao);
  2233. }
  2234. string[] allfilenames = null;
  2235. ArrayList namelist = p[2] as ArrayList;
  2236. if (namelist == null)
  2237. {
  2238. string zipname = p[2]._Str();
  2239. Dictionary<string, object> data;
  2240. if (zipname._IsJson(out data))
  2241. {
  2242. var dic = data;
  2243. string value = dic._Value("value")._Str();
  2244. allfilenames = value.Split("\r\n".ToArray(), StringSplitOptions.RemoveEmptyEntries);
  2245. }
  2246. }
  2247. else
  2248. {
  2249. allfilenames = new string[namelist.Count];
  2250. for (int i = 0; i < namelist.Count; i++)
  2251. {
  2252. allfilenames[i] = namelist[i]._Str();
  2253. }
  2254. }
  2255. IMongoQuery q = null;
  2256. if (allfilenames != null)
  2257. {
  2258. foreach (var f in allfilenames)
  2259. {
  2260. if (string.IsNullOrEmpty(f))
  2261. {
  2262. continue;
  2263. }
  2264. if (!f.StartsWith("/" + this.UserName + "/"))
  2265. {
  2266. throw new NoSecurityException("没有权限", f);
  2267. }
  2268. if (f.EndsWith("/"))
  2269. {
  2270. var folder = f.Trim('/').Trim();
  2271. int count = folder.Split('/').Length;
  2272. IMongoQuery q2 = Query.EQ("_g." + "g" + count, folder.ToLower());
  2273. if (q == null)
  2274. {
  2275. q = q2;
  2276. }
  2277. else
  2278. {
  2279. q = Query.Or(q, q2);
  2280. }
  2281. }
  2282. else
  2283. {
  2284. var q2 = Query.EQ(LNameFlag, f.Trim('/').Trim().ToLower());
  2285. if (q == null)
  2286. {
  2287. q = q2;
  2288. }
  2289. else
  2290. {
  2291. q = Query.Or(q, q2);
  2292. }
  2293. }
  2294. }
  2295. }
  2296. else
  2297. {
  2298. q = GetQuery(group, team);
  2299. }
  2300. string collection = FileCollection;
  2301. if (!string.IsNullOrEmpty(type))
  2302. {
  2303. switch (type.ToLower())
  2304. {
  2305. case "instance":
  2306. collection = InstanceCollection;
  2307. break;
  2308. case "template":
  2309. collection = TemplateCollection;
  2310. break;
  2311. }
  2312. }
  2313. var c = this.dbHelper.Sum(collection, q);
  2314. int limit = DataClient.GetMyLimit(this.UserId, "Download")._Int();
  2315. if (limit > 0 && c > limit)
  2316. {
  2317. string msg = "文件数量太大:" + c + ">" + limit;
  2318. this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + msg, new List<string> { this.UserId }, null);
  2319. throw new OverLimitException(msg);
  2320. }
  2321. var docs = this.dbHelper.Find(collection, q, new List<string> { NameFlag, SizeFlag });
  2322. script.MyScriptTimeout = () =>
  2323. {
  2324. return 60000 * 10;
  2325. };
  2326. //BsonDocument newuserdoc = new BsonDocument();
  2327. //newuserdoc["_exporttime"] = DateTime.UtcNow;
  2328. //this.dbHelper.Update(UserCollection, this.UserId, newuserdoc);
  2329. if (v == "group.export")
  2330. {
  2331. var copygroup = p[5]._Str();
  2332. if (!string.IsNullOrEmpty(copygroup))
  2333. {
  2334. copygroup = copygroup.Trim('/').Trim();
  2335. copygroup = WebUtility.UrlDecode(copygroup);
  2336. }
  2337. string progress = string.Empty;
  2338. Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
  2339. int i = 0;
  2340. int count = docs.Count;
  2341. DateTime dt = DateTime.UtcNow;
  2342. int sizetotal = 0;
  2343. string totalsize = CommonFunction.CountSize(c);
  2344. //Dictionary<string, object> idmapping = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2345. foreach (var d in docs)
  2346. {
  2347. int size = d[SizeFlag].AsInt32;
  2348. sizetotal = sizetotal + size;
  2349. i++;
  2350. var diff = DateTime.UtcNow - dt;
  2351. progress = "大小:" + CommonFunction.CountSize(sizetotal) + "/" + totalsize + "; 进度:" + i.ToString() + "/" + count.ToString() + "; 时间:" + diff.TotalSeconds + "; 机器:" + ServerInfo.Domain + "; 状态:" + !script.StackObj.Stopped + " " + script.StackObj.LastError;
  2352. DataClient dc = new DataClient(this.CopyToken());
  2353. dc.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + progress, new List<string> { this.UserId }, null);
  2354. if (script.StackObj.Stopped)
  2355. {
  2356. return null;
  2357. }
  2358. string name = d[NameFlag].AsString;
  2359. if (!string.IsNullOrEmpty(copygroup))
  2360. {
  2361. int grouplength = group.Length;
  2362. string othername = name.Remove(0, grouplength);
  2363. name = copygroup + othername;
  2364. }
  2365. byte[] result;
  2366. if (collection == DataClient.InstanceCollection)
  2367. {
  2368. var vvv = this.FindDocumentById(collection, d[IDFlag].ToString(), new string[] { TemplateFlag, Definitions.ValueFlag });
  2369. var value = vvv[Definitions.ValueFlag] as BsonDocument;
  2370. Dictionary<string, object> rrr = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2371. rrr["tid"] = vvv[TemplateFlag].ToString();
  2372. rrr["value"] = value.ToDictionary();
  2373. result = rrr._Json()._Bytes(false);
  2374. }
  2375. else
  2376. {
  2377. result = this.GetValueResult(d, collection);
  2378. }
  2379. int lastindex = name.IndexOf('/');
  2380. string filename = name.Remove(0, lastindex + 1);
  2381. if (p[4]._Bool())
  2382. {
  2383. files[filename + ".$." + d.GetString(IDFlag)] = result;
  2384. }
  2385. else
  2386. {
  2387. files[filename] = result;
  2388. }
  2389. //idmapping[filename ] = d.GetString(IDFlag);
  2390. }
  2391. //files["$.idmapping"] = idmapping._Json()._Bytes(false);
  2392. var values = Zip.ToBytes(files);
  2393. return values;
  2394. }
  2395. else
  2396. {
  2397. string newid = NewId;
  2398. int i = 0;
  2399. int count = docs.Count;
  2400. DateTime dt = DateTime.UtcNow;
  2401. int grouplength = group.Length;
  2402. string datestring = DateTime.UtcNow.ToString("_MMdd_HHmmss_fff");
  2403. foreach (var d in docs)
  2404. {
  2405. i++;
  2406. var diff = DateTime.UtcNow - dt;
  2407. string progress = i.ToString() + "/" + count.ToString() + "; 时间:" + diff.TotalSeconds + "; 状态:" + !script.StackObj.Stopped + " " + script.StackObj.LastError;
  2408. this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + progress, null, null);
  2409. if (script.StackObj.Stopped)
  2410. {
  2411. return null;
  2412. }
  2413. string name = d[NameFlag].AsString;
  2414. string othername = name.Remove(0, grouplength);
  2415. string newfilename = group + datestring + othername;
  2416. string path = null;
  2417. switch (type)
  2418. {
  2419. case "instance":
  2420. var vvv = this.FindDocumentById(collection, d[IDFlag].ToString(), new string[] { TemplateFlag, Definitions.ValueFlag });
  2421. var value = vvv[Definitions.ValueFlag] as BsonDocument;
  2422. TemplateModel tm = new TemplateModel();
  2423. tm.Cons = ConditionModel.Create(value.ToDictionary(), string.Empty);
  2424. this.PublishInstance(ref path, newfilename, string.Empty, string.Empty, vvv[TemplateFlag].ToString(), DataOperations.Upsert, tm, fornew: true);
  2425. break;
  2426. case "template":
  2427. vvv = this.FindDocumentById(collection, d["_id"].ToString(), new string[] { Definitions.ValueFlag });
  2428. var resultstring = vvv[Definitions.ValueFlag].ToString();
  2429. this.PublishTemplate(ref path, newfilename, string.Empty, string.Empty, resultstring, fornew: true);
  2430. break;
  2431. default:
  2432. byte[] result = this.GetValueResult(d, collection);
  2433. UploadFileByName(out path, newfilename, result, DataOperations.Insert, string.Empty, false, fornew: true);
  2434. break;
  2435. }
  2436. }
  2437. string msg = "导出完成!";
  2438. this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + msg, new List<string> { this.UserId }, null);
  2439. return true;
  2440. }
  2441. }
  2442. catch (Exception ex)
  2443. {
  2444. Thread.Sleep(1000);
  2445. this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "; 错误:" + ex._msg(), new List<string> { this.UserId }, null);
  2446. throw ex;
  2447. }
  2448. finally
  2449. {
  2450. script.MyScriptTimeout = null;
  2451. //BsonDocument newuserdoc = new BsonDocument();
  2452. //newuserdoc["_exporttime"] = DateTime.MinValue;
  2453. //this.dbHelper.Update(UserCollection, this.UserId, newuserdoc);
  2454. }
  2455. };
  2456. case "file.export":
  2457. return () =>
  2458. {
  2459. string filename = p[0]._Str().Trim('/').Trim();
  2460. //if (!this.GetFirstName(filename).Equals(this.UserName, StringComparison.OrdinalIgnoreCase))
  2461. //{
  2462. // throw new NoSecurityException("没有权限", filename);//(filename, this.UserName);
  2463. //}
  2464. string type = p[1]._Str();
  2465. string collection = FileCollection;
  2466. CollectionType ct = CollectionType.File;
  2467. switch (type)
  2468. {
  2469. case "instance":
  2470. collection = InstanceCollection;
  2471. ct = CollectionType.Instance;
  2472. break;
  2473. case "template":
  2474. collection = TemplateCollection;
  2475. ct = CollectionType.Template;
  2476. break;
  2477. }
  2478. var d = this.FindDocumentByName(collection, filename, new string[] { IDFlag, NameFlag, UserFlag });
  2479. if (d == null)
  2480. {
  2481. return null;
  2482. }
  2483. this.CheckSecurity(ct, d, SecurityType.Read);
  2484. byte[] result = this.GetValueResult(d, collection);
  2485. Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
  2486. files[filename] = result;
  2487. var values = Zip.ToBytes(files);
  2488. return values;
  2489. };
  2490. case "file.delete":
  2491. case "group.delete":
  2492. return () =>
  2493. {
  2494. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2495. r["err"] = string.Empty;
  2496. string type = "file";
  2497. string filename = p[0]._Str();
  2498. //object obj2;
  2499. //if (vget.TryGetValue("filename", out obj2))
  2500. //{
  2501. // filename = obj2._Str();
  2502. //}
  2503. string[] fs = filename.Split('?');
  2504. filename = fs[0];
  2505. if (fs.Length > 1)
  2506. {
  2507. type = fs[1];
  2508. }
  2509. bool isgroup = false;
  2510. if (v == "group.delete" || filename.EndsWith("/"))
  2511. {
  2512. isgroup = true;
  2513. }
  2514. //bool backup = p[1]._Bool();
  2515. string team = p[1]._Str();
  2516. string path = filename;
  2517. if (isgroup)
  2518. {
  2519. script.MyScriptTimeout = () =>
  2520. {
  2521. return 60000 * 10;
  2522. };
  2523. IMongoQuery q = GetQuery(filename, team);
  2524. string collection = FileCollection;
  2525. switch (type)
  2526. {
  2527. case "instance":
  2528. collection = InstanceCollection;
  2529. break;
  2530. case "template":
  2531. collection = TemplateCollection;
  2532. break;
  2533. }
  2534. var docs = this.dbHelper.Find(collection, q, new List<string> { IDFlag });
  2535. foreach (var d in docs)
  2536. {
  2537. string id2 = d[IDFlag].ToString();
  2538. path = id2;
  2539. switch (type)
  2540. {
  2541. case "instance":
  2542. this.DeleteInstance(id2);
  2543. break;
  2544. case "template":
  2545. this.DeleteTemplate(id2);
  2546. break;
  2547. default:
  2548. this.DeleteFile(id2);
  2549. break;
  2550. }
  2551. }
  2552. script.MyScriptTimeout = null;
  2553. }
  2554. else
  2555. {
  2556. switch (type)
  2557. {
  2558. case "instance":
  2559. this.DeleteInstance(filename);
  2560. break;
  2561. case "template":
  2562. this.DeleteTemplate(filename);
  2563. break;
  2564. default:
  2565. this.DeleteFile(filename);
  2566. break;
  2567. }
  2568. }
  2569. r["path"] = path;
  2570. r["type"] = type;
  2571. r["filename"] = filename;
  2572. return r;
  2573. };
  2574. case "instances":
  2575. return () =>
  2576. {
  2577. if (string.IsNullOrEmpty(this.UserId))
  2578. {
  2579. return null;
  2580. }
  2581. string search = p[0]._Str();
  2582. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  2583. if (!string.IsNullOrEmpty(search))
  2584. {
  2585. string lsearch = search.ToLower();
  2586. IMongoQuery mq = Query.Or(Query.Matches(LNameFlag, new BsonRegularExpression(lsearch)), Query.Matches(LDescriptionFlag, new BsonRegularExpression(lsearch)));
  2587. q = Query.And(q, mq);
  2588. }
  2589. var docs = this.dbHelper.Find(InstanceCollection, q, new List<string> { NameFlag }, sortby: new SortByDocument(ModifiedFlag, -1));
  2590. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  2591. foreach (var doc in docs)
  2592. {
  2593. string id = doc[NameFlag].ToString();
  2594. Dictionary<string, object> value = this.GetInstance(id)._Dic()._DicValue() as Dictionary<string, object>;
  2595. var v2 = value._DicKeys(id);
  2596. foreach (var keyvalue in v2)
  2597. {
  2598. list.Add(new Dictionary<string, object> { { "_name", keyvalue.Key }, { "id", keyvalue.Key.ToLower()._MD5() } });
  2599. }
  2600. }
  2601. return list;
  2602. };
  2603. case "publish":
  2604. {
  2605. return () =>
  2606. {
  2607. string name = p[0]._Str();
  2608. string value = p[1]._Str();
  2609. IList touser = p[2] as IList;
  2610. Dictionary<string, object> cp = p[3] as Dictionary<string, object>;
  2611. if (touser != null)
  2612. {
  2613. int count = touser.Count;
  2614. for (int i = 0; i < count; i++)
  2615. {
  2616. string user = touser[i].ToString();
  2617. if (user.Length != 24)
  2618. {
  2619. string userid = this.GetUserId(user);
  2620. if (string.IsNullOrEmpty(userid))
  2621. {
  2622. throw new UserNotExistException("用户不存在:" + user);
  2623. }
  2624. touser[i] = userid;
  2625. }
  2626. else
  2627. {
  2628. string userid = this.GetUserName(user);
  2629. if (string.IsNullOrEmpty(userid))
  2630. {
  2631. throw new UserNotExistException("用户不存在:" + user);
  2632. }
  2633. }
  2634. }
  2635. }
  2636. Dictionary<string, MyInstanceModel> models = null;
  2637. object data = null;
  2638. if (vget.TryGetValue("data()", out data))
  2639. {
  2640. object attr = null;
  2641. InstanceAttr myattr = null;
  2642. if (vget.TryGetValue("attr()", out attr))
  2643. {
  2644. myattr = attr as InstanceAttr;
  2645. }
  2646. if (myattr != null)
  2647. {
  2648. touser = myattr.To;
  2649. cp = myattr.CustomProperty;
  2650. }
  2651. Dictionary<string, object> refdata = data as Dictionary<string, object>;
  2652. if (refdata != null)
  2653. {
  2654. object m = null;
  2655. if (refdata.TryGetValue("value", out m))
  2656. {
  2657. models = (Dictionary<string, MyInstanceModel>)m;
  2658. this.myInstanceModels = models;
  2659. }
  2660. }
  2661. }
  2662. this.UpdateInstance(name, value, to: touser, cp: cp, models: models);
  2663. return true;
  2664. };
  2665. }
  2666. case "template.history":
  2667. return () =>
  2668. {
  2669. string tid = p[0]._Str();
  2670. tid = HttpUtility.UrlDecode(tid);
  2671. if (tid.StartsWith("/"))
  2672. {
  2673. tid = tid._Path(this.GetSource());
  2674. }
  2675. var valuefield = "doc._value";
  2676. List<string> fields = new List<string>() { valuefield, UserFlag, "id", "name", "desc", "tag" };
  2677. BsonDocument doc = this.dbHelper.FindDocumentByQuery(TemplateHistoryCollection, Query.EQ(IDFlag, tid), fields.ToArray());
  2678. if (doc == null)
  2679. {
  2680. throw new NotExistException("不存在:" + tid);
  2681. }
  2682. var id = doc.GetString("id");
  2683. this.CheckSecurity(id, CollectionType.Template, SecurityType.Read);
  2684. var tempDoc = doc.Value(valuefield) as BsonDocument;
  2685. string owner = doc[UserFlag].ToString();
  2686. RefreshTemplate(ref owner, tempDoc);
  2687. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2688. result["id"] = id;
  2689. result["name"] = doc.GetString("name");
  2690. result["desc"] = doc.GetString("desc");
  2691. result["tag"] = doc.GetString("tag");
  2692. result["value"] = tempDoc.ToDictionary();
  2693. return result;
  2694. };
  2695. case "template.get":
  2696. return () =>
  2697. {
  2698. string tid = p[0]._Str();
  2699. tid = HttpUtility.UrlDecode(tid);
  2700. if (string.IsNullOrEmpty(tid))
  2701. {
  2702. return null;
  2703. }
  2704. if (tid.StartsWith("/"))
  2705. {
  2706. tid = tid._Path(this.GetSource());
  2707. }
  2708. BsonDocument tempDoc = this.FindDocumentById(TemplateCollection, tid, new string[] { Definitions.ValueFlag, UserFlag, NameFlag });
  2709. if (tempDoc == null)
  2710. {
  2711. throw new NotExistException("模板不存在:" + tid);
  2712. }
  2713. this.CheckSecurity(CollectionType.Template, tempDoc, SecurityType.Read);
  2714. string owner = tempDoc[UserFlag].ToString();
  2715. tempDoc = tempDoc[Definitions.ValueFlag] as BsonDocument;
  2716. BsonDocument returnDoc = tempDoc;
  2717. RefreshTemplate(ref owner, tempDoc);
  2718. return returnDoc.ToDictionary();
  2719. };
  2720. case "instance.data":
  2721. return () =>
  2722. {
  2723. string objname = p[0].ToString();
  2724. var obj2 = objname;
  2725. int index = objname.IndexOf('.');
  2726. string property = string.Empty;
  2727. if (index != -1)
  2728. {
  2729. property = objname.Substring(index + 1).ToLower();
  2730. objname = objname.Substring(0, index);
  2731. }
  2732. var doc = this.GetInstanceDoc(objname);
  2733. while (!string.IsNullOrEmpty(property))
  2734. {
  2735. index = property.IndexOf('.');
  2736. string left = string.Empty;
  2737. if (index != -1)
  2738. {
  2739. left = property.Substring(index + 1);
  2740. property = property.Substring(0, index);
  2741. }
  2742. BsonValue bv;
  2743. doc.TryGetValue(property, out bv);
  2744. doc = bv.AsBsonDocument;
  2745. property = left;
  2746. }
  2747. return doc.ToDictionary()._DicValue();
  2748. };
  2749. case "instance":
  2750. case "instance.update":
  2751. return () =>
  2752. {
  2753. string objname = p[0].ToString();
  2754. var obj2 = objname;
  2755. if (p.Count == 1)
  2756. {
  2757. int index = objname.IndexOf('.');
  2758. string property = string.Empty;
  2759. if (index != -1)
  2760. {
  2761. property = objname.Substring(index + 1).ToLower();
  2762. objname = objname.Substring(0, index);
  2763. }
  2764. var doc = this.GetInstanceDoc(objname);
  2765. while (!string.IsNullOrEmpty(property))
  2766. {
  2767. index = property.IndexOf('.');
  2768. string left = string.Empty;
  2769. if (index != -1)
  2770. {
  2771. left = property.Substring(index + 1);
  2772. property = property.Substring(0, index);
  2773. }
  2774. BsonValue bv;
  2775. doc.TryGetValue(property, out bv);
  2776. doc = bv.AsBsonDocument;
  2777. property = left;
  2778. }
  2779. return doc.ToDictionary();
  2780. }
  2781. string value = p[1].ToString();
  2782. this.UpdateInstance(objname, value, null, null);
  2783. return null;
  2784. };
  2785. //case "instance.exist":
  2786. // return () =>
  2787. // {
  2788. // var iid = this.GetInstanceIdByName(p[0]._Str());
  2789. // return !string.IsNullOrEmpty(iid);
  2790. // };
  2791. case "instance.change":
  2792. return () =>
  2793. {
  2794. string objid = p[0].ToString();
  2795. string instname = p[1].ToString();
  2796. string newname = p[2].ToString();
  2797. string desc = p[3]._Str();
  2798. string team = p[4]._Str();
  2799. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2800. r["err"] = string.Empty;
  2801. PublishInstance(ref objid, instname, desc, string.Empty, null, option: DataOperations.Update, newname: newname, fornew: false, team: team);
  2802. r["id"] = objid;
  2803. return r;
  2804. };
  2805. case "instance.new":
  2806. return () =>
  2807. {
  2808. string objid = string.Empty;
  2809. string objname = p[0].ToString();
  2810. string instname = p[1]._Str();
  2811. string team = p[2]._Str();
  2812. string desc = p[3]._Str();
  2813. string tid = this.GetTemplateId(objname);
  2814. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2815. r["err"] = string.Empty;
  2816. if (string.IsNullOrEmpty(instname))
  2817. {
  2818. string username = this.UserName;
  2819. if (!string.IsNullOrEmpty(team))
  2820. {
  2821. var doc = this.FindDocumentById(TeamCollection, team, new string[] { UserFlag });
  2822. string user = doc[UserFlag].ToString();
  2823. username = this.GetUserName(user);// team.Substring(0, i);
  2824. }
  2825. instname = username + "/Instance_" + DateTime.UtcNow.ToString("yyyyMMddHHmmss_fff") + "/" + this.GetLastName(objname);
  2826. }
  2827. PublishInstance(ref objid, instname, desc, string.Empty, tid, fornew: true, team: team);
  2828. r["id"] = objid;
  2829. return r;
  2830. };
  2831. case "instance.delete":
  2832. return () =>
  2833. {
  2834. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2835. r["err"] = string.Empty;
  2836. //try
  2837. //{
  2838. string filename = p[0]._Str();
  2839. this.DeleteInstance(filename);
  2840. //this.SendResultMessage("DeleteInstance: " + filename + ";");
  2841. //}
  2842. //catch (Exception ex)
  2843. //{
  2844. //SendResultMessage("DeleteInstance: " + ex._msg());
  2845. //r["err"] = ex._msg();
  2846. //}
  2847. return r;
  2848. };
  2849. case "base":
  2850. return () =>
  2851. {
  2852. object mytemp;
  2853. if (vget.TryGetValue("t()", out mytemp))
  2854. {
  2855. var mytempid = mytemp.ToString();
  2856. var node = this.GetTemplateNode(mytempid);
  2857. var rid = node.GetString(ReferenceFlag);
  2858. if (string.IsNullOrEmpty(rid))
  2859. {
  2860. string type = "Debug";
  2861. string msg = "执行base()时,没有发现父类。";
  2862. string feature = "Console";
  2863. this.PublishUserLog(type, msg, feature);
  2864. return null;
  2865. }
  2866. node = this.GetTemplateNode(rid);
  2867. var change = node.GetString(OnChangeFlag);
  2868. vget["t()"] = rid;
  2869. this.RunWorkflow(this.CopyToken(), change, vget);
  2870. vget["t()"] = mytemp;
  2871. }
  2872. return true;
  2873. };
  2874. case "template.delete2":
  2875. return () =>
  2876. {
  2877. string filename = p[0]._Str();
  2878. var doc = this.FindDocumentByName(TemplateCollection, filename, new string[] { UserFlag, NameFlag, LGroupFlag });
  2879. if (doc == null)
  2880. {
  2881. throw new NotExistException("模板不存在:" + filename);
  2882. }
  2883. var objId = doc[IDFlag].AsString;
  2884. this.CheckSecurity(objId, CollectionType.Template, SecurityType.Write);
  2885. var collection = DataClient.DataCollection + "_" + objId;
  2886. if (this.dbHelper.CollectionExist(collection))
  2887. {
  2888. this.dbHelper.DeleteCollection(collection);
  2889. }
  2890. this.dbHelper.Remove(InstanceCollection, Query.EQ(TemplateFlag, objId));
  2891. IMongoQuery q1 = Query.EQ("_id", objId);
  2892. this.dbHelper.Remove(TemplateCollection, q1);
  2893. return true;
  2894. };
  2895. case "template.delete":
  2896. return () =>
  2897. {
  2898. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2899. r["err"] = string.Empty;
  2900. string filename = p[0]._Str();
  2901. this.DeleteTemplate(filename);
  2902. return r;
  2903. };
  2904. #endregion
  2905. #region SystemFunction
  2906. case "crc":
  2907. return () =>
  2908. {
  2909. var data = (byte[])p[0];
  2910. var offset = p[1]._Int();
  2911. var length = p[2]._Int();
  2912. var crc = CustomProtocol.Core.GetCRC(data, offset, length);
  2913. return crc;
  2914. };
  2915. case "crc32":
  2916. return () =>
  2917. {
  2918. var data = (byte[])p[0];
  2919. var crc = CustomProtocol.Core.GetCRC32(data);
  2920. return crc;
  2921. };
  2922. case "fillbytes":
  2923. return () =>
  2924. {
  2925. var data = (byte[])p[0];
  2926. var length = p[1]._Int();
  2927. var defaultbyte = (byte)(p[1]._Int());
  2928. var result = CustomProtocol.Support.FillByte(data, length, defaultbyte);
  2929. return result;
  2930. };
  2931. case "script.parse":
  2932. return () =>
  2933. {
  2934. var s = script.ToDictionary(p[0]._Str());
  2935. return s;
  2936. };
  2937. case "server.url":
  2938. return () =>
  2939. {
  2940. string port = string.Empty;
  2941. if (ServerInfo.WebPort != "80")
  2942. {
  2943. port = ":" + ServerInfo.WebPort;
  2944. }
  2945. return "http://" + ServerInfo.ServerIP + port;
  2946. };
  2947. case "api.info":
  2948. return () =>
  2949. {
  2950. var group = p[0]._Str();
  2951. group = group._Path(this.ClientInfo.PageSource);
  2952. var fields = new string[] { NameFlag, DescriptionFlag, Definitions.ValueFlag };
  2953. //string g1 = this.GetLGroup(group);
  2954. var folder = group.Trim('/').Trim();
  2955. int count = folder.Split('/').Length;
  2956. IMongoQuery q2 = Query.EQ("_g." + "g" + count, folder.ToLower());
  2957. IMongoQuery q_all = Query.And(Query.EQ(TypeFlag, ".ds"), Query.EQ(UserFlag, this.UserId), q2);
  2958. var docs = this.dbHelper.Find(FileCollection, q_all, new List<string> { IDFlag });
  2959. List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
  2960. foreach (var doc in docs)
  2961. {
  2962. var d = this.FindDocumentById(FileCollection, doc[IDFlag].ToString(), fields);
  2963. var scriptstring = d[Definitions.ValueFlag].AsByteArray._Str(false);
  2964. var scriptinfo_List = script.GetFunctionInfo(scriptstring, (s) =>
  2965. {
  2966. string content = this.GetDSContent(s + ".ds", true, this.UserName);
  2967. return content;
  2968. });
  2969. int count2 = scriptinfo_List.Count;
  2970. if (count2 > 0)
  2971. {
  2972. for (int i = 0; i < count2; i++)
  2973. {
  2974. Dictionary<string, object> scriptinfo = scriptinfo_List[i];
  2975. if (string.IsNullOrEmpty(scriptinfo["summary"]._Str()))
  2976. {
  2977. continue;
  2978. }
  2979. var scriptname = "/" + d[NameFlag].AsString;
  2980. scriptinfo["name"] = scriptname;
  2981. scriptinfo["desc"] = scriptinfo["description"]._Str();
  2982. var method = scriptinfo["method"]._Str();
  2983. List<Dictionary<string, object>> parameters = new List<Dictionary<string, object>>();
  2984. switch (method)
  2985. {
  2986. case "get":
  2987. Dictionary<string, object> pa = scriptinfo["parameters"] as Dictionary<string, object>;
  2988. foreach (var kv in pa)
  2989. {
  2990. var para2 = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2991. para2["in"] = "query";
  2992. para2["name"] = kv.Key;
  2993. var ppp = kv.Value as Dictionary<string, object>;
  2994. var desc = ppp._Value("description");
  2995. if (desc != null)
  2996. {
  2997. para2["description"] = desc;
  2998. }
  2999. para2["type"] = ppp._Value("type");
  3000. para2["default"] = ppp._Value("default") ?? string.Empty;
  3001. var required = ppp._Value("required");
  3002. if (required != null)
  3003. {
  3004. para2["required"] = required._Bool();
  3005. }
  3006. parameters.Add(para2);
  3007. }
  3008. break;
  3009. case "post":
  3010. var para = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3011. para["in"] = "body";
  3012. para["name"] = "参数名";
  3013. para["description"] = "参数描述";
  3014. Dictionary<string, object> schema = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3015. schema["type"] = "object";
  3016. Dictionary<string, object> pa2 = scriptinfo["parameters"] as Dictionary<string, object>;
  3017. List<string> requiredlist = new List<string>();
  3018. foreach (var kv in pa2)
  3019. {
  3020. var ppp = kv.Value as Dictionary<string, object>;
  3021. var required = ppp._Value("required");
  3022. if (required != null)
  3023. {
  3024. ppp.Remove("required");
  3025. requiredlist.Add(kv.Key);
  3026. }
  3027. }
  3028. if (requiredlist.Count > 0)
  3029. {
  3030. schema["required"] = requiredlist;
  3031. }
  3032. schema["properties"] = pa2;
  3033. para["schema"] = schema;
  3034. parameters.Add(para);
  3035. break;
  3036. }
  3037. scriptinfo["parameters"] = parameters;
  3038. scriptinfo["method"] = method;
  3039. result.Add(scriptinfo);
  3040. }
  3041. }
  3042. }
  3043. return result;
  3044. };
  3045. //case "functions":
  3046. // return () =>
  3047. // {
  3048. // var result = new Dictionary<string, object>();
  3049. // foreach (var kv in MyFunction.Methods)
  3050. // {
  3051. // Dictionary<string, object> ps = new Dictionary<string, object>();
  3052. // ps["IsStatic"] = kv.Value.IsStatic;
  3053. // ps["ParaNames"] = kv.Value.ParaNames;
  3054. // result[kv.Key] = ps;
  3055. // }
  3056. // return result;
  3057. // };
  3058. case "license.key":
  3059. return () =>
  3060. {
  3061. var kv = DatabaseHelper.CreateLicenseKey(p[0].ToString());
  3062. return kv;
  3063. };
  3064. case "license.create":
  3065. return () =>
  3066. {
  3067. int i = 0;
  3068. return DatabaseHelper.CreateLicense(p[i++]._Str(), p[i++]._Str(), p[i++]._Time(), (Dictionary<string, object>)p[i++], p[i++]._Str(), p[i++]._Str());
  3069. };
  3070. case "status":
  3071. return () =>
  3072. {
  3073. return this.GetAllServerStatus();
  3074. };
  3075. //case "debug":
  3076. // return () =>
  3077. // {
  3078. // var debug = p[0]._Bool();
  3079. // ServerInfo.Debug = debug;
  3080. // return debug;
  3081. // };
  3082. case "uploadform":
  3083. return () =>
  3084. {
  3085. return ServerSetting.uploadfilecontent;
  3086. };
  3087. case "checkindex":
  3088. return () =>
  3089. {
  3090. if (!this.IsAdmin)
  3091. {
  3092. throw new NoSecurityException("checkindex", this.UserName);
  3093. }
  3094. //DatabaseHelper.CheckIndex(FileCollection, LNameFlag);
  3095. return true;
  3096. };
  3097. case "servers":
  3098. return () =>
  3099. {
  3100. if (!this.IsAdmin)
  3101. {
  3102. throw new NoSecurityException("没有权限", "servers");//("servers", this.UserName);
  3103. }
  3104. return AllServers;
  3105. };
  3106. case "wait":
  3107. return () =>
  3108. {
  3109. var ms = Support.Int(p[0]);
  3110. Thread.Sleep(ms);
  3111. return null;
  3112. };
  3113. case "input":
  3114. return () =>
  3115. {
  3116. return new Dictionary<string, object>(vget, StringComparer.OrdinalIgnoreCase);
  3117. };
  3118. case "access":
  3119. return () =>
  3120. {
  3121. //if (!this.IsAdmin)
  3122. //{
  3123. // throw new NoSecurityException("用户[" + this.UserName + "]没有权限调用函数:", "access");
  3124. //}
  3125. if (p.Count > 2)
  3126. {
  3127. }
  3128. if (p.Count == 2)
  3129. {
  3130. string username = p[0]._Str().ToLower();
  3131. if (string.IsNullOrEmpty(username))
  3132. {
  3133. return false;
  3134. }
  3135. BsonDocument userdoc = null;
  3136. if (username._Length() == 24)
  3137. {
  3138. userdoc = this.FindDocumentById(UserCollection, username, new string[] { PassWordFlag, SysTokenFlag, NameFlag });//, IsAdminFlag
  3139. }
  3140. else
  3141. {
  3142. userdoc = this.FindDocumentByName(UserCollection, username, new string[] { PassWordFlag, SysTokenFlag, NameFlag });//, IsAdminFlag
  3143. }
  3144. if (userdoc == null)
  3145. {
  3146. throw new NotExistException("用户不存在:" + username);
  3147. }
  3148. //var isadmin = userdoc.GetBool(IsAdminFlag);
  3149. if (this.IsAdmin)//isadmin &&
  3150. {
  3151. }
  3152. else
  3153. {
  3154. string password = p[1]._Str()._MD5();
  3155. if (userdoc.GetString(PassWordFlag) != password)
  3156. {
  3157. throw new WrongPasswordException("用户密码错误:" + username);
  3158. }
  3159. }
  3160. var usertoken = userdoc.GetString(SysTokenFlag);
  3161. this.Init(usertoken);
  3162. return true;
  3163. //this.AccessToken = userdoc.GetString(SysTokenFlag);
  3164. //this.AccessUser = userdoc.GetString(NameFlag);
  3165. //this.AccessUserId = userdoc.GetString(IDFlag);
  3166. }
  3167. string user = null;
  3168. if (string.IsNullOrEmpty(this.SourceName))
  3169. {
  3170. user = this.GetFirstName(this.ClientInfo.PageSource);
  3171. }
  3172. else
  3173. {
  3174. user = this.GetFirstName(this.SourceName);
  3175. }
  3176. if (!string.IsNullOrEmpty(user))
  3177. {
  3178. string token = this.GetSysToken(user, true);
  3179. this.Init(token);
  3180. }
  3181. bool forowner = false;
  3182. if (p.Count == 1)
  3183. {
  3184. forowner = p[0]._Bool();
  3185. }
  3186. if (!forowner)
  3187. {
  3188. if (this.IsAdmin)
  3189. {
  3190. this.Init(this.AccessToken);
  3191. }
  3192. else
  3193. {
  3194. //throw new NoSecurityException("用户[" + this.UserName + "]没有权限调用函数:", "access");
  3195. }
  3196. }
  3197. return true;
  3198. };
  3199. case "runds":
  3200. return () =>
  3201. {
  3202. var wf = p[0]._Str();
  3203. if (wf.StartsWith("/$"))
  3204. {
  3205. string st = this.GetSystemFileString(DataClient.SystemSettingFileName);
  3206. var setjson = st._Dic2();
  3207. var dspath = setjson._Value("dspath")._Str();
  3208. if (!string.IsNullOrEmpty(dspath))
  3209. {
  3210. wf = "/" + dspath.Trim('/') + "/" + wf.TrimStart("/$".ToArray());
  3211. }
  3212. }
  3213. var para = p[1] as Dictionary<string, object>;
  3214. var mytoken = this.CopyToken();
  3215. mytoken.input = para;
  3216. var wfhelper = new WorkflowHelpler();
  3217. var r = wfhelper.GetResultByName(this, mytoken, wf, null, timeout: p[2]._Int());
  3218. return r;
  3219. };
  3220. case "run":
  3221. case "job":
  3222. return () =>
  3223. {
  3224. var wf = p[0]._Str();
  3225. if (wf.StartsWith("/$"))
  3226. {
  3227. string st = this.GetSystemFileString(DataClient.SystemSettingFileName);
  3228. var setjson = st._Dic2();
  3229. var dspath = setjson._Value("dspath")._Str();
  3230. if (!string.IsNullOrEmpty(dspath))
  3231. {
  3232. wf = "/" + dspath.Trim('/') + "/" + wf.TrimStart("/$".ToArray());
  3233. }
  3234. }
  3235. //if (p.Count == 1)
  3236. //{
  3237. // return RunMyFunction(wf, p, vget, script)();
  3238. //}
  3239. //var tokenObj = this.CopyToken();
  3240. this.PulishJob(this.SysToken, wf, Support.Number(p[1]), p[2]._Str());
  3241. return null;
  3242. };
  3243. case "iid":
  3244. return () =>
  3245. {
  3246. var iid = p[0]._Str();
  3247. string realid = this.GetRealInstanceName(iid, null);
  3248. return realid;
  3249. };
  3250. case "sessions":
  3251. return () =>
  3252. {
  3253. return GetAllSessionsOnServers();
  3254. };
  3255. case "onlines":
  3256. return () =>
  3257. {
  3258. var iid = p[0]._Str();
  3259. string realid = this.GetRealInstanceName(iid, null);
  3260. return GetOnlinesOnServers(realid);
  3261. };
  3262. case "subs":
  3263. return () =>
  3264. {
  3265. var iid = p[0]._Str();
  3266. string realid = this.GetRealInstanceName(iid, null);
  3267. return GetSubscribersOnServers(realid);
  3268. };
  3269. case "jobs":
  3270. return () =>
  3271. {
  3272. if (!this.IsAdmin)
  3273. {
  3274. throw new NoSecurityException("没有权限", "jobs");//("jobs()", this.UserName);
  3275. }
  3276. var list = this.GetAllJobs();
  3277. return list;
  3278. };
  3279. case "myjobs":
  3280. return () =>
  3281. {
  3282. var team = p[0]._Str();
  3283. string userid;
  3284. //
  3285. IMongoQuery q = null;
  3286. string checkgroup = string.Empty;
  3287. if (!string.IsNullOrEmpty(team))
  3288. {
  3289. var docteam = this.FindDocumentById(TeamCollection, team, new string[] { "_us", UserFlag, NameFlag, "_g" });
  3290. bool hassecurity = false;
  3291. string teamname = team;
  3292. if (docteam != null)
  3293. {
  3294. teamname = docteam.GetString(NameFlag);
  3295. userid = docteam.GetString(UserFlag);
  3296. if (userid == this.UserId)
  3297. {
  3298. hassecurity = true;
  3299. }
  3300. else
  3301. {
  3302. BsonArray ba = docteam.GetArray("_us");
  3303. foreach (var b in ba)
  3304. {
  3305. var id = b.GetString("id");
  3306. if (id == "*")
  3307. {
  3308. hassecurity = true;
  3309. break;
  3310. }
  3311. var ok = b.GetBool("ok");
  3312. if (ok && id == this.UserId)
  3313. {
  3314. hassecurity = true;
  3315. break;
  3316. }
  3317. }
  3318. }
  3319. }
  3320. if (!hassecurity)
  3321. {
  3322. throw new NoSecurityException("用户[" + this.UserName + "]没有团队[" + teamname + "]访问权限");
  3323. }
  3324. string _g = docteam.GetString("_g");
  3325. userid = docteam.GetString(UserFlag);
  3326. if (string.IsNullOrEmpty(_g))
  3327. {
  3328. q = Query.EQ(IDFlag, string.Empty);
  3329. }
  3330. else
  3331. {
  3332. checkgroup = "/" + _g.Trim('/');
  3333. q = Query.EQ(UserFlag, docteam.GetString(UserFlag));
  3334. }
  3335. }
  3336. else
  3337. {
  3338. q = Query.EQ(UserFlag, this.UserId);
  3339. }
  3340. //
  3341. Dictionary<string, object> myjobs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3342. var docs = this.dbHelper.Find(JobCollection, q, new List<string> { "_id", "_ms", "_wf", "_server", "_server_addr", "_cluster", "_time", "_uid", "_created", "_modified", "_muser", "_starttime", "_errors", "_lasterror" });
  3343. foreach (var doc in docs)
  3344. {
  3345. var wfobj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3346. var wfid = doc["_wf"].AsString;
  3347. var d = this.FindDocumentById(FileCollection, wfid, new string[] { NameFlag });
  3348. string wfname = d.GetString(NameFlag);
  3349. if (!("/" + wfname).StartsWith(checkgroup))
  3350. {
  3351. continue;
  3352. }
  3353. doc["wfname"] = wfname;
  3354. myjobs[wfid] = doc.ToDictionary();
  3355. }
  3356. return myjobs;
  3357. };
  3358. case "cookies":
  3359. return () =>
  3360. {
  3361. this.Cookies = new List<MyCookie>();
  3362. var cookies = p[0] as Dictionary<string, object>;
  3363. foreach (var cookie in cookies)
  3364. {
  3365. MyCookie c = new MyCookie() { Name = cookie.Key, Value = cookie.Value._Str() };
  3366. c.Scope = this.UserName;
  3367. //c.Expires = DateTime.UtcNow.Add(TimeSpan.FromMinutes(30));
  3368. var pp = p[1];
  3369. c.Expires = pp._Time();
  3370. this.Cookies.Add(c);
  3371. }
  3372. return null;
  3373. };
  3374. case "out":
  3375. return () =>
  3376. {
  3377. this.Output = p[0] as Dictionary<string, object>;
  3378. return null;
  3379. };
  3380. case "cachedtime":
  3381. return () =>
  3382. {
  3383. return this.cachetime;
  3384. };
  3385. case "cache":
  3386. return () =>
  3387. {
  3388. this.IsCache = true;
  3389. return null;
  3390. };
  3391. case "redirect":
  3392. return () =>
  3393. {
  3394. throw new RedirectException(p[0]._Str());
  3395. };
  3396. case "md5":
  3397. return () =>
  3398. {
  3399. return p[0]._Str()._MD5();
  3400. };
  3401. case "aes.encode":
  3402. return () =>
  3403. {
  3404. return aes.Encrypt(p[0]._ObjBytes(), p[1]._ObjBytes());
  3405. };
  3406. //case "aes.decode":
  3407. // return () =>
  3408. // {
  3409. // return CommonFunction.AESDecrypt(p[0]._ObjBytes(), p[1]._Str(), p[2]._ObjBytes());
  3410. // };
  3411. case "sms":
  3412. return () =>
  3413. {
  3414. string accessKeyId = p[0]._Str();
  3415. string accessKeySecret = p[1]._Str();
  3416. string PhoneNumbers = p[2]._Str();
  3417. string SignName = p[3]._Str();
  3418. string TemplateCode = p[4]._Str();
  3419. Dictionary<string, object> TemplateParam = p[5] as Dictionary<string, object>;
  3420. var result = AliyunSms.SendSms(accessKeyId, accessKeySecret, PhoneNumbers, SignName, TemplateCode, TemplateParam);
  3421. return result;
  3422. };
  3423. case "email":
  3424. return () =>
  3425. {
  3426. this.SendEmail(p[0]._Str(), p[1]._Int(), p[2]._Str(), p[3]._Str(), p[4]._Str(), p[5]._Str(), p[6]._Str(), p[7]._Str(), p[8]._Str());
  3427. return true;
  3428. };
  3429. case "page":
  3430. return () =>
  3431. {
  3432. return this.ClientInfo.PageSource;
  3433. };
  3434. case "method":
  3435. return () =>
  3436. {
  3437. return this.ClientInfo.PageMethod;
  3438. };
  3439. case "query":
  3440. return () =>
  3441. {
  3442. return this.ClientInfo.PageQuery;
  3443. };
  3444. case "referer":
  3445. return () =>
  3446. {
  3447. return this.ClientInfo.Referer;
  3448. };
  3449. case "ip":
  3450. return () =>
  3451. {
  3452. return this.ClientInfo.IP;
  3453. };
  3454. case "bytelimit":
  3455. return () =>
  3456. {
  3457. return ServerInfo.ByteLimit;
  3458. };
  3459. case "v":
  3460. return () =>
  3461. {
  3462. Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3463. string validateId;
  3464. string vcode;
  3465. string url = p[0].ToString();
  3466. CreateValidate(url, out validateId, out vcode);
  3467. r["vid"] = validateId;
  3468. r["vcode"] = vcode;
  3469. r["query"] = vget;
  3470. r["source"] = this.ClientInfo.Referer;
  3471. return r;
  3472. };
  3473. case "log.set":
  3474. return () =>
  3475. {
  3476. string type = p[0]._Str();
  3477. string msg = p[1]._Str();
  3478. string feature = p[2]._Str();
  3479. this.PublishUserLog(type, msg, feature, p[3] as Dictionary<string, object>);
  3480. return true;
  3481. };
  3482. case "log.get":
  3483. return () =>
  3484. {
  3485. string type = p[0]._Str();
  3486. int page = p[1]._Int();
  3487. int pagesize = p[2]._Int();
  3488. string query = p[3]._Str();
  3489. List<string> fields = p[4]._StrList();
  3490. return this.GetUserLog(type, page, pagesize, query, vget: vget, fields: fields);
  3491. };
  3492. case "clearuserlog":
  3493. return () =>
  3494. {
  3495. if (!this.IsAdmin)
  3496. {
  3497. throw new NoSecurityException("没有权限", v);//("clearlog", this.UserName);
  3498. }
  3499. return this.ClearLog(UserLogCollection, p[0]._Int());
  3500. };
  3501. case "user":
  3502. return () =>
  3503. {
  3504. string username = this.AccessUser;
  3505. return username;
  3506. };
  3507. case "userid":
  3508. return () =>
  3509. {
  3510. string username = this.AccessUserId;
  3511. return username;
  3512. };
  3513. case "isadmin":
  3514. return () =>
  3515. {
  3516. return this.IsAdmin;
  3517. };
  3518. case "accessuser":
  3519. return () =>
  3520. {
  3521. Dictionary<string, object> info2 = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3522. info2["name"] = "";
  3523. info2["isadmin"] = "";
  3524. var u = this.FindDocumentById(UserCollection, this.AccessUserId, new string[] { LNameFlag, IsAdminFlag });
  3525. if (u != null)
  3526. {
  3527. info2["name"] = u.GetString(LNameFlag);
  3528. info2["isadmin"] = u.GetBool(IsAdminFlag);
  3529. }
  3530. return info2;
  3531. };
  3532. case "client":
  3533. return () =>
  3534. {
  3535. var r = this.ClientInfo.ToDictionary();
  3536. var input = r.GetDic("input");
  3537. if (input == null)
  3538. {
  3539. r["input"] = vget;
  3540. }
  3541. return r;
  3542. };
  3543. case "template.symbols":
  3544. return () =>
  3545. {
  3546. var tid = p[0]._Str();
  3547. var noinst = p[1]._Bool();
  3548. var relative = p[2]._Bool();
  3549. var ismobile = this.ClientInfo.UserAgent._IsMobileDevice();
  3550. var symbols = GetSymbolFromTemplate(tid, noinst, relative, ismobile, vget: vget);
  3551. return symbols;
  3552. };
  3553. case "ismobile":
  3554. return () =>
  3555. {
  3556. var agent = p[0]._Str();
  3557. if (string.IsNullOrEmpty(agent))
  3558. {
  3559. agent = this.ClientInfo.UserAgent;
  3560. }
  3561. var ismobile = agent._IsMobileDevice();
  3562. return ismobile;
  3563. };
  3564. case "template.allsymbols":
  3565. return () =>
  3566. {
  3567. var tid = p[0]._Str();
  3568. var symbols = GetSymbolFromTemplate(tid, true, false, false, vget, true);
  3569. return symbols;
  3570. };
  3571. case "share.symbols":
  3572. return () =>
  3573. {
  3574. var symbols = GetSymbolFromSetting(p[0]._Str(), p[1]._Str());
  3575. return symbols;
  3576. };
  3577. case "ref.refresh":
  3578. return () =>
  3579. {
  3580. var tid = p[0]._Str();
  3581. string root;
  3582. string property;
  3583. tid = this.GetTemplateId(tid, out root, out property);
  3584. this.CheckSecurity(root, CollectionType.Template, SecurityType.Read);
  3585. tid = root + property;
  3586. List<BsonDocument> instances = new List<BsonDocument>();
  3587. List<string> fs = new List<string> { NameFlag, UserFlag };
  3588. var docs2 = this.dbHelper.Find(InstanceCollection, Query.EQ(TemplateFlag, root), fs);
  3589. foreach (var doc in docs2)
  3590. {
  3591. doc.Add("fullname", "/" + doc.GetString(IDFlag) + property);
  3592. instances.Add(doc);
  3593. }
  3594. List<string> scripts = new List<string>();
  3595. var q1 = Query.ElemMatch("_r", Query.EQ("rid", root));
  3596. var expdoc = this.dbHelper.Find(TemplateCollection, q1, new List<string> { "_r" });
  3597. foreach (var exp in expdoc)
  3598. {
  3599. var myid = exp.GetString(IDFlag);
  3600. var mytids = exp.GetArray("_r");
  3601. foreach (var mytid in mytids)
  3602. {
  3603. var iidstr = mytid.GetString("rid");
  3604. if (iidstr != root)
  3605. {
  3606. continue;
  3607. }
  3608. var tidstr = mytid.GetString("tid");
  3609. string root2 = string.Empty;
  3610. string property2 = string.Empty;
  3611. tidstr = this.GetTemplateId(myid + "." + tidstr, out root2, out property2);
  3612. IMongoQuery q = Query.And(Query.EQ(TemplateFlag, root2));
  3613. var docs = this.dbHelper.Find(InstanceCollection, q, fs);
  3614. foreach (var doc in docs)
  3615. {
  3616. var iid = doc.GetString(IDFlag) + property2;
  3617. string fullname = "/" + iid + property;
  3618. doc.Add("fullname", fullname);
  3619. instances.Add(doc);
  3620. }
  3621. }
  3622. }
  3623. foreach (var doc in instances)
  3624. {
  3625. //var property2 = doc.GetString("property2");
  3626. //var iid = doc.GetString(IDFlag) + property2;
  3627. this.InstanceId = doc.GetString(IDFlag);
  3628. string tempId = null;
  3629. string userId = null;
  3630. BsonDocument instDoc = null;
  3631. string keyBase = null;
  3632. string keyFlag = null;
  3633. string instRoot = null;
  3634. BsonDocument tempDoc;
  3635. string clientname;
  3636. string fullname = doc.GetString("fullname");// "/" + iid + property;
  3637. this.GetInstanceInformation(fullname, out instRoot, out userId, out keyBase, out keyFlag, out instDoc, out tempDoc, out clientname, out tempId, SecurityType.Read, null);
  3638. BsonValue bv;
  3639. if (tempDoc.TryGetValue(Definitions.ValueFlag, out bv))
  3640. {
  3641. string valueexp = bv.ToString().Trim();
  3642. if (valueexp.StartsWith("="))
  3643. {
  3644. var data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3645. data["this"] = clientname;
  3646. Dictionary<string, object> inputs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3647. inputs["value"] = this.myInstanceModels;
  3648. data["data()"] = inputs;
  3649. string scriptstring = clientname + valueexp;
  3650. this.RunScript(scriptstring, data);
  3651. scripts.Add(scriptstring);
  3652. }
  3653. }
  3654. }
  3655. return scripts;
  3656. };
  3657. case "template.instances":
  3658. return () =>
  3659. {
  3660. var tid = p[0]._Str();
  3661. var query = p[1]._Str();
  3662. var fields = p[2] as ArrayList;
  3663. List<string> flist = null;
  3664. if (fields != null)
  3665. {
  3666. flist = new List<string>();
  3667. foreach (var f in fields)
  3668. {
  3669. flist.Add(f._Str());
  3670. }
  3671. }
  3672. var sortby = p[3] as Dictionary<string, object>;
  3673. var instances = GetInstancesByTemplate(tid, query, flist, sortby, vget: vget);
  3674. return instances;
  3675. };
  3676. case "src":
  3677. return () =>
  3678. {
  3679. if (string.IsNullOrEmpty(this.SourceName))
  3680. {
  3681. return this.ClientInfo.PageSource;
  3682. }
  3683. return this.SourceName;
  3684. };
  3685. case "pageowner":
  3686. return () =>
  3687. {
  3688. var top = p[0]._Bool();
  3689. if (top)
  3690. {
  3691. return this.GetFirstName(this.ClientInfo.PageSource);
  3692. }
  3693. if (string.IsNullOrEmpty(this.SourceName))
  3694. {
  3695. return this.GetFirstName(this.ClientInfo.PageSource);
  3696. }
  3697. string user = this.GetFirstName(this.SourceName);
  3698. return user;
  3699. };
  3700. case "owner":
  3701. return () =>
  3702. {
  3703. return this.UserName;
  3704. //return this.ClientInfo.UserName;
  3705. };
  3706. case "user.find":
  3707. return () =>
  3708. {
  3709. if (!this.IsAdmin)
  3710. {
  3711. throw new NoSecurityException("没有权限");
  3712. }
  3713. string p0 = p[0]._Str();
  3714. IMongoQuery q = Query.Null;
  3715. if (!string.IsNullOrEmpty(p0))
  3716. {
  3717. q = Query.Matches(LNameFlag, new BsonRegularExpression("/.*" + p0.ToLower() + ".*/"));
  3718. }
  3719. var docs = dbHelper.Find(UserCollection, q, new List<string> { NameFlag, EmailFlag, PhoneFlag, NickNameFlag, "_lasttime", "_lastip" }, 100);
  3720. return docs.ToDictionaryList();
  3721. };
  3722. case "ws":
  3723. return () =>
  3724. {
  3725. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3726. string s = WsRoleServers.AvailableServer.Address;
  3727. if (string.IsNullOrEmpty(s))
  3728. {
  3729. return string.Empty;
  3730. }
  3731. string[] ss = s.Split('|');
  3732. string port = ss[1];
  3733. string ws = "ws";
  3734. if (this.ClientInfo.Protocol == "https")
  3735. {
  3736. ws = "wss";
  3737. port = ss[2];
  3738. }
  3739. string portstr = ":" + port;
  3740. if (port == "80" || port == "443")
  3741. {
  3742. portstr = string.Empty;
  3743. }
  3744. var ip = ss[0];
  3745. if (ip == "localhost")
  3746. {
  3747. ip = ServerInfo.ServerIP;
  3748. }
  3749. string wsip = ws + "://" + ip + portstr;
  3750. return wsip;
  3751. };
  3752. #endregion
  3753. #region Team Function
  3754. case "team.shares":
  3755. return () =>
  3756. {
  3757. string teamid = p[0]._Str();
  3758. if (string.IsNullOrEmpty(teamid))
  3759. {
  3760. var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3761. result["rows"] = null;
  3762. result["count"] = 0;
  3763. return result;
  3764. }
  3765. var doc = this.FindDocumentById(TeamCollection, teamid, new string[] { UserFlag, "_us", "_g" });
  3766. if (doc == null)
  3767. {
  3768. throw new NotExistException("团队不存在:" + teamid);
  3769. }
  3770. bool isok = false;
  3771. string userid = doc.GetString(UserFlag);
  3772. if (userid == this.UserId)
  3773. {
  3774. isok = true;
  3775. }
  3776. else
  3777. {
  3778. BsonArray ba = doc["_us"].AsBsonArray;
  3779. foreach (var b in ba)
  3780. {
  3781. string id = b.GetString("id");
  3782. if (id == "*")
  3783. {
  3784. isok = true;
  3785. break;
  3786. }
  3787. if (id == this.UserId)
  3788. {
  3789. isok = true;
  3790. break;
  3791. }
  3792. }
  3793. }
  3794. if (!isok)
  3795. {
  3796. throw new NoSecurityException("没有共享", teamid);
  3797. }
  3798. string t = p[1]._Str();
  3799. string search = p[2]._Str();
  3800. int page = p[3]._Int();
  3801. int pagesize = p[4]._Int();
  3802. string collection = FileCollection;
  3803. string group = "/" + doc.GetString("_g").Trim('/');
  3804. IMongoQuery q = Query.Matches(LGroupFlag, new BsonRegularExpression("^" + group)); // Query.EQ(TeamFlag, teamid);
  3805. switch (t)
  3806. {
  3807. case "template":
  3808. collection = TemplateCollection;
  3809. break;
  3810. case "instance":
  3811. collection = InstanceCollection;
  3812. break;
  3813. case "file":
  3814. collection = FileCollection;
  3815. //q = Query.And(q, Query.Or(Query.EQ(TypeFlag, ".html"), Query.EQ(TypeFlag, ".zip")));
  3816. break;
  3817. }
  3818. if (!string.IsNullOrEmpty(search))
  3819. {
  3820. string lsearch = search.ToLower();
  3821. IMongoQuery mq = Query.Or(Query.Matches(LNameFlag, new BsonRegularExpression(lsearch)), Query.Matches(LDescriptionFlag, new BsonRegularExpression(lsearch)));
  3822. q = Query.And(q, mq);
  3823. }
  3824. var fields = new List<string> { NameFlag, DescriptionFlag, ModifiedFlag, "_user" };
  3825. return this.dbHelper.FindPage(collection, q, page, pagesize, fields, sortby: new SortByDocument(ModifiedFlag, -1));
  3826. };
  3827. case "shareteams":
  3828. return () =>
  3829. {
  3830. int page = p[0]._Int();
  3831. int pagesize = p[1]._Int();
  3832. string search = p[2]._Str();
  3833. IMongoQuery q1 = Query.EQ(UserFlag, this.UserId);
  3834. //IMongoQuery q4 = Query.EQ("id", "*");
  3835. IMongoQuery q5 = Query.EQ("id", this.UserId);
  3836. IMongoQuery q6 = Query.EQ("ok", true);
  3837. var qus1 = Query.ElemMatch("_us", Query.And(q5, q6));
  3838. var q = Query.Or(q1, qus1);
  3839. List<BsonDocument> result = new List<BsonDocument>();
  3840. if (!string.IsNullOrEmpty(search))
  3841. {
  3842. string lsearch = search.ToLower();
  3843. IMongoQuery mq = Query.Or(Query.Matches(LNameFlag, new BsonRegularExpression(lsearch)), Query.Matches(LDescriptionFlag, new BsonRegularExpression(lsearch)));
  3844. qus1 = Query.And(qus1, mq);
  3845. }
  3846. var docs = this.dbHelper.FindPage(TeamCollection, q, page, pagesize, new List<string> { NameFlag, ModifiedFlag, DescriptionFlag, "_owner", "_users", "_g" }, sortby: new SortByDocument(ModifiedFlag, -1));
  3847. return docs;
  3848. };
  3849. case "team.users":
  3850. return () =>
  3851. {
  3852. string filename = p[0]._Str();
  3853. string type = p[1]._Str();
  3854. var users = this.GetTeamUsers(type, filename);
  3855. return users;
  3856. };
  3857. case "team.info":
  3858. return () =>
  3859. {
  3860. string teamid = p[0]._Str();
  3861. if (string.IsNullOrEmpty(teamid))
  3862. {
  3863. throw new NotExistException("团队id为空!");
  3864. }
  3865. var doc4 = this.dbHelper.FindDocumentByQuery(TeamCollection, Query.EQ(IDFlag, teamid), new string[] { IDFlag, NameFlag, UserFlag, "_us" });
  3866. if (doc4 == null)
  3867. {
  3868. throw new NotExistException("团队不存在:" + teamid);
  3869. //throw new NoSecurityException("没有权限", teamid);
  3870. }
  3871. bool hassec = false;
  3872. if (doc4.GetString(UserFlag) == this.UserId)
  3873. {
  3874. hassec = true;
  3875. }
  3876. else
  3877. {
  3878. BsonArray usdoc = doc4["_us"] as BsonArray;
  3879. foreach (var ud in usdoc)
  3880. {
  3881. string userid = ud.GetString("id");
  3882. bool ok = ud.GetBool("ok");
  3883. if (userid == "*" || (userid == this.UserId && ok))
  3884. {
  3885. hassec = true;
  3886. break;
  3887. }
  3888. }
  3889. }
  3890. if (!hassec)
  3891. {
  3892. throw new NoSecurityException("没有权限:", teamid);
  3893. }
  3894. Dictionary<string, object> dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  3895. dic["id"] = doc4.GetString(IDFlag);
  3896. dic["name"] = doc4.GetString(NameFlag);
  3897. string uid = doc4.GetString(UserFlag);
  3898. string uname = this.GetUserName(uid);
  3899. dic["user"] = uname;
  3900. return dic;
  3901. };
  3902. case "team.list":
  3903. return () =>
  3904. {
  3905. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  3906. var docs = this.dbHelper.Find(TeamCollection, q, new List<string> { NameFlag, ModifiedFlag, DescriptionFlag, "_owner", "_users", "_g" }, sortby: new SortByDocument(ModifiedFlag, -1));
  3907. return docs;
  3908. };
  3909. case "team.joined":
  3910. return () =>
  3911. {
  3912. IMongoQuery q = Query.NE(UserFlag, this.UserId);
  3913. IMongoQuery q4 = Query.EQ("id", "*");
  3914. IMongoQuery q1 = Query.EQ("id", this.UserId);
  3915. IMongoQuery q2 = Query.EQ("ok", true);
  3916. IMongoQuery q3 = Query.EQ("ok", false);
  3917. var qus1 = Query.ElemMatch("_us", Query.Or(q4, Query.And(q1, q2)));
  3918. var qus2 = Query.ElemMatch("_us", Query.And(q1, q3));
  3919. List<BsonDocument> result = new List<BsonDocument>();
  3920. var docs = this.dbHelper.Find(TeamCollection, Query.And(q, qus1), new List<string> { NameFlag, ModifiedFlag, DescriptionFlag, "_owner", "_users", "_g" }, sortby: new SortByDocument(ModifiedFlag, -1));
  3921. foreach (var doc in docs)
  3922. {
  3923. doc.Add("_ok", true);
  3924. result.Add(doc);
  3925. }
  3926. var docs2 = this.dbHelper.Find(TeamCollection, Query.And(q, qus2), new List<string> { NameFlag, ModifiedFlag, DescriptionFlag, "_owner", "_users", "_g" }, sortby: new SortByDocument(ModifiedFlag, -1));
  3927. foreach (var doc in docs2)
  3928. {
  3929. doc.Add("_ok", false);
  3930. result.Add(doc);
  3931. }
  3932. return result;
  3933. };
  3934. case "team.add":
  3935. return () =>
  3936. {
  3937. var result = this.PublishTeam(null, p[0]._Str(), p[1]._Str(), p[2]._Str(), p[3]._Str());
  3938. return result;
  3939. };
  3940. case "team.update":
  3941. return () =>
  3942. {
  3943. var result = this.PublishTeam(p[0]._Str(), p[1]._Str(), p[2]._Str(), p[3]._Str(), p[4]._Str());
  3944. return result;
  3945. };
  3946. case "team.remove":
  3947. return () =>
  3948. {
  3949. if (string.IsNullOrEmpty(this.UserId))
  3950. {
  3951. throw new NoSecurityException("没有权限", v);
  3952. }
  3953. string id = p[0]._Str();
  3954. var myteam = this.FindDocumentById(TeamCollection, id, new string[] { UserFlag });
  3955. if (myteam == null)
  3956. {
  3957. throw new NotExistException("团队不存在");
  3958. }
  3959. if (myteam[UserFlag].ToString() != this.UserId)
  3960. {
  3961. throw new NoSecurityException("没有权限", myteam.GetString(NameFlag));
  3962. }
  3963. IMongoQuery q = Query.EQ(IDFlag, id);
  3964. this.dbHelper.Remove(TeamCollection, q);
  3965. return null;
  3966. };
  3967. case "team.join":
  3968. return () =>
  3969. {
  3970. if (string.IsNullOrEmpty(this.UserId))
  3971. {
  3972. throw new NoSecurityException("没有权限", v);
  3973. }
  3974. string id = p[0]._Str();
  3975. IMongoQuery q1 = Query.EQ(IDFlag, id);
  3976. IMongoQuery q2 = Query.ElemMatch("_us", Query.EQ("id", this.UserId));
  3977. var myteam = this.dbHelper.FindDocumentByQuery(TeamCollection, Query.And(q1, q2), new string[] { "_us", "_uid", "_name" });
  3978. if (myteam == null)
  3979. {
  3980. throw new NotExistException("团队不存在或未共享:" + id);
  3981. }
  3982. IMongoQuery q = Query.EQ(IDFlag, id);
  3983. BsonDocument doc = new BsonDocument();
  3984. doc.Add("_us.$.ok", p[1]._Bool());
  3985. this.dbHelper.Update(TeamCollection, id, doc, q: Query.And(q1, q2));
  3986. string uid = myteam["_uid"].ToString();
  3987. BsonArray usdoc = myteam["_us"] as BsonArray;
  3988. List<string> userslist = new List<string>();
  3989. userslist.Add(uid);
  3990. if (!userslist.Contains(this.UserId))
  3991. {
  3992. userslist.Add(this.UserId);
  3993. }
  3994. foreach (var ud in usdoc)
  3995. {
  3996. string userid = ud.GetString("id");
  3997. bool ok = ud.GetBool("ok");
  3998. if (ok)
  3999. {
  4000. if (!userslist.Contains(userid))
  4001. {
  4002. userslist.Add(userid);
  4003. }
  4004. }
  4005. }
  4006. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  4007. result["id"] = myteam.GetString(IDFlag);
  4008. result["name"] = myteam.GetString(NameFlag);
  4009. result["members"] = userslist;
  4010. result["owner"] = this.GetUserName(uid);
  4011. result["username"] = this.UserName;
  4012. result["add"] = p[1]._Bool();
  4013. return result;
  4014. };
  4015. #endregion
  4016. #region Data Function
  4017. case "dataquery":
  4018. return () =>
  4019. {
  4020. var iid = p[0]._Str();
  4021. var mode = p[1]._Str();
  4022. var type = p[2]._Str();
  4023. var cachename = p[3]._Str();
  4024. if (string.IsNullOrEmpty(iid))
  4025. {
  4026. throw new EmptyNameException("实例名不能为空");
  4027. }
  4028. int index = iid.IndexOf('.');
  4029. this.CheckSecurity(iid.Substring(0, index), CollectionType.Instance, SecurityType.Read);
  4030. string cname = null;
  4031. if (!string.IsNullOrEmpty(cachename))
  4032. {
  4033. cname = cachename + "|" + iid + "|" + mode + "|" + type;
  4034. List<Dictionary<string, object>> data;
  4035. if (MapReduceCaches.Get<List<Dictionary<string, object>>>(cname, out data))
  4036. {
  4037. return data;
  4038. }
  4039. }
  4040. IMongoQuery q = Query.EQ("id", iid);
  4041. DateTime from;
  4042. Func<BsonDocument, DateTime> getDate = null;
  4043. Dictionary<DateTime, object> result = new Dictionary<DateTime, object>();
  4044. var now = DateTime.UtcNow;
  4045. switch (mode)
  4046. {
  4047. case "year":
  4048. var count = 3;
  4049. var fromdate = now.AddYears(count * -1);
  4050. from = Support.Date(fromdate.Year);
  4051. for (int i = 0; i < count; i++)
  4052. {
  4053. result.Add(from.AddYears(i), null);
  4054. }
  4055. getDate = (doc) =>
  4056. {
  4057. var dt = doc.GetDateTime("doc._time");
  4058. return Support.Date(dt.Year);
  4059. };
  4060. break;
  4061. case "month":
  4062. count = 12;
  4063. fromdate = now.AddMonths(count * -1);
  4064. from = Support.Date(fromdate.Year, fromdate.Month);
  4065. for (int i = 0; i < count; i++)
  4066. {
  4067. result.Add(from.AddMonths(i), null);
  4068. }
  4069. getDate = (doc) =>
  4070. {
  4071. var dt = doc.GetDateTime("doc._time");
  4072. return Support.Date(dt.Year, dt.Month);
  4073. };
  4074. break;
  4075. case "day":
  4076. count = 30;
  4077. fromdate = now.AddDays(count * -1);
  4078. from = Support.Date(fromdate.Year, fromdate.Month, fromdate.Day);
  4079. for (int i = 0; i < count; i++)
  4080. {
  4081. result.Add(from.AddDays(i), null);
  4082. }
  4083. getDate = (doc) =>
  4084. {
  4085. var dt = doc.GetDateTime("doc._time");
  4086. return Support.Date(dt.Year, dt.Month, dt.Day);
  4087. };
  4088. break;
  4089. case "hour":
  4090. count = 24;
  4091. fromdate = now.AddHours(count * -1);
  4092. from = Support.Date(fromdate.Year, fromdate.Month, fromdate.Day, fromdate.Hour);
  4093. for (int i = 0; i < count; i++)
  4094. {
  4095. result.Add(from.AddHours(i), null);
  4096. }
  4097. getDate = (doc) =>
  4098. {
  4099. var dt = doc.GetDateTime("doc._time");
  4100. return Support.Date(dt.Year, dt.Month, dt.Day, dt.Hour);
  4101. };
  4102. break;
  4103. case "minute":
  4104. count = 60;
  4105. fromdate = now.AddMinutes(count * -1);
  4106. from = Support.Date(fromdate.Year, fromdate.Month, fromdate.Day, fromdate.Hour, fromdate.Minute);
  4107. for (int i = 0; i < count; i++)
  4108. {
  4109. result.Add(from.AddMinutes(i), null);
  4110. }
  4111. getDate = (doc) =>
  4112. {
  4113. var dt = doc.GetDateTime("doc._time");
  4114. return Support.Date(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute);
  4115. };
  4116. break;
  4117. case "second":
  4118. count = 60;
  4119. fromdate = now.AddSeconds(count * -1);
  4120. from = Support.Date(fromdate.Year, fromdate.Month, fromdate.Day, fromdate.Hour, fromdate.Minute, fromdate.Second);
  4121. for (int i = 0; i < count; i++)
  4122. {
  4123. result.Add(from.AddSeconds(i), null);
  4124. }
  4125. getDate = (doc) =>
  4126. {
  4127. var dt = doc.GetDateTime("doc._time");
  4128. return Support.Date(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
  4129. };
  4130. break;
  4131. default:
  4132. throw new InvalidParameterException();
  4133. }
  4134. q = Query.And(q, Query.GTE("time", from));
  4135. var docs = this.dbHelper.Find("InstanceHistory", q, new List<string>() { "doc._time", "doc._value" });
  4136. Func<IEnumerable<BsonDocument>, decimal> getSum = null;
  4137. switch (type)
  4138. {
  4139. case "count":
  4140. getSum = (a) => { return a.Count(); };
  4141. break;
  4142. case "sum":
  4143. getSum = (a) => { return a.Sum(c => c.GetDecimal("doc._value")); };
  4144. break;
  4145. case "average":
  4146. getSum = (a) => { return a.Average(c => c.GetDecimal("doc._value")); };
  4147. break;
  4148. case "min":
  4149. getSum = (a) => { return a.Min(c => c.GetDecimal("doc._value")); };
  4150. break;
  4151. case "max":
  4152. getSum = (a) => { return a.Max(c => c.GetDecimal("doc._value")); };
  4153. break;
  4154. default:
  4155. throw new InvalidParameterException();
  4156. }
  4157. var groupList = docs.GroupBy(m => new
  4158. {
  4159. Key = getDate(m)
  4160. }).
  4161. Select(a => new
  4162. {
  4163. Key = a.Key.Key,
  4164. Value = getSum(a)
  4165. }).ToList();
  4166. foreach (var kv in groupList)
  4167. {
  4168. result[kv.Key] = Math.Round(kv.Value, 2);
  4169. }
  4170. List<Dictionary<string, object>> output = new List<Dictionary<string, object>>();
  4171. foreach (var kv in result)
  4172. {
  4173. Dictionary<string, object> o = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  4174. o["_id"] = kv.Key;
  4175. o["value"] = kv.Value;
  4176. output.Add(o);
  4177. }
  4178. if (!string.IsNullOrEmpty(cname))
  4179. {
  4180. MapReduceCaches.Add(cname, output);
  4181. }
  4182. return output;
  4183. };
  4184. case "instancehistory":
  4185. return () =>
  4186. {
  4187. var iid = p[0]._Str();
  4188. if (string.IsNullOrEmpty(iid))
  4189. {
  4190. throw new EmptyNameException("实例名不能为空");
  4191. }
  4192. int index = iid.IndexOf('.');
  4193. this.CheckSecurity(iid.Substring(0, index), CollectionType.Instance, SecurityType.Read);
  4194. var cachename = p[6]._Str();
  4195. string cname = null;
  4196. if (!string.IsNullOrEmpty(cachename))
  4197. {
  4198. cname = cachename + "|" + iid + "|" + this.UserId;
  4199. List<Dictionary<string, object>> data;
  4200. if (MapReduceCaches.Get<List<Dictionary<string, object>>>(cname, out data))
  4201. {
  4202. return data;
  4203. }
  4204. }
  4205. var query = p[1]._Str();
  4206. IMongoQuery q = Query.EQ("doc.id", iid);
  4207. if (!string.IsNullOrEmpty(query))
  4208. {
  4209. q = Query.And(q, this.GetMyQuery(query, (name) =>
  4210. {
  4211. return name;
  4212. }, (name, value) =>
  4213. {
  4214. return BsonTypeMapper.MapToBsonValue(value);
  4215. }, vget));
  4216. }
  4217. var map = script.GetFunctionDef(p.Get(2).Name);
  4218. var reduce = script.GetFunctionDef(p.Get(3).Name);
  4219. var finalize = script.GetFunctionDef(p.Get(4).Name);
  4220. var para = p[5] as Dictionary<string, object>;
  4221. var result = this.GetMapReduceResult("InstanceHistory", q, map, reduce, finalize, para, cname);
  4222. return result;
  4223. };
  4224. case "mapreduce":
  4225. return () =>
  4226. {
  4227. var cachename = p[6]._Str();
  4228. if (!string.IsNullOrEmpty(cachename))
  4229. {
  4230. List<Dictionary<string, object>> data;
  4231. if (MapReduceCaches.Get<List<Dictionary<string, object>>>(cachename + "|" + this.UserId, out data))
  4232. {
  4233. return data;
  4234. }
  4235. }
  4236. var collection = p[0]._Str();
  4237. var query = p[1]._Str();
  4238. IMongoQuery q = Query.And(Query.EQ(UserFlag, this.UserId));
  4239. if (!string.IsNullOrEmpty(query))
  4240. {
  4241. q = Query.And(q, this.GetMyQuery(query, (name) =>
  4242. {
  4243. return name;
  4244. }, (name, value) =>
  4245. {
  4246. return BsonTypeMapper.MapToBsonValue(value);
  4247. }, vget));
  4248. }
  4249. var map = script.GetFunctionDef(p.Get(2).Name);
  4250. var reduce = script.GetFunctionDef(p.Get(3).Name);
  4251. var finalize = script.GetFunctionDef(p.Get(4).Name);
  4252. var para = p[5] as Dictionary<string, object>;
  4253. var result = this.GetMapReduceResult(collection, q, map, reduce, finalize, para, cachename);
  4254. return result;
  4255. };
  4256. case "data.union":
  4257. return () =>
  4258. {
  4259. var datas = p[0] as ArrayList;
  4260. var fields = p[1] as ArrayList;
  4261. var page = p[2]._Int();
  4262. var pagesize = p[3]._Int();
  4263. var sort = p[4] as Dictionary<string, object>;
  4264. SortByDocument sortby = new SortByDocument(sort);
  4265. var result = new List<Dictionary<string, object>>();
  4266. foreach (var table in datas)
  4267. {
  4268. var data = table as ArrayList;
  4269. foreach (var dic in data)
  4270. {
  4271. int i = 0;
  4272. var mydata = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  4273. var d = dic as Dictionary<string, object>;
  4274. foreach (var kv in d)
  4275. {
  4276. mydata[fields[i]._Str()] = kv.Value;
  4277. i++;
  4278. }
  4279. result.Add(mydata);
  4280. }
  4281. }
  4282. var count = result.Count;
  4283. result = DataClient.Sort(result, sortby);
  4284. int skip = -1;
  4285. int limit = -1;
  4286. if (page > 0 && pagesize > 0)
  4287. {
  4288. skip = (page - 1) * pagesize;
  4289. limit = pagesize;
  4290. }
  4291. if (skip >= 0 || limit >= 0)
  4292. {
  4293. IEnumerable<Dictionary<string, object>> mr = result;
  4294. if (skip >= 0)
  4295. {
  4296. mr = mr.Skip(skip);
  4297. }
  4298. if (limit >= 0)
  4299. {
  4300. mr = mr.Take(limit);
  4301. }
  4302. result = mr.ToList();
  4303. }
  4304. Dictionary<string, object> result2 = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  4305. result2["count"] = count;
  4306. result2["rows"] = result;
  4307. return result2;
  4308. };
  4309. case "data.backup":
  4310. return () =>
  4311. {
  4312. return null;
  4313. };
  4314. case "data.querycount":
  4315. return () =>
  4316. {
  4317. string tid = p[0]._Str();//模板
  4318. tid = HttpUtility.UrlDecode(tid);
  4319. if (tid.StartsWith("/"))
  4320. {
  4321. tid = tid._Path(this.GetSource());
  4322. }
  4323. var query = p[1]._Str();
  4324. if (string.IsNullOrEmpty(this.UserId))
  4325. {
  4326. throw new NoSecurityException("没有登录");
  4327. }
  4328. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  4329. var index = tid.IndexOf('.');
  4330. var property = "";
  4331. if (index != -1)
  4332. {
  4333. property = tid.Substring(index);
  4334. tid = tid.Substring(0, index);
  4335. }
  4336. tid = this.GetTemplateId(tid);
  4337. if (string.IsNullOrEmpty(tid))
  4338. {
  4339. throw new NotExistException("模板不存在:" + p[0]._Str());
  4340. }
  4341. var tdoc = this.GetTemplateNode(tid);
  4342. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  4343. //=======================================================
  4344. //q = Query.And(q, Query.EQ(TemplateFlag, tid));
  4345. var collection = DataCollection + "_" + tid;
  4346. if (!string.IsNullOrEmpty(query))
  4347. {
  4348. var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
  4349. BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
  4350. this.CheckTemplate(tempdoc);
  4351. tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
  4352. IMongoQuery q2 = this.GetMyQuery(query,
  4353. (name) =>
  4354. {
  4355. var lname = name.ToLower();
  4356. if (lname.StartsWith("$"))
  4357. {
  4358. return lname.Substring(1);
  4359. }
  4360. switch (lname)
  4361. {
  4362. case "_id":
  4363. case "_created":
  4364. case "_modified":
  4365. case "_muser":
  4366. return lname;
  4367. }
  4368. return Definitions.ValueFlag + property + "." + lname;
  4369. },
  4370. (name, value) =>
  4371. {
  4372. var lname = name.ToLower();
  4373. if (lname.StartsWith("$"))
  4374. {
  4375. return lname.Substring(1);
  4376. }
  4377. switch (lname)
  4378. {
  4379. case "_id":
  4380. return value._Str();
  4381. case "_created":
  4382. case "_modified":
  4383. return Convert.ToDateTime(value);
  4384. case "_muser":
  4385. return value._Str();
  4386. }
  4387. if (!string.IsNullOrEmpty(property))
  4388. {
  4389. name = property.Trim('.') + "." + lname;
  4390. }
  4391. BsonDocument doc = tempdoc.Value(name) as BsonDocument;
  4392. var dbindex = doc.GetBool("_dbindex");
  4393. var _dbunique = doc.GetBool("_dbunique");
  4394. if (dbindex || _dbunique)
  4395. {
  4396. DatabaseHelper.CheckIndex(collection, new string[] { Definitions.ValueFlag + property + "." + lname }, _dbunique);
  4397. }
  4398. //if(doc)
  4399. return this.ConvertType(doc.Type(), value._Str(), doc.Array());
  4400. }, vget
  4401. );
  4402. if (q2 != null)
  4403. {
  4404. q = Query.And(q, q2);
  4405. }
  4406. }
  4407. var count = this.dbHelper.Count(collection, q);
  4408. return count;
  4409. };
  4410. case "data.status":
  4411. return () =>
  4412. {
  4413. string tid = p[0]._Str();//模板
  4414. tid = HttpUtility.UrlDecode(tid);
  4415. if (tid.StartsWith("/"))
  4416. {
  4417. tid = tid._Path(this.GetSource());
  4418. }
  4419. if (string.IsNullOrEmpty(this.UserId))
  4420. {
  4421. throw new NoSecurityException("没有登录");
  4422. }
  4423. var index = tid.IndexOf('.');
  4424. var property = "";
  4425. if (index != -1)
  4426. {
  4427. property = tid.Substring(index);
  4428. tid = tid.Substring(0, index);
  4429. }
  4430. tid = this.GetTemplateId(tid);
  4431. if (string.IsNullOrEmpty(tid))
  4432. {
  4433. throw new NotExistException("模板不存在:" + p[0]._Str());
  4434. }
  4435. var tdoc = this.GetTemplateNode(tid);
  4436. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  4437. //=======================================================
  4438. var collection = DataCollection + "_" + tid;
  4439. return this.dbHelper.GetStats(collection);
  4440. };
  4441. case "data.list":
  4442. case "data.query":
  4443. return () =>
  4444. {
  4445. string tid = p[0]._Str();//模板
  4446. tid = HttpUtility.UrlDecode(tid);
  4447. if (string.IsNullOrEmpty(tid))
  4448. {
  4449. return null;
  4450. }
  4451. if (tid.StartsWith("/"))
  4452. {
  4453. tid = tid._Path(this.GetSource());
  4454. }
  4455. var query = p[1]._Str();
  4456. var page = p[2]._Int(1);
  4457. var pagesize = p[3]._Int(100);
  4458. var sortby = p[4] as Dictionary<string, object>;
  4459. var fs = p[5] as ArrayList;
  4460. var expain = p[6]._Bool();
  4461. if (string.IsNullOrEmpty(this.UserId))
  4462. {
  4463. throw new NoSecurityException("没有登录");
  4464. }
  4465. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  4466. var index = tid.IndexOf('.');
  4467. var property = "";
  4468. if (index != -1)
  4469. {
  4470. property = tid.Substring(index);
  4471. tid = tid.Substring(0, index);
  4472. }
  4473. tid = this.GetTemplateId(tid);
  4474. if (string.IsNullOrEmpty(tid))
  4475. {
  4476. throw new NotExistException("模板不存在:" + p[0]._Str());
  4477. }
  4478. var tdoc = this.GetTemplateNode(tid);
  4479. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  4480. //=======================================================
  4481. //q = Query.And(q, Query.EQ(TemplateFlag, tid));
  4482. var collection = DataCollection + "_" + tid;
  4483. var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
  4484. BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
  4485. this.CheckTemplate(tempdoc);
  4486. tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
  4487. Dictionary<string, object> myvalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  4488. this.GetInstance(null, tid, SecurityType.Read, ref myvalues, emptyid: Definitions.ValueFlag + property, initvalues: null, once: true, usename: true);
  4489. var valuedic2 = myvalues._DicKeyObjects(Definitions.ValueFlag);
  4490. if (!string.IsNullOrEmpty(query))
  4491. {
  4492. IMongoQuery q2 = this.GetMyQuery(query,
  4493. (name) =>
  4494. {
  4495. var lname = name.ToLower();
  4496. if (lname.StartsWith("$"))
  4497. {
  4498. return lname.Substring(1);
  4499. }
  4500. switch (lname)
  4501. {
  4502. case "_id":
  4503. case "_created":
  4504. case "_modified":
  4505. case "_muser":
  4506. return lname;
  4507. }
  4508. return Definitions.ValueFlag + property + "." + lname;
  4509. },
  4510. (name, value) =>
  4511. {
  4512. var lname = name.ToLower();
  4513. if (lname.StartsWith("$"))
  4514. {
  4515. return lname.Substring(1);
  4516. }
  4517. switch (lname)
  4518. {
  4519. case "_id":
  4520. return value._Str();
  4521. case "_created":
  4522. case "_modified":
  4523. return Convert.ToDateTime(value);
  4524. case "_muser":
  4525. return value._Str();
  4526. }
  4527. if (!string.IsNullOrEmpty(property))
  4528. {
  4529. name = property.Trim('.') + "." + lname;
  4530. }
  4531. BsonDocument doc = tempdoc.Value(name) as BsonDocument;
  4532. var dbindex = doc.GetBool("_dbindex");
  4533. var _dbunique = doc.GetBool("_dbunique");
  4534. if (dbindex || _dbunique)
  4535. {
  4536. DatabaseHelper.CheckIndex(collection, new string[] { Definitions.ValueFlag + property + "." + lname }, _dbunique);
  4537. }
  4538. //if(doc)
  4539. return this.ConvertType(doc.Type(), value._Str(), doc.Array());
  4540. }, vget
  4541. );
  4542. if (q2 != null)
  4543. {
  4544. q = Query.And(q, q2);
  4545. }
  4546. }
  4547. List<string> ffs = new List<string>();
  4548. Dictionary<string, object> fdic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  4549. if (fs == null)
  4550. {
  4551. ffs.Add(IDFlag);
  4552. }
  4553. else
  4554. {
  4555. foreach (var f in fs)
  4556. {
  4557. string ftr = f.ToString();
  4558. var lname = ftr.ToLower();
  4559. if (lname.StartsWith("$"))
  4560. {
  4561. lname = lname.Substring(1);
  4562. if (lname == "_value")
  4563. {
  4564. foreach (var kv in valuedic2)
  4565. {
  4566. fdic[kv.Key] = kv.Value;
  4567. }
  4568. }
  4569. ffs.Add(lname);
  4570. }
  4571. else
  4572. {
  4573. switch (lname)
  4574. {
  4575. case "_id":
  4576. case "_created":
  4577. case "_modified":
  4578. case "_muser":
  4579. case "_value":
  4580. if (lname == "_value")
  4581. {
  4582. foreach (var kv in valuedic2)
  4583. {
  4584. fdic[kv.Key] = kv.Value;
  4585. }
  4586. }
  4587. ffs.Add(lname);
  4588. break;
  4589. default:
  4590. BsonElement e;
  4591. if (tempdoc.TryGetElement(lname, out e))
  4592. {
  4593. ffs.Add(Definitions.ValueFlag + property + "." + lname);
  4594. fdic[e.Name] = valuedic2[e.Name];
  4595. }
  4596. break;
  4597. }
  4598. }
  4599. }
  4600. }
  4601. SortByDocument sdoc = null;
  4602. if (sortby != null)
  4603. {
  4604. sdoc = new SortByDocument();
  4605. foreach (var kv in sortby)
  4606. {
  4607. var lname = kv.Key;
  4608. if (lname.StartsWith("$"))
  4609. {
  4610. sdoc[lname.Substring(1)] = BsonValue.Create(kv.Value);
  4611. }
  4612. else
  4613. {
  4614. switch (lname)
  4615. {
  4616. case "_id":
  4617. case "_created":
  4618. case "_modified":
  4619. case "_muser":
  4620. sdoc[lname] = BsonValue.Create(kv.Value);
  4621. break;
  4622. default:
  4623. sdoc[Definitions.ValueFlag + property + "." + lname] = BsonValue.Create(kv.Value);
  4624. break;
  4625. }
  4626. }
  4627. }
  4628. }
  4629. Func<List<BsonDocument>, List<Dictionary<string, object>>> mapping = (ds) =>
  4630. {
  4631. List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
  4632. foreach (var doc in ds)
  4633. {
  4634. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  4635. foreach (var kv in doc)
  4636. {
  4637. var k = kv.Name;
  4638. if (k == "_value")
  4639. {
  4640. var valuedoc = kv.Value as BsonDocument;
  4641. var value = new Dictionary<string, object>(fdic, StringComparer.OrdinalIgnoreCase);
  4642. var keys = value.Keys.ToArray();
  4643. foreach (var key in keys)
  4644. {
  4645. BsonValue value2;
  4646. if (valuedoc.TryGetValue(key.ToLower(), out value2))
  4647. {
  4648. value[key] = value2.Value();
  4649. }
  4650. }
  4651. result[k] = value;
  4652. }
  4653. else
  4654. {
  4655. result[k] = kv.Value.Value();
  4656. }
  4657. }
  4658. //BsonValue _value;
  4659. //if (doc.TryGetValue("_value", out _value))
  4660. //{
  4661. // Dictionary<string, object> valuedic = _value as Dictionary<string, object>;
  4662. // foreach (var f in ffs)
  4663. // {
  4664. // if (f.StartsWith("_value."))
  4665. // {
  4666. // var key = f.Substring(7);
  4667. // object obj;
  4668. // if (!valuedic._TryGet(key, out obj))
  4669. // {
  4670. // //valuedic._Set(key, tempdoc.Value(key).Value("_value").Value());
  4671. // var val = tempdoc.Value(key) as BsonDocument;
  4672. // var o = this.ConvertType(val.Type(), val.GetString("_value"), val.Array()).Value();
  4673. // valuedic._Set(key, o);
  4674. // }
  4675. // }
  4676. // }
  4677. results.Add(result);
  4678. }
  4679. return results;
  4680. };
  4681. var docs = this.dbHelper.FindPage(collection, q, page, pagesize, ffs, sdoc, mapping, expain);
  4682. //docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
  4683. return docs;
  4684. };
  4685. case "data.deletebyquery":
  4686. return () =>
  4687. {
  4688. string tid = p[0]._Str();//模板
  4689. tid = HttpUtility.UrlDecode(tid);
  4690. if (tid.StartsWith("/"))
  4691. {
  4692. tid = tid._Path(this.GetSource());
  4693. }
  4694. var query = p[1]._Str();
  4695. if (string.IsNullOrEmpty(this.UserId))
  4696. {
  4697. throw new NoSecurityException("没有登录");
  4698. }
  4699. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  4700. var index = tid.IndexOf('.');
  4701. var property = "";
  4702. if (index != -1)
  4703. {
  4704. property = tid.Substring(index);
  4705. tid = tid.Substring(0, index);
  4706. }
  4707. tid = this.GetTemplateId(tid);
  4708. if (string.IsNullOrEmpty(tid))
  4709. {
  4710. throw new NotExistException("模板不存在:" + p[0]._Str());
  4711. }
  4712. var tdoc = this.GetTemplateNode(tid);
  4713. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  4714. //=======================================================
  4715. //q = Query.And(q, Query.EQ(TemplateFlag, tid));
  4716. var collection = DataCollection + "_" + tid;
  4717. if (!string.IsNullOrEmpty(query))
  4718. {
  4719. var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
  4720. BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
  4721. this.CheckTemplate(tempdoc);
  4722. tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
  4723. IMongoQuery q2 = this.GetMyQuery(query,
  4724. (name) =>
  4725. {
  4726. var lname = name.ToLower();
  4727. if (lname.StartsWith("$"))
  4728. {
  4729. return lname.Substring(1);
  4730. }
  4731. switch (lname)
  4732. {
  4733. case "_id":
  4734. case "_created":
  4735. case "_modified":
  4736. case "_muser":
  4737. return lname;
  4738. }
  4739. return Definitions.ValueFlag + property + "." + lname;
  4740. },
  4741. (name, value) =>
  4742. {
  4743. var lname = name.ToLower();
  4744. if (lname.StartsWith("$"))
  4745. {
  4746. return lname.Substring(1);
  4747. }
  4748. switch (lname)
  4749. {
  4750. case "_id":
  4751. return value._Str();
  4752. case "_created":
  4753. case "_modified":
  4754. return Convert.ToDateTime(value);
  4755. case "_muser":
  4756. return value._Str();
  4757. }
  4758. if (!string.IsNullOrEmpty(property))
  4759. {
  4760. name = property.Trim('.') + "." + lname;
  4761. }
  4762. BsonDocument doc = tempdoc.Value(name) as BsonDocument;
  4763. var dbindex = doc.GetBool("_dbindex");
  4764. var _dbunique = doc.GetBool("_dbunique");
  4765. if (dbindex || _dbunique)
  4766. {
  4767. DatabaseHelper.CheckIndex(collection, new string[] { Definitions.ValueFlag + property + "." + lname }, _dbunique);
  4768. }
  4769. //if(doc)
  4770. return this.ConvertType(doc.Type(), value._Str(), doc.Array());
  4771. }, vget
  4772. );
  4773. if (q2 != null)
  4774. {
  4775. q = Query.And(q, q2);
  4776. }
  4777. }
  4778. this.dbHelper.Remove(collection, q);
  4779. //var docs = this.dbHelper.FindPage(collection, q, page, pagesize, ffs, sdoc, null);
  4780. //docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
  4781. return true;
  4782. };
  4783. case "data.count":
  4784. return () =>
  4785. {
  4786. string tid = p[0]._Str();//模板
  4787. tid = HttpUtility.UrlDecode(tid);
  4788. if (tid.StartsWith("/"))
  4789. {
  4790. tid = tid._Path(this.GetSource());
  4791. }
  4792. var query = p[1]._Str();
  4793. if (string.IsNullOrEmpty(this.UserId))
  4794. {
  4795. throw new NoSecurityException("没有登录");
  4796. }
  4797. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  4798. var index = tid.IndexOf('.');
  4799. var property = "";
  4800. if (index != -1)
  4801. {
  4802. property = tid.Substring(index);
  4803. tid = tid.Substring(0, index);
  4804. }
  4805. tid = this.GetTemplateId(tid);
  4806. if (string.IsNullOrEmpty(tid))
  4807. {
  4808. throw new NotExistException("模板不存在:" + p[0]._Str());
  4809. }
  4810. var tdoc = this.GetTemplateNode(tid);
  4811. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  4812. //=======================================================
  4813. //q = Query.And(q, Query.EQ(TemplateFlag, tid));
  4814. var collection = DataCollection + "_" + tid;
  4815. if (!string.IsNullOrEmpty(query))
  4816. {
  4817. var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
  4818. BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
  4819. this.CheckTemplate(tempdoc);
  4820. tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
  4821. IMongoQuery q2 = this.GetMyQuery(query,
  4822. (name) =>
  4823. {
  4824. var lname = name.ToLower();
  4825. if (lname.StartsWith("$"))
  4826. {
  4827. return lname.Substring(1);
  4828. }
  4829. switch (lname)
  4830. {
  4831. case "_id":
  4832. case "_created":
  4833. case "_modified":
  4834. case "_muser":
  4835. return lname;
  4836. }
  4837. return Definitions.ValueFlag + property + "." + lname;
  4838. },
  4839. (name, value) =>
  4840. {
  4841. var lname = name.ToLower();
  4842. if (lname.StartsWith("$"))
  4843. {
  4844. return lname.Substring(1);
  4845. }
  4846. switch (lname)
  4847. {
  4848. case "_id":
  4849. return value._Str();
  4850. case "_created":
  4851. case "_modified":
  4852. return Convert.ToDateTime(value);
  4853. case "_muser":
  4854. return value._Str();
  4855. }
  4856. if (!string.IsNullOrEmpty(property))
  4857. {
  4858. name = property.Trim('.') + "." + lname;
  4859. }
  4860. BsonDocument doc = tempdoc.Value(name) as BsonDocument;
  4861. var dbindex = doc.GetBool("_dbindex");
  4862. var _dbunique = doc.GetBool("_dbunique");
  4863. if (dbindex || _dbunique)
  4864. {
  4865. DatabaseHelper.CheckIndex(collection, new string[] { Definitions.ValueFlag + property + "." + lname }, _dbunique);
  4866. }
  4867. //if(doc)
  4868. return this.ConvertType(doc.Type(), value._Str(), doc.Array());
  4869. }, vget
  4870. );
  4871. if (q2 != null)
  4872. {
  4873. q = Query.And(q, q2);
  4874. }
  4875. }
  4876. return this.dbHelper.Count(collection, q);
  4877. };
  4878. case "history.query":
  4879. return () =>
  4880. {
  4881. string name = p[0]._Str();//模板
  4882. name = HttpUtility.UrlDecode(name);
  4883. int wen = name.IndexOf("?");
  4884. string type = "f";
  4885. CollectionType filetype = CollectionType.File;
  4886. string historytype = FileHistoryCollection;
  4887. if (wen != -1)
  4888. {
  4889. type = name.Substring(wen + 1)[0].ToString().ToLower();
  4890. name = name.Substring(0, wen);
  4891. }
  4892. switch (type)
  4893. {
  4894. case "f":
  4895. filetype = CollectionType.File;
  4896. historytype = FileHistoryCollection;
  4897. break;
  4898. case "t":
  4899. filetype = CollectionType.Template;
  4900. historytype = TemplateHistoryCollection;
  4901. break;
  4902. case "i":
  4903. filetype = CollectionType.Instance;
  4904. historytype = InstanceHistoryCollection;
  4905. break;
  4906. }
  4907. var page = p[1]._Int(1);
  4908. var pagesize = p[2]._Int(100);
  4909. if (string.IsNullOrEmpty(this.UserId))
  4910. {
  4911. throw new NoSecurityException("没有登录");
  4912. }
  4913. BsonDocument doc = this.FindDocumentById(filetype.ToString(), name, new string[] { UserFlag, NameFlag });
  4914. var docid = string.Empty;
  4915. if (doc == null)
  4916. {
  4917. doc = this.dbHelper.FindDocumentByQuery(historytype, Query.And(Query.EQ("flag", "delete"), Query.EQ("lname", name)), new string[] { "id", "_uid", "name" });
  4918. if (doc != null)
  4919. {
  4920. docid = doc.GetString("id");
  4921. doc[NameFlag] = doc["name"];
  4922. }
  4923. }
  4924. else
  4925. {
  4926. docid = doc.GetString(IDFlag);
  4927. }
  4928. if (doc == null)
  4929. {
  4930. throw new NotExistException("不存在:" + name);
  4931. }
  4932. CheckSecurity(filetype, doc, SecurityType.Read);
  4933. //this.CheckSecurity(name, filetype, SecurityType.Read);
  4934. //=======================================================
  4935. IMongoQuery q = Query.EQ("id", docid);
  4936. var docs = this.dbHelper.FindPage(historytype, q, page, pagesize, new List<string> { IDFlag, "desc", "time", "user", "name", "size", "flag", "muser", "tag" }, new SortByDocument("time", -1), null);
  4937. //docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
  4938. docs["type"] = type;
  4939. return docs;
  4940. };
  4941. case "instance.history":
  4942. return () =>
  4943. {
  4944. string iname = p[0]._Str().ToLower();
  4945. var index = iname.IndexOf('.');
  4946. if (index == -1)
  4947. {
  4948. throw new InvalidNameException("实例节点名不合法:" + iname);
  4949. }
  4950. var prop = iname.Substring(index);
  4951. var instname = iname.Substring(0, index);
  4952. string historytype = InstanceHistoryCollection;
  4953. var page = p[2]._Int(1);
  4954. var pagesize = p[3]._Int(100);
  4955. var sortby = p[4] as Dictionary<string, object>;
  4956. SortByDocument sdoc = null;
  4957. if (sortby != null)
  4958. {
  4959. sdoc = new SortByDocument();
  4960. foreach (var kv in sortby)
  4961. {
  4962. sdoc[kv.Key] = BsonValue.Create(kv.Value);
  4963. }
  4964. }
  4965. if (sdoc == null)
  4966. {
  4967. sdoc = new SortByDocument();
  4968. sdoc["time"] = 1;
  4969. }
  4970. if (string.IsNullOrEmpty(this.UserId))
  4971. {
  4972. throw new NoSecurityException("没有登录");
  4973. }
  4974. var doc = this.FindDocumentByName(InstanceCollection, instname, new string[] { TemplateFlag, IDFlag, NameFlag, UserFlag });
  4975. if (doc == null)
  4976. {
  4977. throw new NotExistException("实例不存在:" + instname);
  4978. }
  4979. this.CheckSecurity(CollectionType.Instance, doc, SecurityType.Read);
  4980. //this.CheckSecurity(name, filetype, SecurityType.Read);
  4981. //=======================================================
  4982. var tid = doc.GetString(TemplateFlag);
  4983. var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
  4984. BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
  4985. this.CheckTemplate(tempdoc);
  4986. tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
  4987. var id = doc.GetString(IDFlag);
  4988. IMongoQuery q = Query.EQ("id", "/" + id + prop);
  4989. var query = p[1]._Str();
  4990. if (!string.IsNullOrEmpty(query))
  4991. {
  4992. IMongoQuery q2 = this.GetMyQuery(query,
  4993. (name) =>
  4994. {
  4995. var lname = name.ToLower();
  4996. if (lname == "value")
  4997. {
  4998. return "doc._value";
  4999. }
  5000. return lname;
  5001. },
  5002. (name, value) =>
  5003. {
  5004. var lname = name.ToLower();
  5005. if (lname == "time")
  5006. {
  5007. return this.ConvertType(ItemDataType.DateTime, value._Str(), false);
  5008. }
  5009. else if (lname == "value")
  5010. {
  5011. BsonDocument tdoc = tempdoc.Value(prop.Remove(0, 1)) as BsonDocument;
  5012. return this.ConvertType(tdoc.Type(), value._Str(), tdoc.Array());
  5013. }
  5014. return BsonValue.Create(value);
  5015. }, vget
  5016. );
  5017. if (q2 != null)
  5018. {
  5019. q = Query.And(q, q2);
  5020. }
  5021. }
  5022. Func<List<BsonDocument>, List<Dictionary<string, object>>> mapping = (ds) =>
  5023. {
  5024. List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
  5025. foreach (var d in ds)
  5026. {
  5027. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5028. result["time"] = d.GetDateTime("time");
  5029. result["value"] = d.Value("doc._value").Value();
  5030. results.Add(result);
  5031. }
  5032. return results;
  5033. };
  5034. var docs = this.dbHelper.FindPage(historytype, q, page, pagesize, new List<string> { "id", "doc._time", "doc._value" }, sdoc, mapping);
  5035. //docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
  5036. return docs;
  5037. };
  5038. case "file.history":
  5039. case "history.get":
  5040. return () =>
  5041. {
  5042. var hid = p[0]._Str();
  5043. var valuefield = "doc._value";
  5044. List<string> fields = new List<string>() { valuefield, UserFlag, "id", "name" };
  5045. fields.Add("doc._gz");
  5046. BsonDocument doc = this.dbHelper.FindDocumentByQuery(FileHistoryCollection, Query.EQ(IDFlag, hid), fields.ToArray());
  5047. if (doc == null)
  5048. {
  5049. throw new NotExistException("不存在:" + hid);
  5050. }
  5051. var id = doc.GetString("id");
  5052. this.CheckSecurity(id, CollectionType.File, SecurityType.Read);
  5053. bool gz = doc.GetBool("doc._gz");
  5054. byte[] vvv = doc.Value(valuefield).AsByteArray;
  5055. if (gz)
  5056. {
  5057. vvv = CommonFunction.Decompress(vvv);
  5058. }
  5059. var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5060. result["value"] = vvv._Str(false);
  5061. result["name"] = doc.GetString("name");
  5062. return result;
  5063. };
  5064. case "data.group":
  5065. return () =>
  5066. {
  5067. var docs = p[0] as List<Dictionary<string, object>>;
  5068. var type = p[1]._Str();
  5069. var field = p[2]._Str();
  5070. Func<IEnumerable<Dictionary<string, object>>, decimal> getSum = null;
  5071. switch (type)
  5072. {
  5073. case "count":
  5074. getSum = (a) => { return a.Count(); };
  5075. break;
  5076. case "sum":
  5077. getSum = (a) => { return a.Sum(c => c.GetDecimal(field)); };
  5078. break;
  5079. case "average":
  5080. getSum = (a) => { return a.Average(c => c.GetDecimal(field)); };
  5081. break;
  5082. case "min":
  5083. getSum = (a) => { return a.Min(c => c.GetDecimal(field)); };
  5084. break;
  5085. case "max":
  5086. getSum = (a) => { return a.Max(c => c.GetDecimal(field)); };
  5087. break;
  5088. default:
  5089. throw new InvalidParameterException();
  5090. }
  5091. var groupList = docs.GroupBy(m => new
  5092. {
  5093. Key = m// getDate(m)
  5094. }).
  5095. Select(a => new
  5096. {
  5097. Key = a.Key.Key,
  5098. Value = getSum(a)
  5099. }).ToList();
  5100. Dictionary<object, object> result = new Dictionary<object, object>();
  5101. foreach (var kv in groupList)
  5102. {
  5103. result[kv.Key] = Math.Round(kv.Value, 2);
  5104. }
  5105. List<Dictionary<string, object>> output = new List<Dictionary<string, object>>();
  5106. foreach (var kv in result)
  5107. {
  5108. Dictionary<string, object> o = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5109. o["_id"] = kv.Key;
  5110. o["value"] = kv.Value;
  5111. output.Add(o);
  5112. }
  5113. return output;
  5114. };
  5115. case "instance.query":
  5116. return () =>
  5117. {
  5118. string tid = p[0]._Str();//模板
  5119. tid = HttpUtility.UrlDecode(tid);
  5120. if (tid.StartsWith("/"))
  5121. {
  5122. tid = tid._Path(this.GetSource());
  5123. }
  5124. var query = p[1]._Str();
  5125. var page = p[2]._Int(1);
  5126. var pagesize = p[3]._Int(100);
  5127. var sortby = p[4] as Dictionary<string, object>;
  5128. var fs = p[5] as ArrayList;
  5129. if (fs != null && fs.Count == 0)
  5130. {
  5131. fs = null;
  5132. }
  5133. if (string.IsNullOrEmpty(this.UserId))
  5134. {
  5135. throw new NoSecurityException("没有登录");
  5136. }
  5137. //IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  5138. var index = tid.IndexOf('.');
  5139. var property = "";
  5140. if (index != -1)
  5141. {
  5142. property = tid.Substring(index);
  5143. tid = tid.Substring(0, index);
  5144. }
  5145. tid = this.GetTemplateId(tid);
  5146. if (string.IsNullOrEmpty(tid))
  5147. {
  5148. throw new NotExistException("模板不存在:" + p[0]._Str());
  5149. }
  5150. IMongoQuery q = Query.EQ(TemplateFlag, tid);
  5151. //var tdoc = this.GetTemplateNode(tid);
  5152. BsonDocument tdoc = this.FindDocumentById(CollectionType.Template.ToString(), tid, new string[] { UserFlag, NameFlag });
  5153. if (tdoc.GetString(UserFlag) != this.UserId)
  5154. {
  5155. CheckSecurity(CollectionType.Template, tdoc, SecurityType.Read);
  5156. q = Query.And(q, Query.EQ(UserFlag, this.UserId));
  5157. }
  5158. //this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  5159. //=======================================================
  5160. var collection = InstanceCollection;
  5161. var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
  5162. BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
  5163. this.CheckTemplate(tempdoc);
  5164. tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
  5165. if (!string.IsNullOrEmpty(query))
  5166. {
  5167. IMongoQuery q2 = this.GetMyQuery(query,
  5168. (name) =>
  5169. {
  5170. var lname = name.ToLower();
  5171. if (lname.StartsWith("$"))
  5172. {
  5173. return lname.Substring(1);
  5174. }
  5175. switch (lname)
  5176. {
  5177. case "_id":
  5178. case "_created":
  5179. case "_modified":
  5180. case "_muser":
  5181. return lname;
  5182. }
  5183. return Definitions.ValueFlag + property + "." + lname + "." + Definitions.ValueFlag;
  5184. },
  5185. (name, value) =>
  5186. {
  5187. var lname = name.ToLower();
  5188. if (lname.StartsWith("$"))
  5189. {
  5190. return value._Str();
  5191. }
  5192. switch (lname)
  5193. {
  5194. case "_id":
  5195. return value._Str();
  5196. case "_created":
  5197. case "_modified":
  5198. return Convert.ToDateTime(value);
  5199. case "_muser":
  5200. return value._Str();
  5201. }
  5202. if (!string.IsNullOrEmpty(property))
  5203. {
  5204. name = property.Trim('.') + "." + lname;
  5205. }
  5206. BsonDocument doc = tempdoc.Value(name) as BsonDocument;
  5207. return this.ConvertType(doc.Type(), value._Str(), doc.Array());
  5208. }, vget
  5209. );
  5210. if (q2 != null)
  5211. {
  5212. q = Query.And(q, q2);
  5213. }
  5214. }
  5215. List<string> ffs = new List<string>();
  5216. if (fs == null)
  5217. {
  5218. ffs.Add(CreatedFlag);
  5219. }
  5220. else
  5221. {
  5222. foreach (var f in fs)
  5223. {
  5224. string ftr = f.ToString();
  5225. var lname = ftr.ToLower();
  5226. if (lname.StartsWith("$"))
  5227. {
  5228. ffs.Add(lname.Substring(1));
  5229. }
  5230. else
  5231. {
  5232. switch (lname)
  5233. {
  5234. case "_id":
  5235. case "_created":
  5236. case "_modified":
  5237. case "_muser":
  5238. case "_value":
  5239. ffs.Add(lname);
  5240. break;
  5241. default:
  5242. ffs.Add(Definitions.ValueFlag + property + "." + lname + "." + Definitions.ValueFlag);
  5243. break;
  5244. }
  5245. }
  5246. }
  5247. }
  5248. SortByDocument sdoc = null;
  5249. if (sortby != null)
  5250. {
  5251. sdoc = new SortByDocument();
  5252. foreach (var kv in sortby)
  5253. {
  5254. var lname = kv.Key;
  5255. if (lname.StartsWith("$"))
  5256. {
  5257. sdoc[lname.Substring(1)] = BsonValue.Create(kv.Value);
  5258. }
  5259. else
  5260. {
  5261. switch (lname)
  5262. {
  5263. case "_id":
  5264. case "_created":
  5265. case "_modified":
  5266. case "_muser":
  5267. sdoc[lname] = BsonValue.Create(kv.Value);
  5268. break;
  5269. default:
  5270. sdoc[Definitions.ValueFlag + property + "." + lname + "." + Definitions.ValueFlag] = BsonValue.Create(kv.Value);
  5271. break;
  5272. }
  5273. }
  5274. }
  5275. }
  5276. Func<List<BsonDocument>, List<Dictionary<string, object>>> mapping = (ds) =>
  5277. {
  5278. List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
  5279. foreach (var doc in ds)
  5280. {
  5281. Dictionary<string, object> result = doc.ToDictionary();
  5282. object bv;
  5283. if (result.TryGetValue(Definitions.ValueFlag, out bv))
  5284. {
  5285. var value = bv as Dictionary<string, object>;
  5286. result[Definitions.ValueFlag] = value._DicValue((d) =>
  5287. {
  5288. d.Remove("_cp");
  5289. d.Remove("_time");
  5290. d.Remove("_from");
  5291. d.Remove("_to");
  5292. });
  5293. value = result[Definitions.ValueFlag] as Dictionary<string, object>;
  5294. foreach (var f in ffs)
  5295. {
  5296. if (f.StartsWith("_value.") && f.EndsWith("._value"))
  5297. {
  5298. var key = f.Substring(7);
  5299. var dot = key.LastIndexOf('.');
  5300. key = key.Substring(0, dot);
  5301. object obj;
  5302. if (!value._TryGet(key, out obj))
  5303. {
  5304. var val = tempdoc.Value(key) as BsonDocument;
  5305. var o = this.ConvertType(val.Type(), val.GetString("_value"), val.Array());
  5306. value._Set(key, o);
  5307. }
  5308. }
  5309. }
  5310. }
  5311. results.Add(result);
  5312. }
  5313. return results;
  5314. };
  5315. var docs = this.dbHelper.FindPage(collection, q, page, pagesize, ffs, sdoc, mapping);
  5316. //docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
  5317. return docs;
  5318. };
  5319. case "instance.deletebyquery":
  5320. return () =>
  5321. {
  5322. string tid = p[0]._Str();//模板
  5323. tid = HttpUtility.UrlDecode(tid);
  5324. if (tid.StartsWith("/"))
  5325. {
  5326. tid = tid._Path(this.GetSource());
  5327. }
  5328. var query = p[1]._Str();
  5329. if (string.IsNullOrEmpty(this.UserId))
  5330. {
  5331. throw new NoSecurityException("没有登录");
  5332. }
  5333. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  5334. var index = tid.IndexOf('.');
  5335. var property = "";
  5336. if (index != -1)
  5337. {
  5338. property = tid.Substring(index);
  5339. tid = tid.Substring(0, index);
  5340. }
  5341. tid = this.GetTemplateId(tid);
  5342. if (string.IsNullOrEmpty(tid))
  5343. {
  5344. throw new NotExistException("模板不存在:" + p[0]._Str());
  5345. }
  5346. var tdoc = this.GetTemplateNode(tid);
  5347. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  5348. //=======================================================
  5349. q = Query.And(q, Query.EQ(TemplateFlag, tid));
  5350. var collection = InstanceCollection;
  5351. if (!string.IsNullOrEmpty(query))
  5352. {
  5353. var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
  5354. BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
  5355. this.CheckTemplate(tempdoc);
  5356. tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
  5357. IMongoQuery q2 = this.GetMyQuery(query,
  5358. (name) =>
  5359. {
  5360. var lname = name.ToLower();
  5361. if (lname.StartsWith("$"))
  5362. {
  5363. return lname.Substring(1);
  5364. }
  5365. switch (lname)
  5366. {
  5367. case "_id":
  5368. case "_created":
  5369. case "_modified":
  5370. case "_muser":
  5371. return lname;
  5372. }
  5373. return Definitions.ValueFlag + property + "." + lname + "." + Definitions.ValueFlag;
  5374. },
  5375. (name, value) =>
  5376. {
  5377. var lname = name.ToLower();
  5378. if (lname.StartsWith("$"))
  5379. {
  5380. return value._Str();
  5381. }
  5382. switch (lname)
  5383. {
  5384. case "_id":
  5385. return value._Str();
  5386. case "_created":
  5387. case "_modified":
  5388. return Convert.ToDateTime(value);
  5389. case "_muser":
  5390. return value._Str();
  5391. }
  5392. if (!string.IsNullOrEmpty(property))
  5393. {
  5394. name = property.Trim('.') + "." + lname;
  5395. }
  5396. BsonDocument doc = tempdoc.Value(name) as BsonDocument;
  5397. return this.ConvertType(doc.Type(), value._Str(), doc.Array());
  5398. }, vget
  5399. );
  5400. if (q2 != null)
  5401. {
  5402. q = Query.And(q, q2);
  5403. }
  5404. }
  5405. //var docs = this.dbHelper.FindPage(collection, q, page, pagesize, ffs, sdoc, mapping);
  5406. //docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
  5407. this.dbHelper.Remove(collection, q);
  5408. return true;
  5409. };
  5410. case "data.create":
  5411. case "data.update":
  5412. case "data.insert":
  5413. case "data.insert2":
  5414. return () =>
  5415. {
  5416. if (string.IsNullOrEmpty(this.UserId))
  5417. {
  5418. throw new NoSecurityException("没有权限", v);
  5419. }
  5420. string tid = p[0]._Str();//模板
  5421. tid = HttpUtility.UrlDecode(tid);
  5422. if (tid.StartsWith("/"))
  5423. {
  5424. tid = tid._Path(this.GetSource());
  5425. }
  5426. var tname = tid;
  5427. var index = tid.IndexOf('.');
  5428. var property = "";
  5429. if (index != -1)
  5430. {
  5431. property = tid.Substring(index);
  5432. tid = tid.Substring(0, index);
  5433. }
  5434. tid = this.GetTemplateId(tid);
  5435. if (string.IsNullOrEmpty(tid))
  5436. {
  5437. throw new NotExistException("模板不存在:" + tname);
  5438. }
  5439. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  5440. var collection = DataCollection + "_" + tid;
  5441. var value = p[1] as Dictionary<string, object>;//数据
  5442. var id = p[2]._Str();//更新的数据id
  5443. if (v == "data.update")
  5444. {
  5445. if (string.IsNullOrEmpty(id))
  5446. {
  5447. throw new InvalidParameterException("参数错误:id");
  5448. }
  5449. var doc = this.FindDocumentById(collection, id, new string[] { UserFlag });
  5450. if (doc == null)
  5451. {
  5452. throw new NotExistException("数据不存在");
  5453. }
  5454. if (doc.GetString(UserFlag) != this.UserId)
  5455. {
  5456. throw new NoSecurityException("没有权限");
  5457. }
  5458. //Dictionary<string, object> values = value._DicKeyStrings(Definitions.ValueFlag + property);
  5459. //var docvalue = doc[Definitions.ValueFlag] as BsonDocument;
  5460. //var myvalues = docvalue.ToDictionary()._DicKeys(Definitions.ValueFlag);
  5461. //foreach (var kv in values)
  5462. //{
  5463. // myvalues[kv.Key] = kv.Value;
  5464. //}
  5465. //Dictionary<string, object> ivalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5466. //this.GetInstance(null, tid, SecurityType.Read, ref ivalues, emptyid: Definitions.ValueFlag + property, initvalues: myvalues);
  5467. //BsonDocument udoc = new BsonDocument();
  5468. //foreach (var kv in ivalues)
  5469. //{
  5470. // if (values.ContainsKey(kv.Key))
  5471. // {
  5472. // udoc.Add(kv.Key, BsonValue.Create(kv.Value));
  5473. // }
  5474. //}
  5475. Dictionary<string, object> values = value._DicKeyStrings(Definitions.ValueFlag + property);
  5476. Dictionary<string, object> myvalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5477. this.GetInstance(null, tid, SecurityType.Read, ref myvalues, emptyid: Definitions.ValueFlag + property, initvalues: values, once: true);
  5478. BsonDocument udoc = new BsonDocument();
  5479. foreach (var kv in myvalues)
  5480. {
  5481. if (values.ContainsKey(kv.Key))
  5482. {
  5483. udoc.Add(kv.Key, BsonValue.Create(kv.Value));
  5484. }
  5485. }
  5486. this.dbHelper.Update(collection, id, udoc);
  5487. return true;
  5488. }
  5489. else
  5490. {
  5491. Dictionary<string, object> values = value._DicKeyStrings(Definitions.ValueFlag + property);
  5492. Dictionary<string, object> myvalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5493. this.GetInstance(null, tid, SecurityType.Read, ref myvalues, emptyid: Definitions.ValueFlag + property, initvalues: values, once: true);
  5494. BsonDocument docvalue = CreateDocument(null);
  5495. docvalue.Add(TemplateFlag, tid);
  5496. var valuedic = myvalues._DicKeyObjects(Definitions.ValueFlag);
  5497. docvalue.Add(Definitions.ValueFlag, new BsonDocument(valuedic));
  5498. //if (v == "data.update")
  5499. //{
  5500. // this.dbHelper.Update(collection, id, docvalue);
  5501. //}
  5502. //else
  5503. //{
  5504. if (v == "data.insert2")
  5505. {
  5506. if (!docvalue.Contains(DataClient.CreatedFlag))
  5507. {
  5508. docvalue[DataClient.CreatedFlag] = DateTime.UtcNow;
  5509. }
  5510. docvalue[DataClient.ModifiedUserFlag] = this.UserId ?? string.Empty;
  5511. docvalue[DataClient.ModifiedFlag] = DateTime.UtcNow;
  5512. DatabaseHelper.AddInsert(collection, docvalue);
  5513. }
  5514. else
  5515. {
  5516. this.dbHelper.Insert(collection, docvalue);
  5517. }
  5518. //}
  5519. return true;
  5520. }
  5521. };
  5522. case "data.values":
  5523. return () =>
  5524. {
  5525. if (string.IsNullOrEmpty(this.UserId))
  5526. {
  5527. throw new NoSecurityException("没有权限", v);
  5528. }
  5529. string tid = p[0]._Str();//模板
  5530. tid = HttpUtility.UrlDecode(tid);
  5531. if (tid.StartsWith("/"))
  5532. {
  5533. tid = tid._Path(this.GetSource());
  5534. }
  5535. var tname = tid;
  5536. var index = tid.IndexOf('.');
  5537. var property = "";
  5538. if (index != -1)
  5539. {
  5540. property = tid.Substring(index);
  5541. tid = tid.Substring(0, index);
  5542. }
  5543. tid = this.GetTemplateId(tid);
  5544. if (string.IsNullOrEmpty(tid))
  5545. {
  5546. throw new NotExistException("模板不存在:" + tname);
  5547. }
  5548. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  5549. Dictionary<string, object> values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5550. Dictionary<string, object> myvalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5551. this.GetInstance(null, tid, SecurityType.Read, ref myvalues, emptyid: Definitions.ValueFlag + property, initvalues: values, once: true);
  5552. var valuedic = myvalues._DicKeyObjects(Definitions.ValueFlag);
  5553. return valuedic;
  5554. };
  5555. case "instance.insert":
  5556. return () =>
  5557. {
  5558. if (string.IsNullOrEmpty(this.UserId))
  5559. {
  5560. throw new NoSecurityException("没有权限", v);
  5561. }
  5562. string tid = p[0]._Str();//模板
  5563. tid = HttpUtility.UrlDecode(tid);
  5564. if (tid.StartsWith("/"))
  5565. {
  5566. tid = tid._Path(this.GetSource());
  5567. }
  5568. var instanceId = p[1]._Str();//实例名
  5569. var value = p[2] as Dictionary<string, object>;//数据
  5570. var index = tid.IndexOf('.');
  5571. var property = "";
  5572. if (index != -1)
  5573. {
  5574. property = tid.Substring(index);
  5575. tid = tid.Substring(0, index);
  5576. }
  5577. tid = this.GetTemplateId(tid);
  5578. if (!string.IsNullOrEmpty(tid))
  5579. {
  5580. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  5581. }
  5582. Dictionary<string, object> values = value._DicKeyStrings(property.Trim('.'));
  5583. string iid = null;
  5584. DataOperations operations = DataOperations.Insert;
  5585. instanceId = instanceId.Trim('/');
  5586. this.PublishInstance(ref iid, instanceId, null, null, tid, operations, newvalues: values);
  5587. //this.UpdateInstanceByValues(instanceId, tid, values);
  5588. return true;
  5589. };
  5590. case "path":
  5591. return () =>
  5592. {
  5593. var path = p[0]._Str();
  5594. var rp = p[1]._Str();
  5595. if (string.IsNullOrEmpty(rp))
  5596. {
  5597. path = path._Path(this.GetSource());
  5598. }
  5599. else
  5600. {
  5601. path = path._Path(rp);
  5602. }
  5603. if (!path.StartsWith("/"))
  5604. {
  5605. path = "/" + path;
  5606. }
  5607. return path;
  5608. };
  5609. case "instance.set":
  5610. return () =>
  5611. {
  5612. if (string.IsNullOrEmpty(this.UserId))
  5613. {
  5614. throw new NoSecurityException("没有权限", v);
  5615. }
  5616. if (p.Count == 2)
  5617. {
  5618. var iid = p[0]._Str();//实例名
  5619. var iiindex = iid.IndexOf('.');
  5620. var myprop = string.Empty;
  5621. if (iiindex != -1)
  5622. {
  5623. myprop = iid.Substring(iiindex);
  5624. iid = iid.Substring(0, iiindex);
  5625. }
  5626. var vvs = p[1] as Dictionary<string, object>;//数据
  5627. Dictionary<string, object> myvalues = vvs._DicKeyStrings(myprop.Trim('.'));
  5628. if (!FileExist(iid, InstanceCollection))
  5629. {
  5630. throw new NotExistException("实例不存在:" + iid);
  5631. }
  5632. else
  5633. {
  5634. foreach (var kv in myvalues)
  5635. {
  5636. this.UpdateInstance(iid + "." + kv.Key, kv.Value._Str(), null, null, this.myInstanceModels, null);
  5637. }
  5638. this.UpdateInstanceModels();
  5639. }
  5640. return true;
  5641. }
  5642. string tid = p[0]._Str();//模板
  5643. tid = HttpUtility.UrlDecode(tid);
  5644. if (tid.StartsWith("/"))
  5645. {
  5646. tid = tid._Path(this.GetSource());
  5647. }
  5648. var instanceId = p[1]._Str();//实例名
  5649. this.CheckName(ref instanceId);
  5650. var value = p[2] as Dictionary<string, object>;//数据
  5651. var index = tid.IndexOf('.');
  5652. var property = "";
  5653. if (index != -1)
  5654. {
  5655. property = tid.Substring(index);
  5656. tid = tid.Substring(0, index);
  5657. }
  5658. tid = this.GetTemplateId(tid);
  5659. if (!string.IsNullOrEmpty(tid))
  5660. {
  5661. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  5662. }
  5663. var iiiindex = instanceId.IndexOf('.');
  5664. if (iiiindex != -1)
  5665. {
  5666. property = instanceId.Substring(iiiindex);
  5667. instanceId = instanceId.Substring(0, iiiindex);
  5668. }
  5669. Dictionary<string, object> values = value._DicKeyStrings(property.Trim('.'));
  5670. if (!FileExist(instanceId, InstanceCollection))
  5671. {
  5672. this.UpdateInstanceByValues(instanceId, tid, values);
  5673. }
  5674. else
  5675. {
  5676. foreach (var kv in values)
  5677. {
  5678. this.UpdateInstance(instanceId + "." + kv.Key, kv.Value._Str(), null, null, this.myInstanceModels, null);
  5679. }
  5680. this.UpdateInstanceModels();
  5681. }
  5682. //this.UpdateInstanceByValues(instanceId, tid, values);
  5683. return true;
  5684. };
  5685. case "data.delete":
  5686. return () =>
  5687. {
  5688. if (string.IsNullOrEmpty(this.UserId))
  5689. {
  5690. throw new NoSecurityException("没有权限", v);
  5691. }
  5692. string tid = p[0]._Str();//模板
  5693. tid = HttpUtility.UrlDecode(tid);
  5694. if (tid.StartsWith("/"))
  5695. {
  5696. tid = tid._Path(this.GetSource());
  5697. }
  5698. var index = tid.IndexOf('.');
  5699. var property = "";
  5700. if (index != -1)
  5701. {
  5702. property = tid.Substring(index);
  5703. tid = tid.Substring(0, index);
  5704. }
  5705. tid = this.GetTemplateId(tid);
  5706. this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
  5707. var collection = DataCollection + "_" + tid;
  5708. string id = p[1]._Str();
  5709. var doc = this.FindDocumentById(collection, id, new string[] { IDFlag, UserFlag });
  5710. if (doc == null)
  5711. {
  5712. throw new NotExistException("数据不存在");
  5713. }
  5714. if (doc.GetString(UserFlag) != this.UserId)
  5715. {
  5716. throw new NoSecurityException("没有权限");
  5717. }
  5718. IMongoQuery q = Query.EQ(IDFlag, id);
  5719. this.dbHelper.Remove(collection, q);
  5720. return true;
  5721. };
  5722. #endregion
  5723. #region Console
  5724. case "console.clear":
  5725. return () =>
  5726. {
  5727. IMongoQuery q = Query.EQ(UserFlag, this.UserId);
  5728. long count = this.dbHelper.Count(UserLogCollection, q);
  5729. this.dbHelper.Remove(UserLogCollection, q);
  5730. string type = "Info";
  5731. string msg = string.Format("成功清除 {0} 条日志记录。", count);
  5732. string feature = "Console";
  5733. this.PublishUserLog(type, msg, feature);
  5734. return count;
  5735. };
  5736. case "console.log":
  5737. case "console.info":
  5738. return () =>
  5739. {
  5740. string type = "Info";
  5741. string msg = p[0]._Str();
  5742. string feature = "Console";
  5743. this.PublishUserLog(type, msg, feature, p[1] as Dictionary<string, object>);
  5744. return null;
  5745. };
  5746. case "console.error":
  5747. return () =>
  5748. {
  5749. string type = "Error";
  5750. string msg = p[0]._Str();
  5751. var data = p[1] as Dictionary<string, object>;
  5752. string feature = "Console";
  5753. this.PublishUserLog(type, msg, feature, data);
  5754. return null;
  5755. };
  5756. case "console.debug":
  5757. return () =>
  5758. {
  5759. string type = "Debug";
  5760. string msg = p[0]._Str();
  5761. string feature = "Console";
  5762. this.PublishUserLog(type, msg, feature, p[1] as Dictionary<string, object>);
  5763. return null;
  5764. };
  5765. #endregion
  5766. #region User Function
  5767. case "user.name":
  5768. return () =>
  5769. {
  5770. return this.GetUserName(p[0]._Str());
  5771. };
  5772. case "user.changename":
  5773. return () =>
  5774. {
  5775. this.ChangeUserName(p[0]._Str());
  5776. return "更新成功";
  5777. };
  5778. case "user.add":
  5779. return () =>
  5780. {
  5781. var loginName = p[0]._Str();
  5782. var isNew = p[1]._Bool();
  5783. var nickName = p[2]._Str();
  5784. var phone = p[3]._Str();
  5785. var email = p[4]._Str();
  5786. var password = p[5]._Str();
  5787. var roles = p[6]._StrList();
  5788. string userid = null;
  5789. if (!isNew)
  5790. {
  5791. userid = this.GetUserId(loginName);
  5792. }
  5793. this.PublishUser(ref userid, loginName, password, email, phone, false, false, null, null, nickName);
  5794. string name = loginName.ToLower();
  5795. if (roles != null && roles.Count > 0)
  5796. {
  5797. string settingname = "/" + this.UserName + "/home/instances/setting.json";
  5798. BsonDocument doc = this.FindDocumentByName(FileCollection, settingname, new string[] { Definitions.ValueFlag });
  5799. if (doc != null)
  5800. {
  5801. string str = string.Empty;
  5802. byte[] r = doc[Definitions.ValueFlag].AsByteArray;
  5803. str = CommonFunction.BytesToString(r);
  5804. var result = str._Dic2();
  5805. var groups = result._Value("group") as Dictionary<string, object>;
  5806. foreach (var kv in groups)
  5807. {
  5808. var key = kv.Key;
  5809. var value = kv.Value as Dictionary<string, object>;
  5810. var users = value._Value("users")._Str();
  5811. List<string> userlist = null;
  5812. if (users != null)
  5813. {
  5814. userlist = users.Split(',').ToList();
  5815. userlist.Remove(name);
  5816. }
  5817. else
  5818. {
  5819. userlist = new List<string>();
  5820. }
  5821. if (roles.Contains(key))
  5822. {
  5823. userlist.Add(name);
  5824. }
  5825. value["users"] = string.Join(",", userlist);
  5826. }
  5827. this.UpdateFileContent(settingname, result._Json(false)._Bytes(false));
  5828. }
  5829. }
  5830. return null;
  5831. };
  5832. case "user.update":
  5833. return () =>
  5834. {
  5835. if (p[0] is Dictionary<string, object>)
  5836. {
  5837. var pd = (Dictionary<string, object>)p[0];
  5838. var a = new ArrayList();
  5839. a.Add(pd._Value("username"));
  5840. a.Add(pd._Value("isnew"));
  5841. a.Add(pd._Value("nickname"));
  5842. a.Add(pd._Value("phone"));
  5843. a.Add(pd._Value("email"));
  5844. a.Add(pd._Value("password"));
  5845. a.Add(pd._Value("roles"));
  5846. a.Add(pd._Value("admin"));
  5847. //a.Add(pd._Value("team"));
  5848. //a.Add(pd._Value("tag"));
  5849. ParameterModel pm = new ParameterModel();
  5850. pm.AddRange(a);
  5851. p = pm;
  5852. }
  5853. //{"currentUser":{"loginName":"test","isNew":true,"nickName":"test","phone":"13667164200","email":"a@1.com","password":"123456","roles":["1"],"lastLoginTime":"未登录"}}
  5854. var loginName = p[0]._Str();
  5855. var isNew = p[1]._Bool();
  5856. var nickName = p[2]._Str();
  5857. var phone = p[3]._Str();
  5858. var email = p[4]._Str();
  5859. var password = p[5]._Str();
  5860. var roles = p[6]._StrList();
  5861. var isadmin = p[7]._Str();
  5862. string userid = null;
  5863. if (!isNew)
  5864. {
  5865. userid = this.GetUserId(loginName);
  5866. }
  5867. this.PublishUser(ref userid, loginName, password._MD5(), email, phone, false, false, null, null, nickName, isadmin);
  5868. string name = loginName.ToLower();
  5869. if (roles != null && roles.Count > 0)
  5870. {
  5871. string settingname = "/" + this.UserName + "/home/instances/setting.json";
  5872. BsonDocument doc = this.FindDocumentByName(FileCollection, settingname, new string[] { Definitions.ValueFlag });
  5873. if (doc != null)
  5874. {
  5875. string str = string.Empty;
  5876. byte[] r = doc[Definitions.ValueFlag].AsByteArray;
  5877. str = CommonFunction.BytesToString(r);
  5878. var result = str._Dic2();
  5879. var groups = result._Value("group") as Dictionary<string, object>;
  5880. foreach (var kv in groups)
  5881. {
  5882. var key = kv.Key;
  5883. var value = kv.Value as Dictionary<string, object>;
  5884. var users = value._Value("users")._Str();
  5885. List<string> userlist = null;
  5886. if (users != null)
  5887. {
  5888. userlist = users.Split(',').ToList();
  5889. userlist.Remove(name);
  5890. }
  5891. else
  5892. {
  5893. userlist = new List<string>();
  5894. }
  5895. if (roles.Contains(key))
  5896. {
  5897. userlist.Add(name);
  5898. }
  5899. value["users"] = string.Join(",", userlist);
  5900. }
  5901. this.UpdateFileContent(settingname, result._Json(false)._Bytes(false));
  5902. }
  5903. }
  5904. return null;
  5905. };
  5906. case "user.checksync":
  5907. return () =>
  5908. {
  5909. var doc = this.FindDocumentById(UserCollection, this.UserId, new string[] { "_sync" });
  5910. if (doc != null)
  5911. {
  5912. BsonValue bv;
  5913. if (!doc.TryGetValue("_sync", out bv))
  5914. {
  5915. var valuedoc = new BsonDocument();
  5916. valuedoc.Add("time", DateTime.UtcNow);
  5917. valuedoc.Add("n", 0);
  5918. bv = valuedoc;
  5919. }
  5920. var myvalue = bv as BsonDocument;
  5921. var time = myvalue.GetDateTime("time");
  5922. var n = myvalue.GetInt("n");
  5923. var now = DateTime.UtcNow;
  5924. if (time.Year == now.Year && time.Month == now.Month)
  5925. {
  5926. int limit = DataClient.GetMyLimit(this.UserId, "Sync_Max")._Int();
  5927. if (limit > 0)
  5928. {
  5929. if (n >= limit)
  5930. {
  5931. throw new SyncException("本月同步次数达到最大值:" + n);
  5932. }
  5933. }
  5934. }
  5935. else
  5936. {
  5937. n = 0;
  5938. }
  5939. n++;
  5940. myvalue["n"] = n;
  5941. myvalue["time"] = DateTime.UtcNow;
  5942. var values = new BsonDocument();
  5943. values.Add("_sync", myvalue);
  5944. this.dbHelper.Update(UserCollection, this.UserId, values);
  5945. }
  5946. return true;
  5947. };
  5948. case "user.verify":
  5949. return () =>
  5950. {
  5951. string type = p[0]._Str();
  5952. string value = p[1]._Str();
  5953. switch (type)
  5954. {
  5955. case "0"://用户
  5956. this.CheckName(value, true, 20, true);
  5957. var doc = this.dbHelper.FindDocumentByQuery(UserCollection, Query.EQ(LNameFlag, value.ToLower()), new string[] { IDFlag });
  5958. if (doc != null)
  5959. {
  5960. throw new UserExistException("用户已存在");
  5961. }
  5962. break;
  5963. case "1"://手机
  5964. if (!CommonFunction.IsPhone(value))
  5965. {
  5966. throw new NotPhoneException("手机号格式不对");
  5967. }
  5968. doc = this.dbHelper.FindDocumentByQuery(UserCollection, Query.EQ(PhoneFlag, value.ToLower()), new string[] { IDFlag });
  5969. if (doc != null)
  5970. {
  5971. throw new UserExistException("手机号已存在");
  5972. }
  5973. break;
  5974. case "2"://邮箱
  5975. if (!CommonFunction.IsEmail(value))
  5976. {
  5977. throw new NotPhoneException("邮箱格式不对");
  5978. }
  5979. doc = this.dbHelper.FindDocumentByQuery(UserCollection, Query.EQ(LEmailFlag, value.ToLower()), new string[] { IDFlag });
  5980. if (doc != null)
  5981. {
  5982. throw new UserExistException("邮箱已存在");
  5983. }
  5984. break;
  5985. }
  5986. return null;
  5987. };
  5988. case "user.getused":
  5989. return () =>
  5990. {
  5991. var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  5992. result["count"] = this.dbHelper.GetUsedCount(p[0]._Str());
  5993. result["size"] = this.dbHelper.GetUsedSize(p[0]._Str());
  5994. return result;
  5995. };
  5996. case "vcode.check":
  5997. return () =>
  5998. {
  5999. if (!this.IsAdmin)
  6000. {
  6001. throw new NoSecurityException("没有权限");
  6002. }
  6003. this.CheckValidateCode(p[0]._Str(), p[1]._Str());
  6004. return true;
  6005. };
  6006. case "user.reg":
  6007. return () =>
  6008. {
  6009. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  6010. result["err"] = string.Empty;
  6011. result["type"] = 0;
  6012. try
  6013. {
  6014. string vName = p[0]._Str();
  6015. string vCode = p[1]._Str();
  6016. string userName = p[2]._Str();
  6017. string passWord = p[3]._Str();
  6018. Dictionary<string, object> newinfo = p[4] as Dictionary<string, object>;
  6019. result["type"] = this.Register2(vName, vCode, userName, passWord, newinfo);
  6020. }
  6021. catch (Exception ex)
  6022. {
  6023. result["err"] = ex._msg();
  6024. }
  6025. return result;
  6026. };
  6027. case "user.register":
  6028. return () =>
  6029. {
  6030. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  6031. result["err"] = string.Empty;
  6032. result["type"] = 0;
  6033. try
  6034. {
  6035. result["type"] = this.Register(p[0]._Str(), p[1]._Str(), p[2]._Str(), p[3]._Str(), p[4]._Str(), p[5]._Str(), p[6]._Str()._Dic());
  6036. }
  6037. catch (Exception ex)
  6038. {
  6039. result["err"] = ex._msg();
  6040. }
  6041. return result;
  6042. };
  6043. case "user.logout":
  6044. return () =>
  6045. {
  6046. if (string.IsNullOrEmpty(this.AccessUser))
  6047. {
  6048. return false;
  6049. }
  6050. this.Logout();
  6051. return true;
  6052. };
  6053. case "user.get":
  6054. return () =>
  6055. {
  6056. Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  6057. try
  6058. {
  6059. result = this.GetUser(p[0]._Str(), p[1]._Str(), p[2]._Str(), p[3]._Str());
  6060. }
  6061. catch (Exception ex)
  6062. {
  6063. result["err"] = ex._msg();
  6064. }
  6065. return result;
  6066. };
  6067. case "user.vcode":
  6068. return () =>
  6069. {
  6070. var expiredSeconds = p[1]._Int();
  6071. if (expiredSeconds == 0)
  6072. {
  6073. expiredSeconds = 60;
  6074. }
  6075. return this.VcodeForUser(p[0]._Str(), expiredSeconds);
  6076. };
  6077. case "user.delete":
  6078. return () =>
  6079. {
  6080. this.DeleteUserByName(p[0]._Str());
  6081. return null;
  6082. };
  6083. case "user.vcodeimage":
  6084. return () =>
  6085. {
  6086. byte[] image = null;
  6087. this.ResetValidateCode(p[0]._Str(), p[1]._Str(), out image, false);
  6088. return image;
  6089. };
  6090. case "user.info"://获取用户信息
  6091. return () =>
  6092. {
  6093. Dictionary<string, object> info2 = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  6094. info2["id"] = this.UserId;
  6095. info2["username"] = "";
  6096. info2["email"] = "";
  6097. info2["phone"] = "";
  6098. info2["nick"] = "";
  6099. var u = this.FindDocumentById(UserCollection, this.UserId, new string[] { NameFlag, EmailFlag, PhoneFlag, NickNameFlag });
  6100. if (u != null)
  6101. {
  6102. info2["username"] = u[NameFlag].ToString();
  6103. info2["email"] = u[EmailFlag].ToString();
  6104. info2["phone"] = u[PhoneFlag].ToString();
  6105. info2["nick"] = u.GetString(NickNameFlag);
  6106. }
  6107. return info2;
  6108. };
  6109. case "user.getlimit":
  6110. return () =>
  6111. {
  6112. Dictionary<string, object> limit;
  6113. if (p.Count > 0)
  6114. {
  6115. if (!this.IsAdmin)
  6116. {
  6117. throw new NoSecurityException("没有权限", this.UserName);//("getlimit", this.UserName);
  6118. }
  6119. string user = p[0]._Str();
  6120. BsonDocument doc = this.FindDocumentByName(UserCollection, user, new string[] { IDFlag });
  6121. limit = DataClient.LimitDic(doc[IDFlag].ToString());
  6122. }
  6123. else
  6124. {
  6125. limit = DataClient.LimitDic(this.UserId);
  6126. }
  6127. var limit2 = DataClient.defaultlimit._Dic2();
  6128. foreach (var kv in limit2)
  6129. {
  6130. if (!limit.ContainsKey(kv.Key))
  6131. {
  6132. limit[kv.Key] = "";
  6133. }
  6134. }
  6135. return limit;
  6136. };
  6137. case "defaultlimit":
  6138. return () =>
  6139. {
  6140. return DataClient.defaultlimit._Dic2();
  6141. };
  6142. case "user.setadmin":
  6143. return () =>
  6144. {
  6145. if (!this.IsAdmin)
  6146. {
  6147. throw new NoSecurityException("没有权限", this.UserName);
  6148. }
  6149. var userlist = p[0]._StrList();
  6150. var value = p[1]._Bool();
  6151. foreach (var user in userlist)
  6152. {
  6153. BsonDocument updated = new BsonDocument();
  6154. updated.Add(IsAdminFlag, value);
  6155. this.dbHelper.Update(UserCollection, GetUserId(user), updated);
  6156. }
  6157. return true;
  6158. };
  6159. case "user.setlimit":
  6160. return () =>
  6161. {
  6162. if (!this.IsAdmin)
  6163. {
  6164. throw new NoSecurityException("没有权限", this.UserName);//("getlimit", this.UserName);
  6165. }
  6166. string user = p[0]._Str();
  6167. Dictionary<string, object> obj = p[1] as Dictionary<string, object>;
  6168. //BsonDocument value = new BsonDocument();
  6169. //foreach (var kkk in obj)
  6170. //{
  6171. // value.Add( kkk.Key, BsonValue.Create(kkk.Value));
  6172. //}
  6173. BsonDocument doc = this.FindDocumentByName(UserCollection, user, new string[] { IDFlag });
  6174. BsonDocument updated = new BsonDocument();
  6175. foreach (var kkk in obj)
  6176. {
  6177. updated.Add(LimitFlag + "." + kkk.Key, BsonValue.Create(kkk.Value));
  6178. }
  6179. //updated.Add(LimitFlag, value);
  6180. this.dbHelper.Update(UserCollection, doc[IDFlag].ToString(), updated);
  6181. return true;
  6182. };
  6183. case "user.changeinfo":
  6184. return () =>
  6185. {
  6186. if (string.IsNullOrEmpty(this.UserId))
  6187. {
  6188. throw new Exception("请先登录");
  6189. }
  6190. var userinfo = p[0] as Dictionary<string, object>;
  6191. BsonDocument doc = new BsonDocument();
  6192. object o;
  6193. if (userinfo.TryGetValue("password", out o))
  6194. {
  6195. string password = o._Str();
  6196. if (!string.IsNullOrEmpty(password))
  6197. {
  6198. userinfo.TryGetValue("oldpassword", out o);
  6199. string oldpassword = o._Str();
  6200. if (string.IsNullOrEmpty(oldpassword))
  6201. {
  6202. throw new EmptyPasswordException("旧密码不能为空");
  6203. }
  6204. var userdoc = this.FindDocumentById(UserCollection, this.UserId, new string[] { PassWordFlag });
  6205. if (userdoc.GetString(PassWordFlag) != oldpassword)
  6206. {
  6207. throw new WrongPasswordException("旧密码不匹配");
  6208. }
  6209. doc["_pwd"] = password;
  6210. }
  6211. }
  6212. if (userinfo.TryGetValue("nickname", out o))
  6213. {
  6214. string nickname = o._Str();
  6215. if (!string.IsNullOrEmpty(nickname))
  6216. {
  6217. doc[NickNameFlag] = nickname;
  6218. }
  6219. }
  6220. if (userinfo.TryGetValue("email", out o))
  6221. {
  6222. string name = o._Str();
  6223. if (!string.IsNullOrEmpty(name))
  6224. {
  6225. doc[EmailFlag] = name;
  6226. doc[LEmailFlag] = name.ToLower();
  6227. }
  6228. }
  6229. this.dbHelper.Update(UserCollection, this.UserId, doc);
  6230. string type = "Info";
  6231. this.PublishUserLog(type, "更新资料成功", "UserInfo", null);
  6232. return null;
  6233. };
  6234. case "user.changepassword":
  6235. return () =>
  6236. {
  6237. if (string.IsNullOrEmpty(this.UserId))
  6238. {
  6239. throw new Exception("请先登录");
  6240. }
  6241. string password = p[0]._Str();
  6242. if (string.IsNullOrEmpty(password))
  6243. {
  6244. throw new EmptyPasswordException("密码不能为空");
  6245. }
  6246. BsonDocument doc = new BsonDocument();
  6247. doc["_pwd"] = password;
  6248. this.dbHelper.Update(UserCollection, this.UserId, doc);
  6249. string type = "Info";
  6250. this.PublishUserLog(type, "更新密码成功", "UserInfo", null);
  6251. return null;
  6252. };
  6253. case "user.changeemailorphone":
  6254. return () =>
  6255. {
  6256. if (!this.IsAdmin)
  6257. {
  6258. throw new NoSecurityException("没有权限", this.UserName);//("getlimit", this.UserName);
  6259. }
  6260. var vName = p[0]._Str();
  6261. var vCode = p[1]._Str();
  6262. var newinfo = p[2] as ArrayList;
  6263. this.ChangeEmailOrPhone(vName, vCode, newinfo);
  6264. return null;
  6265. };
  6266. case "user.query":
  6267. return () =>
  6268. {
  6269. if (!this.IsAdmin)
  6270. {
  6271. throw new NoSecurityException("没有权限", this.UserName);//("getlimit", this.UserName);
  6272. }
  6273. var query = p[0]._Str();
  6274. var page = p[1]._Int();
  6275. var pagesize = p[2]._Int();
  6276. var sortby = p[3] as Dictionary<string, object>;
  6277. IMongoQuery q = null;
  6278. if (!string.IsNullOrEmpty(query))
  6279. {
  6280. IMongoQuery q2 = this.GetMyQuery(query,
  6281. (name) =>
  6282. {
  6283. return name;
  6284. },
  6285. (name, value) =>
  6286. {
  6287. return value._Str();
  6288. }, vget
  6289. );
  6290. if (q2 != null)
  6291. {
  6292. if (q == null)
  6293. {
  6294. q = q2;
  6295. }
  6296. else
  6297. {
  6298. q = Query.And(q, q2);
  6299. }
  6300. }
  6301. }
  6302. SortByDocument sdoc = null;
  6303. if (sortby != null)
  6304. {
  6305. sdoc = new SortByDocument();
  6306. foreach (var kv in sortby)
  6307. {
  6308. sdoc[kv.Key] = BsonValue.Create(kv.Value);
  6309. }
  6310. }
  6311. var docs = dbHelper.FindPage(UserCollection, q, page, pagesize, new List<string> { NameFlag, EmailFlag, PhoneFlag, NickNameFlag, "_lasttime", "_lastip", IsAdminFlag }, sdoc);
  6312. return docs;
  6313. };
  6314. #endregion
  6315. #region Device Function
  6316. case "device.log":
  6317. return () =>
  6318. {
  6319. var id = p[0]._Str();
  6320. int index = id.LastIndexOf('$');
  6321. if (index != -1)
  6322. {
  6323. id = id.Substring(index + 1);
  6324. }
  6325. var result = this.dbHelper.Find(DeviceLogCollection, Query.And(Query.EQ(UserFlag, this.UserId), Query.EQ("clientid", id)), new List<string> { "clientid", "ip", "time", "protocol", "user", "status", "reason", "_created" }, sortby: new SortByDocument(CreatedFlag, -1));
  6326. return result;
  6327. };
  6328. case "device.add":
  6329. return () =>
  6330. {
  6331. string id = p[0]._Str();
  6332. string token = p[1]._Str();
  6333. string name = p[2]._Str();
  6334. string inst = p[3]._Str();
  6335. this.PublishDevice(id, token, name, inst, "add");
  6336. return true;
  6337. };
  6338. case "device.instance":
  6339. return () =>
  6340. {
  6341. string id = p[0]._Str();
  6342. string target = p[1]._Str();
  6343. int index = id.LastIndexOf('$');
  6344. if (index != -1)
  6345. {
  6346. id = id.Substring(index + 1);
  6347. }
  6348. var doc = this.dbHelper.FindDocumentByQuery(DeviceCollection, Query.And(Query.EQ(UserFlag, this.UserId), Query.EQ(IDFlag, id)), new string[] { IDFlag });
  6349. if (doc == null)
  6350. {
  6351. throw new NotExistException("设备不存在:" + id);
  6352. }
  6353. var values = new BsonDocument();
  6354. values["_iid"] = target;
  6355. this.dbHelper.Update(DeviceCollection, id, values);
  6356. this.UpdateInstance(target, this.GetDeviceStatus(id, null) ? "true" : "false", null, null);
  6357. return true;
  6358. };
  6359. case "device.updateprop":
  6360. return () =>
  6361. {
  6362. string id = p[0]._Str();
  6363. int index = id.LastIndexOf('$');
  6364. if (index != -1)
  6365. {
  6366. id = id.Substring(index + 1);
  6367. }
  6368. var doc = this.dbHelper.FindDocumentByQuery(DeviceCollection, Query.And(Query.EQ(UserFlag, this.UserId), Query.EQ(IDFlag, id)), new string[] { IDFlag });
  6369. if (doc == null)
  6370. {
  6371. throw new NotExistException("设备不存在:" + id);
  6372. }
  6373. var vs = p[1] as Dictionary<string, object>;
  6374. var values = new BsonDocument(vs);
  6375. this.dbHelper.Update(DeviceCollection, id, values);
  6376. return true;
  6377. };
  6378. case "device.update":
  6379. return () =>
  6380. {
  6381. string id = p[0]._Str();
  6382. string token = p[1]._Str();
  6383. string name = p[2]._Str();
  6384. string inst = p[3]._Str();
  6385. this.PublishDevice(id, token, name, inst, "update");
  6386. return true;
  6387. };
  6388. case "device.delete":
  6389. return () =>
  6390. {
  6391. this.DeleteDevice(p[0]._Str());
  6392. return true;
  6393. };
  6394. case "device.query":
  6395. return () =>
  6396. {
  6397. var result = this.QueryDevice();
  6398. return result;
  6399. };
  6400. case "device.info":
  6401. return () =>
  6402. {
  6403. var result = this.QueryDeviceInfo(p[0]._Str());
  6404. return result;
  6405. };
  6406. #endregion
  6407. #region Modbus
  6408. case "tcp.send":
  6409. return () =>
  6410. {
  6411. SSClient ssc = new SSClient();
  6412. byte[] data = (byte[])p[1];
  6413. int tout = p[2]._Int(30000);
  6414. var result = ssc.MySend("mytcp://" + p[0]._Str(), data, tout);
  6415. return result;
  6416. };
  6417. case "udp.send":
  6418. return () =>
  6419. {
  6420. SSClient ssc = new SSClient();
  6421. byte[] data = (byte[])p[1];
  6422. var result = ssc.SendWithoutReturn("udp://" + p[0]._Str(), data);
  6423. return result;
  6424. };
  6425. case "modbus.send":
  6426. return () =>
  6427. {
  6428. SSClient ssc = new SSClient();
  6429. //
  6430. ModbusService.ModbusProtocol mp = new ModbusService.ModbusProtocol();
  6431. mp.functionCode = 16;
  6432. mp.quantity = 5;
  6433. mp.protocolIdentifier = 0;
  6434. mp.transactionIdentifier = 1;
  6435. mp.unitIdentifier = 1;
  6436. mp.startingAdress = 0;
  6437. mp.sendRegisterValues = new short[5] { 1, 2, 3, 4, 5 };
  6438. mp.quantity = 5;
  6439. mp.SetResponse();
  6440. //byte[] data = new byte[] { 0x00, 0x0f, 0x00, 0x00, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01 };
  6441. byte[] data = mp.GetBytes();
  6442. var result = ssc.MySend("modbus://" + p[0]._Str(), data, 6000);
  6443. return result;
  6444. };
  6445. #endregion
  6446. #region TCPClient
  6447. case "client.exist":
  6448. return () =>
  6449. {
  6450. return MyEasyClient.CheckSession(p[0]._Str());
  6451. };
  6452. case "client.new":
  6453. case "udp.new":
  6454. return () =>
  6455. {
  6456. MyTcpReceiveFilter myfilter = new MyTcpReceiveFilter(null);
  6457. myfilter.myunits = p[1] as ArrayList;
  6458. var action = p[2];
  6459. if (action != null && action is Expression)
  6460. {
  6461. Expression exp = (Expression)action;
  6462. myfilter.ProcessAction = (bytes) =>
  6463. {
  6464. var pm = new ParameterModel();
  6465. pm.Add(bytes);
  6466. exp.m_script.RunFunction(exp, pm);
  6467. };
  6468. }
  6469. if (v == "udp.new")
  6470. {
  6471. myfilter.MyType = System.Net.Sockets.ProtocolType.Udp;
  6472. }
  6473. MyEasyClient.CreateSession(p[0]._Str(), myfilter);
  6474. return null;
  6475. };
  6476. case "client.send":
  6477. return () =>
  6478. {
  6479. MyEasyClient.SendBytes(p[0]._Str(), (byte[])p[1]);
  6480. return null;
  6481. };
  6482. case "unit":
  6483. return () =>
  6484. {
  6485. var obj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  6486. obj["name"] = p[0];
  6487. obj["type"] = p[1];
  6488. obj["length"] = p[2];
  6489. obj["value"] = p[3];
  6490. obj["forlength"] = p[4];
  6491. return obj;
  6492. };
  6493. case "bytes.parse":
  6494. return () =>
  6495. {
  6496. var bytes = (byte[])p[0];
  6497. var units = p[1] as ArrayList;
  6498. var parent = p[2] as ArrayList;
  6499. var allunits = new List<CustomProtocol.Unit>();
  6500. foreach (var unit in units)
  6501. {
  6502. var u = unit as Dictionary<string, object>;
  6503. if (u == null)
  6504. {
  6505. var us = unit._Str().Split('\t');
  6506. allunits.Add(new CustomProtocol.Unit(us[0].Trim(), us[1].Trim(), us[2].Trim()._Int()));
  6507. }
  6508. else
  6509. {
  6510. var myunit = new CustomProtocol.Unit(u);
  6511. allunits.Add(myunit);
  6512. }
  6513. }
  6514. var obj = CustomProtocol.Support.Parse(bytes, allunits.ToArray(), parent: parent);
  6515. return obj;
  6516. };
  6517. case "bytes.obj":
  6518. return () =>
  6519. {
  6520. byte[] data = (byte[])p[0];
  6521. string type = p[1]._Str();
  6522. byte defaultbyte = p[2] == null ? (byte)0 : (byte)p[2];
  6523. var obj = CustomProtocol.Support.ToObj(data, type, defaultbyte);
  6524. return obj;
  6525. };
  6526. case "units.bytes":
  6527. return () =>
  6528. {
  6529. var units = p[0] as ArrayList;
  6530. var data = p[1] as ArrayList;
  6531. byte defaultbyte = 0x00;
  6532. if (p[2] != null)
  6533. {
  6534. defaultbyte = (byte)p[2];
  6535. }
  6536. var allunits = new List<CustomProtocol.Unit>();
  6537. foreach (var unit in units)
  6538. {
  6539. var u = unit as Dictionary<string, object>;
  6540. if (u == null)
  6541. {
  6542. var us = unit._Str().Split('\t');
  6543. allunits.Add(new CustomProtocol.Unit(us[0].Trim(), us[1].Trim(), us[2].Trim()._Int()));
  6544. }
  6545. else
  6546. {
  6547. allunits.Add(new CustomProtocol.Unit(u));
  6548. }
  6549. }
  6550. var bytes = CustomProtocol.Support.UnitsToBytes(allunits.ToArray(), data, defaultbyte);
  6551. return bytes;
  6552. };
  6553. case "bytes.bits":
  6554. return () =>
  6555. {
  6556. var buffer = (byte[])p[0];
  6557. var sb = new StringBuilder();
  6558. for (int i = 0; i < buffer.Length; i++)
  6559. {
  6560. BitArray arr = new BitArray(new byte[] { buffer[i] });
  6561. for (var j = arr.Length - 1; j >= 0; j--)
  6562. {
  6563. sb.Append(arr[j] ? "1" : "0");
  6564. }
  6565. }
  6566. return sb.ToString();
  6567. };
  6568. case "bytes.hex":
  6569. return () =>
  6570. {
  6571. var buffer = (byte[])p[0];
  6572. StringBuilder strBuider = new StringBuilder();
  6573. for (int index = 0; index < buffer.Length; index++)
  6574. {
  6575. strBuider.Append(((int)buffer[index]).ToString("X2"));
  6576. }
  6577. return strBuider.ToString();
  6578. };
  6579. case "hex.bytes":
  6580. return () =>
  6581. {
  6582. var hexString = p[0]._Str();
  6583. hexString = hexString.Replace(" ", "");
  6584. if ((hexString.Length % 2) != 0)
  6585. {
  6586. hexString += " ";
  6587. }
  6588. byte[] returnBytes = new byte[hexString.Length / 2];
  6589. for (int i = 0; i < returnBytes.Length; i++)
  6590. {
  6591. returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
  6592. }
  6593. return returnBytes;
  6594. };
  6595. case "mytcp.send":
  6596. return () =>
  6597. {
  6598. SSClient ssc = new SSClient();
  6599. //byte[] data = new byte[] { 0x00, 0x0f, 0x00, 0x00, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01 };
  6600. byte[] data = (byte[])p[0];
  6601. var result = ssc.SendWithoutReturn("mytcp://" + p[0]._Str(), data);
  6602. return result;
  6603. };
  6604. case "sm2.verify":
  6605. return () =>
  6606. {
  6607. return sm2.Instance.VerifySign(p[0]._ObjBytes(), p[1]._ObjBytes(), p[2]._ObjBytes(), p[3]._Str() ?? "1234567812345678");
  6608. };
  6609. case "sm2.verify2":
  6610. return () =>
  6611. {
  6612. return sm2.Instance.VerifySign(p[0]._ObjBytes(), p[1]._ObjBytes(), p[2]._ObjBytes(), p[3]._ObjBytes(), p[4]._Str() ?? "1234567812345678");
  6613. };
  6614. case "sm2.sign":
  6615. return () =>
  6616. {
  6617. return sm2.Instance.Sign(p[0]._ObjBytes(), p[1]._ObjBytes(), p[2]._Str() ?? "1234567812345678");
  6618. };
  6619. case "sm2.encode":
  6620. return () =>
  6621. {
  6622. var isprivate = false;
  6623. var p2 = p[2];
  6624. if (p2 != null)
  6625. {
  6626. isprivate = p2._Bool();
  6627. }
  6628. return sm2.Instance.Encode(p[0]._ObjBytes(), p[1]._ObjBytes(), isprivate, p[3]._Int());
  6629. };
  6630. case "sm2.decode":
  6631. return () =>
  6632. {
  6633. var isprivate = true;
  6634. var p2 = p[2];
  6635. if (p2 != null)
  6636. {
  6637. isprivate = p2._Bool();
  6638. }
  6639. return sm2.Instance.Decode(p[0]._ObjBytes(), p[1]._ObjBytes(), isprivate, p[3]._Int());
  6640. };
  6641. case "sm2.pair":
  6642. return () =>
  6643. {
  6644. return sm2.Instance.CreateKeyPair();
  6645. };
  6646. #endregion
  6647. }