switch (v)
{
case "dllmethods":
return () =>
{
return DllMethods.Keys.ToArray();
};
case "timeout":
return () =>
{
MyTimeout = p[0]._Int();
return null;
};
case "publishs":
return () =>
{
if (TempGet == null)
{
return null;
}
return TempGet();
};
//case "actions":
// return () =>
// {
// return this.GetAllServerActions();
// };
#region XML操作
case "xml.parse":
return () =>
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(p[0]._Str());
return xmldoc;
};
#endregion
#region 数据库操作
case "dbindex.query":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
var tdoc = this.GetTemplateNode(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
//q = Query.And(q, Query.EQ(TemplateFlag, tid));
var collection = DataCollection + "_" + tid;
return this.dbHelper.QueryIndex(collection);
};
case "dbindex.create":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
var tdoc = this.GetTemplateNode(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
//q = Query.And(q, Query.EQ(TemplateFlag, tid));
var collection = DataCollection + "_" + tid;
this.dbHelper.SetIndex(collection, p[1]._Str(), p[2] as Dictionary<string, object>, p[3]._Bool());
return this.dbHelper.QueryIndex(collection);
};
#endregion
#region 图片相关
case "compressimage":
return () =>
{
byte[] bytes = (byte[])p[0];
int size = p[1]._Int(300);
var result = CommonFunction.CompressImage(bytes, 90, size);
return result;
};
case "checkidcard":
return () =>
{
return CommonFunction.CheckIDCard(p[0]._Str());
};
case "qr"://(内容,级别,版本,比例, bitmap)
return () =>
{
var content = p[0]._Str();
var level = p[1]._Int(1);
var size = p[2]._Int(20);
var format = p[3]._Str();
var drawQuietZones = p[4]._Bool();
ImageFormat imagetype = ImageFormat.Jpeg;
if (!string.IsNullOrEmpty(format))
{
switch (format.ToLower())
{
case "gif":
imagetype = ImageFormat.Gif;
break;
case "jpeg":
imagetype = ImageFormat.Jpeg;
break;
case "png":
imagetype = ImageFormat.Png;
break;
case "tiff":
imagetype = ImageFormat.Tiff;
break;
}
}
QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level);
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(content, eccLevel);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(size, Color.Black, Color.White, drawQuietZones);
MemoryStream stream = new MemoryStream();
qrCodeImage.Save(stream, imagetype);
return CommonFunction.StreamToBytes(stream);
//Base64QRCode.ImageType imagetype = Base64QRCode.ImageType.Jpeg;
//if (!string.IsNullOrEmpty(format))
//{
// switch (format.ToLower())
// {
// case "gif":
// imagetype = Base64QRCode.ImageType.Gif;
// break;
// case "jpeg":
// imagetype = Base64QRCode.ImageType.Jpeg;
// break;
// case "png":
// imagetype = Base64QRCode.ImageType.Png;
// break;
// }
//}
//QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level);
////QRCodeGenerator qrGenerator = new QRCodeGenerator();
////QRCodeData qrCodeData = qrGenerator.CreateQrCode(content, eccLevel);
//QRCodeGenerator qrGenerator = new QRCodeGenerator();
//QRCodeData qrCodeData = qrGenerator.CreateQrCode(content, eccLevel);
//Base64QRCode qrCode = new Base64QRCode(qrCodeData);
//string qrCodeImageAsBase64 = qrCode.GetGraphic(20, Color.Black, Color.White, false, imagetype);
//return Base64Helper.FromBase64String(qrCodeImageAsBase64);
};
#endregion
#region Business
//case "actions":
// return () =>
// {
// return this.GetAllServerActions();
// };
case "send":
return () =>
{
var serverid = p[0]._Str();
var clientid = p[1]._Str();
var data = (byte[])p[2];
var result = RunMethodOnAllServers((client) =>
{
return client.SendBytes(serverid, clientid, data);
});
return result;
};
case "token":
return () =>
{
return NewToken(this.UserId ?? NewId);
};
case "rest.get":
return () =>
{
string url = p[0]._Str();
SSClient client = new SSClient();
string ct;
byte[] r = client.Get(out ct, url, p[1] as Dictionary<string, object>, p[2]._Bool(), p[3]._Int(30000));
string contenttype;
string charset;
this.GetContentType(ct, out contenttype, out charset);
if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase))
{
var str = CommonFunction.BytesToString(r, charset);
Dictionary<string, object> data;
if (str._IsJson(out data))
{
return data;
}
}
return r;
};
case "rest.post":
return () =>
{
string url = p[0]._Str();
var target = p[5];
if (target != null)
{
var server = DataClient.GetServer(target._Str());
if (server == null)
{
throw new Exception("指定的服务器不存在:" + target._Str());
}
var client = ServiceHelpler.GetBPClient1(server);
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());
var r = (byte[])result["r"];
var ct = result["ct"].ToString();
string contenttype;
string charset;
this.GetContentType(ct, out contenttype, out charset);
var str = CommonFunction.BytesToString(r, charset);
Dictionary<string, object> data;
if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase) && str._IsJson(out data))
{
return data;
}
return str;
}
else
{
SSClient client = new SSClient();
string ct;
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());
string contenttype;
string charset;
this.GetContentType(ct, out contenttype, out charset);
var str = CommonFunction.BytesToString(r, charset);
Dictionary<string, object> data;
if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase) && str._IsJson(out data))
{
return data;
}
return str;
}
};
case "rest.put":
return () =>
{
string url = p[0]._Str();
SSClient client = new SSClient();
string ct;
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));
string contenttype;
string charset;
this.GetContentType(ct, out contenttype, out charset);
var str = CommonFunction.BytesToString(r, charset);
Dictionary<string, object> data;
if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase) && str._IsJson(out data))
{
return data;
}
return str;
};
case "rest.delete":
return () =>
{
string url = p[0]._Str();
SSClient client = new SSClient();
string ct;
byte[] r = client.Delete(out ct, url, p[1] as Dictionary<string, object>, p[2]._Bool(), p[3]._Int(30000));
string contenttype;
string charset;
this.GetContentType(ct, out contenttype, out charset);
var str = CommonFunction.BytesToString(r, charset);
Dictionary<string, object> data;
if ("application/json".Equals(contenttype, StringComparison.OrdinalIgnoreCase) && str._IsJson(out data))
{
return data;
}
return str;
};
#endregion
#region 类型转换
case "substring2":
return () =>
{
return CommonFunction.GetSubString(p[0]._Str(), p[1]._Int(), p[2]._Int());
};
case "length2":
return () =>
{
return CommonFunction.GetLength(p[0]._Str());
};
case "rsa.encrypewithprivate":
return () =>
{
return DataAccess.bc.rsa.EncryptWithPrivate(p[0]._Str(), p[1]._Str());
};
case "hash":
return () =>
{
var bytes = (byte[])p[0];
string hash = HashHelper.ComputeMD5(bytes);
return hash;
};
case "random":
return () =>
{
int rv = myrandom.Next(p[0]._Int(), p[1]._Int());
return rv;
};
case "id":
return () =>
{
return NewId;
};
case "md":
return () =>
{
MarkdownSharp.Markdown md = new MarkdownSharp.Markdown();
var html = md.Transform(p[0]._Str());
return html;
};
case "json":
return () =>
{
var para = p[0];
return para._Json();
};
case "obj":
return () =>
{
//var obj = script.RunScript("=" + p[0]._Str());
//return obj;
var obj = this.RunScript("=" + p[0]._Str(), vget, functions, timeout);
return obj;
};
case "script.run":
case "test":
return () =>
{
var obj = this.RunScript(p[0]._Str(), vget, functions, timeout);
return obj;
};
case "int":
return () =>
{
return Support.Int(p[0]);
};
case "int64":
return () =>
{
return Support.Int64(p[0]);
};
case "string":
return () =>
{
bool base64 = true;
if (p.Count > 1)
{
base64 = p[1]._Bool();
}
return p[0]._Str(base64: base64);
};
case "number":
return () =>
{
return Support.Number(p[0]);
};
case "localtime":
return () =>
{
DateTime dt = (DateTime)p[0];
return dt.ToLocalTime();
};
case "dateformat":
return () =>
{
DateTime dt = (DateTime)p[0];
return dt.ToString(p[1]._Str());
};
case "bytes":
return () =>
{
bool base64 = true;
if (p.Count > 1)
{
base64 = p[1]._Bool();
}
return p[0]._ObjBytes(base64);
};
case "byte":
return () =>
{
var data = Support.Int(p[0]);
return (byte)data;
};
case "timestamp":
return () =>
{
var time = p[0]._Time();
System.DateTime startTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t;
};
#endregion
#region 字符串函数
case "string.encode":
return () =>
{
return encode(p[0]._Str());
};
case "string.decode":
return () =>
{
return decode(p[0]._Str());
};
#endregion
#region Object Function
case "share":
return () =>
{
var name = p[0]._Str();
var value = p[1]._Str();
var sec = p[2]._Str();
string ctype;
var id = this.CheckAndGetObjectId(name, out ctype);
var values = new BsonDocument();
values[ShareFlag] = value ?? "0";
//values[SecurityFlag] = sec ?? "0";
this.dbHelper.Update(ctype, id, values, nobackup: true);
var doc = this.FindDocumentById(ctype, id, new string[] { ShareFlag });
return doc.GetString(ShareFlag);
};
case "sync":
return () =>
{
byte[] vbytes = p[0]._ObjBytes();
Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
Zip.Unzip(vbytes, (name, value) =>
{
files[name] = value;
});
byte[] licensebytes;
if (!files.TryGetValue("admin/license", out licensebytes))
{
throw new NoSecurityException("没有发现license文件");
}
var license = CommonFunction.BytesToString(licensebytes);
var ls = DatabaseHelper.GetLicenseFeatures(license);
var user = ls["user"].ToString();
var type = ls["type"].ToString();
if (type != "sync")
{
throw new NoSecurityException("license类型不对");
}
if (DataClient.licenseuser != user)
{
throw new NoSecurityException(string.Format("license用户 {1} 不对,需要用户:{0}", DataClient.licenseuser, user));
}
var pkg1 = ls["pkg1"].ToString();
var hash1 = ls["hash1"].ToString();
byte[] zipfiles;
if (!files.TryGetValue(pkg1, out zipfiles))
{
throw new NoSecurityException("没有发现同步的文件");
}
var pkg2 = ls["pkg2"].ToString();
var hash2 = ls["hash2"].ToString();
byte[] ziptemplates;
if (!files.TryGetValue(pkg2, out ziptemplates))
{
throw new NoSecurityException("没有发现同步的模板");
}
string filehash = HashHelper.ComputeMD5(zipfiles);
if (filehash != hash1)
{
throw new NoSecurityException("文件hash不对");
}
string templatehash = HashHelper.ComputeMD5(ziptemplates);
if (templatehash != hash2)
{
throw new NoSecurityException("模板hash不对");
}
Zip.Unzip(zipfiles, (name, value) =>
{
string path;
string description = string.Empty;
var myname = name;
int index = myname.IndexOf("/admin/");
if (index == -1)
{
myname = "/admin/" + name;
}
else
{
myname = name.Substring(index);
}
this.UploadFileByName(out path, myname, value, DataOperations.Upsert, description, true, fornew: false, min: false, oid: null, team: null);
});
Zip.Unzip(ziptemplates, (name, value) =>
{
string path = null;
string description = string.Empty;
var myname = name;
int index = myname.IndexOf("/admin/");
if (index == -1)
{
myname = "/admin/" + name;
}
else
{
myname = name.Substring(index);
}
this.PublishTemplate(ref path, myname, description, string.Empty, value._Str(false), upsert: true, fornew: false, oid: null, team: null);
});
return true;
};
case "zip":
return () =>
{
Dictionary<string, object> list = p[0] as Dictionary<string, object>;
Dictionary<string, byte[]> bytes = new Dictionary<string, byte[]>();
foreach (var kv in list)
{
bytes[kv.Key] = (byte[])kv.Value;
}
return Zip.ToBytes(bytes);
};
case "zip.add":
return () =>
{
byte[] values = (byte[])p[0];
var files = p[1];
Dictionary<string, object> list = null;
if (files is Dictionary<string, object>)
{
list = (Dictionary<string, object>)p[1];
}
else if (files is byte[])
{
list = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Zip.Unzip((byte[])files, (name, value) =>
{
list[name] = value;
});
}
else
{
return values;
}
Dictionary<string, byte[]> bytes = new Dictionary<string, byte[]>();
foreach (var kv in list)
{
bytes[kv.Key] = (byte[])kv.Value;
}
return Zip.AddBytes(values, bytes);
};
case "object.get":
return () =>
{
var collection = p[0]._Str();
var id = p[1]._Str();
var query = p[2]._Str();
var sortby = p[3] as Dictionary<string, object>;
BsonDocument doc3 = this.FindDocumentById(collection, id, new string[] { NameFlag, DescriptionFlag, UserFlag });
if (doc3 == null)
{
throw new NotExistException("不存在:" + id);
}
this.CheckTeamSecurity(doc3);
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["id"] = doc3[IDFlag].ToString();
r["name"] = doc3[NameFlag].ToString();
return r;
};
case "object.query":
return () =>
{
var collection = p[0]._Str();
if (string.IsNullOrEmpty(collection))
{
collection = "f";
}
switch (collection.ToLower().First())
{
case 't':
collection = CollectionType.Template.ToString();
break;
case 'i':
collection = CollectionType.Instance.ToString();
break;
default:
collection = CollectionType.File.ToString();
break;
}
var group = p[1]._Str();
var query = p[2]._Str();
var sortby = p[3] as Dictionary<string, object>;
bool nofolder = p[4]._Bool();
bool relative = p[5]._Bool();
string team = p[6]._Str();
return this.GetObjectsInfoByQuery(collection, group, query, sortby, nofolder, relative, vget, team);
};
case "object.rename":
return () =>
{
var collection = p[0]._Str();
var id = p[1]._Str();
var name = p[2]._Str();
return this.RenameObject(collection, id, name, false, false);
};
case "object.desc":
return () =>
{
var collection = p[0]._Str();
var id = p[1]._Str();
var desc = p[2]._Str();
CollectionType objcollection = CollectionType.File;
switch (collection.ToLower().First())
{
case 'f':
objcollection = CollectionType.File;
break;
case 't':
objcollection = CollectionType.Template;
break;
case 'i':
objcollection = CollectionType.Instance;
break;
}
this.CheckSecurity(id, objcollection, SecurityType.Write);
var values = new BsonDocument();
values[DescriptionFlag] = desc;
this.dbHelper.Update(objcollection.ToString(), id, values);
return true;
};
case "object.delete":
return () =>
{
var collection = p[0]._Str();
var id = p[1]._Str();
var name = p[2]._Str();
return this.RenameObject(collection, id, name, false, true);
};
case "object.namecheck":
return () =>
{
var name = p[0]._Str();
this.CheckName(name, false, 30, true);
return true;
};
case "object.copy":
return () =>
{
var collection = p[0]._Str();
var id = p[1]._Str();
var name = p[2]._Str();
return this.RenameObject(collection, id, name, true, false);
};
case "object.move":
return () =>
{
var collection = p[0]._Str();
var oid = p[1]._Str();
var did = p[2]._Str();
var mode = p[3]._Str();
string name = string.Empty;
if (oid.StartsWith("_"))
{
name = decode(oid);//admin/a/b
}
else
{
name = this.GetFileName(oid);//admin/a/1.html
}
string folder = decode(did);//admin/c/d
int index = name.LastIndexOf('/');
string filename = name.Substring(index + 1);
folder = folder + "/" + filename;
return this.RenameObject(collection, oid, "/" + folder, mode == "copy", false);
};
case "object.folders":
return () =>
{
var collection = p[0]._Str();
var group = p[1]._Str();
var query = p[2]._Str();
var sortby = p[3] as Dictionary<string, object>;
return this.GetGroupStructure(collection, group, query, sortby, vget: vget);
};
case "object.add":
return () =>
{
var collection = p[0]._Str();
var name = p[1]._Str();
var vp = p[2];
byte[] value;
if (vp is byte[])
{
value = (byte[])p[2];
}
else
{
value = p[2]._ObjBytes(false);
}
var description = p[3]._Str();
bool isoverride = p[4]._Bool();
return this.CreateObject(collection, name, value, description, isoverride);
};
case "history.zip":
return () =>
{
string hid = p[0]._Str();
string type = p[1]._Str();
if (string.IsNullOrEmpty(type))
{
type = "f";
}
char t = type.ToLower().First();
string valuefield = string.Empty;
string collection = "FileHistory";
CollectionType objcollection = CollectionType.File;
switch (t)
{
case 'f':
type = "file";
collection = "FileHistory";
objcollection = CollectionType.File;
valuefield = "doc._value";
break;
case 't':
type = "template";
collection = "TemplateHistory";
objcollection = CollectionType.Template;
valuefield = "doc._value_";
break;
case 'i':
type = "instance";
collection = "InstanceHistory";
objcollection = CollectionType.Instance;
valuefield = "doc";
break;
}
List<string> fields = new List<string>() { valuefield, UserFlag, "id", "name", "desc", "tag" };
if (t == 'f')
{
fields.Add("doc._gz");
}
BsonDocument doc = this.dbHelper.FindDocumentByQuery(collection, Query.EQ(IDFlag, hid), fields.ToArray());
if (doc == null)
{
throw new NotExistException("不存在:" + hid);
}
var id = doc.GetString("id");
this.CheckSecurity(id, objcollection, SecurityType.Read);
var name = doc.GetString("name") + ".$." + id;
Dictionary<string, byte[]> result = new Dictionary<string, byte[]>();
switch (t)
{
case 'f':
type = "file";
bool gz = doc.GetBool("doc._gz");
byte[] vvv = doc.Value(valuefield).AsByteArray;
if (gz)
{
vvv = CommonFunction.Decompress(vvv);
}
result[name] = vvv;
break;
case 't':
type = "template";
result[name] = doc.Value(valuefield).AsString._Bytes(false);
break;
case 'i':
type = "instance";
result[name] = doc.Value(valuefield)._Json()._Bytes(false);
break;
}
return Zip.ToBytes(result);
};
case "history":
case "history.delete":
return () =>
{
string type = "file";
string filename = p[0]._Str().Trim('/');
string hid = p[1]._Str();
bool deleted = p[2]._Bool();
var count = p[3]._Int();
var team = p[4]._Str();
string[] fs = filename.Split('?');
filename = fs[0];
if (fs.Length > 1)
{
type = fs[1];
}
//this.CheckMyFileName(filename);
string valuefield = string.Empty;
string collection = "FileHistory";
CollectionType objcollection = CollectionType.File;
switch (type.ToLower().First())
{
case 'f':
type = "file";
collection = "FileHistory";
objcollection = CollectionType.File;
valuefield = "doc._value";
break;
case 't':
type = "template";
collection = "TemplateHistory";
objcollection = CollectionType.Template;
valuefield = "doc._value_";
break;
case 'i':
type = "instance";
collection = "InstanceHistory";
objcollection = CollectionType.Instance;
valuefield = "doc";
break;
}
if (v == "history.delete")
{
BsonDocument dochistory = this.dbHelper.FindDocumentByQuery(collection, Query.EQ(IDFlag, hid), new string[] { UserFlag });
if (dochistory == null)
{
throw new NotExistException("记录不存在");
}
if (dochistory[UserFlag].ToString() != this.UserId)
{
throw new NoSecurityException("没有权限", hid);
}
this.dbHelper.Remove(collection, Query.EQ(IDFlag, hid), true);
return true;
}
IMongoQuery q = null;
if (string.IsNullOrEmpty(hid))
{
if (filename.Contains('/'))
{
//q = Query.Matches("lname", new BsonRegularExpression(filename.ToLower()));
q = Query.EQ("lname", filename.ToLower());
}
else
{
q = Query.EQ("id", filename);
}
}
if (deleted)
{
if (string.IsNullOrEmpty(hid))
{
var q2 = Query.EQ(UserFlag, this.UserId);
IMongoQuery searchquery = Query.Matches("lname", new BsonRegularExpression("/.*" + filename.ToLower() + ".*/"));
q = Query.And(searchquery, Query.EQ("flag", "delete"), q2);
}
}
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(hid))
{
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);//
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (var doc in docs)
{
Dictionary<string, object> obj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
obj["id"] = doc[IDFlag].ToString();
obj["desc"] = doc.Value("desc").Value();
obj["time"] = doc.Value("time").Value();
obj["user"] = doc.Value("user").Value();
obj["name"] = doc.Value("name").Value();
obj["size"] = doc.Value("size").Value();
obj["flag"] = doc.Value("flag").Value();
obj["muser"] = doc.Value("muser").Value();
obj["tag"] = doc.Value("tag").Value();
list.Add(obj);
}
result["count"] = list.Count;
result["data"] = list;
return result;
}
else
{
List<string> fields = new List<string>() { valuefield, UserFlag, "id", "name", "desc", "tag" };
if (type.ToLower().First() == 'f')
{
fields.Add("doc._gz");
}
BsonDocument doc = this.dbHelper.FindDocumentByQuery(collection, Query.EQ(IDFlag, hid), fields.ToArray());
if (doc == null)
{
throw new NotExistException("不存在:" + hid);
}
var id = doc.GetString("id");
this.CheckSecurity(id, objcollection, SecurityType.Read);
switch (type.ToLower().First())
{
case 'f':
type = "file";
bool gz = doc.GetBool("doc._gz");
byte[] vvv = doc.Value(valuefield).AsByteArray;
if (gz)
{
vvv = CommonFunction.Decompress(vvv);
}
result["value"] = vvv._Str(false);
break;
case 't':
type = "template";
result["value"] = doc.Value(valuefield).AsString;
break;
case 'i':
type = "instance";
result["value"] = doc.Value(valuefield)._Json();
break;
}
if (deleted)
{
filename = doc.GetString("name");
result["id"] = doc.GetString("id");
result["desc"] = doc.GetString("desc");
result["tag"] = doc.GetString("tag");
}
result["name"] = filename;
result["t"] = type;
return result;
}
};
case "history.restore":
return () =>
{
string type = "file";
string filename = p[0]._Str().Trim('/');
string[] fs = filename.Split('?');
filename = fs[0];
if (fs.Length > 1)
{
type = fs[1];
}
//this.CheckMyFileName(filename);
string valuefield = string.Empty;
string collection = "FileHistory";
switch (type.ToLower().First())
{
case 'f':
type = "file";
collection = "FileHistory";
valuefield = "doc._value";
break;
case 't':
type = "template";
collection = "TemplateHistory";
valuefield = "doc._value_";
break;
case 'i':
type = "instance";
collection = "InstanceHistory";
valuefield = "doc";
break;
}
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
IMongoQuery searchquery = Query.Matches("lname", new BsonRegularExpression("/.*" + filename.ToLower() + ".*/"));
q = Query.And(q, searchquery);
q = Query.And(q, Query.EQ("flag", "delete"));
List<BsonDocument> docs = this.dbHelper.Find(collection, q, new List<string> { IDFlag, "name" });//
Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
foreach (var doc in docs)
{
Dictionary<string, object> obj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
var id = doc[IDFlag].ToString();
var name = doc.GetString("name");
List<string> fields = new List<string>() { valuefield };
if (type.ToLower().First() == 'f')
{
fields.Add("doc._gz");
}
BsonDocument valuedoc = this.dbHelper.FindDocumentByQuery(collection, Query.EQ(IDFlag, id), fields.ToArray());
if (valuedoc == null)
{
continue;
}
byte[] vvv = null;
switch (type.ToLower().First())
{
case 'f':
type = "file";
bool gz = valuedoc.GetBool("doc._gz");
vvv = valuedoc.Value(valuefield).AsByteArray;
if (gz)
{
vvv = CommonFunction.Decompress(vvv);
}
//result["value"] = vvv._Str(false);
break;
case 't':
type = "template";
vvv = valuedoc.Value(valuefield).AsString._Bytes(false);
break;
case 'i':
type = "instance";
vvv = valuedoc.Value(valuefield)._Json()._Bytes(false);
break;
}
files[name] = vvv;
}
var values = Zip.ToBytes(files);
return values;
};
case "mymessages":
return () =>
{
var collection = InstanceHistoryCollection;
var query = p[0]._Str();
var page = p[1]._Int(1);
var pagesize = p[2]._Int(100);
var sortby = p[3] as Dictionary<string, object>;
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
IMongoQuery q = Query.And(Query.EQ(UserFlag, this.UserId));
if (!string.IsNullOrEmpty(query))
{
q = Query.And(q, this.GetMyQuery(query, (name) =>
{
return name;
}, (name, value) =>
{
return BsonTypeMapper.MapToBsonValue(value);
}, vget));
}
List<string> fs = new List<string> { "doc" };
SortByDocument sdoc = null;
if (sortby != null)
{
sdoc = new SortByDocument(sortby);
}
Func<List<BsonDocument>, List<Dictionary<string, object>>> mapping = (ds) =>
{
List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
foreach (var doc in ds)
{
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["id"] = doc.GetString("_id");
result["nodename"] = doc.GetString("doc._name");
string userid = doc.GetString("doc._muser");
result["username"] = this.GetUserName(userid);
result["time"] = doc.GetDateTime("doc._time");
result["value"] = doc.Value("doc._value").Value();
result["type"] = result["value"].GetType().Name;
results.Add(result);
}
return results;
};
var docs = this.dbHelper.FindPage(collection, q, page, pagesize, fs, sdoc, mapping);
return docs;
};
case "mymessage":
return () =>
{
//string userid = this.UserId;
string name = p[0]._Str();
var page = p[2]._Int();
var pagesize = p[3]._Int();
string clientname = name;
string tempId = null;
string userId = null;
BsonDocument instDoc = null;
BsonDocument tempDoc = null;
string keyBase = null;
string keyFlag = null;
string instRoot = null;
this.GetInstanceInformation(name, out instRoot, out userId, out keyBase, out keyFlag, out instDoc, out tempDoc, out clientname, out tempId, SecurityType.Read);
List<BsonDocument> docs = new List<BsonDocument>();
var count = 0;
if (tempDoc.GetBool(HistoryFlag))
{
IMongoQuery q1 = Query.EQ("doc.id", clientname);
IMongoQuery q3 = Query.Or(Query.EQ("doc." + Definitions.ToFlag, "*"), Query.EQ("doc." + Definitions.ToFlag, this.UserId));
IMongoQuery q = Query.And(q1, q3);
string search = p[1]._Str();
if (!string.IsNullOrEmpty(search))
{
IMongoQuery searchquery = Query.Matches("doc._value", new BsonRegularExpression("/.*" + search + ".*/"));
q = Query.And(q, searchquery);
}
//var docs2 = this.dbHelper.FindPage(InstanceHistoryCollection, q, page, pagesize, new List<string> { "doc" }, new SortByDocument("time", -1), null);
int skip = -1;
int limit = -1;
if (page > 0 && pagesize > 0)
{
skip = (page - 1) * pagesize;
limit = pagesize;
}
var docs2 = this.dbHelper.Find(out count, InstanceHistoryCollection, q, new List<string> { "doc" }, sortby: new SortByDocument("time", -1), limit: limit, skip: skip);
foreach (var doc in docs2)
{
instDoc = doc["doc"] as BsonDocument;
instDoc["id"] = doc[IDFlag].ToString();
docs.Add(instDoc);
}
}
else
{
instDoc.Add("id", instDoc[IDFlag].ToString());
IList to = instDoc.GetList(Definitions.ToFlag);
if (to == null)
{
docs.Add(instDoc);
}
if (to.Contains("*") || to.Contains(this.UserId))
{
docs.Add(instDoc);
}
count = docs.Count;
}
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (var doc in docs)
{
Dictionary<string, object> obj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
obj["id"] = doc["id"].ToString();
string _from = doc.GetString(Definitions.FromFlag);
obj["from"] = this.GetUserName(_from);
obj["value"] = doc.GetString("_value");
obj["time"] = doc.GetDateTime("_time");
BsonValue cp;
if (doc.TryGetValue(Definitions.CpFlag, out cp))
{
var mycp = (cp as BsonDocument).ToDictionary();
if (mycp != null)
{
obj["cp"] = mycp;
}
}
list.Add(obj);
}
result["count"] = count;
result["rows"] = list;
return result;
};
case "template.info":
return () =>
{
string filename = p[0]._Str();
filename = System.Web.HttpUtility.UrlDecode(filename);
string collection = TemplateCollection;
BsonDocument doc = this.FindDocumentByName(collection, filename, new string[] { NameFlag, DescriptionFlag, UserFlag, ShareFlag, CreatedFlag, ModifiedFlag });
if (doc == null)
{
return null;
//throw new NotExistException("不存在:" + filename);
}
//this.CheckSecurity(ct, doc, SecurityType.Read);
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
string id = doc[IDFlag].ToString();
string name = doc[NameFlag].ToString();
string desc = doc[DescriptionFlag].ToString();
result["path"] = name;
result["id"] = id;
int index = name.LastIndexOf('/');
result["name"] = name.Substring(index + 1);
result["desc"] = desc;
result["share"] = doc.Value(ShareFlag);
result["uid"] = doc.Value(UserFlag);
result["created"] = doc.Value(CreatedFlag);
result["updated"] = doc.Value(ModifiedFlag);
return result;
};
case "object.info":
return () =>
{
string filename = p[0]._Str();
filename = System.Web.HttpUtility.UrlDecode(filename);
char t = 'f';
string str = p[1]._Str()._Trim();
if (!string.IsNullOrEmpty(str))
{
t = str.ToLower().First();
}
string collection = FileCollection;
//CollectionType ct = CollectionType.File;
switch (t)
{
case 't':
collection = TemplateCollection;
//ct = CollectionType.Template;
break;
case 'i':
collection = InstanceCollection;
//ct = CollectionType.Instance;
break;
}
BsonDocument doc = this.FindDocumentByName(collection, filename, new string[] { NameFlag, DescriptionFlag, UserFlag, TypeFlag, ShareFlag, CreatedFlag, ModifiedFlag });
if (doc == null)
{
return null;
//throw new NotExistException("不存在:" + filename);
}
//this.CheckSecurity(ct, doc, SecurityType.Read);
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
string id = doc[IDFlag].ToString();
string name = doc[NameFlag].ToString();
string desc = doc[DescriptionFlag].ToString();
result["path"] = name;
result["type"] = doc.GetString(TypeFlag);
result["id"] = id;
int index = name.LastIndexOf('/');
result["name"] = name.Substring(index + 1);
result["desc"] = desc;
result["share"] = doc.Value(ShareFlag);
result["uid"] = doc.Value(UserFlag);
result["created"] = doc.Value(CreatedFlag);
result["updated"] = doc.Value(ModifiedFlag);
return result;
};
case "objects":
return () =>
{
char t = 'f';
string type = "file";
string str = p[0]._Str()._Trim();
if (!string.IsNullOrEmpty(str))
{
t = str.ToLower().First();
}
string group = p[1]._Str();
string action = p[2]._Str();
string search = p[3]._Str();
string team = p[4]._Str();
var sort = p[5] as Dictionary<string, object>;
SortByDocument sortby = null;
if (sort != null)
{
sortby = new SortByDocument(sort);
}
string collection = FileCollection;
switch (t)
{
case 't':
type = "template";
collection = TemplateCollection;
break;
case 'i':
type = "instance";
collection = InstanceCollection;
break;
}
List<string> fields = new List<string> { IDFlag, UserFlag, NameFlag, DescriptionFlag, GroupFlag, TemplateFlag, SizeFlag };
if (group.StartsWith("/"))
{
string g = group.TrimStart('/') + "/";
int i = g.IndexOf('/');
group = g.Remove(0, i);
group = group.Trim('/').Trim();
}
var r = this.GetDocs(collection, group, fields, null, search, team, sortby);
//if (!string.IsNullOrEmpty(action))
//{
// action = "return " + action + ";" + script;
//}
var nodes = this.ConvertTree3(r, type, group, action, functions, team);
return nodes;
};
case "updatefilename":
return () =>
{
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
string oldname = p[0]._Str();
string type = "file";
string[] fs = oldname.Split('?');
oldname = fs[0];
if (fs.Length > 1)
{
type = fs[1];
}
string newname = p[1]._Str();
var team = p[2]._Str();
oldname = WebUtility.UrlDecode(oldname);
newname = WebUtility.UrlDecode(newname);
newname = newname._Path();
r["name"] = newname;
switch (type.ToLower().First())
{
case 'f':
var doc = this.FindDocumentByName(FileCollection, oldname, new string[] { IDFlag });
if (doc == null)
{
throw new NotExistException(oldname + " 不存在");//ServerException.FileNotExist(oldname);
}
string fileid = doc[IDFlag].ToString();
this.UploadFile(ref fileid, newname, null, null, null, false, true, team: team);
break;
case 't':
this.UpdateTemplateName(oldname, newname, team);
break;
case 'i':
this.UpdateInstanceName(oldname, newname, team);
break;
}
r["path"] = oldname;
r["type"] = type;
r["filename"] = newname;
return r;
};
case "file.update2"://不备份
return () =>
{
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
string filename = p[0]._Str();
filename = filename._Path(this.ClientInfo.PageSource);
string filevalue = p[1]._Str();
string nodeid = p[2]._Str();
var ddoc = this.FindDocumentByName(FileCollection, filename, new string[] { IDFlag });
string fileid = null;
if (ddoc != null)
{
fileid = ddoc[IDFlag].AsString;
}
UploadFile(ref fileid, filename, null, null,
filevalue._Bytes(false), false, false, onlycontent: true, nodeid: nodeid, nobackup: true);
r["path"] = filename;
r["type"] = "file";
r["filename"] = filename;
return r;
};
case "file.update":
return () =>
{
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
string filename = p[0]._Str();
filename = filename._Path(this.ClientInfo.PageSource);
string filevalue = p[1]._Str();
string nodeid = p[2]._Str();
bool nominhtml = p[3]._Bool();
bool nobackup = p[4]._Bool();
var ddoc = this.FindDocumentByName(FileCollection, filename, new string[] { IDFlag });
string fileid = null;
if (ddoc != null)
{
fileid = ddoc[IDFlag].AsString;
}
UploadFile(ref fileid, filename, null, null,
filevalue._Bytes(false), false, false, onlycontent: true, nodeid: nodeid, nominhtml: nominhtml, nobackup: nobackup);
r["path"] = filename;
r["type"] = "file";
r["filename"] = filename;
return r;
};
case "group.update":
return () =>
{
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
r["msg"] = string.Empty;
string oldname = p[0]._Str();
string type = "file";
string[] fs = oldname.Split('?');
oldname = fs[0];
if (fs.Length > 1)
{
type = fs[1];
}
string newname = p[1]._Str();
string team = p[2]._Str();
oldname = WebUtility.UrlDecode(oldname).Trim('/').Trim();
newname = WebUtility.UrlDecode(newname).Trim('/').Trim();
newname = newname._Path();
r["name"] = newname;
string olduser = this.GetFirstName(oldname);
string newuser = this.GetFirstName(newname);
//if (!olduser.Equals(newuser, StringComparison.OrdinalIgnoreCase))
//{
// throw new NoSecurityException("没有权限", oldname);//(oldname, this.UserName);
//}
if (!newuser.Equals(olduser, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidNameException(newname + " 不合法");//ServerException.InvalidName(newname);
}
if (Regex.Match(newname, @"[\\:\*\?""<>\|]", RegexOptions.IgnoreCase).Success)
{
throw new InvalidNameException("不合法的名称:" + newname); //ServerException.InvalidName(newname);
}
IMongoQuery q = GetQuery(oldname, team);
string collection = FileCollection;
switch (type.ToLower().First())
{
case 'i':
collection = InstanceCollection;
break;
case 't':
collection = TemplateCollection;
break;
}
var docs = this.dbHelper.Find(collection, q, new List<string> { IDFlag, NameFlag });
foreach (var doc in docs)
{
string id = doc[IDFlag].ToString();
string name = doc[NameFlag].ToString();
string objName = newname + "/" + name.Remove(0, oldname.Length);
string user = string.Empty;
string groupName = string.Empty;
CheckNameAndGroup(id, collection, ref objName, ref groupName, ref user);
this.GetRealName(ref objName, ref groupName, user);
BsonDocument values = new BsonDocument();
string lname = objName.ToLower();
string lgroup = GetLGroup(groupName);
this.AddNameMapping(lname, ref values);
values.Add(LNameFlag, lname);
values.Add(NameFlag, objName);
values.Add(GroupFlag, groupName);
values.Add(LGroupFlag, lgroup);
this.dbHelper.Update(collection, id, values);
}
r["msg"] = "updated: " + docs.Count;
return r;
};
case "symbol.cps":
return () =>
{
var symbolname = p[0]._Str();
if (string.IsNullOrEmpty(symbolname))
{
return null;
}
var doc = this.FindDocumentByName(FileCollection, symbolname, new string[] { Definitions.ValueFlag, DescriptionFlag, NameFlag });
if (doc == null)
{
throw new NotExistException("图形不存在:" + symbolname);
}
var vv = doc[Definitions.ValueFlag].AsByteArray._Str(false);
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(vv);
var nodes = xmldoc.GetElementsByTagName("customproperty");
Dictionary<string, object> data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var node in nodes)
{
var e = node as XmlElement;
var name = e.GetAttribute("name");
var id = e.GetAttribute("id");
var value = e.GetAttribute("value");
var type = e.GetAttribute("type");
var description = e.GetAttribute("description");
Dictionary<string, object> prop = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
prop["_value"] = value;
switch (type)
{
case "bool":
prop["_type"] = ItemDataType.Boolean;
break;
case "string":
prop["_type"] = ItemDataType.String;
break;
case "number":
prop["_type"] = ItemDataType.Decimal;
break;
}
prop["_desc"] = description;
prop["_change"] = "";
prop["_rid"] = "";
prop["_array"] = false;
prop["_ro"] = false;
prop["_history"] = false;
prop["_id"] = id;
data[name] = prop;
}
return data;
};
case "symbol.getimg":
return () =>
{
var name = p[0]._Str();
var value = p[1]._Str();
string ctype;
var id = this.CheckAndGetObjectId(name, out ctype);
var doc = this.FindDocumentById(ctype, id, new string[] { "_img" });
var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["id"] = doc.GetString(IDFlag);
result["img"] = doc.GetString("_img") ?? "";
return result;
};
case "symbol.saveimg":
return () =>
{
var name = p[0]._Str();
var value = p[1]._Str();
if (string.IsNullOrEmpty(value))
{
return false;
}
string ctype;
var id = this.CheckAndGetObjectId(name, out ctype);
var values = new BsonDocument();
values["_img"] = value;
values["_img2"] = "1";
this.dbHelper.Update(ctype, id, values, nobackup: true);
return true;
};
case "symbol.embeddedlist":
return () =>
{
var list = p[0]._StrList();
var sec = p[1]._Bool();
var dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var name in list)
{
if (dic.ContainsKey(name))
{
continue;
}
var parents = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
this.GetEmbeddedList(name, dic, this.UserId, parents, sec);
}
return dic;
};
case "symbol.template":
return () =>
{
var symbolname = p[0]._Str();
var doc = this.FindDocumentByName(FileCollection, symbolname, new string[] { Definitions.ValueFlag, DescriptionFlag, NameFlag });
var vv = doc[Definitions.ValueFlag].AsByteArray._Str(false);
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(vv);
var nodes = xmldoc.GetElementsByTagName("customproperty");
Dictionary<string, object> dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, object> data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
string me = this.GetLastName(doc[NameFlag].ToString());
dic[me] = data;
data["_symbol"] = symbolname;
data["_value"] = "";
data["_desc"] = doc.GetString(DescriptionFlag);
data["_change"] = "";
data["_rid"] = "";
data["_array"] = false;
data["_ro"] = false;
data["_history"] = false;
foreach (var node in nodes)
{
var e = node as XmlElement;
var name = e.GetAttribute("name");
var value = e.GetAttribute("value");
var type = e.GetAttribute("type");
var description = e.GetAttribute("description");
Dictionary<string, object> prop = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
prop["_value"] = value;
switch (type)
{
case "bool":
prop["_type"] = ItemDataType.Boolean;
break;
case "string":
prop["_type"] = ItemDataType.String;
break;
case "number":
prop["_type"] = ItemDataType.Decimal;
break;
}
prop["_desc"] = description;
prop["_change"] = "";
prop["_rid"] = "";
prop["_array"] = false;
prop["_ro"] = false;
prop["_history"] = false;
data[name] = prop;
}
return dic;
};
case "template.changeprop":
return () =>
{
//changeprop(tid, prop, value
var fullname = p[0]._Str();
var prop = p[1]._Str();
var value = p[2]._Str();
var tid = fullname;
var property = string.Empty;
int index = fullname.IndexOf('.');
if (index != -1)
{
tid = fullname.Substring(0, index);
property = fullname.Substring(index + 1);
}
BsonDocument tempDoc = this.FindDocumentById(TemplateCollection, tid, new string[] { Definitions.ValueFlag, UserFlag, NameFlag });
if (tempDoc == null)
{
throw new NotExistException("模板不存在:" + tid);
}
this.CheckSecurity(CollectionType.Template, tempDoc, SecurityType.Read);
tid = tempDoc.GetString(IDFlag);
tempDoc = tempDoc[Definitions.ValueFlag] as BsonDocument;
var ps = property.Split(".".ToArray(), StringSplitOptions.RemoveEmptyEntries);
var doc = tempDoc;
foreach (var pp in ps)
{
var e = doc.Find(pp);
doc = e.Value as BsonDocument;
}
if (value == null)
{
doc.Remove(prop);
}
else
{
doc[prop] = value;
}
this.PublishTemplate(ref tid, null, null, null, tempDoc.ToString(), true);
return true;
};
case "instance.templateid":
return () =>
{
string inst = p[0]._Str();
var tdoc = this.FindDocumentByName(InstanceCollection, inst, new string[] { TemplateFlag });
if (tdoc == null)
{
throw new NotExistException("实例不存在:" + inst);
}
return tdoc.GetString(TemplateFlag);
};
case "instance.template":
return () =>
{
var iname = p[0].ToString();
var tempnode = this.GetNodeForInstance(iname);
//foreach (var t in tempnode.Elements.ToList())
//{
// if (t.Value is BsonDocument)
// {
// tempnode.Remove(t.Name);
// }
//}
return tempnode.ToDictionary();
};
case "template.reference":
return () =>
{
var rid = p[0].ToString();
if (string.IsNullOrEmpty(rid))
{
return null;
}
var tempnode = this.GetTemplateNode(rid);
foreach (var t in tempnode.Elements.ToList())
{
if (t.Value is BsonDocument)
{
tempnode.Remove(t.Name);
}
}
return tempnode.ToDictionary();
};
case "instance.removeevent":
return () =>
{
var iid = p[0]._Str();
var id = p[2]._Str();
this.RemoveInstanceEvent(iid, id);
return null;
};
case "instance.setevent":
return () =>
{
var iid = p[0]._Str();
var e = p[1]._Str();
var id = p[2]._Str();
if (string.IsNullOrEmpty(e))
{
this.RemoveInstanceEvent(iid, id);
return null;
}
this.SetInstanceEvent(iid, e, id);
var dic = this.GetMyInstanceValue(iid, this.UserId, null, null);
TokenObject tokenObj = this.CopyToken();
Dictionary<string, object> data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, object> inputs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
inputs["id"] = dic.GetString("id");
inputs["value"] = this.myInstanceModels;
data["data()"] = inputs;
data["this"] = dic.GetString("id");
this.RunWorkflow(tokenObj, e, data);
return dic;
};
case "instance.binding":
return () =>
{
var iid = p[0]._Str();
var id = p[1]._Str();
var remove = p[2]._Bool();
if (remove)
{
this.RemoveInstanceEvent(iid, id);
return null;
}
var e = id + "=this";
this.SetInstanceEvent(iid, e, id);
var dic = this.GetMyInstanceValue(iid, this.UserId, null, null);
TokenObject tokenObj = this.CopyToken();
Dictionary<string, object> data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, object> inputs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
inputs["id"] = dic.GetString("id");
inputs["value"] = this.myInstanceModels;
data["data()"] = inputs;
data["this"] = dic.GetString("id");
this.RunWorkflow(tokenObj, e, data);
return dic;
};
case "instance.get":
return () =>
{
var dic = this.GetMyInstanceValue(p[0]._Str(), this.UserId, null, null);
return dic;
};
//case "instance.time":
// return () =>
// {
// return null;
// };
case "instance.symbol":
return () =>
{
Dictionary<string, object> cp = p[1] as Dictionary<string, object>;
Dictionary<string, object> size = p[2] as Dictionary<string, object>;
string clientname;
string username;
var symbolname = this.GetInstanceSymbol(p[0]._Str(), out clientname, out username);
var sn = symbolname.Trim('/');
if (sn.StartsWith("this/", StringComparison.OrdinalIgnoreCase))
{
symbolname = username + "/" + sn.Remove(0, 5);
}
var doc = this.FindDocumentByName(FileCollection, symbolname, new string[] { Definitions.ValueFlag });
if (doc == null)
{
throw new NotExistException("图形不存在:" + symbolname);
}
var value = doc[Definitions.ValueFlag].AsByteArray._Str(false);
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(value);
if (cp != null)
{
var nodes = xmldoc.GetElementsByTagName("customproperty");
foreach (var node in nodes)
{
var e = node as XmlElement;
var name = e.GetAttribute("name");
object obj;
if (cp != null && cp.TryGetValue(name, out obj))
{
e.SetAttribute("value", obj._Str());
}
}
}
if (size != null)
{
var nodes = xmldoc.GetElementsByTagName("mxGraphModel");
foreach (var node in nodes)
{
var e = node as XmlElement;
object obj;
if (size != null)
{
if (size.TryGetValue("width", out obj))
{
e.SetAttribute("pageWidth", obj._Str());
}
if (size.TryGetValue("height", out obj))
{
e.SetAttribute("pageHeight", obj._Str());
}
}
}
}
return xmldoc.InnerXml;
};
case "file.exist":
return () =>
{
string filename = p[0]._Str();
string collection = FileCollection;
return this.FileExist(filename, collection);
};
case "template.exist":
return () =>
{
string filename = p[0]._Str();
string collection = TemplateCollection;
return this.FileExist(filename, collection);
};
case "instance.exist":
return () =>
{
string filename = p[0]._Str();
string collection = InstanceCollection;
return this.FileExist(filename, collection);
};
case "setteam":
return () =>
{
this.SetTeam(p[0]._Str(), p[1]._Str());
return true;
};
case "file":
case "template":
return () =>
{
if (p[0] is Dictionary<string, object>)
{
var pd = (Dictionary<string, object>)p[0];
var a = new ArrayList();
a.Add(pd._Value("name"));
a.Add(pd._Value("value"));
a.Add(pd._Value("desc"));
a.Add(pd._Value("ispkg"));
a.Add(pd._Value("ignoreexist"));
a.Add(pd._Value("isnew"));
a.Add(pd._Value("min"));
a.Add(pd._Value("id"));
a.Add(pd._Value("team"));
a.Add(pd._Value("tag"));
ParameterModel pm = new ParameterModel();
pm.AddRange(a);
p = pm;
}
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
string path = string.Empty;
string filename = p[0]._Str();
string type = v;
r["err"] = string.Empty;
//try
//{
filename = filename._Path(this.ClientInfo.PageSource);
r["name"] = filename;
string[] fs222 = filename.Split('|');
string newname = null;
if (fs222.Length > 1)
{
filename = fs222[0];
newname = fs222[1];
newname = newname._Path(this.ClientInfo.PageSource);
r["name"] = newname;
}
string[] fs = filename.Split('?');
filename = fs[0];
this.CheckName(ref filename);
if (fs.Length > 1)
{
type = fs[1].ToLower();
}
if (filename.EndsWith("/"))
{
throw new InvalidNameException("文件名不合法");
}
if (p.Count == 1)
{
switch (type)
{
case "instance":
BsonDocument doc3 = this.FindDocumentByName(InstanceCollection, filename, new string[] { NameFlag, DescriptionFlag, TemplateFlag, UserFlag });
if (doc3 == null)
{
throw new NotExistException("不存在:" + filename);// ServerException.NotExist(filename);
}
filename = doc3[NameFlag].ToString();
this.CheckTeamSecurity(doc3);
doc3.Remove(UserFlag);
string vs3 = this.GetInstance(filename);
r["value"] = vs3;
r["property"] = doc3.ToDictionary();
return r;
case "template":
BsonDocument doc2 = this.FindDocumentByName(TemplateCollection, filename, new string[] { NameFlag, DescriptionFlag, UserFlag, "_value", "_value_" });
if (doc2 == null)
{
throw new NotExistException("不存在:" + filename);//ServerException.NotExist(filename);
}
filename = doc2[NameFlag].ToString();
this.CheckTeamSecurity(doc2);
doc2.Remove(UserFlag);
string vs2 = null;
BsonValue bv;
if (doc2.TryGetValue("_value_", out bv))
{
doc2.Remove("_value_");
vs2 = bv.AsString;
}
if (doc2.TryGetValue("_value", out bv))
{
doc2.Remove("_value");
if (vs2 == null)
{
vs2 = bv._Json();
}
}
r["value"] = vs2;
r["property"] = doc2.ToDictionary();
return r;
default:
BsonDocument doc = this.FindDocumentByName(FileCollection, filename, new string[] { NameFlag, DescriptionFlag, UserFlag, SizeFlag });
if (doc == null)
{
throw new NotExistException(filename + " 不存在");//ServerException.FileNotExist(filename);
}
filename = doc[NameFlag].ToString();
this.CheckTeamSecurity(doc);
doc.Remove(UserFlag);
//doc.Remove(TeamFlag);
//string fileExt = Path.GetExtension(filename);
byte[] vs = null;
int size = 0;
if (doc.TryGetValue(SizeFlag, out bv))
{
size = bv.AsInt32;
}
if (size < 10000 * 1000)
{
vs = this.GetFileContent(filename);
}
if (doc == null)
{
throw new NotExistException(filename + " 不存在");
}
r["value"] = vs._Str(false);
r["property"] = doc.ToDictionary();
return r;
}
}
byte[] vbytes = null;
if (p[1] != null)
{
if (p[1] is byte[])
{
vbytes = (byte[])p[1];
}
else
{
string vstr = p[1]._Str();
vbytes = vstr._ObjBytes(false);
}
}
bool content = true;
if (p.Count > 2)
{
content = false;
}
string description = p[2]._Str();
bool ispkg = p[3]._Bool();
bool ignoreexist = p[4]._Bool();
bool isnew = p[5]._Bool();
bool min = p[6]._Bool();
string id = p[7]._Str();
if (id == "null" || id == "undefined")
{
id = null;
}
string team = p[8]._Str();
string tag = p[9]._Str();
string objid = null;
script.MyScriptTimeout = () =>
{
return 60000 * 10;
};
Action<byte[], string, string, string, string, bool> uploadAction = null;
Action<byte[], string, string> unzipAction = (mybytes, mygroup, mytype) =>
{
Zip.Unzip(mybytes, (name, value) =>
{
uploadAction(value, mygroup, mytype, name, null, true);
});
};
uploadAction = (myvalue, mygroup, mytype, myname, mynewname, mycontent) =>
{
if (myname.EndsWith(".$template$.zip"))
{
if (string.IsNullOrEmpty(mygroup))
{
int lastindex = myname.LastIndexOf('/');
if (lastindex > 0)
{
mygroup = myname.Substring(0, lastindex);
}
}
unzipAction(myvalue, mygroup, "template");
return;
}
if (!string.IsNullOrEmpty(mygroup))
{
myname = mygroup + "/" + myname;
}
if (ignoreexist && FileExist(myname))
{
return;
}
path = null;
switch (mytype)
{
case "instance":
var values = myvalue._Str(false)._Dic();
TemplateModel tm = new TemplateModel();
tm.Cons = ConditionModel.Create(values, string.Empty);
this.PublishInstance(ref path, myname, description, string.Empty, null, DataOperations.Upsert, tm, newname: mynewname, fornew: isnew, oid: id, team: team);
objid = path;
break;
case "template":
this.PublishTemplate(ref path, myname, description, string.Empty, myvalue._Str(false), upsert: true, newname: mynewname, fornew: isnew, oid: id, team: team, tag: tag);
objid = path;
break;
default:
objid = UploadFileByName(out path, myname, myvalue, DataOperations.Upsert, description, mycontent, newname: mynewname, fornew: isnew, min: min, oid: id, team: team, tag: tag);
path = objid;
break;
}
};
if (ispkg)
{
string group = string.Empty;
int lastindex = filename.LastIndexOf('/');
if (lastindex > 0)
{
group = filename.Substring(0, lastindex);
}
if (vbytes != null && vbytes.Length > 0)
{
unzipAction(vbytes, group, type);
}
}
else
{
if (!filename.Contains('/'))
{
string collection = FileCollection;
switch (type)
{
case "instance":
collection = InstanceCollection;
break;
case "template":
collection = TemplateCollection;
break;
default:
collection = FileCollection;
break;
}
var doc = this.FindDocumentById(collection, filename, new string[] { NameFlag });
if (doc == null)
{
throw new NotExistException("不存在:" + filename);
}
filename = doc.GetString(NameFlag);
path = doc.GetString(IDFlag);
}
if (filename.Equals(newname, StringComparison.OrdinalIgnoreCase))
{
newname = null;
}
uploadAction(vbytes, null, type, filename, newname, content);
//switch (type)
//{
// case "instance":
// var values = p[1]._Str(false)._Dic();
// TemplateModel tm = new TemplateModel();
// tm.Cons = ConditionModel.Create(values, string.Empty);
// this.PublishInstance(ref path, filename, description, string.Empty, null, DataOperations.Upsert, tm, newname: newname, fornew: isnew, oid: id, team: team);
// objid = path;
// break;
// case "template":
// this.PublishTemplate(ref path, filename, description, string.Empty, p[1]._Str(false), upsert: true, newname: newname, fornew: isnew, oid: id, team: team, tag: tag);
// objid = path;
// break;
// default:
// objid = UploadFileByName(out path, filename, vbytes, DataOperations.Upsert, description, content, newname: newname, fornew: isnew, min: min, oid: id, team: team, tag: tag);
// break;
//}
}
//SendResultMessage("Save " + type + ": " + filename + "; path: " + path);
//}
//catch (Exception ex)
//{
// throw ex;
// //SendResultMessage("Save " + type + ": " + ex._msg());
// //r["err"] = ex._msg();
//}
r["id"] = objid;
r["path"] = path;
r["type"] = type;
r["filename"] = filename;
script.MyScriptTimeout = null;
return r;
};
case "file.bytes":
return () =>
{
try
{
string filename = p[0]._Str();
byte[] vs = this.GetFileContent(filename);
return vs;
}
catch (Exception ex)
{
Log.LogMessage("Error", ex.Message);
//SendResultMessage("file.bytes: " + ex._msg());
return null;
}
};
case "group.copy":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("需要登录");
}
bool fornew = p[2]._Bool();
string group = p[0]._Str().Trim('/').Trim();
group = WebUtility.UrlDecode(group);
string copygroup = p[1]._Str().Trim('/').Trim();
copygroup = WebUtility.UrlDecode(copygroup);
string type = "file";
var wenhao = group.IndexOf('?');
if (wenhao != -1)
{
type = group.Substring(wenhao + 1);
group = group.Substring(0, wenhao);
}
string collection = FileCollection;
if (!string.IsNullOrEmpty(type))
{
switch (type.ToLower())
{
case "instance":
collection = InstanceCollection;
break;
case "template":
collection = TemplateCollection;
break;
}
}
var q = GetQuery(group, null);
var c = this.dbHelper.Sum(collection, q);
int limit = DataClient.GetMyLimit(this.UserId, "Download")._Int();
if (limit > 0 && c > limit)
{
string msg = "文件数量太大:" + c + ">" + limit;
this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + msg, new List<string> { this.UserId }, null);
throw new OverLimitException(msg);
}
var docs = this.dbHelper.Find(collection, q, new List<string> { NameFlag, SizeFlag });
int grouplength = group.Length;
foreach (var d in docs)
{
string name = d[NameFlag].AsString;
string othername = name.Remove(0, grouplength);
string newfilename = copygroup + othername;
string path = null;
switch (type)
{
case "instance":
var vvv = this.FindDocumentById(collection, d[IDFlag].ToString(), new string[] { TemplateFlag, Definitions.ValueFlag });
var value = vvv[Definitions.ValueFlag] as BsonDocument;
TemplateModel tm = new TemplateModel();
tm.Cons = ConditionModel.Create(value.ToDictionary(), string.Empty);
this.PublishInstance(ref path, newfilename, string.Empty, string.Empty, vvv[TemplateFlag].ToString(), DataOperations.Upsert, tm, fornew: fornew);
break;
case "template":
vvv = this.FindDocumentById(collection, d["_id"].ToString(), new string[] { Definitions.ValueFlag });
var resultstring = vvv[Definitions.ValueFlag].ToString();
this.PublishTemplate(ref path, newfilename, string.Empty, string.Empty, resultstring, fornew: fornew);
break;
default:
byte[] result = this.GetValueResult(d, collection);
UploadFileByName(out path, newfilename, result, DataOperations.Upsert, string.Empty, false, fornew: fornew);
break;
}
}
return null;
};
case "group.export":
case "group.clone":
//script.
return () =>
{
try
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("需要登录");
}
//var userdoc = this.FindDocumentById(UserCollection, this.UserId, new string[] { "_exporttime" });
//BsonValue bv;
//if (userdoc.TryGetValue("_exporttime", out bv))
//{
// var t = bv.ToUniversalTime();
// var diff = DateTime.UtcNow - t;
// if (diff.TotalMinutes < 1)
// {
// throw new TimeLimitException("间隔时间需要大于1分钟");
// }
//}
string group = p[0]._Str().Trim('/').Trim();
group = WebUtility.UrlDecode(group);
string team = p[3]._Str();
string type = p[1]._Str();
var wenhao = group.IndexOf('?');
if (wenhao != -1)
{
type = group.Substring(wenhao + 1);
group = group.Substring(0, wenhao);
}
string[] allfilenames = null;
ArrayList namelist = p[2] as ArrayList;
if (namelist == null)
{
string zipname = p[2]._Str();
Dictionary<string, object> data;
if (zipname._IsJson(out data))
{
var dic = data;
string value = dic._Value("value")._Str();
allfilenames = value.Split("\r\n".ToArray(), StringSplitOptions.RemoveEmptyEntries);
}
}
else
{
allfilenames = new string[namelist.Count];
for (int i = 0; i < namelist.Count; i++)
{
allfilenames[i] = namelist[i]._Str();
}
}
IMongoQuery q = null;
if (allfilenames != null)
{
foreach (var f in allfilenames)
{
if (string.IsNullOrEmpty(f))
{
continue;
}
if (!f.StartsWith("/" + this.UserName + "/"))
{
throw new NoSecurityException("没有权限", f);
}
if (f.EndsWith("/"))
{
var folder = f.Trim('/').Trim();
int count = folder.Split('/').Length;
IMongoQuery q2 = Query.EQ("_g." + "g" + count, folder.ToLower());
if (q == null)
{
q = q2;
}
else
{
q = Query.Or(q, q2);
}
}
else
{
var q2 = Query.EQ(LNameFlag, f.Trim('/').Trim().ToLower());
if (q == null)
{
q = q2;
}
else
{
q = Query.Or(q, q2);
}
}
}
}
else
{
q = GetQuery(group, team);
}
string collection = FileCollection;
if (!string.IsNullOrEmpty(type))
{
switch (type.ToLower())
{
case "instance":
collection = InstanceCollection;
break;
case "template":
collection = TemplateCollection;
break;
}
}
var c = this.dbHelper.Sum(collection, q);
int limit = DataClient.GetMyLimit(this.UserId, "Download")._Int();
if (limit > 0 && c > limit)
{
string msg = "文件数量太大:" + c + ">" + limit;
this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + msg, new List<string> { this.UserId }, null);
throw new OverLimitException(msg);
}
var docs = this.dbHelper.Find(collection, q, new List<string> { NameFlag, SizeFlag });
script.MyScriptTimeout = () =>
{
return 60000 * 10;
};
//BsonDocument newuserdoc = new BsonDocument();
//newuserdoc["_exporttime"] = DateTime.UtcNow;
//this.dbHelper.Update(UserCollection, this.UserId, newuserdoc);
if (v == "group.export")
{
var copygroup = p[5]._Str();
if (!string.IsNullOrEmpty(copygroup))
{
copygroup = copygroup.Trim('/').Trim();
copygroup = WebUtility.UrlDecode(copygroup);
}
string progress = string.Empty;
Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
int i = 0;
int count = docs.Count;
DateTime dt = DateTime.UtcNow;
int sizetotal = 0;
string totalsize = CommonFunction.CountSize(c);
//Dictionary<string, object> idmapping = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var d in docs)
{
int size = d[SizeFlag].AsInt32;
sizetotal = sizetotal + size;
i++;
var diff = DateTime.UtcNow - dt;
progress = "大小:" + CommonFunction.CountSize(sizetotal) + "/" + totalsize + "; 进度:" + i.ToString() + "/" + count.ToString() + "; 时间:" + diff.TotalSeconds + "; 机器:" + ServerInfo.Domain + "; 状态:" + !script.StackObj.Stopped + " " + script.StackObj.LastError;
DataClient dc = new DataClient(this.CopyToken());
dc.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + progress, new List<string> { this.UserId }, null);
if (script.StackObj.Stopped)
{
return null;
}
string name = d[NameFlag].AsString;
if (!string.IsNullOrEmpty(copygroup))
{
int grouplength = group.Length;
string othername = name.Remove(0, grouplength);
name = copygroup + othername;
}
byte[] result;
if (collection == DataClient.InstanceCollection)
{
var vvv = this.FindDocumentById(collection, d[IDFlag].ToString(), new string[] { TemplateFlag, Definitions.ValueFlag });
var value = vvv[Definitions.ValueFlag] as BsonDocument;
Dictionary<string, object> rrr = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
rrr["tid"] = vvv[TemplateFlag].ToString();
rrr["value"] = value.ToDictionary();
result = rrr._Json()._Bytes(false);
}
else
{
result = this.GetValueResult(d, collection);
}
int lastindex = name.IndexOf('/');
string filename = name.Remove(0, lastindex + 1);
if (p[4]._Bool())
{
files[filename + ".$." + d.GetString(IDFlag)] = result;
}
else
{
files[filename] = result;
}
//idmapping[filename ] = d.GetString(IDFlag);
}
//files["$.idmapping"] = idmapping._Json()._Bytes(false);
var values = Zip.ToBytes(files);
return values;
}
else
{
string newid = NewId;
int i = 0;
int count = docs.Count;
DateTime dt = DateTime.UtcNow;
int grouplength = group.Length;
string datestring = DateTime.UtcNow.ToString("_MMdd_HHmmss_fff");
foreach (var d in docs)
{
i++;
var diff = DateTime.UtcNow - dt;
string progress = i.ToString() + "/" + count.ToString() + "; 时间:" + diff.TotalSeconds + "; 状态:" + !script.StackObj.Stopped + " " + script.StackObj.LastError;
this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + progress, null, null);
if (script.StackObj.Stopped)
{
return null;
}
string name = d[NameFlag].AsString;
string othername = name.Remove(0, grouplength);
string newfilename = group + datestring + othername;
string path = null;
switch (type)
{
case "instance":
var vvv = this.FindDocumentById(collection, d[IDFlag].ToString(), new string[] { TemplateFlag, Definitions.ValueFlag });
var value = vvv[Definitions.ValueFlag] as BsonDocument;
TemplateModel tm = new TemplateModel();
tm.Cons = ConditionModel.Create(value.ToDictionary(), string.Empty);
this.PublishInstance(ref path, newfilename, string.Empty, string.Empty, vvv[TemplateFlag].ToString(), DataOperations.Upsert, tm, fornew: true);
break;
case "template":
vvv = this.FindDocumentById(collection, d["_id"].ToString(), new string[] { Definitions.ValueFlag });
var resultstring = vvv[Definitions.ValueFlag].ToString();
this.PublishTemplate(ref path, newfilename, string.Empty, string.Empty, resultstring, fornew: true);
break;
default:
byte[] result = this.GetValueResult(d, collection);
UploadFileByName(out path, newfilename, result, DataOperations.Insert, string.Empty, false, fornew: true);
break;
}
}
string msg = "导出完成!";
this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "|" + msg, new List<string> { this.UserId }, null);
return true;
}
}
catch (Exception ex)
{
Thread.Sleep(1000);
this.UpdateInstance("/" + this.UserName + "/msg.message", this.Id + "; 错误:" + ex._msg(), new List<string> { this.UserId }, null);
throw ex;
}
finally
{
script.MyScriptTimeout = null;
//BsonDocument newuserdoc = new BsonDocument();
//newuserdoc["_exporttime"] = DateTime.MinValue;
//this.dbHelper.Update(UserCollection, this.UserId, newuserdoc);
}
};
case "file.export":
return () =>
{
string filename = p[0]._Str().Trim('/').Trim();
//if (!this.GetFirstName(filename).Equals(this.UserName, StringComparison.OrdinalIgnoreCase))
//{
// throw new NoSecurityException("没有权限", filename);//(filename, this.UserName);
//}
string type = p[1]._Str();
string collection = FileCollection;
CollectionType ct = CollectionType.File;
switch (type)
{
case "instance":
collection = InstanceCollection;
ct = CollectionType.Instance;
break;
case "template":
collection = TemplateCollection;
ct = CollectionType.Template;
break;
}
var d = this.FindDocumentByName(collection, filename, new string[] { IDFlag, NameFlag, UserFlag });
if (d == null)
{
return null;
}
this.CheckSecurity(ct, d, SecurityType.Read);
byte[] result = this.GetValueResult(d, collection);
Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
files[filename] = result;
var values = Zip.ToBytes(files);
return values;
};
case "file.delete":
case "group.delete":
return () =>
{
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
string type = "file";
string filename = p[0]._Str();
//object obj2;
//if (vget.TryGetValue("filename", out obj2))
//{
// filename = obj2._Str();
//}
string[] fs = filename.Split('?');
filename = fs[0];
if (fs.Length > 1)
{
type = fs[1];
}
bool isgroup = false;
if (v == "group.delete" || filename.EndsWith("/"))
{
isgroup = true;
}
//bool backup = p[1]._Bool();
string team = p[1]._Str();
string path = filename;
if (isgroup)
{
script.MyScriptTimeout = () =>
{
return 60000 * 10;
};
IMongoQuery q = GetQuery(filename, team);
string collection = FileCollection;
switch (type)
{
case "instance":
collection = InstanceCollection;
break;
case "template":
collection = TemplateCollection;
break;
}
var docs = this.dbHelper.Find(collection, q, new List<string> { IDFlag });
foreach (var d in docs)
{
string id2 = d[IDFlag].ToString();
path = id2;
switch (type)
{
case "instance":
this.DeleteInstance(id2);
break;
case "template":
this.DeleteTemplate(id2);
break;
default:
this.DeleteFile(id2);
break;
}
}
script.MyScriptTimeout = null;
}
else
{
switch (type)
{
case "instance":
this.DeleteInstance(filename);
break;
case "template":
this.DeleteTemplate(filename);
break;
default:
this.DeleteFile(filename);
break;
}
}
r["path"] = path;
r["type"] = type;
r["filename"] = filename;
return r;
};
case "instances":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
return null;
}
string search = p[0]._Str();
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
if (!string.IsNullOrEmpty(search))
{
string lsearch = search.ToLower();
IMongoQuery mq = Query.Or(Query.Matches(LNameFlag, new BsonRegularExpression(lsearch)), Query.Matches(LDescriptionFlag, new BsonRegularExpression(lsearch)));
q = Query.And(q, mq);
}
var docs = this.dbHelper.Find(InstanceCollection, q, new List<string> { NameFlag }, sortby: new SortByDocument(ModifiedFlag, -1));
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (var doc in docs)
{
string id = doc[NameFlag].ToString();
Dictionary<string, object> value = this.GetInstance(id)._Dic()._DicValue() as Dictionary<string, object>;
var v2 = value._DicKeys(id);
foreach (var keyvalue in v2)
{
list.Add(new Dictionary<string, object> { { "_name", keyvalue.Key }, { "id", keyvalue.Key.ToLower()._MD5() } });
}
}
return list;
};
case "publish":
{
return () =>
{
string name = p[0]._Str();
string value = p[1]._Str();
IList touser = p[2] as IList;
Dictionary<string, object> cp = p[3] as Dictionary<string, object>;
if (touser != null)
{
int count = touser.Count;
for (int i = 0; i < count; i++)
{
string user = touser[i].ToString();
if (user.Length != 24)
{
string userid = this.GetUserId(user);
if (string.IsNullOrEmpty(userid))
{
throw new UserNotExistException("用户不存在:" + user);
}
touser[i] = userid;
}
else
{
string userid = this.GetUserName(user);
if (string.IsNullOrEmpty(userid))
{
throw new UserNotExistException("用户不存在:" + user);
}
}
}
}
Dictionary<string, MyInstanceModel> models = null;
object data = null;
if (vget.TryGetValue("data()", out data))
{
object attr = null;
InstanceAttr myattr = null;
if (vget.TryGetValue("attr()", out attr))
{
myattr = attr as InstanceAttr;
}
if (myattr != null)
{
touser = myattr.To;
cp = myattr.CustomProperty;
}
Dictionary<string, object> refdata = data as Dictionary<string, object>;
if (refdata != null)
{
object m = null;
if (refdata.TryGetValue("value", out m))
{
models = (Dictionary<string, MyInstanceModel>)m;
this.myInstanceModels = models;
}
}
}
this.UpdateInstance(name, value, to: touser, cp: cp, models: models);
return true;
};
}
case "template.history":
return () =>
{
string tid = p[0]._Str();
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var valuefield = "doc._value";
List<string> fields = new List<string>() { valuefield, UserFlag, "id", "name", "desc", "tag" };
BsonDocument doc = this.dbHelper.FindDocumentByQuery(TemplateHistoryCollection, Query.EQ(IDFlag, tid), fields.ToArray());
if (doc == null)
{
throw new NotExistException("不存在:" + tid);
}
var id = doc.GetString("id");
this.CheckSecurity(id, CollectionType.Template, SecurityType.Read);
var tempDoc = doc.Value(valuefield) as BsonDocument;
string owner = doc[UserFlag].ToString();
RefreshTemplate(ref owner, tempDoc);
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["id"] = id;
result["name"] = doc.GetString("name");
result["desc"] = doc.GetString("desc");
result["tag"] = doc.GetString("tag");
result["value"] = tempDoc.ToDictionary();
return result;
};
case "template.get":
return () =>
{
string tid = p[0]._Str();
tid = HttpUtility.UrlDecode(tid);
if (string.IsNullOrEmpty(tid))
{
return null;
}
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
BsonDocument tempDoc = this.FindDocumentById(TemplateCollection, tid, new string[] { Definitions.ValueFlag, UserFlag, NameFlag });
if (tempDoc == null)
{
throw new NotExistException("模板不存在:" + tid);
}
this.CheckSecurity(CollectionType.Template, tempDoc, SecurityType.Read);
string owner = tempDoc[UserFlag].ToString();
tempDoc = tempDoc[Definitions.ValueFlag] as BsonDocument;
BsonDocument returnDoc = tempDoc;
RefreshTemplate(ref owner, tempDoc);
return returnDoc.ToDictionary();
};
case "instance.data":
return () =>
{
string objname = p[0].ToString();
var obj2 = objname;
int index = objname.IndexOf('.');
string property = string.Empty;
if (index != -1)
{
property = objname.Substring(index + 1).ToLower();
objname = objname.Substring(0, index);
}
var doc = this.GetInstanceDoc(objname);
while (!string.IsNullOrEmpty(property))
{
index = property.IndexOf('.');
string left = string.Empty;
if (index != -1)
{
left = property.Substring(index + 1);
property = property.Substring(0, index);
}
BsonValue bv;
doc.TryGetValue(property, out bv);
doc = bv.AsBsonDocument;
property = left;
}
return doc.ToDictionary()._DicValue();
};
case "instance":
case "instance.update":
return () =>
{
string objname = p[0].ToString();
var obj2 = objname;
if (p.Count == 1)
{
int index = objname.IndexOf('.');
string property = string.Empty;
if (index != -1)
{
property = objname.Substring(index + 1).ToLower();
objname = objname.Substring(0, index);
}
var doc = this.GetInstanceDoc(objname);
while (!string.IsNullOrEmpty(property))
{
index = property.IndexOf('.');
string left = string.Empty;
if (index != -1)
{
left = property.Substring(index + 1);
property = property.Substring(0, index);
}
BsonValue bv;
doc.TryGetValue(property, out bv);
doc = bv.AsBsonDocument;
property = left;
}
return doc.ToDictionary();
}
string value = p[1].ToString();
this.UpdateInstance(objname, value, null, null);
return null;
};
//case "instance.exist":
// return () =>
// {
// var iid = this.GetInstanceIdByName(p[0]._Str());
// return !string.IsNullOrEmpty(iid);
// };
case "instance.change":
return () =>
{
string objid = p[0].ToString();
string instname = p[1].ToString();
string newname = p[2].ToString();
string desc = p[3]._Str();
string team = p[4]._Str();
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
PublishInstance(ref objid, instname, desc, string.Empty, null, option: DataOperations.Update, newname: newname, fornew: false, team: team);
r["id"] = objid;
return r;
};
case "instance.new":
return () =>
{
string objid = string.Empty;
string objname = p[0].ToString();
string instname = p[1]._Str();
string team = p[2]._Str();
string desc = p[3]._Str();
string tid = this.GetTemplateId(objname);
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
if (string.IsNullOrEmpty(instname))
{
string username = this.UserName;
if (!string.IsNullOrEmpty(team))
{
var doc = this.FindDocumentById(TeamCollection, team, new string[] { UserFlag });
string user = doc[UserFlag].ToString();
username = this.GetUserName(user);// team.Substring(0, i);
}
instname = username + "/Instance_" + DateTime.UtcNow.ToString("yyyyMMddHHmmss_fff") + "/" + this.GetLastName(objname);
}
PublishInstance(ref objid, instname, desc, string.Empty, tid, fornew: true, team: team);
r["id"] = objid;
return r;
};
case "instance.delete":
return () =>
{
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
//try
//{
string filename = p[0]._Str();
this.DeleteInstance(filename);
//this.SendResultMessage("DeleteInstance: " + filename + ";");
//}
//catch (Exception ex)
//{
//SendResultMessage("DeleteInstance: " + ex._msg());
//r["err"] = ex._msg();
//}
return r;
};
case "base":
return () =>
{
object mytemp;
if (vget.TryGetValue("t()", out mytemp))
{
var mytempid = mytemp.ToString();
var node = this.GetTemplateNode(mytempid);
var rid = node.GetString(ReferenceFlag);
if (string.IsNullOrEmpty(rid))
{
string type = "Debug";
string msg = "执行base()时,没有发现父类。";
string feature = "Console";
this.PublishUserLog(type, msg, feature);
return null;
}
node = this.GetTemplateNode(rid);
var change = node.GetString(OnChangeFlag);
vget["t()"] = rid;
this.RunWorkflow(this.CopyToken(), change, vget);
vget["t()"] = mytemp;
}
return true;
};
case "template.delete2":
return () =>
{
string filename = p[0]._Str();
var doc = this.FindDocumentByName(TemplateCollection, filename, new string[] { UserFlag, NameFlag, LGroupFlag });
if (doc == null)
{
throw new NotExistException("模板不存在:" + filename);
}
var objId = doc[IDFlag].AsString;
this.CheckSecurity(objId, CollectionType.Template, SecurityType.Write);
var collection = DataClient.DataCollection + "_" + objId;
if (this.dbHelper.CollectionExist(collection))
{
this.dbHelper.DeleteCollection(collection);
}
this.dbHelper.Remove(InstanceCollection, Query.EQ(TemplateFlag, objId));
IMongoQuery q1 = Query.EQ("_id", objId);
this.dbHelper.Remove(TemplateCollection, q1);
return true;
};
case "template.delete":
return () =>
{
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
r["err"] = string.Empty;
string filename = p[0]._Str();
this.DeleteTemplate(filename);
return r;
};
#endregion
#region SystemFunction
case "crc":
return () =>
{
var data = (byte[])p[0];
var offset = p[1]._Int();
var length = p[2]._Int();
var crc = CustomProtocol.Core.GetCRC(data, offset, length);
return crc;
};
case "crc32":
return () =>
{
var data = (byte[])p[0];
var crc = CustomProtocol.Core.GetCRC32(data);
return crc;
};
case "fillbytes":
return () =>
{
var data = (byte[])p[0];
var length = p[1]._Int();
var defaultbyte = (byte)(p[1]._Int());
var result = CustomProtocol.Support.FillByte(data, length, defaultbyte);
return result;
};
case "script.parse":
return () =>
{
var s = script.ToDictionary(p[0]._Str());
return s;
};
case "server.url":
return () =>
{
string port = string.Empty;
if (ServerInfo.WebPort != "80")
{
port = ":" + ServerInfo.WebPort;
}
return "http://" + ServerInfo.ServerIP + port;
};
case "api.info":
return () =>
{
var group = p[0]._Str();
group = group._Path(this.ClientInfo.PageSource);
var fields = new string[] { NameFlag, DescriptionFlag, Definitions.ValueFlag };
//string g1 = this.GetLGroup(group);
var folder = group.Trim('/').Trim();
int count = folder.Split('/').Length;
IMongoQuery q2 = Query.EQ("_g." + "g" + count, folder.ToLower());
IMongoQuery q_all = Query.And(Query.EQ(TypeFlag, ".ds"), Query.EQ(UserFlag, this.UserId), q2);
var docs = this.dbHelper.Find(FileCollection, q_all, new List<string> { IDFlag });
List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
foreach (var doc in docs)
{
var d = this.FindDocumentById(FileCollection, doc[IDFlag].ToString(), fields);
var scriptstring = d[Definitions.ValueFlag].AsByteArray._Str(false);
var scriptinfo_List = script.GetFunctionInfo(scriptstring, (s) =>
{
string content = this.GetDSContent(s + ".ds", true, this.UserName);
return content;
});
int count2 = scriptinfo_List.Count;
if (count2 > 0)
{
for (int i = 0; i < count2; i++)
{
Dictionary<string, object> scriptinfo = scriptinfo_List[i];
if (string.IsNullOrEmpty(scriptinfo["summary"]._Str()))
{
continue;
}
var scriptname = "/" + d[NameFlag].AsString;
scriptinfo["name"] = scriptname;
scriptinfo["desc"] = scriptinfo["description"]._Str();
var method = scriptinfo["method"]._Str();
List<Dictionary<string, object>> parameters = new List<Dictionary<string, object>>();
switch (method)
{
case "get":
Dictionary<string, object> pa = scriptinfo["parameters"] as Dictionary<string, object>;
foreach (var kv in pa)
{
var para2 = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
para2["in"] = "query";
para2["name"] = kv.Key;
var ppp = kv.Value as Dictionary<string, object>;
var desc = ppp._Value("description");
if (desc != null)
{
para2["description"] = desc;
}
para2["type"] = ppp._Value("type");
para2["default"] = ppp._Value("default") ?? string.Empty;
var required = ppp._Value("required");
if (required != null)
{
para2["required"] = required._Bool();
}
parameters.Add(para2);
}
break;
case "post":
var para = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
para["in"] = "body";
para["name"] = "参数名";
para["description"] = "参数描述";
Dictionary<string, object> schema = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
schema["type"] = "object";
Dictionary<string, object> pa2 = scriptinfo["parameters"] as Dictionary<string, object>;
List<string> requiredlist = new List<string>();
foreach (var kv in pa2)
{
var ppp = kv.Value as Dictionary<string, object>;
var required = ppp._Value("required");
if (required != null)
{
ppp.Remove("required");
requiredlist.Add(kv.Key);
}
}
if (requiredlist.Count > 0)
{
schema["required"] = requiredlist;
}
schema["properties"] = pa2;
para["schema"] = schema;
parameters.Add(para);
break;
}
scriptinfo["parameters"] = parameters;
scriptinfo["method"] = method;
result.Add(scriptinfo);
}
}
}
return result;
};
//case "functions":
// return () =>
// {
// var result = new Dictionary<string, object>();
// foreach (var kv in MyFunction.Methods)
// {
// Dictionary<string, object> ps = new Dictionary<string, object>();
// ps["IsStatic"] = kv.Value.IsStatic;
// ps["ParaNames"] = kv.Value.ParaNames;
// result[kv.Key] = ps;
// }
// return result;
// };
case "license.key":
return () =>
{
var kv = DatabaseHelper.CreateLicenseKey(p[0].ToString());
return kv;
};
case "license.create":
return () =>
{
int i = 0;
return DatabaseHelper.CreateLicense(p[i++]._Str(), p[i++]._Str(), p[i++]._Time(), (Dictionary<string, object>)p[i++], p[i++]._Str(), p[i++]._Str());
};
case "status":
return () =>
{
return this.GetAllServerStatus();
};
//case "debug":
// return () =>
// {
// var debug = p[0]._Bool();
// ServerInfo.Debug = debug;
// return debug;
// };
case "uploadform":
return () =>
{
return ServerSetting.uploadfilecontent;
};
case "checkindex":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("checkindex", this.UserName);
}
//DatabaseHelper.CheckIndex(FileCollection, LNameFlag);
return true;
};
case "servers":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限", "servers");//("servers", this.UserName);
}
return AllServers;
};
case "wait":
return () =>
{
var ms = Support.Int(p[0]);
Thread.Sleep(ms);
return null;
};
case "input":
return () =>
{
return new Dictionary<string, object>(vget, StringComparer.OrdinalIgnoreCase);
};
case "access":
return () =>
{
//if (!this.IsAdmin)
//{
// throw new NoSecurityException("用户[" + this.UserName + "]没有权限调用函数:", "access");
//}
if (p.Count > 2)
{
}
if (p.Count == 2)
{
string username = p[0]._Str().ToLower();
if (string.IsNullOrEmpty(username))
{
return false;
}
BsonDocument userdoc = null;
if (username._Length() == 24)
{
userdoc = this.FindDocumentById(UserCollection, username, new string[] { PassWordFlag, SysTokenFlag, NameFlag });//, IsAdminFlag
}
else
{
userdoc = this.FindDocumentByName(UserCollection, username, new string[] { PassWordFlag, SysTokenFlag, NameFlag });//, IsAdminFlag
}
if (userdoc == null)
{
throw new NotExistException("用户不存在:" + username);
}
//var isadmin = userdoc.GetBool(IsAdminFlag);
if (this.IsAdmin)//isadmin &&
{
}
else
{
string password = p[1]._Str()._MD5();
if (userdoc.GetString(PassWordFlag) != password)
{
throw new WrongPasswordException("用户密码错误:" + username);
}
}
var usertoken = userdoc.GetString(SysTokenFlag);
this.Init(usertoken);
return true;
//this.AccessToken = userdoc.GetString(SysTokenFlag);
//this.AccessUser = userdoc.GetString(NameFlag);
//this.AccessUserId = userdoc.GetString(IDFlag);
}
string user = null;
if (string.IsNullOrEmpty(this.SourceName))
{
user = this.GetFirstName(this.ClientInfo.PageSource);
}
else
{
user = this.GetFirstName(this.SourceName);
}
if (!string.IsNullOrEmpty(user))
{
string token = this.GetSysToken(user, true);
this.Init(token);
}
bool forowner = false;
if (p.Count == 1)
{
forowner = p[0]._Bool();
}
if (!forowner)
{
if (this.IsAdmin)
{
this.Init(this.AccessToken);
}
else
{
//throw new NoSecurityException("用户[" + this.UserName + "]没有权限调用函数:", "access");
}
}
return true;
};
case "runds":
return () =>
{
var wf = p[0]._Str();
if (wf.StartsWith("/$"))
{
string st = this.GetSystemFileString(DataClient.SystemSettingFileName);
var setjson = st._Dic2();
var dspath = setjson._Value("dspath")._Str();
if (!string.IsNullOrEmpty(dspath))
{
wf = "/" + dspath.Trim('/') + "/" + wf.TrimStart("/$".ToArray());
}
}
var para = p[1] as Dictionary<string, object>;
var mytoken = this.CopyToken();
mytoken.input = para;
var wfhelper = new WorkflowHelpler();
var r = wfhelper.GetResultByName(this, mytoken, wf, null, timeout: p[2]._Int());
return r;
};
case "run":
case "job":
return () =>
{
var wf = p[0]._Str();
if (wf.StartsWith("/$"))
{
string st = this.GetSystemFileString(DataClient.SystemSettingFileName);
var setjson = st._Dic2();
var dspath = setjson._Value("dspath")._Str();
if (!string.IsNullOrEmpty(dspath))
{
wf = "/" + dspath.Trim('/') + "/" + wf.TrimStart("/$".ToArray());
}
}
//if (p.Count == 1)
//{
// return RunMyFunction(wf, p, vget, script)();
//}
//var tokenObj = this.CopyToken();
this.PulishJob(this.SysToken, wf, Support.Number(p[1]), p[2]._Str());
return null;
};
case "iid":
return () =>
{
var iid = p[0]._Str();
string realid = this.GetRealInstanceName(iid, null);
return realid;
};
case "sessions":
return () =>
{
return GetAllSessionsOnServers();
};
case "onlines":
return () =>
{
var iid = p[0]._Str();
string realid = this.GetRealInstanceName(iid, null);
return GetOnlinesOnServers(realid);
};
case "subs":
return () =>
{
var iid = p[0]._Str();
string realid = this.GetRealInstanceName(iid, null);
return GetSubscribersOnServers(realid);
};
case "jobs":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限", "jobs");//("jobs()", this.UserName);
}
var list = this.GetAllJobs();
return list;
};
case "myjobs":
return () =>
{
var team = p[0]._Str();
string userid;
//
IMongoQuery q = null;
string checkgroup = string.Empty;
if (!string.IsNullOrEmpty(team))
{
var docteam = this.FindDocumentById(TeamCollection, team, new string[] { "_us", UserFlag, NameFlag, "_g" });
bool hassecurity = false;
string teamname = team;
if (docteam != null)
{
teamname = docteam.GetString(NameFlag);
userid = docteam.GetString(UserFlag);
if (userid == this.UserId)
{
hassecurity = true;
}
else
{
BsonArray ba = docteam.GetArray("_us");
foreach (var b in ba)
{
var id = b.GetString("id");
if (id == "*")
{
hassecurity = true;
break;
}
var ok = b.GetBool("ok");
if (ok && id == this.UserId)
{
hassecurity = true;
break;
}
}
}
}
if (!hassecurity)
{
throw new NoSecurityException("用户[" + this.UserName + "]没有团队[" + teamname + "]访问权限");
}
string _g = docteam.GetString("_g");
userid = docteam.GetString(UserFlag);
if (string.IsNullOrEmpty(_g))
{
q = Query.EQ(IDFlag, string.Empty);
}
else
{
checkgroup = "/" + _g.Trim('/');
q = Query.EQ(UserFlag, docteam.GetString(UserFlag));
}
}
else
{
q = Query.EQ(UserFlag, this.UserId);
}
//
Dictionary<string, object> myjobs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
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" });
foreach (var doc in docs)
{
var wfobj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
var wfid = doc["_wf"].AsString;
var d = this.FindDocumentById(FileCollection, wfid, new string[] { NameFlag });
string wfname = d.GetString(NameFlag);
if (!("/" + wfname).StartsWith(checkgroup))
{
continue;
}
doc["wfname"] = wfname;
myjobs[wfid] = doc.ToDictionary();
}
return myjobs;
};
case "cookies":
return () =>
{
this.Cookies = new List<MyCookie>();
var cookies = p[0] as Dictionary<string, object>;
foreach (var cookie in cookies)
{
MyCookie c = new MyCookie() { Name = cookie.Key, Value = cookie.Value._Str() };
c.Scope = this.UserName;
//c.Expires = DateTime.UtcNow.Add(TimeSpan.FromMinutes(30));
var pp = p[1];
c.Expires = pp._Time();
this.Cookies.Add(c);
}
return null;
};
case "out":
return () =>
{
this.Output = p[0] as Dictionary<string, object>;
return null;
};
case "cachedtime":
return () =>
{
return this.cachetime;
};
case "cache":
return () =>
{
this.IsCache = true;
return null;
};
case "redirect":
return () =>
{
throw new RedirectException(p[0]._Str());
};
case "md5":
return () =>
{
return p[0]._Str()._MD5();
};
case "aes.encode":
return () =>
{
return aes.Encrypt(p[0]._ObjBytes(), p[1]._ObjBytes());
};
//case "aes.decode":
// return () =>
// {
// return CommonFunction.AESDecrypt(p[0]._ObjBytes(), p[1]._Str(), p[2]._ObjBytes());
// };
case "sms":
return () =>
{
string accessKeyId = p[0]._Str();
string accessKeySecret = p[1]._Str();
string PhoneNumbers = p[2]._Str();
string SignName = p[3]._Str();
string TemplateCode = p[4]._Str();
Dictionary<string, object> TemplateParam = p[5] as Dictionary<string, object>;
var result = AliyunSms.SendSms(accessKeyId, accessKeySecret, PhoneNumbers, SignName, TemplateCode, TemplateParam);
return result;
};
case "email":
return () =>
{
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());
return true;
};
case "page":
return () =>
{
return this.ClientInfo.PageSource;
};
case "method":
return () =>
{
return this.ClientInfo.PageMethod;
};
case "query":
return () =>
{
return this.ClientInfo.PageQuery;
};
case "referer":
return () =>
{
return this.ClientInfo.Referer;
};
case "ip":
return () =>
{
return this.ClientInfo.IP;
};
case "bytelimit":
return () =>
{
return ServerInfo.ByteLimit;
};
case "v":
return () =>
{
Dictionary<string, object> r = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
string validateId;
string vcode;
string url = p[0].ToString();
CreateValidate(url, out validateId, out vcode);
r["vid"] = validateId;
r["vcode"] = vcode;
r["query"] = vget;
r["source"] = this.ClientInfo.Referer;
return r;
};
case "log.set":
return () =>
{
string type = p[0]._Str();
string msg = p[1]._Str();
string feature = p[2]._Str();
this.PublishUserLog(type, msg, feature, p[3] as Dictionary<string, object>);
return true;
};
case "log.get":
return () =>
{
string type = p[0]._Str();
int page = p[1]._Int();
int pagesize = p[2]._Int();
string query = p[3]._Str();
List<string> fields = p[4]._StrList();
return this.GetUserLog(type, page, pagesize, query, vget: vget, fields: fields);
};
case "clearuserlog":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限", v);//("clearlog", this.UserName);
}
return this.ClearLog(UserLogCollection, p[0]._Int());
};
case "user":
return () =>
{
string username = this.AccessUser;
return username;
};
case "userid":
return () =>
{
string username = this.AccessUserId;
return username;
};
case "isadmin":
return () =>
{
return this.IsAdmin;
};
case "accessuser":
return () =>
{
Dictionary<string, object> info2 = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
info2["name"] = "";
info2["isadmin"] = "";
var u = this.FindDocumentById(UserCollection, this.AccessUserId, new string[] { LNameFlag, IsAdminFlag });
if (u != null)
{
info2["name"] = u.GetString(LNameFlag);
info2["isadmin"] = u.GetBool(IsAdminFlag);
}
return info2;
};
case "client":
return () =>
{
var r = this.ClientInfo.ToDictionary();
var input = r.GetDic("input");
if (input == null)
{
r["input"] = vget;
}
return r;
};
case "template.symbols":
return () =>
{
var tid = p[0]._Str();
var noinst = p[1]._Bool();
var relative = p[2]._Bool();
var ismobile = this.ClientInfo.UserAgent._IsMobileDevice();
var symbols = GetSymbolFromTemplate(tid, noinst, relative, ismobile, vget: vget);
return symbols;
};
case "ismobile":
return () =>
{
var agent = p[0]._Str();
if (string.IsNullOrEmpty(agent))
{
agent = this.ClientInfo.UserAgent;
}
var ismobile = agent._IsMobileDevice();
return ismobile;
};
case "template.allsymbols":
return () =>
{
var tid = p[0]._Str();
var symbols = GetSymbolFromTemplate(tid, true, false, false, vget, true);
return symbols;
};
case "share.symbols":
return () =>
{
var symbols = GetSymbolFromSetting(p[0]._Str(), p[1]._Str());
return symbols;
};
case "ref.refresh":
return () =>
{
var tid = p[0]._Str();
string root;
string property;
tid = this.GetTemplateId(tid, out root, out property);
this.CheckSecurity(root, CollectionType.Template, SecurityType.Read);
tid = root + property;
List<BsonDocument> instances = new List<BsonDocument>();
List<string> fs = new List<string> { NameFlag, UserFlag };
var docs2 = this.dbHelper.Find(InstanceCollection, Query.EQ(TemplateFlag, root), fs);
foreach (var doc in docs2)
{
doc.Add("fullname", "/" + doc.GetString(IDFlag) + property);
instances.Add(doc);
}
List<string> scripts = new List<string>();
var q1 = Query.ElemMatch("_r", Query.EQ("rid", root));
var expdoc = this.dbHelper.Find(TemplateCollection, q1, new List<string> { "_r" });
foreach (var exp in expdoc)
{
var myid = exp.GetString(IDFlag);
var mytids = exp.GetArray("_r");
foreach (var mytid in mytids)
{
var iidstr = mytid.GetString("rid");
if (iidstr != root)
{
continue;
}
var tidstr = mytid.GetString("tid");
string root2 = string.Empty;
string property2 = string.Empty;
tidstr = this.GetTemplateId(myid + "." + tidstr, out root2, out property2);
IMongoQuery q = Query.And(Query.EQ(TemplateFlag, root2));
var docs = this.dbHelper.Find(InstanceCollection, q, fs);
foreach (var doc in docs)
{
var iid = doc.GetString(IDFlag) + property2;
string fullname = "/" + iid + property;
doc.Add("fullname", fullname);
instances.Add(doc);
}
}
}
foreach (var doc in instances)
{
//var property2 = doc.GetString("property2");
//var iid = doc.GetString(IDFlag) + property2;
this.InstanceId = doc.GetString(IDFlag);
string tempId = null;
string userId = null;
BsonDocument instDoc = null;
string keyBase = null;
string keyFlag = null;
string instRoot = null;
BsonDocument tempDoc;
string clientname;
string fullname = doc.GetString("fullname");// "/" + iid + property;
this.GetInstanceInformation(fullname, out instRoot, out userId, out keyBase, out keyFlag, out instDoc, out tempDoc, out clientname, out tempId, SecurityType.Read, null);
BsonValue bv;
if (tempDoc.TryGetValue(Definitions.ValueFlag, out bv))
{
string valueexp = bv.ToString().Trim();
if (valueexp.StartsWith("="))
{
var data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
data["this"] = clientname;
Dictionary<string, object> inputs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
inputs["value"] = this.myInstanceModels;
data["data()"] = inputs;
string scriptstring = clientname + valueexp;
this.RunScript(scriptstring, data);
scripts.Add(scriptstring);
}
}
}
return scripts;
};
case "template.instances":
return () =>
{
var tid = p[0]._Str();
var query = p[1]._Str();
var fields = p[2] as ArrayList;
List<string> flist = null;
if (fields != null)
{
flist = new List<string>();
foreach (var f in fields)
{
flist.Add(f._Str());
}
}
var sortby = p[3] as Dictionary<string, object>;
var instances = GetInstancesByTemplate(tid, query, flist, sortby, vget: vget);
return instances;
};
case "src":
return () =>
{
if (string.IsNullOrEmpty(this.SourceName))
{
return this.ClientInfo.PageSource;
}
return this.SourceName;
};
case "pageowner":
return () =>
{
var top = p[0]._Bool();
if (top)
{
return this.GetFirstName(this.ClientInfo.PageSource);
}
if (string.IsNullOrEmpty(this.SourceName))
{
return this.GetFirstName(this.ClientInfo.PageSource);
}
string user = this.GetFirstName(this.SourceName);
return user;
};
case "owner":
return () =>
{
return this.UserName;
//return this.ClientInfo.UserName;
};
case "user.find":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限");
}
string p0 = p[0]._Str();
IMongoQuery q = Query.Null;
if (!string.IsNullOrEmpty(p0))
{
q = Query.Matches(LNameFlag, new BsonRegularExpression("/.*" + p0.ToLower() + ".*/"));
}
var docs = dbHelper.Find(UserCollection, q, new List<string> { NameFlag, EmailFlag, PhoneFlag, NickNameFlag, "_lasttime", "_lastip" }, 100);
return docs.ToDictionaryList();
};
case "ws":
return () =>
{
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
string s = WsRoleServers.AvailableServer.Address;
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
string[] ss = s.Split('|');
string port = ss[1];
string ws = "ws";
if (this.ClientInfo.Protocol == "https")
{
ws = "wss";
port = ss[2];
}
string portstr = ":" + port;
if (port == "80" || port == "443")
{
portstr = string.Empty;
}
var ip = ss[0];
if (ip == "localhost")
{
ip = ServerInfo.ServerIP;
}
string wsip = ws + "://" + ip + portstr;
return wsip;
};
#endregion
#region Team Function
case "team.shares":
return () =>
{
string teamid = p[0]._Str();
if (string.IsNullOrEmpty(teamid))
{
var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["rows"] = null;
result["count"] = 0;
return result;
}
var doc = this.FindDocumentById(TeamCollection, teamid, new string[] { UserFlag, "_us", "_g" });
if (doc == null)
{
throw new NotExistException("团队不存在:" + teamid);
}
bool isok = false;
string userid = doc.GetString(UserFlag);
if (userid == this.UserId)
{
isok = true;
}
else
{
BsonArray ba = doc["_us"].AsBsonArray;
foreach (var b in ba)
{
string id = b.GetString("id");
if (id == "*")
{
isok = true;
break;
}
if (id == this.UserId)
{
isok = true;
break;
}
}
}
if (!isok)
{
throw new NoSecurityException("没有共享", teamid);
}
string t = p[1]._Str();
string search = p[2]._Str();
int page = p[3]._Int();
int pagesize = p[4]._Int();
string collection = FileCollection;
string group = "/" + doc.GetString("_g").Trim('/');
IMongoQuery q = Query.Matches(LGroupFlag, new BsonRegularExpression("^" + group)); // Query.EQ(TeamFlag, teamid);
switch (t)
{
case "template":
collection = TemplateCollection;
break;
case "instance":
collection = InstanceCollection;
break;
case "file":
collection = FileCollection;
//q = Query.And(q, Query.Or(Query.EQ(TypeFlag, ".html"), Query.EQ(TypeFlag, ".zip")));
break;
}
if (!string.IsNullOrEmpty(search))
{
string lsearch = search.ToLower();
IMongoQuery mq = Query.Or(Query.Matches(LNameFlag, new BsonRegularExpression(lsearch)), Query.Matches(LDescriptionFlag, new BsonRegularExpression(lsearch)));
q = Query.And(q, mq);
}
var fields = new List<string> { NameFlag, DescriptionFlag, ModifiedFlag, "_user" };
return this.dbHelper.FindPage(collection, q, page, pagesize, fields, sortby: new SortByDocument(ModifiedFlag, -1));
};
case "shareteams":
return () =>
{
int page = p[0]._Int();
int pagesize = p[1]._Int();
string search = p[2]._Str();
IMongoQuery q1 = Query.EQ(UserFlag, this.UserId);
//IMongoQuery q4 = Query.EQ("id", "*");
IMongoQuery q5 = Query.EQ("id", this.UserId);
IMongoQuery q6 = Query.EQ("ok", true);
var qus1 = Query.ElemMatch("_us", Query.And(q5, q6));
var q = Query.Or(q1, qus1);
List<BsonDocument> result = new List<BsonDocument>();
if (!string.IsNullOrEmpty(search))
{
string lsearch = search.ToLower();
IMongoQuery mq = Query.Or(Query.Matches(LNameFlag, new BsonRegularExpression(lsearch)), Query.Matches(LDescriptionFlag, new BsonRegularExpression(lsearch)));
qus1 = Query.And(qus1, mq);
}
var docs = this.dbHelper.FindPage(TeamCollection, q, page, pagesize, new List<string> { NameFlag, ModifiedFlag, DescriptionFlag, "_owner", "_users", "_g" }, sortby: new SortByDocument(ModifiedFlag, -1));
return docs;
};
case "team.users":
return () =>
{
string filename = p[0]._Str();
string type = p[1]._Str();
var users = this.GetTeamUsers(type, filename);
return users;
};
case "team.info":
return () =>
{
string teamid = p[0]._Str();
if (string.IsNullOrEmpty(teamid))
{
throw new NotExistException("团队id为空!");
}
var doc4 = this.dbHelper.FindDocumentByQuery(TeamCollection, Query.EQ(IDFlag, teamid), new string[] { IDFlag, NameFlag, UserFlag, "_us" });
if (doc4 == null)
{
throw new NotExistException("团队不存在:" + teamid);
//throw new NoSecurityException("没有权限", teamid);
}
bool hassec = false;
if (doc4.GetString(UserFlag) == this.UserId)
{
hassec = true;
}
else
{
BsonArray usdoc = doc4["_us"] as BsonArray;
foreach (var ud in usdoc)
{
string userid = ud.GetString("id");
bool ok = ud.GetBool("ok");
if (userid == "*" || (userid == this.UserId && ok))
{
hassec = true;
break;
}
}
}
if (!hassec)
{
throw new NoSecurityException("没有权限:", teamid);
}
Dictionary<string, object> dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
dic["id"] = doc4.GetString(IDFlag);
dic["name"] = doc4.GetString(NameFlag);
string uid = doc4.GetString(UserFlag);
string uname = this.GetUserName(uid);
dic["user"] = uname;
return dic;
};
case "team.list":
return () =>
{
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var docs = this.dbHelper.Find(TeamCollection, q, new List<string> { NameFlag, ModifiedFlag, DescriptionFlag, "_owner", "_users", "_g" }, sortby: new SortByDocument(ModifiedFlag, -1));
return docs;
};
case "team.joined":
return () =>
{
IMongoQuery q = Query.NE(UserFlag, this.UserId);
IMongoQuery q4 = Query.EQ("id", "*");
IMongoQuery q1 = Query.EQ("id", this.UserId);
IMongoQuery q2 = Query.EQ("ok", true);
IMongoQuery q3 = Query.EQ("ok", false);
var qus1 = Query.ElemMatch("_us", Query.Or(q4, Query.And(q1, q2)));
var qus2 = Query.ElemMatch("_us", Query.And(q1, q3));
List<BsonDocument> result = new List<BsonDocument>();
var docs = this.dbHelper.Find(TeamCollection, Query.And(q, qus1), new List<string> { NameFlag, ModifiedFlag, DescriptionFlag, "_owner", "_users", "_g" }, sortby: new SortByDocument(ModifiedFlag, -1));
foreach (var doc in docs)
{
doc.Add("_ok", true);
result.Add(doc);
}
var docs2 = this.dbHelper.Find(TeamCollection, Query.And(q, qus2), new List<string> { NameFlag, ModifiedFlag, DescriptionFlag, "_owner", "_users", "_g" }, sortby: new SortByDocument(ModifiedFlag, -1));
foreach (var doc in docs2)
{
doc.Add("_ok", false);
result.Add(doc);
}
return result;
};
case "team.add":
return () =>
{
var result = this.PublishTeam(null, p[0]._Str(), p[1]._Str(), p[2]._Str(), p[3]._Str());
return result;
};
case "team.update":
return () =>
{
var result = this.PublishTeam(p[0]._Str(), p[1]._Str(), p[2]._Str(), p[3]._Str(), p[4]._Str());
return result;
};
case "team.remove":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有权限", v);
}
string id = p[0]._Str();
var myteam = this.FindDocumentById(TeamCollection, id, new string[] { UserFlag });
if (myteam == null)
{
throw new NotExistException("团队不存在");
}
if (myteam[UserFlag].ToString() != this.UserId)
{
throw new NoSecurityException("没有权限", myteam.GetString(NameFlag));
}
IMongoQuery q = Query.EQ(IDFlag, id);
this.dbHelper.Remove(TeamCollection, q);
return null;
};
case "team.join":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有权限", v);
}
string id = p[0]._Str();
IMongoQuery q1 = Query.EQ(IDFlag, id);
IMongoQuery q2 = Query.ElemMatch("_us", Query.EQ("id", this.UserId));
var myteam = this.dbHelper.FindDocumentByQuery(TeamCollection, Query.And(q1, q2), new string[] { "_us", "_uid", "_name" });
if (myteam == null)
{
throw new NotExistException("团队不存在或未共享:" + id);
}
IMongoQuery q = Query.EQ(IDFlag, id);
BsonDocument doc = new BsonDocument();
doc.Add("_us.$.ok", p[1]._Bool());
this.dbHelper.Update(TeamCollection, id, doc, q: Query.And(q1, q2));
string uid = myteam["_uid"].ToString();
BsonArray usdoc = myteam["_us"] as BsonArray;
List<string> userslist = new List<string>();
userslist.Add(uid);
if (!userslist.Contains(this.UserId))
{
userslist.Add(this.UserId);
}
foreach (var ud in usdoc)
{
string userid = ud.GetString("id");
bool ok = ud.GetBool("ok");
if (ok)
{
if (!userslist.Contains(userid))
{
userslist.Add(userid);
}
}
}
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["id"] = myteam.GetString(IDFlag);
result["name"] = myteam.GetString(NameFlag);
result["members"] = userslist;
result["owner"] = this.GetUserName(uid);
result["username"] = this.UserName;
result["add"] = p[1]._Bool();
return result;
};
#endregion
#region Data Function
case "dataquery":
return () =>
{
var iid = p[0]._Str();
var mode = p[1]._Str();
var type = p[2]._Str();
var cachename = p[3]._Str();
if (string.IsNullOrEmpty(iid))
{
throw new EmptyNameException("实例名不能为空");
}
int index = iid.IndexOf('.');
this.CheckSecurity(iid.Substring(0, index), CollectionType.Instance, SecurityType.Read);
string cname = null;
if (!string.IsNullOrEmpty(cachename))
{
cname = cachename + "|" + iid + "|" + mode + "|" + type;
List<Dictionary<string, object>> data;
if (MapReduceCaches.Get<List<Dictionary<string, object>>>(cname, out data))
{
return data;
}
}
IMongoQuery q = Query.EQ("id", iid);
DateTime from;
Func<BsonDocument, DateTime> getDate = null;
Dictionary<DateTime, object> result = new Dictionary<DateTime, object>();
var now = DateTime.UtcNow;
switch (mode)
{
case "year":
var count = 3;
var fromdate = now.AddYears(count * -1);
from = Support.Date(fromdate.Year);
for (int i = 0; i < count; i++)
{
result.Add(from.AddYears(i), null);
}
getDate = (doc) =>
{
var dt = doc.GetDateTime("doc._time");
return Support.Date(dt.Year);
};
break;
case "month":
count = 12;
fromdate = now.AddMonths(count * -1);
from = Support.Date(fromdate.Year, fromdate.Month);
for (int i = 0; i < count; i++)
{
result.Add(from.AddMonths(i), null);
}
getDate = (doc) =>
{
var dt = doc.GetDateTime("doc._time");
return Support.Date(dt.Year, dt.Month);
};
break;
case "day":
count = 30;
fromdate = now.AddDays(count * -1);
from = Support.Date(fromdate.Year, fromdate.Month, fromdate.Day);
for (int i = 0; i < count; i++)
{
result.Add(from.AddDays(i), null);
}
getDate = (doc) =>
{
var dt = doc.GetDateTime("doc._time");
return Support.Date(dt.Year, dt.Month, dt.Day);
};
break;
case "hour":
count = 24;
fromdate = now.AddHours(count * -1);
from = Support.Date(fromdate.Year, fromdate.Month, fromdate.Day, fromdate.Hour);
for (int i = 0; i < count; i++)
{
result.Add(from.AddHours(i), null);
}
getDate = (doc) =>
{
var dt = doc.GetDateTime("doc._time");
return Support.Date(dt.Year, dt.Month, dt.Day, dt.Hour);
};
break;
case "minute":
count = 60;
fromdate = now.AddMinutes(count * -1);
from = Support.Date(fromdate.Year, fromdate.Month, fromdate.Day, fromdate.Hour, fromdate.Minute);
for (int i = 0; i < count; i++)
{
result.Add(from.AddMinutes(i), null);
}
getDate = (doc) =>
{
var dt = doc.GetDateTime("doc._time");
return Support.Date(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute);
};
break;
case "second":
count = 60;
fromdate = now.AddSeconds(count * -1);
from = Support.Date(fromdate.Year, fromdate.Month, fromdate.Day, fromdate.Hour, fromdate.Minute, fromdate.Second);
for (int i = 0; i < count; i++)
{
result.Add(from.AddSeconds(i), null);
}
getDate = (doc) =>
{
var dt = doc.GetDateTime("doc._time");
return Support.Date(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
};
break;
default:
throw new InvalidParameterException();
}
q = Query.And(q, Query.GTE("time", from));
var docs = this.dbHelper.Find("InstanceHistory", q, new List<string>() { "doc._time", "doc._value" });
Func<IEnumerable<BsonDocument>, decimal> getSum = null;
switch (type)
{
case "count":
getSum = (a) => { return a.Count(); };
break;
case "sum":
getSum = (a) => { return a.Sum(c => c.GetDecimal("doc._value")); };
break;
case "average":
getSum = (a) => { return a.Average(c => c.GetDecimal("doc._value")); };
break;
case "min":
getSum = (a) => { return a.Min(c => c.GetDecimal("doc._value")); };
break;
case "max":
getSum = (a) => { return a.Max(c => c.GetDecimal("doc._value")); };
break;
default:
throw new InvalidParameterException();
}
var groupList = docs.GroupBy(m => new
{
Key = getDate(m)
}).
Select(a => new
{
Key = a.Key.Key,
Value = getSum(a)
}).ToList();
foreach (var kv in groupList)
{
result[kv.Key] = Math.Round(kv.Value, 2);
}
List<Dictionary<string, object>> output = new List<Dictionary<string, object>>();
foreach (var kv in result)
{
Dictionary<string, object> o = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
o["_id"] = kv.Key;
o["value"] = kv.Value;
output.Add(o);
}
if (!string.IsNullOrEmpty(cname))
{
MapReduceCaches.Add(cname, output);
}
return output;
};
case "instancehistory":
return () =>
{
var iid = p[0]._Str();
if (string.IsNullOrEmpty(iid))
{
throw new EmptyNameException("实例名不能为空");
}
int index = iid.IndexOf('.');
this.CheckSecurity(iid.Substring(0, index), CollectionType.Instance, SecurityType.Read);
var cachename = p[6]._Str();
string cname = null;
if (!string.IsNullOrEmpty(cachename))
{
cname = cachename + "|" + iid + "|" + this.UserId;
List<Dictionary<string, object>> data;
if (MapReduceCaches.Get<List<Dictionary<string, object>>>(cname, out data))
{
return data;
}
}
var query = p[1]._Str();
IMongoQuery q = Query.EQ("doc.id", iid);
if (!string.IsNullOrEmpty(query))
{
q = Query.And(q, this.GetMyQuery(query, (name) =>
{
return name;
}, (name, value) =>
{
return BsonTypeMapper.MapToBsonValue(value);
}, vget));
}
var map = script.GetFunctionDef(p.Get(2).Name);
var reduce = script.GetFunctionDef(p.Get(3).Name);
var finalize = script.GetFunctionDef(p.Get(4).Name);
var para = p[5] as Dictionary<string, object>;
var result = this.GetMapReduceResult("InstanceHistory", q, map, reduce, finalize, para, cname);
return result;
};
case "mapreduce":
return () =>
{
var cachename = p[6]._Str();
if (!string.IsNullOrEmpty(cachename))
{
List<Dictionary<string, object>> data;
if (MapReduceCaches.Get<List<Dictionary<string, object>>>(cachename + "|" + this.UserId, out data))
{
return data;
}
}
var collection = p[0]._Str();
var query = p[1]._Str();
IMongoQuery q = Query.And(Query.EQ(UserFlag, this.UserId));
if (!string.IsNullOrEmpty(query))
{
q = Query.And(q, this.GetMyQuery(query, (name) =>
{
return name;
}, (name, value) =>
{
return BsonTypeMapper.MapToBsonValue(value);
}, vget));
}
var map = script.GetFunctionDef(p.Get(2).Name);
var reduce = script.GetFunctionDef(p.Get(3).Name);
var finalize = script.GetFunctionDef(p.Get(4).Name);
var para = p[5] as Dictionary<string, object>;
var result = this.GetMapReduceResult(collection, q, map, reduce, finalize, para, cachename);
return result;
};
case "data.union":
return () =>
{
var datas = p[0] as ArrayList;
var fields = p[1] as ArrayList;
var page = p[2]._Int();
var pagesize = p[3]._Int();
var sort = p[4] as Dictionary<string, object>;
SortByDocument sortby = new SortByDocument(sort);
var result = new List<Dictionary<string, object>>();
foreach (var table in datas)
{
var data = table as ArrayList;
foreach (var dic in data)
{
int i = 0;
var mydata = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
var d = dic as Dictionary<string, object>;
foreach (var kv in d)
{
mydata[fields[i]._Str()] = kv.Value;
i++;
}
result.Add(mydata);
}
}
var count = result.Count;
result = DataClient.Sort(result, sortby);
int skip = -1;
int limit = -1;
if (page > 0 && pagesize > 0)
{
skip = (page - 1) * pagesize;
limit = pagesize;
}
if (skip >= 0 || limit >= 0)
{
IEnumerable<Dictionary<string, object>> mr = result;
if (skip >= 0)
{
mr = mr.Skip(skip);
}
if (limit >= 0)
{
mr = mr.Take(limit);
}
result = mr.ToList();
}
Dictionary<string, object> result2 = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result2["count"] = count;
result2["rows"] = result;
return result2;
};
case "data.backup":
return () =>
{
return null;
};
case "data.querycount":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var query = p[1]._Str();
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
var tdoc = this.GetTemplateNode(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
//q = Query.And(q, Query.EQ(TemplateFlag, tid));
var collection = DataCollection + "_" + tid;
if (!string.IsNullOrEmpty(query))
{
var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
this.CheckTemplate(tempdoc);
tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
IMongoQuery q2 = this.GetMyQuery(query,
(name) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
return lname;
}
return Definitions.ValueFlag + property + "." + lname;
},
(name, value) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
return value._Str();
case "_created":
case "_modified":
return Convert.ToDateTime(value);
case "_muser":
return value._Str();
}
if (!string.IsNullOrEmpty(property))
{
name = property.Trim('.') + "." + lname;
}
BsonDocument doc = tempdoc.Value(name) as BsonDocument;
var dbindex = doc.GetBool("_dbindex");
var _dbunique = doc.GetBool("_dbunique");
if (dbindex || _dbunique)
{
DatabaseHelper.CheckIndex(collection, new string[] { Definitions.ValueFlag + property + "." + lname }, _dbunique);
}
//if(doc)
return this.ConvertType(doc.Type(), value._Str(), doc.Array());
}, vget
);
if (q2 != null)
{
q = Query.And(q, q2);
}
}
var count = this.dbHelper.Count(collection, q);
return count;
};
case "data.status":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
var tdoc = this.GetTemplateNode(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
var collection = DataCollection + "_" + tid;
return this.dbHelper.GetStats(collection);
};
case "data.list":
case "data.query":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (string.IsNullOrEmpty(tid))
{
return null;
}
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var query = p[1]._Str();
var page = p[2]._Int(1);
var pagesize = p[3]._Int(100);
var sortby = p[4] as Dictionary<string, object>;
var fs = p[5] as ArrayList;
var expain = p[6]._Bool();
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
var tdoc = this.GetTemplateNode(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
//q = Query.And(q, Query.EQ(TemplateFlag, tid));
var collection = DataCollection + "_" + tid;
var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
this.CheckTemplate(tempdoc);
tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
Dictionary<string, object> myvalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
this.GetInstance(null, tid, SecurityType.Read, ref myvalues, emptyid: Definitions.ValueFlag + property, initvalues: null, once: true, usename: true);
var valuedic2 = myvalues._DicKeyObjects(Definitions.ValueFlag);
if (!string.IsNullOrEmpty(query))
{
IMongoQuery q2 = this.GetMyQuery(query,
(name) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
return lname;
}
return Definitions.ValueFlag + property + "." + lname;
},
(name, value) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
return value._Str();
case "_created":
case "_modified":
return Convert.ToDateTime(value);
case "_muser":
return value._Str();
}
if (!string.IsNullOrEmpty(property))
{
name = property.Trim('.') + "." + lname;
}
BsonDocument doc = tempdoc.Value(name) as BsonDocument;
var dbindex = doc.GetBool("_dbindex");
var _dbunique = doc.GetBool("_dbunique");
if (dbindex || _dbunique)
{
DatabaseHelper.CheckIndex(collection, new string[] { Definitions.ValueFlag + property + "." + lname }, _dbunique);
}
//if(doc)
return this.ConvertType(doc.Type(), value._Str(), doc.Array());
}, vget
);
if (q2 != null)
{
q = Query.And(q, q2);
}
}
List<string> ffs = new List<string>();
Dictionary<string, object> fdic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
if (fs == null)
{
ffs.Add(IDFlag);
}
else
{
foreach (var f in fs)
{
string ftr = f.ToString();
var lname = ftr.ToLower();
if (lname.StartsWith("$"))
{
lname = lname.Substring(1);
if (lname == "_value")
{
foreach (var kv in valuedic2)
{
fdic[kv.Key] = kv.Value;
}
}
ffs.Add(lname);
}
else
{
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
case "_value":
if (lname == "_value")
{
foreach (var kv in valuedic2)
{
fdic[kv.Key] = kv.Value;
}
}
ffs.Add(lname);
break;
default:
BsonElement e;
if (tempdoc.TryGetElement(lname, out e))
{
ffs.Add(Definitions.ValueFlag + property + "." + lname);
fdic[e.Name] = valuedic2[e.Name];
}
break;
}
}
}
}
SortByDocument sdoc = null;
if (sortby != null)
{
sdoc = new SortByDocument();
foreach (var kv in sortby)
{
var lname = kv.Key;
if (lname.StartsWith("$"))
{
sdoc[lname.Substring(1)] = BsonValue.Create(kv.Value);
}
else
{
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
sdoc[lname] = BsonValue.Create(kv.Value);
break;
default:
sdoc[Definitions.ValueFlag + property + "." + lname] = BsonValue.Create(kv.Value);
break;
}
}
}
}
Func<List<BsonDocument>, List<Dictionary<string, object>>> mapping = (ds) =>
{
List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
foreach (var doc in ds)
{
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var kv in doc)
{
var k = kv.Name;
if (k == "_value")
{
var valuedoc = kv.Value as BsonDocument;
var value = new Dictionary<string, object>(fdic, StringComparer.OrdinalIgnoreCase);
var keys = value.Keys.ToArray();
foreach (var key in keys)
{
BsonValue value2;
if (valuedoc.TryGetValue(key.ToLower(), out value2))
{
value[key] = value2.Value();
}
}
result[k] = value;
}
else
{
result[k] = kv.Value.Value();
}
}
//BsonValue _value;
//if (doc.TryGetValue("_value", out _value))
//{
// Dictionary<string, object> valuedic = _value as Dictionary<string, object>;
// foreach (var f in ffs)
// {
// if (f.StartsWith("_value."))
// {
// var key = f.Substring(7);
// object obj;
// if (!valuedic._TryGet(key, out obj))
// {
// //valuedic._Set(key, tempdoc.Value(key).Value("_value").Value());
// var val = tempdoc.Value(key) as BsonDocument;
// var o = this.ConvertType(val.Type(), val.GetString("_value"), val.Array()).Value();
// valuedic._Set(key, o);
// }
// }
// }
results.Add(result);
}
return results;
};
var docs = this.dbHelper.FindPage(collection, q, page, pagesize, ffs, sdoc, mapping, expain);
//docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
return docs;
};
case "data.deletebyquery":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var query = p[1]._Str();
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
var tdoc = this.GetTemplateNode(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
//q = Query.And(q, Query.EQ(TemplateFlag, tid));
var collection = DataCollection + "_" + tid;
if (!string.IsNullOrEmpty(query))
{
var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
this.CheckTemplate(tempdoc);
tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
IMongoQuery q2 = this.GetMyQuery(query,
(name) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
return lname;
}
return Definitions.ValueFlag + property + "." + lname;
},
(name, value) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
return value._Str();
case "_created":
case "_modified":
return Convert.ToDateTime(value);
case "_muser":
return value._Str();
}
if (!string.IsNullOrEmpty(property))
{
name = property.Trim('.') + "." + lname;
}
BsonDocument doc = tempdoc.Value(name) as BsonDocument;
var dbindex = doc.GetBool("_dbindex");
var _dbunique = doc.GetBool("_dbunique");
if (dbindex || _dbunique)
{
DatabaseHelper.CheckIndex(collection, new string[] { Definitions.ValueFlag + property + "." + lname }, _dbunique);
}
//if(doc)
return this.ConvertType(doc.Type(), value._Str(), doc.Array());
}, vget
);
if (q2 != null)
{
q = Query.And(q, q2);
}
}
this.dbHelper.Remove(collection, q);
//var docs = this.dbHelper.FindPage(collection, q, page, pagesize, ffs, sdoc, null);
//docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
return true;
};
case "data.count":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var query = p[1]._Str();
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
var tdoc = this.GetTemplateNode(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
//q = Query.And(q, Query.EQ(TemplateFlag, tid));
var collection = DataCollection + "_" + tid;
if (!string.IsNullOrEmpty(query))
{
var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
this.CheckTemplate(tempdoc);
tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
IMongoQuery q2 = this.GetMyQuery(query,
(name) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
return lname;
}
return Definitions.ValueFlag + property + "." + lname;
},
(name, value) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
return value._Str();
case "_created":
case "_modified":
return Convert.ToDateTime(value);
case "_muser":
return value._Str();
}
if (!string.IsNullOrEmpty(property))
{
name = property.Trim('.') + "." + lname;
}
BsonDocument doc = tempdoc.Value(name) as BsonDocument;
var dbindex = doc.GetBool("_dbindex");
var _dbunique = doc.GetBool("_dbunique");
if (dbindex || _dbunique)
{
DatabaseHelper.CheckIndex(collection, new string[] { Definitions.ValueFlag + property + "." + lname }, _dbunique);
}
//if(doc)
return this.ConvertType(doc.Type(), value._Str(), doc.Array());
}, vget
);
if (q2 != null)
{
q = Query.And(q, q2);
}
}
return this.dbHelper.Count(collection, q);
};
case "history.query":
return () =>
{
string name = p[0]._Str();//模板
name = HttpUtility.UrlDecode(name);
int wen = name.IndexOf("?");
string type = "f";
CollectionType filetype = CollectionType.File;
string historytype = FileHistoryCollection;
if (wen != -1)
{
type = name.Substring(wen + 1)[0].ToString().ToLower();
name = name.Substring(0, wen);
}
switch (type)
{
case "f":
filetype = CollectionType.File;
historytype = FileHistoryCollection;
break;
case "t":
filetype = CollectionType.Template;
historytype = TemplateHistoryCollection;
break;
case "i":
filetype = CollectionType.Instance;
historytype = InstanceHistoryCollection;
break;
}
var page = p[1]._Int(1);
var pagesize = p[2]._Int(100);
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
BsonDocument doc = this.FindDocumentById(filetype.ToString(), name, new string[] { UserFlag, NameFlag });
var docid = string.Empty;
if (doc == null)
{
doc = this.dbHelper.FindDocumentByQuery(historytype, Query.And(Query.EQ("flag", "delete"), Query.EQ("lname", name)), new string[] { "id", "_uid", "name" });
if (doc != null)
{
docid = doc.GetString("id");
doc[NameFlag] = doc["name"];
}
}
else
{
docid = doc.GetString(IDFlag);
}
if (doc == null)
{
throw new NotExistException("不存在:" + name);
}
CheckSecurity(filetype, doc, SecurityType.Read);
//this.CheckSecurity(name, filetype, SecurityType.Read);
//=======================================================
IMongoQuery q = Query.EQ("id", docid);
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);
//docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
docs["type"] = type;
return docs;
};
case "instance.history":
return () =>
{
string iname = p[0]._Str().ToLower();
var index = iname.IndexOf('.');
if (index == -1)
{
throw new InvalidNameException("实例节点名不合法:" + iname);
}
var prop = iname.Substring(index);
var instname = iname.Substring(0, index);
string historytype = InstanceHistoryCollection;
var page = p[2]._Int(1);
var pagesize = p[3]._Int(100);
var sortby = p[4] as Dictionary<string, object>;
SortByDocument sdoc = null;
if (sortby != null)
{
sdoc = new SortByDocument();
foreach (var kv in sortby)
{
sdoc[kv.Key] = BsonValue.Create(kv.Value);
}
}
if (sdoc == null)
{
sdoc = new SortByDocument();
sdoc["time"] = 1;
}
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
var doc = this.FindDocumentByName(InstanceCollection, instname, new string[] { TemplateFlag, IDFlag, NameFlag, UserFlag });
if (doc == null)
{
throw new NotExistException("实例不存在:" + instname);
}
this.CheckSecurity(CollectionType.Instance, doc, SecurityType.Read);
//this.CheckSecurity(name, filetype, SecurityType.Read);
//=======================================================
var tid = doc.GetString(TemplateFlag);
var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
this.CheckTemplate(tempdoc);
tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
var id = doc.GetString(IDFlag);
IMongoQuery q = Query.EQ("id", "/" + id + prop);
var query = p[1]._Str();
if (!string.IsNullOrEmpty(query))
{
IMongoQuery q2 = this.GetMyQuery(query,
(name) =>
{
var lname = name.ToLower();
if (lname == "value")
{
return "doc._value";
}
return lname;
},
(name, value) =>
{
var lname = name.ToLower();
if (lname == "time")
{
return this.ConvertType(ItemDataType.DateTime, value._Str(), false);
}
else if (lname == "value")
{
BsonDocument tdoc = tempdoc.Value(prop.Remove(0, 1)) as BsonDocument;
return this.ConvertType(tdoc.Type(), value._Str(), tdoc.Array());
}
return BsonValue.Create(value);
}, vget
);
if (q2 != null)
{
q = Query.And(q, q2);
}
}
Func<List<BsonDocument>, List<Dictionary<string, object>>> mapping = (ds) =>
{
List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
foreach (var d in ds)
{
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["time"] = d.GetDateTime("time");
result["value"] = d.Value("doc._value").Value();
results.Add(result);
}
return results;
};
var docs = this.dbHelper.FindPage(historytype, q, page, pagesize, new List<string> { "id", "doc._time", "doc._value" }, sdoc, mapping);
//docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
return docs;
};
case "file.history":
case "history.get":
return () =>
{
var hid = p[0]._Str();
var valuefield = "doc._value";
List<string> fields = new List<string>() { valuefield, UserFlag, "id", "name" };
fields.Add("doc._gz");
BsonDocument doc = this.dbHelper.FindDocumentByQuery(FileHistoryCollection, Query.EQ(IDFlag, hid), fields.ToArray());
if (doc == null)
{
throw new NotExistException("不存在:" + hid);
}
var id = doc.GetString("id");
this.CheckSecurity(id, CollectionType.File, SecurityType.Read);
bool gz = doc.GetBool("doc._gz");
byte[] vvv = doc.Value(valuefield).AsByteArray;
if (gz)
{
vvv = CommonFunction.Decompress(vvv);
}
var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["value"] = vvv._Str(false);
result["name"] = doc.GetString("name");
return result;
};
case "data.group":
return () =>
{
var docs = p[0] as List<Dictionary<string, object>>;
var type = p[1]._Str();
var field = p[2]._Str();
Func<IEnumerable<Dictionary<string, object>>, decimal> getSum = null;
switch (type)
{
case "count":
getSum = (a) => { return a.Count(); };
break;
case "sum":
getSum = (a) => { return a.Sum(c => c.GetDecimal(field)); };
break;
case "average":
getSum = (a) => { return a.Average(c => c.GetDecimal(field)); };
break;
case "min":
getSum = (a) => { return a.Min(c => c.GetDecimal(field)); };
break;
case "max":
getSum = (a) => { return a.Max(c => c.GetDecimal(field)); };
break;
default:
throw new InvalidParameterException();
}
var groupList = docs.GroupBy(m => new
{
Key = m// getDate(m)
}).
Select(a => new
{
Key = a.Key.Key,
Value = getSum(a)
}).ToList();
Dictionary<object, object> result = new Dictionary<object, object>();
foreach (var kv in groupList)
{
result[kv.Key] = Math.Round(kv.Value, 2);
}
List<Dictionary<string, object>> output = new List<Dictionary<string, object>>();
foreach (var kv in result)
{
Dictionary<string, object> o = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
o["_id"] = kv.Key;
o["value"] = kv.Value;
output.Add(o);
}
return output;
};
case "instance.query":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var query = p[1]._Str();
var page = p[2]._Int(1);
var pagesize = p[3]._Int(100);
var sortby = p[4] as Dictionary<string, object>;
var fs = p[5] as ArrayList;
if (fs != null && fs.Count == 0)
{
fs = null;
}
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
//IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
IMongoQuery q = Query.EQ(TemplateFlag, tid);
//var tdoc = this.GetTemplateNode(tid);
BsonDocument tdoc = this.FindDocumentById(CollectionType.Template.ToString(), tid, new string[] { UserFlag, NameFlag });
if (tdoc.GetString(UserFlag) != this.UserId)
{
CheckSecurity(CollectionType.Template, tdoc, SecurityType.Read);
q = Query.And(q, Query.EQ(UserFlag, this.UserId));
}
//this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
var collection = InstanceCollection;
var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
this.CheckTemplate(tempdoc);
tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
if (!string.IsNullOrEmpty(query))
{
IMongoQuery q2 = this.GetMyQuery(query,
(name) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
return lname;
}
return Definitions.ValueFlag + property + "." + lname + "." + Definitions.ValueFlag;
},
(name, value) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return value._Str();
}
switch (lname)
{
case "_id":
return value._Str();
case "_created":
case "_modified":
return Convert.ToDateTime(value);
case "_muser":
return value._Str();
}
if (!string.IsNullOrEmpty(property))
{
name = property.Trim('.') + "." + lname;
}
BsonDocument doc = tempdoc.Value(name) as BsonDocument;
return this.ConvertType(doc.Type(), value._Str(), doc.Array());
}, vget
);
if (q2 != null)
{
q = Query.And(q, q2);
}
}
List<string> ffs = new List<string>();
if (fs == null)
{
ffs.Add(CreatedFlag);
}
else
{
foreach (var f in fs)
{
string ftr = f.ToString();
var lname = ftr.ToLower();
if (lname.StartsWith("$"))
{
ffs.Add(lname.Substring(1));
}
else
{
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
case "_value":
ffs.Add(lname);
break;
default:
ffs.Add(Definitions.ValueFlag + property + "." + lname + "." + Definitions.ValueFlag);
break;
}
}
}
}
SortByDocument sdoc = null;
if (sortby != null)
{
sdoc = new SortByDocument();
foreach (var kv in sortby)
{
var lname = kv.Key;
if (lname.StartsWith("$"))
{
sdoc[lname.Substring(1)] = BsonValue.Create(kv.Value);
}
else
{
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
sdoc[lname] = BsonValue.Create(kv.Value);
break;
default:
sdoc[Definitions.ValueFlag + property + "." + lname + "." + Definitions.ValueFlag] = BsonValue.Create(kv.Value);
break;
}
}
}
}
Func<List<BsonDocument>, List<Dictionary<string, object>>> mapping = (ds) =>
{
List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
foreach (var doc in ds)
{
Dictionary<string, object> result = doc.ToDictionary();
object bv;
if (result.TryGetValue(Definitions.ValueFlag, out bv))
{
var value = bv as Dictionary<string, object>;
result[Definitions.ValueFlag] = value._DicValue((d) =>
{
d.Remove("_cp");
d.Remove("_time");
d.Remove("_from");
d.Remove("_to");
});
value = result[Definitions.ValueFlag] as Dictionary<string, object>;
foreach (var f in ffs)
{
if (f.StartsWith("_value.") && f.EndsWith("._value"))
{
var key = f.Substring(7);
var dot = key.LastIndexOf('.');
key = key.Substring(0, dot);
object obj;
if (!value._TryGet(key, out obj))
{
var val = tempdoc.Value(key) as BsonDocument;
var o = this.ConvertType(val.Type(), val.GetString("_value"), val.Array());
value._Set(key, o);
}
}
}
}
results.Add(result);
}
return results;
};
var docs = this.dbHelper.FindPage(collection, q, page, pagesize, ffs, sdoc, mapping);
//docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
return docs;
};
case "instance.deletebyquery":
return () =>
{
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var query = p[1]._Str();
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有登录");
}
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + p[0]._Str());
}
var tdoc = this.GetTemplateNode(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
//=======================================================
q = Query.And(q, Query.EQ(TemplateFlag, tid));
var collection = InstanceCollection;
if (!string.IsNullOrEmpty(query))
{
var fields = new string[] { NameFlag, Definitions.ValueFlag, UserFlag, ReferenceFlag };
BsonDocument tempdoc = this.FindDocumentByName(TemplateCollection, tid, fields);
this.CheckTemplate(tempdoc);
tempdoc = tempdoc[Definitions.ValueFlag].AsBsonDocument;
IMongoQuery q2 = this.GetMyQuery(query,
(name) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return lname.Substring(1);
}
switch (lname)
{
case "_id":
case "_created":
case "_modified":
case "_muser":
return lname;
}
return Definitions.ValueFlag + property + "." + lname + "." + Definitions.ValueFlag;
},
(name, value) =>
{
var lname = name.ToLower();
if (lname.StartsWith("$"))
{
return value._Str();
}
switch (lname)
{
case "_id":
return value._Str();
case "_created":
case "_modified":
return Convert.ToDateTime(value);
case "_muser":
return value._Str();
}
if (!string.IsNullOrEmpty(property))
{
name = property.Trim('.') + "." + lname;
}
BsonDocument doc = tempdoc.Value(name) as BsonDocument;
return this.ConvertType(doc.Type(), value._Str(), doc.Array());
}, vget
);
if (q2 != null)
{
q = Query.And(q, q2);
}
}
//var docs = this.dbHelper.FindPage(collection, q, page, pagesize, ffs, sdoc, mapping);
//docs["template"] = tdoc.ToDictionary()._InfoFromTemplate(new string[] { "_desc", "_type" });
this.dbHelper.Remove(collection, q);
return true;
};
case "data.create":
case "data.update":
case "data.insert":
case "data.insert2":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有权限", v);
}
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var tname = tid;
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + tname);
}
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
var collection = DataCollection + "_" + tid;
var value = p[1] as Dictionary<string, object>;//数据
var id = p[2]._Str();//更新的数据id
if (v == "data.update")
{
if (string.IsNullOrEmpty(id))
{
throw new InvalidParameterException("参数错误:id");
}
var doc = this.FindDocumentById(collection, id, new string[] { UserFlag });
if (doc == null)
{
throw new NotExistException("数据不存在");
}
if (doc.GetString(UserFlag) != this.UserId)
{
throw new NoSecurityException("没有权限");
}
//Dictionary<string, object> values = value._DicKeyStrings(Definitions.ValueFlag + property);
//var docvalue = doc[Definitions.ValueFlag] as BsonDocument;
//var myvalues = docvalue.ToDictionary()._DicKeys(Definitions.ValueFlag);
//foreach (var kv in values)
//{
// myvalues[kv.Key] = kv.Value;
//}
//Dictionary<string, object> ivalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
//this.GetInstance(null, tid, SecurityType.Read, ref ivalues, emptyid: Definitions.ValueFlag + property, initvalues: myvalues);
//BsonDocument udoc = new BsonDocument();
//foreach (var kv in ivalues)
//{
// if (values.ContainsKey(kv.Key))
// {
// udoc.Add(kv.Key, BsonValue.Create(kv.Value));
// }
//}
Dictionary<string, object> values = value._DicKeyStrings(Definitions.ValueFlag + property);
Dictionary<string, object> myvalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
this.GetInstance(null, tid, SecurityType.Read, ref myvalues, emptyid: Definitions.ValueFlag + property, initvalues: values, once: true);
BsonDocument udoc = new BsonDocument();
foreach (var kv in myvalues)
{
if (values.ContainsKey(kv.Key))
{
udoc.Add(kv.Key, BsonValue.Create(kv.Value));
}
}
this.dbHelper.Update(collection, id, udoc);
return true;
}
else
{
Dictionary<string, object> values = value._DicKeyStrings(Definitions.ValueFlag + property);
Dictionary<string, object> myvalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
this.GetInstance(null, tid, SecurityType.Read, ref myvalues, emptyid: Definitions.ValueFlag + property, initvalues: values, once: true);
BsonDocument docvalue = CreateDocument(null);
docvalue.Add(TemplateFlag, tid);
var valuedic = myvalues._DicKeyObjects(Definitions.ValueFlag);
docvalue.Add(Definitions.ValueFlag, new BsonDocument(valuedic));
//if (v == "data.update")
//{
// this.dbHelper.Update(collection, id, docvalue);
//}
//else
//{
if (v == "data.insert2")
{
if (!docvalue.Contains(DataClient.CreatedFlag))
{
docvalue[DataClient.CreatedFlag] = DateTime.UtcNow;
}
docvalue[DataClient.ModifiedUserFlag] = this.UserId ?? string.Empty;
docvalue[DataClient.ModifiedFlag] = DateTime.UtcNow;
DatabaseHelper.AddInsert(collection, docvalue);
}
else
{
this.dbHelper.Insert(collection, docvalue);
}
//}
return true;
}
};
case "data.values":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有权限", v);
}
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var tname = tid;
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (string.IsNullOrEmpty(tid))
{
throw new NotExistException("模板不存在:" + tname);
}
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
Dictionary<string, object> values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, object> myvalues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
this.GetInstance(null, tid, SecurityType.Read, ref myvalues, emptyid: Definitions.ValueFlag + property, initvalues: values, once: true);
var valuedic = myvalues._DicKeyObjects(Definitions.ValueFlag);
return valuedic;
};
case "instance.insert":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有权限", v);
}
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var instanceId = p[1]._Str();//实例名
var value = p[2] as Dictionary<string, object>;//数据
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (!string.IsNullOrEmpty(tid))
{
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
}
Dictionary<string, object> values = value._DicKeyStrings(property.Trim('.'));
string iid = null;
DataOperations operations = DataOperations.Insert;
instanceId = instanceId.Trim('/');
this.PublishInstance(ref iid, instanceId, null, null, tid, operations, newvalues: values);
//this.UpdateInstanceByValues(instanceId, tid, values);
return true;
};
case "path":
return () =>
{
var path = p[0]._Str();
var rp = p[1]._Str();
if (string.IsNullOrEmpty(rp))
{
path = path._Path(this.GetSource());
}
else
{
path = path._Path(rp);
}
if (!path.StartsWith("/"))
{
path = "/" + path;
}
return path;
};
case "instance.set":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有权限", v);
}
if (p.Count == 2)
{
var iid = p[0]._Str();//实例名
var iiindex = iid.IndexOf('.');
var myprop = string.Empty;
if (iiindex != -1)
{
myprop = iid.Substring(iiindex);
iid = iid.Substring(0, iiindex);
}
var vvs = p[1] as Dictionary<string, object>;//数据
Dictionary<string, object> myvalues = vvs._DicKeyStrings(myprop.Trim('.'));
if (!FileExist(iid, InstanceCollection))
{
throw new NotExistException("实例不存在:" + iid);
}
else
{
foreach (var kv in myvalues)
{
this.UpdateInstance(iid + "." + kv.Key, kv.Value._Str(), null, null, this.myInstanceModels, null);
}
this.UpdateInstanceModels();
}
return true;
}
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var instanceId = p[1]._Str();//实例名
this.CheckName(ref instanceId);
var value = p[2] as Dictionary<string, object>;//数据
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
if (!string.IsNullOrEmpty(tid))
{
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
}
var iiiindex = instanceId.IndexOf('.');
if (iiiindex != -1)
{
property = instanceId.Substring(iiiindex);
instanceId = instanceId.Substring(0, iiiindex);
}
Dictionary<string, object> values = value._DicKeyStrings(property.Trim('.'));
if (!FileExist(instanceId, InstanceCollection))
{
this.UpdateInstanceByValues(instanceId, tid, values);
}
else
{
foreach (var kv in values)
{
this.UpdateInstance(instanceId + "." + kv.Key, kv.Value._Str(), null, null, this.myInstanceModels, null);
}
this.UpdateInstanceModels();
}
//this.UpdateInstanceByValues(instanceId, tid, values);
return true;
};
case "data.delete":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new NoSecurityException("没有权限", v);
}
string tid = p[0]._Str();//模板
tid = HttpUtility.UrlDecode(tid);
if (tid.StartsWith("/"))
{
tid = tid._Path(this.GetSource());
}
var index = tid.IndexOf('.');
var property = "";
if (index != -1)
{
property = tid.Substring(index);
tid = tid.Substring(0, index);
}
tid = this.GetTemplateId(tid);
this.CheckSecurity(tid, CollectionType.Template, SecurityType.Read);
var collection = DataCollection + "_" + tid;
string id = p[1]._Str();
var doc = this.FindDocumentById(collection, id, new string[] { IDFlag, UserFlag });
if (doc == null)
{
throw new NotExistException("数据不存在");
}
if (doc.GetString(UserFlag) != this.UserId)
{
throw new NoSecurityException("没有权限");
}
IMongoQuery q = Query.EQ(IDFlag, id);
this.dbHelper.Remove(collection, q);
return true;
};
#endregion
#region Console
case "console.clear":
return () =>
{
IMongoQuery q = Query.EQ(UserFlag, this.UserId);
long count = this.dbHelper.Count(UserLogCollection, q);
this.dbHelper.Remove(UserLogCollection, q);
string type = "Info";
string msg = string.Format("成功清除 {0} 条日志记录。", count);
string feature = "Console";
this.PublishUserLog(type, msg, feature);
return count;
};
case "console.log":
case "console.info":
return () =>
{
string type = "Info";
string msg = p[0]._Str();
string feature = "Console";
this.PublishUserLog(type, msg, feature, p[1] as Dictionary<string, object>);
return null;
};
case "console.error":
return () =>
{
string type = "Error";
string msg = p[0]._Str();
var data = p[1] as Dictionary<string, object>;
string feature = "Console";
this.PublishUserLog(type, msg, feature, data);
return null;
};
case "console.debug":
return () =>
{
string type = "Debug";
string msg = p[0]._Str();
string feature = "Console";
this.PublishUserLog(type, msg, feature, p[1] as Dictionary<string, object>);
return null;
};
#endregion
#region User Function
case "user.name":
return () =>
{
return this.GetUserName(p[0]._Str());
};
case "user.changename":
return () =>
{
this.ChangeUserName(p[0]._Str());
return "更新成功";
};
case "user.add":
return () =>
{
var loginName = p[0]._Str();
var isNew = p[1]._Bool();
var nickName = p[2]._Str();
var phone = p[3]._Str();
var email = p[4]._Str();
var password = p[5]._Str();
var roles = p[6]._StrList();
string userid = null;
if (!isNew)
{
userid = this.GetUserId(loginName);
}
this.PublishUser(ref userid, loginName, password, email, phone, false, false, null, null, nickName);
string name = loginName.ToLower();
if (roles != null && roles.Count > 0)
{
string settingname = "/" + this.UserName + "/home/instances/setting.json";
BsonDocument doc = this.FindDocumentByName(FileCollection, settingname, new string[] { Definitions.ValueFlag });
if (doc != null)
{
string str = string.Empty;
byte[] r = doc[Definitions.ValueFlag].AsByteArray;
str = CommonFunction.BytesToString(r);
var result = str._Dic2();
var groups = result._Value("group") as Dictionary<string, object>;
foreach (var kv in groups)
{
var key = kv.Key;
var value = kv.Value as Dictionary<string, object>;
var users = value._Value("users")._Str();
List<string> userlist = null;
if (users != null)
{
userlist = users.Split(',').ToList();
userlist.Remove(name);
}
else
{
userlist = new List<string>();
}
if (roles.Contains(key))
{
userlist.Add(name);
}
value["users"] = string.Join(",", userlist);
}
this.UpdateFileContent(settingname, result._Json(false)._Bytes(false));
}
}
return null;
};
case "user.update":
return () =>
{
if (p[0] is Dictionary<string, object>)
{
var pd = (Dictionary<string, object>)p[0];
var a = new ArrayList();
a.Add(pd._Value("username"));
a.Add(pd._Value("isnew"));
a.Add(pd._Value("nickname"));
a.Add(pd._Value("phone"));
a.Add(pd._Value("email"));
a.Add(pd._Value("password"));
a.Add(pd._Value("roles"));
a.Add(pd._Value("admin"));
//a.Add(pd._Value("team"));
//a.Add(pd._Value("tag"));
ParameterModel pm = new ParameterModel();
pm.AddRange(a);
p = pm;
}
//{"currentUser":{"loginName":"test","isNew":true,"nickName":"test","phone":"13667164200","email":"a@1.com","password":"123456","roles":["1"],"lastLoginTime":"未登录"}}
var loginName = p[0]._Str();
var isNew = p[1]._Bool();
var nickName = p[2]._Str();
var phone = p[3]._Str();
var email = p[4]._Str();
var password = p[5]._Str();
var roles = p[6]._StrList();
var isadmin = p[7]._Str();
string userid = null;
if (!isNew)
{
userid = this.GetUserId(loginName);
}
this.PublishUser(ref userid, loginName, password._MD5(), email, phone, false, false, null, null, nickName, isadmin);
string name = loginName.ToLower();
if (roles != null && roles.Count > 0)
{
string settingname = "/" + this.UserName + "/home/instances/setting.json";
BsonDocument doc = this.FindDocumentByName(FileCollection, settingname, new string[] { Definitions.ValueFlag });
if (doc != null)
{
string str = string.Empty;
byte[] r = doc[Definitions.ValueFlag].AsByteArray;
str = CommonFunction.BytesToString(r);
var result = str._Dic2();
var groups = result._Value("group") as Dictionary<string, object>;
foreach (var kv in groups)
{
var key = kv.Key;
var value = kv.Value as Dictionary<string, object>;
var users = value._Value("users")._Str();
List<string> userlist = null;
if (users != null)
{
userlist = users.Split(',').ToList();
userlist.Remove(name);
}
else
{
userlist = new List<string>();
}
if (roles.Contains(key))
{
userlist.Add(name);
}
value["users"] = string.Join(",", userlist);
}
this.UpdateFileContent(settingname, result._Json(false)._Bytes(false));
}
}
return null;
};
case "user.checksync":
return () =>
{
var doc = this.FindDocumentById(UserCollection, this.UserId, new string[] { "_sync" });
if (doc != null)
{
BsonValue bv;
if (!doc.TryGetValue("_sync", out bv))
{
var valuedoc = new BsonDocument();
valuedoc.Add("time", DateTime.UtcNow);
valuedoc.Add("n", 0);
bv = valuedoc;
}
var myvalue = bv as BsonDocument;
var time = myvalue.GetDateTime("time");
var n = myvalue.GetInt("n");
var now = DateTime.UtcNow;
if (time.Year == now.Year && time.Month == now.Month)
{
int limit = DataClient.GetMyLimit(this.UserId, "Sync_Max")._Int();
if (limit > 0)
{
if (n >= limit)
{
throw new SyncException("本月同步次数达到最大值:" + n);
}
}
}
else
{
n = 0;
}
n++;
myvalue["n"] = n;
myvalue["time"] = DateTime.UtcNow;
var values = new BsonDocument();
values.Add("_sync", myvalue);
this.dbHelper.Update(UserCollection, this.UserId, values);
}
return true;
};
case "user.verify":
return () =>
{
string type = p[0]._Str();
string value = p[1]._Str();
switch (type)
{
case "0"://用户
this.CheckName(value, true, 20, true);
var doc = this.dbHelper.FindDocumentByQuery(UserCollection, Query.EQ(LNameFlag, value.ToLower()), new string[] { IDFlag });
if (doc != null)
{
throw new UserExistException("用户已存在");
}
break;
case "1"://手机
if (!CommonFunction.IsPhone(value))
{
throw new NotPhoneException("手机号格式不对");
}
doc = this.dbHelper.FindDocumentByQuery(UserCollection, Query.EQ(PhoneFlag, value.ToLower()), new string[] { IDFlag });
if (doc != null)
{
throw new UserExistException("手机号已存在");
}
break;
case "2"://邮箱
if (!CommonFunction.IsEmail(value))
{
throw new NotPhoneException("邮箱格式不对");
}
doc = this.dbHelper.FindDocumentByQuery(UserCollection, Query.EQ(LEmailFlag, value.ToLower()), new string[] { IDFlag });
if (doc != null)
{
throw new UserExistException("邮箱已存在");
}
break;
}
return null;
};
case "user.getused":
return () =>
{
var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["count"] = this.dbHelper.GetUsedCount(p[0]._Str());
result["size"] = this.dbHelper.GetUsedSize(p[0]._Str());
return result;
};
case "vcode.check":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限");
}
this.CheckValidateCode(p[0]._Str(), p[1]._Str());
return true;
};
case "user.reg":
return () =>
{
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["err"] = string.Empty;
result["type"] = 0;
try
{
string vName = p[0]._Str();
string vCode = p[1]._Str();
string userName = p[2]._Str();
string passWord = p[3]._Str();
Dictionary<string, object> newinfo = p[4] as Dictionary<string, object>;
result["type"] = this.Register2(vName, vCode, userName, passWord, newinfo);
}
catch (Exception ex)
{
result["err"] = ex._msg();
}
return result;
};
case "user.register":
return () =>
{
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
result["err"] = string.Empty;
result["type"] = 0;
try
{
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());
}
catch (Exception ex)
{
result["err"] = ex._msg();
}
return result;
};
case "user.logout":
return () =>
{
if (string.IsNullOrEmpty(this.AccessUser))
{
return false;
}
this.Logout();
return true;
};
case "user.get":
return () =>
{
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
try
{
result = this.GetUser(p[0]._Str(), p[1]._Str(), p[2]._Str(), p[3]._Str());
}
catch (Exception ex)
{
result["err"] = ex._msg();
}
return result;
};
case "user.vcode":
return () =>
{
var expiredSeconds = p[1]._Int();
if (expiredSeconds == 0)
{
expiredSeconds = 60;
}
return this.VcodeForUser(p[0]._Str(), expiredSeconds);
};
case "user.delete":
return () =>
{
this.DeleteUserByName(p[0]._Str());
return null;
};
case "user.vcodeimage":
return () =>
{
byte[] image = null;
this.ResetValidateCode(p[0]._Str(), p[1]._Str(), out image, false);
return image;
};
case "user.info"://获取用户信息
return () =>
{
Dictionary<string, object> info2 = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
info2["id"] = this.UserId;
info2["username"] = "";
info2["email"] = "";
info2["phone"] = "";
info2["nick"] = "";
var u = this.FindDocumentById(UserCollection, this.UserId, new string[] { NameFlag, EmailFlag, PhoneFlag, NickNameFlag });
if (u != null)
{
info2["username"] = u[NameFlag].ToString();
info2["email"] = u[EmailFlag].ToString();
info2["phone"] = u[PhoneFlag].ToString();
info2["nick"] = u.GetString(NickNameFlag);
}
return info2;
};
case "user.getlimit":
return () =>
{
Dictionary<string, object> limit;
if (p.Count > 0)
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限", this.UserName);//("getlimit", this.UserName);
}
string user = p[0]._Str();
BsonDocument doc = this.FindDocumentByName(UserCollection, user, new string[] { IDFlag });
limit = DataClient.LimitDic(doc[IDFlag].ToString());
}
else
{
limit = DataClient.LimitDic(this.UserId);
}
var limit2 = DataClient.defaultlimit._Dic2();
foreach (var kv in limit2)
{
if (!limit.ContainsKey(kv.Key))
{
limit[kv.Key] = "";
}
}
return limit;
};
case "defaultlimit":
return () =>
{
return DataClient.defaultlimit._Dic2();
};
case "user.setadmin":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限", this.UserName);
}
var userlist = p[0]._StrList();
var value = p[1]._Bool();
foreach (var user in userlist)
{
BsonDocument updated = new BsonDocument();
updated.Add(IsAdminFlag, value);
this.dbHelper.Update(UserCollection, GetUserId(user), updated);
}
return true;
};
case "user.setlimit":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限", this.UserName);//("getlimit", this.UserName);
}
string user = p[0]._Str();
Dictionary<string, object> obj = p[1] as Dictionary<string, object>;
//BsonDocument value = new BsonDocument();
//foreach (var kkk in obj)
//{
// value.Add( kkk.Key, BsonValue.Create(kkk.Value));
//}
BsonDocument doc = this.FindDocumentByName(UserCollection, user, new string[] { IDFlag });
BsonDocument updated = new BsonDocument();
foreach (var kkk in obj)
{
updated.Add(LimitFlag + "." + kkk.Key, BsonValue.Create(kkk.Value));
}
//updated.Add(LimitFlag, value);
this.dbHelper.Update(UserCollection, doc[IDFlag].ToString(), updated);
return true;
};
case "user.changeinfo":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new Exception("请先登录");
}
var userinfo = p[0] as Dictionary<string, object>;
BsonDocument doc = new BsonDocument();
object o;
if (userinfo.TryGetValue("password", out o))
{
string password = o._Str();
if (!string.IsNullOrEmpty(password))
{
userinfo.TryGetValue("oldpassword", out o);
string oldpassword = o._Str();
if (string.IsNullOrEmpty(oldpassword))
{
throw new EmptyPasswordException("旧密码不能为空");
}
var userdoc = this.FindDocumentById(UserCollection, this.UserId, new string[] { PassWordFlag });
if (userdoc.GetString(PassWordFlag) != oldpassword)
{
throw new WrongPasswordException("旧密码不匹配");
}
doc["_pwd"] = password;
}
}
if (userinfo.TryGetValue("nickname", out o))
{
string nickname = o._Str();
if (!string.IsNullOrEmpty(nickname))
{
doc[NickNameFlag] = nickname;
}
}
if (userinfo.TryGetValue("email", out o))
{
string name = o._Str();
if (!string.IsNullOrEmpty(name))
{
doc[EmailFlag] = name;
doc[LEmailFlag] = name.ToLower();
}
}
this.dbHelper.Update(UserCollection, this.UserId, doc);
string type = "Info";
this.PublishUserLog(type, "更新资料成功", "UserInfo", null);
return null;
};
case "user.changepassword":
return () =>
{
if (string.IsNullOrEmpty(this.UserId))
{
throw new Exception("请先登录");
}
string password = p[0]._Str();
if (string.IsNullOrEmpty(password))
{
throw new EmptyPasswordException("密码不能为空");
}
BsonDocument doc = new BsonDocument();
doc["_pwd"] = password;
this.dbHelper.Update(UserCollection, this.UserId, doc);
string type = "Info";
this.PublishUserLog(type, "更新密码成功", "UserInfo", null);
return null;
};
case "user.changeemailorphone":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限", this.UserName);//("getlimit", this.UserName);
}
var vName = p[0]._Str();
var vCode = p[1]._Str();
var newinfo = p[2] as ArrayList;
this.ChangeEmailOrPhone(vName, vCode, newinfo);
return null;
};
case "user.query":
return () =>
{
if (!this.IsAdmin)
{
throw new NoSecurityException("没有权限", this.UserName);//("getlimit", this.UserName);
}
var query = p[0]._Str();
var page = p[1]._Int();
var pagesize = p[2]._Int();
var sortby = p[3] as Dictionary<string, object>;
IMongoQuery q = null;
if (!string.IsNullOrEmpty(query))
{
IMongoQuery q2 = this.GetMyQuery(query,
(name) =>
{
return name;
},
(name, value) =>
{
return value._Str();
}, vget
);
if (q2 != null)
{
if (q == null)
{
q = q2;
}
else
{
q = Query.And(q, q2);
}
}
}
SortByDocument sdoc = null;
if (sortby != null)
{
sdoc = new SortByDocument();
foreach (var kv in sortby)
{
sdoc[kv.Key] = BsonValue.Create(kv.Value);
}
}
var docs = dbHelper.FindPage(UserCollection, q, page, pagesize, new List<string> { NameFlag, EmailFlag, PhoneFlag, NickNameFlag, "_lasttime", "_lastip", IsAdminFlag }, sdoc);
return docs;
};
#endregion
#region Device Function
case "device.log":
return () =>
{
var id = p[0]._Str();
int index = id.LastIndexOf('$');
if (index != -1)
{
id = id.Substring(index + 1);
}
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));
return result;
};
case "device.add":
return () =>
{
string id = p[0]._Str();
string token = p[1]._Str();
string name = p[2]._Str();
string inst = p[3]._Str();
this.PublishDevice(id, token, name, inst, "add");
return true;
};
case "device.instance":
return () =>
{
string id = p[0]._Str();
string target = p[1]._Str();
int index = id.LastIndexOf('$');
if (index != -1)
{
id = id.Substring(index + 1);
}
var doc = this.dbHelper.FindDocumentByQuery(DeviceCollection, Query.And(Query.EQ(UserFlag, this.UserId), Query.EQ(IDFlag, id)), new string[] { IDFlag });
if (doc == null)
{
throw new NotExistException("设备不存在:" + id);
}
var values = new BsonDocument();
values["_iid"] = target;
this.dbHelper.Update(DeviceCollection, id, values);
this.UpdateInstance(target, this.GetDeviceStatus(id, null) ? "true" : "false", null, null);
return true;
};
case "device.updateprop":
return () =>
{
string id = p[0]._Str();
int index = id.LastIndexOf('$');
if (index != -1)
{
id = id.Substring(index + 1);
}
var doc = this.dbHelper.FindDocumentByQuery(DeviceCollection, Query.And(Query.EQ(UserFlag, this.UserId), Query.EQ(IDFlag, id)), new string[] { IDFlag });
if (doc == null)
{
throw new NotExistException("设备不存在:" + id);
}
var vs = p[1] as Dictionary<string, object>;
var values = new BsonDocument(vs);
this.dbHelper.Update(DeviceCollection, id, values);
return true;
};
case "device.update":
return () =>
{
string id = p[0]._Str();
string token = p[1]._Str();
string name = p[2]._Str();
string inst = p[3]._Str();
this.PublishDevice(id, token, name, inst, "update");
return true;
};
case "device.delete":
return () =>
{
this.DeleteDevice(p[0]._Str());
return true;
};
case "device.query":
return () =>
{
var result = this.QueryDevice();
return result;
};
case "device.info":
return () =>
{
var result = this.QueryDeviceInfo(p[0]._Str());
return result;
};
#endregion
#region Modbus
case "tcp.send":
return () =>
{
SSClient ssc = new SSClient();
byte[] data = (byte[])p[1];
int tout = p[2]._Int(30000);
var result = ssc.MySend("mytcp://" + p[0]._Str(), data, tout);
return result;
};
case "udp.send":
return () =>
{
SSClient ssc = new SSClient();
byte[] data = (byte[])p[1];
var result = ssc.SendWithoutReturn("udp://" + p[0]._Str(), data);
return result;
};
case "modbus.send":
return () =>
{
SSClient ssc = new SSClient();
//
ModbusService.ModbusProtocol mp = new ModbusService.ModbusProtocol();
mp.functionCode = 16;
mp.quantity = 5;
mp.protocolIdentifier = 0;
mp.transactionIdentifier = 1;
mp.unitIdentifier = 1;
mp.startingAdress = 0;
mp.sendRegisterValues = new short[5] { 1, 2, 3, 4, 5 };
mp.quantity = 5;
mp.SetResponse();
//byte[] data = new byte[] { 0x00, 0x0f, 0x00, 0x00, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01 };
byte[] data = mp.GetBytes();
var result = ssc.MySend("modbus://" + p[0]._Str(), data, 6000);
return result;
};
#endregion
#region TCPClient
case "client.exist":
return () =>
{
return MyEasyClient.CheckSession(p[0]._Str());
};
case "client.new":
case "udp.new":
return () =>
{
MyTcpReceiveFilter myfilter = new MyTcpReceiveFilter(null);
myfilter.myunits = p[1] as ArrayList;
var action = p[2];
if (action != null && action is Expression)
{
Expression exp = (Expression)action;
myfilter.ProcessAction = (bytes) =>
{
var pm = new ParameterModel();
pm.Add(bytes);
exp.m_script.RunFunction(exp, pm);
};
}
if (v == "udp.new")
{
myfilter.MyType = System.Net.Sockets.ProtocolType.Udp;
}
MyEasyClient.CreateSession(p[0]._Str(), myfilter);
return null;
};
case "client.send":
return () =>
{
MyEasyClient.SendBytes(p[0]._Str(), (byte[])p[1]);
return null;
};
case "unit":
return () =>
{
var obj = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
obj["name"] = p[0];
obj["type"] = p[1];
obj["length"] = p[2];
obj["value"] = p[3];
obj["forlength"] = p[4];
return obj;
};
case "bytes.parse":
return () =>
{
var bytes = (byte[])p[0];
var units = p[1] as ArrayList;
var parent = p[2] as ArrayList;
var allunits = new List<CustomProtocol.Unit>();
foreach (var unit in units)
{
var u = unit as Dictionary<string, object>;
if (u == null)
{
var us = unit._Str().Split('\t');
allunits.Add(new CustomProtocol.Unit(us[0].Trim(), us[1].Trim(), us[2].Trim()._Int()));
}
else
{
var myunit = new CustomProtocol.Unit(u);
allunits.Add(myunit);
}
}
var obj = CustomProtocol.Support.Parse(bytes, allunits.ToArray(), parent: parent);
return obj;
};
case "bytes.obj":
return () =>
{
byte[] data = (byte[])p[0];
string type = p[1]._Str();
byte defaultbyte = p[2] == null ? (byte)0 : (byte)p[2];
var obj = CustomProtocol.Support.ToObj(data, type, defaultbyte);
return obj;
};
case "units.bytes":
return () =>
{
var units = p[0] as ArrayList;
var data = p[1] as ArrayList;
byte defaultbyte = 0x00;
if (p[2] != null)
{
defaultbyte = (byte)p[2];
}
var allunits = new List<CustomProtocol.Unit>();
foreach (var unit in units)
{
var u = unit as Dictionary<string, object>;
if (u == null)
{
var us = unit._Str().Split('\t');
allunits.Add(new CustomProtocol.Unit(us[0].Trim(), us[1].Trim(), us[2].Trim()._Int()));
}
else
{
allunits.Add(new CustomProtocol.Unit(u));
}
}
var bytes = CustomProtocol.Support.UnitsToBytes(allunits.ToArray(), data, defaultbyte);
return bytes;
};
case "bytes.bits":
return () =>
{
var buffer = (byte[])p[0];
var sb = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
BitArray arr = new BitArray(new byte[] { buffer[i] });
for (var j = arr.Length - 1; j >= 0; j--)
{
sb.Append(arr[j] ? "1" : "0");
}
}
return sb.ToString();
};
case "bytes.hex":
return () =>
{
var buffer = (byte[])p[0];
StringBuilder strBuider = new StringBuilder();
for (int index = 0; index < buffer.Length; index++)
{
strBuider.Append(((int)buffer[index]).ToString("X2"));
}
return strBuider.ToString();
};
case "hex.bytes":
return () =>
{
var hexString = p[0]._Str();
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
{
hexString += " ";
}
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
}
return returnBytes;
};
case "mytcp.send":
return () =>
{
SSClient ssc = new SSClient();
//byte[] data = new byte[] { 0x00, 0x0f, 0x00, 0x00, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01 };
byte[] data = (byte[])p[0];
var result = ssc.SendWithoutReturn("mytcp://" + p[0]._Str(), data);
return result;
};
case "sm2.verify":
return () =>
{
return sm2.Instance.VerifySign(p[0]._ObjBytes(), p[1]._ObjBytes(), p[2]._ObjBytes(), p[3]._Str() ?? "1234567812345678");
};
case "sm2.verify2":
return () =>
{
return sm2.Instance.VerifySign(p[0]._ObjBytes(), p[1]._ObjBytes(), p[2]._ObjBytes(), p[3]._ObjBytes(), p[4]._Str() ?? "1234567812345678");
};
case "sm2.sign":
return () =>
{
return sm2.Instance.Sign(p[0]._ObjBytes(), p[1]._ObjBytes(), p[2]._Str() ?? "1234567812345678");
};
case "sm2.encode":
return () =>
{
var isprivate = false;
var p2 = p[2];
if (p2 != null)
{
isprivate = p2._Bool();
}
return sm2.Instance.Encode(p[0]._ObjBytes(), p[1]._ObjBytes(), isprivate, p[3]._Int());
};
case "sm2.decode":
return () =>
{
var isprivate = true;
var p2 = p[2];
if (p2 != null)
{
isprivate = p2._Bool();
}
return sm2.Instance.Decode(p[0]._ObjBytes(), p[1]._ObjBytes(), isprivate, p[3]._Int());
};
case "sm2.pair":
return () =>
{
return sm2.Instance.CreateKeyPair();
};
#endregion
}