public Yield GetUsers(DreamContext context, DreamMessage request, Result <DreamMessage> response) { // TODO (steveb): add 'emailfilter' and use it to obsolete 'usernameemailfilter'; 'usernamefilter', 'fullnamefilter', and 'emailfilter' // should be OR'ed together when they are present. PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ); uint totalCount; uint queryCount; var users = UserBL.GetUsersByQuery(context, null, out totalCount, out queryCount); XDoc result = new XDoc("users"); result.Attr("count", users.Count()); result.Attr("querycount", queryCount); result.Attr("totalcount", totalCount); result.Attr("href", DekiContext.Current.ApiUri.At("users")); bool verbose = context.GetParam <bool>("verbose", true); foreach (UserBE u in users) { if (verbose) { result.Add(UserBL.GetUserXmlVerbose(u, null, Utils.ShowPrivateUserInfo(u), true, true)); } else { result.Add(UserBL.GetUserXml(u, null, Utils.ShowPrivateUserInfo(u))); } } response.Return(DreamMessage.Ok(result)); yield break; }
private static XDoc GetServiceOverview(XDoc service) { // generate a document containing the overview information for a service XDoc overviewDoc = new XDoc("html"); overviewDoc.Start("h2").Value("Overview").End(); overviewDoc.Add(GetWarning()); overviewDoc.Start("strong").Value("Assembly: ").End().Value(service["assembly"].Contents); overviewDoc.Add(new XDoc("br")); overviewDoc.Start("strong").Value("Class: ").End().Value(service["class"].Contents); overviewDoc.Add(new XDoc("br")); overviewDoc.Start("strong").Value("SID: ").End().Value(service["sid"].Contents); overviewDoc.Start("h5").Value("Configuration").End(); overviewDoc.Add(GetTable(new string[] { "Name", "Type", "Description" }, service["configuration/entry"])); overviewDoc.Start("h5").Value("Features").End(); XDoc featuresDoc = new XDoc("features"); foreach (XDoc featureDoc in service["features/feature"]) { string name = featureDoc["pattern"].Contents; if (!IsExcludedFeature(name)) { featuresDoc.Start("feature").Start("name").Value(String.Format("[[./{0}|{1}]]", name.Replace("/", "//"), name)).End().Start("description").Value(featureDoc["description"].Contents).End().End(); } } overviewDoc.Add(GetTable(new string[] { "Name", "Description" }, featuresDoc["feature"])); return(overviewDoc); }
internal static XDoc ExecuteFork(Plug env, DreamHeaders headers, XDoc fork) { // execute script commands XDoc reply = new XDoc("results"); string ID = fork["@ID"].Contents; if (!string.IsNullOrEmpty(ID)) { reply.Attr("ID", ID); } // TODO (steveb): we should use a 'fixed capacity' cue which marks itself as done when 'count' is reached XDoc forks = fork.Elements; foreach (XDoc cmd in forks) { // TODO (steveb): we should be doing this in parallel, not sequentially! try { reply.Add(ExecuteCommand(env, headers, cmd)); } catch (Exception e) { reply.Add(new XException(e)); } } return(reply); }
public DreamMessage GetContentHandler(DreamContext context, DreamMessage message) { user user = Authenticate(context, message, DekiUserLevel.User); page page = Authorize(context, user, DekiAccessLevel.Read, "pageid"); DekiContext deki = new DekiContext(message, this.DekiConfig); bool nofollow = (context.Uri.GetParam("nofollow", 0, null) != null); string contents = page.getContent(nofollow); string xml = string.Format(DekiWikiService.XHTML_LOOSE, contents); XDoc doc = XDoc.FromXml(xml); if (doc == null) { LogUtils.LogWarning(_log, "GetContentHandler: null document page content", page.PrefixedName, contents); throw new DreamAbortException(DreamMessage.BadRequest("null document")); } XDoc result = new XDoc("list"); string type = context.Uri.GetParam("type", 0, null); string id = context.Uri.GetParam("id", 0, null); if (id != null) { XDoc widget = doc[string.Format("//default:span[@widgetid={0}]", id)]; if (widget.IsEmpty) { LogUtils.LogWarning(_log, "GetContentHandler: widget not found for ID", id); return DreamMessage.NotFound(""); } LogUtils.LogTrace(_log, "GetContentHandler: widget by id (id, xspan)", id, widget); result.Add(ConvertFromXSpan(widget)); } else if (type != null) { foreach (XDoc widget in doc[string.Format("//default:span[@widgettype='{0}']", type)]) result.Add(ConvertFromXSpan(widget)); LogUtils.LogTrace(_log, "GetContentHandler: widget by type (type, #)", type, result.Count); } else { foreach (XDoc widget in doc["//default:span[@class='widget']"]) result.Add(ConvertFromXSpan(widget)); LogUtils.LogTrace(_log, "GetContentHandler: all widgets (#)", type, result.Count); } return DreamMessage.Ok(result); }
//--- Methods --- /// <summary> /// Create a subscription document. /// </summary> /// <returns>Subscription Xml document.</returns> public XDoc AsDocument() { XDoc doc = new XDoc("subscription") .Attr("id", Id); foreach (XUri channel in Channels) { doc.Elem("channel", channel); } if (Resources != null) { foreach (XUri resource in Resources) { doc.Elem("uri.resource", resource); } } if (Cookie != null) { doc.Add(Cookie.AsSetCookieDocument); } if (_isProxy) { doc.Elem("uri.proxy", Destination); } foreach (DispatcherRecipient recipient in Recipients) { doc.Add(recipient.AsDocument()); } return(doc); }
private static XDoc AppendBanXml(XDoc doc, BanBE ban) { UserBE createdBy = UserBL.GetUserById(ban.ByUserId); doc.Attr("id", ban.Id); doc.Attr("href", DekiContext.Current.ApiUri.At("site", "bans", ban.Id.ToString())); if (createdBy != null) { doc.Add(UserBL.GetUserXml(createdBy, "createdby", Utils.ShowPrivateUserInfo(createdBy))); } doc.Elem("date.modified", ban.LastEdit); doc.Elem("description", ban.Reason); doc.Elem("date.expires", ban.Expires); doc.Add(PermissionsBL.GetPermissionXml(ban.RevokeMask, "revoked")); doc.Start("ban.addresses"); if (ban.BanAddresses != null) { foreach (string address in ban.BanAddresses) { doc.Elem("address", address); } } doc.End(); doc.Start("ban.users"); if (ban.BanUserIds != null) { var banUsers = DbUtils.CurrentSession.Users_GetByIds(ban.BanUserIds); foreach (UserBE u in banUsers) { doc.Add(UserBL.GetUserXml(u, null, Utils.ShowPrivateUserInfo(createdBy))); } } doc.End(); return(doc); }
public static XDoc GetGroupXmlVerbose(GroupBE group, string relation) { XDoc groupXml = GetGroupXml(group, relation); ServiceBE authService = ServiceBL.GetServiceById(group.ServiceId); if (authService != null) { groupXml.Add(ServiceBL.GetServiceXml(authService, "authentication")); } groupXml.Start("users"); if (group.UserIdsList != null) { groupXml.Attr("count", group.UserIdsList.Length); } groupXml.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString(), "users")); groupXml.End(); //Permissions for the group RoleBE role = PermissionsBL.GetRoleById(group.RoleId); groupXml.Add(PermissionsBL.GetRoleXml(role, "group")); return(groupXml); }
public XDoc GetTagXml(TagBE tag, bool showPages, string pageFilterLanguage) { string uriText = null, titleText = null; switch (tag.Type) { case TagType.DEFINE: uriText = Utils.AsPublicUiUri(tag.DefinedTo.Title); titleText = tag.Name; break; case TagType.DATE: uriText = _dekiContext.UiUri.Uri.AtPath("Special:Events").With("from", tag.Name).ToString(); DateTime date = DateTime.ParseExact(tag.Name, "yyyy-MM-dd", _culture, DateTimeStyles.None); titleText = date.ToString("D", _culture); break; case TagType.TEXT: if (null != tag.DefinedTo) { uriText = Utils.AsPublicUiUri(tag.DefinedTo.Title); } else { uriText = _dekiContext.UiUri.AtPath("Special:Tags").With("tag", tag.Name).ToString(); } titleText = tag.Name; break; } XDoc result = new XDoc("tag"); result.Attr("value", tag.PrefixedName); result.Attr("id", tag.Id); result.Attr("href", _dekiContext.ApiUri.At("site", "tags", tag.Id.ToString()).ToString()); if (tag.OccuranceCount > 0) { result.Attr("count", tag.OccuranceCount); } result.Elem("type", tag.Type.ToString().ToLowerInvariant()); result.Elem("uri", uriText); result.Elem("title", titleText); if (null != tag.RelatedPages) { result.Add(PageBL.GetPageListXml(tag.RelatedPages, "related")); } if (showPages) { IList <PageBE> pages = GetTaggedPages(tag); if (pageFilterLanguage != null) { // filter pages by language pages = (from page in pages where page.Language == pageFilterLanguage select page).ToList(); } result.Add(PageBL.GetPageListXml(pages, "pages")); } return(result); }
public DreamMessage GetContentHandler(DreamContext context, DreamMessage message) { user user = Authenticate(context, message, DekiUserLevel.User); page page = Authorize(context, user, DekiAccessLevel.Read, "pageid"); DekiContext deki = new DekiContext(message, this.DekiConfig); bool nofollow = (context.Uri.GetParam("nofollow", 0, null) != null); string contents = page.getContent(nofollow); string xml = string.Format(DekiWikiService.XHTML_LOOSE, contents); XDoc doc = XDoc.FromXml(xml); if (doc == null) { LogUtils.LogWarning(_log, "GetContentHandler: null document page content", page.PrefixedName, contents); throw new DreamAbortException(DreamMessage.BadRequest("null document")); } XDoc result = new XDoc("list"); string type = context.Uri.GetParam("type", 0, null); string id = context.Uri.GetParam("id", 0, null); if (id != null) { XDoc widget = doc[string.Format("//default:span[@widgetid={0}]", id)]; if (widget.IsEmpty) { LogUtils.LogWarning(_log, "GetContentHandler: widget not found for ID", id); return(DreamMessage.NotFound("")); } LogUtils.LogTrace(_log, "GetContentHandler: widget by id (id, xspan)", id, widget); result.Add(ConvertFromXSpan(widget)); } else if (type != null) { foreach (XDoc widget in doc[string.Format("//default:span[@widgettype='{0}']", type)]) { result.Add(ConvertFromXSpan(widget)); } LogUtils.LogTrace(_log, "GetContentHandler: widget by type (type, #)", type, result.Count); } else { foreach (XDoc widget in doc["//default:span[@class='widget']"]) { result.Add(ConvertFromXSpan(widget)); } LogUtils.LogTrace(_log, "GetContentHandler: all widgets (#)", type, result.Count); } return(DreamMessage.Ok(result)); }
private void InsertRecord(DirectoryRecord record) { // add value to directory lock (_directory) { _directory[record.Name] = record; } // check if value has an expiration time if (record.HasExpiration) { TimerFactory.New(record.Expiration, OnExpire, record.Name, TaskEnv.New()); } SaveToFileSystem(record.Name, record.Value); // notify event channel XDoc notify = new XDoc("insert").Attr("name", record.Name); if (record.HasExpiration) { notify.Attr("expire", record.Expiration); } notify.Add(record.Value); _events.Post(notify, new Result <DreamMessage>(TimeSpan.MaxValue)); }
public Yield GetGroupUsers(DreamContext context, DreamMessage request, Result <DreamMessage> response) { PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ); GroupBE group = GetGroupFromUrl(); DreamMessage responseMsg = null; uint totalCount; uint queryCount; var usersInGroup = UserBL.GetUsersByQuery(context, group.Id, out totalCount, out queryCount); XDoc ret = new XDoc("users"); ret.Attr("count", usersInGroup.Count()); ret.Attr("querycount", queryCount); ret.Attr("totalcount", totalCount); ret.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString(), "users")); foreach (UserBE member in usersInGroup) { ret.Add(UserBL.GetUserXml(member, null, Utils.ShowPrivateUserInfo(member))); } responseMsg = DreamMessage.Ok(ret); response.Return(responseMsg); yield break; }
private static XDoc GetFeatureOverview(XDoc feature) { // generate a document containing the overview information for a feature XDoc overviewDoc = new XDoc("html"); overviewDoc.Start("h2").Value("Overview").End(); overviewDoc.Add(GetWarning()); overviewDoc.Start("p").Start("strong").Value(feature["access"].Contents + ". ").End().Value(feature["description"].Contents).End(); XDoc uriParams = new XDoc("uriParams"); XDoc queryParams = new XDoc("queryParams"); foreach(XDoc param in feature["param"]) { string paramName = param["name"].Contents; if(paramName.StartsWith("{")) { if(feature["pattern"].Contents.Contains(paramName)) { param["name"].ReplaceValue(paramName.Trim(new char[] { '{', '}' })); uriParams.Add(param); } } else { queryParams.Add(param); } } overviewDoc.Start("h5").Value("Uri Parameters").End(); overviewDoc.Add(GetTable(new string[] { "Name", "Type", "Description" }, uriParams["param"])); overviewDoc.Start("h5").Value("Query Parameters").End(); overviewDoc.Add(GetTable(new string[] { "Name", "Type", "Description" }, queryParams["param"])); overviewDoc.Start("h5").Value("Return Codes").End(); XDoc statusesDoc = new XDoc("statuses"); foreach(XDoc statusDoc in feature["status"]) { DreamStatus status = (DreamStatus)statusDoc["@value"].AsInt; statusesDoc.Start("status").Elem("name", status.ToString()).Elem("value", (int)status).Elem("description", statusDoc.Contents).End(); } overviewDoc.Add(GetTable(new string[] { "Name", "Value", "Description" }, statusesDoc["status"])); return overviewDoc; }
public XDoc GetAttachmentRevisionListXml(IList <ResourceBE> fileList, XUri href) { XDoc attachmentListDoc = null; attachmentListDoc = new XDoc("files"); attachmentListDoc.Attr("count", fileList == null ? 0 : fileList.Count); if (href != null) { attachmentListDoc.Attr("href", href); } if (fileList != null) { List <ResourceBE> sortedFiles = new List <ResourceBE>(fileList); sortedFiles = SortFileListByNameAndRevision(sortedFiles); //HACK: Convenient place to ensure all images that haven't been identified are looked at IdentifyUnknownImages(sortedFiles); //Add attachment info to list wrapper xml foreach (ResourceBE att in sortedFiles) { attachmentListDoc.Add(GetFileXml(att, true, null, null)); } } return(attachmentListDoc); }
private void Add(XUri href, XDoc manifestXml) { string data = Convert.ToString(_id++); AddRequest("GET", href, data); manifestXml.Attr("dataid", data); _manifestDoc.Add(manifestXml); }
private static DreamMessage Response(string methodName, XDoc body) { var doc = new XDoc("response").Elem("method", methodName); if (body != null) { doc.Add(body); } return(DreamMessage.Ok(doc)); }
private static XDoc GetFeatureOverview(XDoc feature) { // generate a document containing the overview information for a feature XDoc overviewDoc = new XDoc("html"); overviewDoc.Start("h2").Value("Overview").End(); overviewDoc.Add(GetWarning()); overviewDoc.Start("p").Start("strong").Value(feature["access"].Contents + ". ").End().Value(feature["description"].Contents).End(); XDoc uriParams = new XDoc("uriParams"); XDoc queryParams = new XDoc("queryParams"); foreach (XDoc param in feature["param"]) { string paramName = param["name"].Contents; if (paramName.StartsWith("{")) { if (feature["pattern"].Contents.Contains(paramName)) { param["name"].ReplaceValue(paramName.Trim(new char[] { '{', '}' })); uriParams.Add(param); } } else { queryParams.Add(param); } } overviewDoc.Start("h5").Value("Uri Parameters").End(); overviewDoc.Add(GetTable(new string[] { "Name", "Type", "Description" }, uriParams["param"])); overviewDoc.Start("h5").Value("Query Parameters").End(); overviewDoc.Add(GetTable(new string[] { "Name", "Type", "Description" }, queryParams["param"])); overviewDoc.Start("h5").Value("Return Codes").End(); XDoc statusesDoc = new XDoc("statuses"); foreach (XDoc statusDoc in feature["status"]) { DreamStatus status = (DreamStatus)statusDoc["@value"].AsInt; statusesDoc.Start("status").Elem("name", status.ToString()).Elem("value", (int)status).Elem("description", statusDoc.Contents).End(); } overviewDoc.Add(GetTable(new string[] { "Name", "Value", "Description" }, statusesDoc["status"])); return(overviewDoc); }
protected Yield DiagnosticGetAllSubscriptionSets(DreamContext context, DreamMessage request, Result <DreamMessage> response) { XDoc sets = new XDoc("subscription-sets"); foreach (PubSubSubscriptionSet set in _dispatcher.GetAllSubscriptionSets()) { sets.Add(set.AsDocument()); } response.Return(DreamMessage.Ok(sets)); yield break; }
public Yield GetAllRecords(DreamContext context, DreamMessage request, Result<DreamMessage> response) { XDoc result = new XDoc("list"); lock(_directory) { foreach(KeyValuePair<string, DirectoryRecord> entry in _directory) { result.Add(entry.Value.ToXDoc()); } } response.Return(DreamMessage.Ok(result)); yield break; }
public Yield GetSiteRoles(DreamContext context, DreamMessage request, Result<DreamMessage> response) { IList<RoleBE> roles = DbUtils.CurrentSession.RolesRestrictions_GetRoles(); XDoc ret = new XDoc("roles"); ret.Attr("href", DekiContext.Current.ApiUri.At("site", "roles")); if (roles != null) { foreach (RoleBE r in roles) { ret.Add(PermissionsBL.GetRoleXml(r, null)); } } response.Return(DreamMessage.Ok(ret)); yield break; }
public Yield GetAllRecords(DreamContext context, DreamMessage request, Result <DreamMessage> response) { XDoc result = new XDoc("list"); lock (_directory) { foreach (KeyValuePair <string, DirectoryRecord> entry in _directory) { result.Add(entry.Value.ToXDoc()); } } response.Return(DreamMessage.Ok(result)); yield break; }
public XDoc BuildReport(params Report[] reports) { foreach (var r in reports) { r.AddStatsToDocument(); Total += r.Total; Missing += r.Missing; Stale += r.Stale; Document.Add(r.Document); } AddStatsToDocument(); return(Document); }
private void SaveUsersAndGroupsToXML() { XDoc doc = new XDoc(UsersAndGroupsXMLRootName); foreach (string confluenceUserName in _convertedUsers.Keys) { ACConverterUserInfo userInfo = _convertedUsers[confluenceUserName]; XDoc userDoc = new XDoc(UserXMLTagName); userDoc.Attr(ConfluenceUserNameXMLAttributeName, confluenceUserName); userDoc.Attr(DekiUserNameXMLAttributeName, userInfo.DekiUserName); doc.Add(userDoc); } foreach (string confluenceGroupName in _convertedGroups.Keys) { ACConverterGroupInfo groupInfo = _convertedGroups[confluenceGroupName]; XDoc groupDoc = new XDoc(GroupXMLTagName); groupDoc.Attr(ConfluenceGroupNameXMLAttributeName, confluenceGroupName); groupDoc.Attr(DekiGroupNameXMLAttributeName, groupInfo.DekiGroupName); doc.Add(groupDoc); } doc.Save(ConvertedUsersAndGroupsFileName); }
internal static XDoc ExecuteScript(Plug env, DreamHeaders headers, XDoc script) { // execute script commands XDoc reply = new XDoc("results"); string ID = script["@ID"].Contents; if(!string.IsNullOrEmpty(ID)) { reply.Attr("ID", ID); } foreach(XDoc cmd in script.Elements) { reply.Add(ExecuteCommand(env, headers, cmd)); } return reply; }
private void SetError(XDoc doc, string wikiId, string status, Exception e, string message, params object[] args) { var exceptionMessage = e == null ? "" : e.Message; _log.DebugFormat("[" + wikiId + "] " + message + ": " + exceptionMessage, args); doc.Start("status") .Attr("code", status) .Elem("message", string.Format(message, args)); if (e != null) { doc.Add(new XException(e)); } doc.End(); }
internal static XDoc ExecuteFork(Plug env, DreamHeaders headers, XDoc fork) { // execute script commands XDoc reply = new XDoc("results"); string ID = fork["@ID"].Contents; if(!string.IsNullOrEmpty(ID)) { reply.Attr("ID", ID); } // TODO (steveb): we should use a 'fixed capacity' cue which marks itself as done when 'count' is reached XDoc forks = fork.Elements; foreach(XDoc cmd in forks) { // TODO (steveb): we should be doing this in parallel, not sequentially! try { reply.Add(ExecuteCommand(env, headers, cmd)); } catch(Exception e) { reply.Add(new XException(e)); } } return reply; }
/// <summary> /// Create a <see cref="IDreamService"/> on a given <see cref="DreamHost"/>. /// </summary> /// <param name="hostInfo">The info instance for the target <see cref="DreamHost"/>.</param> /// <param name="sid">Service Identifier</param> /// <param name="pathPrefix">Path prefix to use for randomly generated path (primarily used to more easily recognize the service in logs).</param> /// <param name="extraConfig">Additional configuration to use for service instantiation.</param> /// <returns>An instance of <see cref="DreamServiceInfo"/> for easy service access</returns> public static DreamServiceInfo CreateService(this DreamHostInfo hostInfo, string sid, string pathPrefix, XDoc extraConfig) { string path = (string.IsNullOrEmpty(pathPrefix)) ? StringUtil.CreateAlphaNumericKey(6).ToLower() : pathPrefix + "_" + StringUtil.CreateAlphaNumericKey(3).ToLower(); XDoc config = new XDoc("config") .Elem("sid", sid) .Elem("path", path); if (extraConfig != null) { foreach (XDoc extra in extraConfig["*"]) { config.Add(extra); } } return(CreateService(hostInfo, config)); }
private void AssertFeature(string pattern, Result <DreamMessage> result, XDoc expected) { var feature = _blueprint[string.Format("features/feature[pattern='{0}']", pattern)]; Assert.IsTrue(feature.Any(), string.Format("service doesn't have a feature for {0}", pattern)); var doc = new XDoc("response").Elem("method", feature["method"].AsText); if (expected != null) { doc.Add(expected); } var response = result.Wait(); Assert.IsTrue(response.IsSuccessful, response.GetErrorString()); Assert.AreEqual(doc.ToCompactString(), response.ToDocument().ToCompactString()); }
internal static XDoc ExecuteScript(Plug env, DreamHeaders headers, XDoc script) { // execute script commands XDoc reply = new XDoc("results"); string ID = script["@ID"].Contents; if (!string.IsNullOrEmpty(ID)) { reply.Attr("ID", ID); } foreach (XDoc cmd in script.Elements) { reply.Add(ExecuteCommand(env, headers, cmd)); } return(reply); }
//--- Methods --- /// <summary> /// Create a new subscription set document. /// </summary> /// <returns>Set Xml document.</returns> public XDoc AsDocument() { XDoc doc = new XDoc("subscription-set") .Attr("max-failures", MaxFailures) .Elem("uri.owner", Owner); if (Version.HasValue) { doc.Attr("version", Version.Value); } foreach (PubSubSubscription subscription in Subscriptions) { doc.Add(subscription.AsDocument()); } return(doc); }
public Yield GetSiteRoles(DreamContext context, DreamMessage request, Result <DreamMessage> response) { IList <RoleBE> roles = DbUtils.CurrentSession.RolesRestrictions_GetRoles(); XDoc ret = new XDoc("roles"); ret.Attr("href", DekiContext.Current.ApiUri.At("site", "roles")); if (roles != null) { foreach (RoleBE r in roles) { ret.Add(PermissionsBL.GetRoleXml(r, null)); } } response.Return(DreamMessage.Ok(ret)); yield break; }
public Yield GetGroups(DreamContext context, DreamMessage request, Result<DreamMessage> response) { PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ); uint totalCount, queryCount; IList<GroupBE> groups = GroupBL.GetGroupsByQuery(context, out totalCount, out queryCount); XDoc result = new XDoc("groups"); result.Attr("count", groups.Count); result.Attr("querycount", queryCount); result.Attr("totalcount", totalCount); result.Attr("href", DekiContext.Current.ApiUri.At("groups")); foreach(GroupBE g in groups) { result.Add(GroupBL.GetGroupXmlVerbose(g, null)); } response.Return(DreamMessage.Ok(result)); yield break; }
/// <summary> /// Create a new mock service instance. /// </summary> /// <param name="hostInfo">Host info.</param> /// <param name="extraConfig">Additional service configuration.</param> /// <param name="privateStorage">Use private storage</param> /// <returns>New mock service info instance.</returns> public static MockServiceInfo CreateMockService(DreamHostInfo hostInfo, XDoc extraConfig, bool privateStorage) { var path = StringUtil.CreateAlphaNumericKey(8); var type = privateStorage ? typeof(MockServiceWithPrivateStorage) : typeof(MockService); var config = new XDoc("config") .Elem("class", type.FullName) .Elem("path", path); if (extraConfig != null) { foreach (var extra in extraConfig["*"]) { config.Add(extra); } } hostInfo.Host.Self.At("services").Post(config); _log.DebugFormat("path: {0}", path); return(new MockServiceInfo(hostInfo, path, MockRegister[path])); }
public Yield GetServices(DreamContext context, DreamMessage request, Result<DreamMessage> response) { bool privateDetails = PermissionsBL.IsUserAllowed(DekiContext.Current.User, Permissions.ADMIN); //Private feature requires api-key uint totalCount; uint queryCount; IList<ServiceBE> services = ServiceBL.GetServicesByQuery(context, out totalCount, out queryCount); XDoc result = new XDoc("services"); result.Attr("count", services.Count); result.Attr("querycount", queryCount); result.Attr("totalcount", totalCount); result.Attr("href", DekiContext.Current.ApiUri.At("site", "services")); foreach(ServiceBE s in services) { result.Add(ServiceBL.GetServiceXmlVerbose(DekiContext.Current.Instance, s, null, privateDetails)); } response.Return(DreamMessage.Ok(result)); yield break; }
public Yield FeatureGetGroups(DreamContext context, DreamMessage request, Result <DreamMessage> response) { Authenticate(context, request); Group[] groups = GetGroups(); if (groups == null) { response.Return(DreamMessage.NotFound("No groups found")); } else { XDoc result = new XDoc("groups"); foreach (Group group in groups) { result.Add(group.ToXml()); } response.Return(DreamMessage.Ok(result)); } yield break; }
//--- Class Methods --- private static void Main(string[] args) { Plug host = null; try { // create the dream environment XDoc dreamConfigDoc = new XDoc("config"); dreamConfigDoc.Elem("server-name", MKS_PATH); dreamConfigDoc.Elem("service-dir", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); dreamConfigDoc.Elem("apikey", API_KEY); host = (new DreamHost(dreamConfigDoc)).Self.With("apikey", API_KEY); host.At("load").With("name", "mindtouch.deki.mwconverter").Post(); host.At("load").With("name", "mindtouch.deki").Post(); host.At("load").With("name", "mindtouch.indexservice").Post(); host.At("load").With("name", "mindtouch.deki.services").Post(); } catch (Exception e) { Console.WriteLine("An unexpected error occurred while creating the dream host."); Console.WriteLine(e); Environment.Exit(1); } try { // load the configuration information XDoc converterConfigDoc = XDocFactory.LoadFrom(CONFIG_FILE, MimeType.XML); XDoc dekiConfigDoc = XDocFactory.LoadFrom(converterConfigDoc["//deki/startup-xml"].Contents, MimeType.XML)["//config"]; dekiConfigDoc["path"].ReplaceValue("converter"); dekiConfigDoc["sid"].ReplaceValue("http://services.mindtouch.com/deki/internal/2007/12/mediawiki-converter"); dekiConfigDoc.Add(converterConfigDoc["//mediawiki"]); host.At("services").Post(dekiConfigDoc); } catch (Exception e) { Console.WriteLine("An unexpected error occurred while loading the converter configuration settings."); Console.WriteLine(e); Environment.Exit(1); } Plug service = Plug.New(host.Uri.AtAbsolutePath("converter"), TimeSpan.MaxValue); service.PostAsync(); Console.ReadLine(); }
private void PageChanged(DateTime eventTime, PageBE page, UserBE user, XDoc extra, params string[] path) { try { XUri channel = _channel.At(PAGES).At(path); XUri resource = PageBL.GetUriCanonical(page).WithHost(_wikiid); string[] origin = new string[] { PageBL.GetUriCanonical(page).AsServerUri().ToString(), XUri.Localhost + "/" + page.Title.AsUiUriPath() }; XDoc doc = new XDoc("deki-event") .Elem("channel", channel) // BUGBUGBUG: This will generally generate a Uri based on the request that caused the event, // which may not really be canonical .Elem("uri", PageBL.GetUriCanonical(page).AsPublicUri().ToString()) .Elem("pageid", page.ID) .Start("user") .Attr("id", user.ID) .Attr("anonymous", UserBL.IsAnonymous(user)) .Elem("uri", UserBL.GetUri(user)) .End() .Start("content.uri") .Attr("type", "application/xml") .Value(PageBL.GetUriContentsCanonical(page).With("format", "xhtml").AsServerUri().ToString()) .End() .Elem("revision.uri", PageBL.GetUriRevisionCanonical(page).AsServerUri().ToString()) .Elem("tags.uri", PageBL.GetUriCanonical(page).At("tags").AsServerUri().ToString()) .Elem("comments.uri", PageBL.GetUriCanonical(page).At("comments").AsServerUri().ToString()) .Elem("path", page.Title.AsUiUriPath()); if (extra != null) { doc.Add(extra); } Queue(eventTime, channel, resource, origin, doc); if (page.Title.IsTalk) { PageBE front = PageBL.GetPageByTitle(page.Title.AsFront()); if ((front != null) && (front.ID > 0)) { PageChanged(eventTime, front, user, extra, ArrayUtil.Concat(new string[] { DEPENDENTS_CHANGED, TALK }, path)); } } } catch (Exception e) { _log.WarnExceptionMethodCall(e, "PageChanged", "event couldn't be created"); } }
private static XDoc BuildXmlSiteMap(PageBE current, XDoc doc, Dictionary <ulong, PageBE> allowedPagesById) { doc.Add(PageBL.GetPageXml(current, null)); XDoc y = doc[doc.AsXmlNode.LastChild].Start("subpages"); if (!ArrayUtil.IsNullOrEmpty(current.ChildPages)) { PageBE[] visibleChildren = Array.FindAll(current.ChildPages, delegate(PageBE child) { return(allowedPagesById.ContainsKey(child.ID)); }); foreach (PageBE child in visibleChildren) { BuildXmlSiteMap(child, y, allowedPagesById); } } y.End(); return(doc); }
//--- Class Methods --- /// <summary> /// Convert an XSpan document to a regular Xml document. /// </summary> /// <param name="xspan">XSpan document.</param> /// <returns>New Xml document instance.</returns> public static XDoc FromXSpan(XDoc xspan) { XDoc xml = new XDoc(xspan["@class"].Contents); foreach(XDoc attr in xspan["@*"]) { if(attr.Name.StartsWithInvariant("xml:")) xml.Attr(attr.Name.Substring("xml:".Length), attr.Contents); } string value = xspan["text()"].Contents; if(value.Length != 0) xml.Value(value); foreach(XDoc child in xspan.Elements) xml.Add(FromXSpan(child)); return xml; }
public void RunScript(XDoc script, string path) { // check if a filename was provided string filename = script["@src"].AsText; if(filename != null) { // check if filename is relative if(!Path.IsPathRooted(filename) && (path != null)) { filename = Path.Combine(path, filename); } // attempt to load script file if(!File.Exists(filename)) { throw new FileNotFoundException(string.Format("script not found: {0}", filename)); } script = XDocFactory.LoadFrom(filename, MimeType.XML); } // execute script if(script == null) { throw new Exception(string.Format("invalid script: {0}", script.AsText)); } // convert <config> element into a <script> element if(script.HasName("config")) { XDoc doc = new XDoc("script"); doc.Start("action").Attr("verb", "POST").Attr("path", "/host/services"); doc.Add(script); doc.End(); script = doc; } // execute script _host.At("execute").Post(script); }
private void SaveConvertedUsersAndGroups() { XDoc usersDoc = new XDoc(ConvertedUsersRootName); foreach (string tWikiUserName in _convertedUsers.Keys) { XDoc userDoc = new XDoc(ConvertedUserTagName); userDoc.Attr(TWikiUserNameAttribute, tWikiUserName); userDoc.Attr(DekiUserNameAttribute, _convertedUsers[tWikiUserName].DekiName); usersDoc.Add(userDoc); } foreach (string tWikiGroupName in _convertedGroups.Keys) { XDoc groupDoc = new XDoc(ConvertedGroupTagName); groupDoc.Attr(TWikiGroupNameAttribute, tWikiGroupName); groupDoc.Attr(DekiGroupNameAttribute, _convertedGroups[tWikiGroupName].DekiName); usersDoc.Add(groupDoc); } usersDoc.Save(ConvertedUsersFileName); }
internal Yield PostServices(DreamContext context, DreamMessage request, Result<DreamMessage> response) { ServiceBL.EnsureServiceAdministrationAllowed(); if(request.HasDocument && !request.ToDocument().IsEmpty) { //Add or Modify a service ServiceBE service = ServiceBL.PostServiceFromXml(request.ToDocument(), null); response.Return(DreamMessage.Ok(ServiceBL.GetServiceXmlVerbose(DekiContext.Current.Instance, service, null))); } else { //Backward compatibility: posting an empty document restarts all local services XDoc ret = new XDoc("services"); foreach(ServiceBE service in ServiceBL.RestartServices()) { ret.Add(ServiceBL.GetServiceXml(service, null)); } response.Return(DreamMessage.Ok(ret)); } yield break; }
/// <summary> /// Create a new host with provided configuration and an Inversion of Control container. /// </summary> /// <remarks> /// The IoC container is also injected into default activator, so that <see cref="IDreamService"/> instances /// can be resolved from the container. The host configuration is provided to the container as a typed parameter. /// </remarks> /// <param name="config">Host configuration.</param> /// <param name="container">IoC Container.</param> public DreamHost(XDoc config, IContainer container) { if(config == null) { throw new ArgumentNullException("config"); } // read host settings string appDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName); int limit = config["connect-limit"].AsInt ?? 0; int httpPort = config["http-port"].AsInt ?? DEFAULT_PORT; AuthenticationSchemes authenticationScheme = AuthenticationSchemes.Anonymous; string authShemes = config["authentication-shemes"].AsText; if(!String.IsNullOrEmpty(authShemes)) { try { authenticationScheme = (AuthenticationSchemes)Enum.Parse(typeof(AuthenticationSchemes), authShemes, true); } catch(Exception e) { _log.Warn(String.Format("invalid authetication scheme specified :{0}", authShemes), e); } } // get the authtoken for whitelisting dream.in.* query args _dreamInParamAuthtoken = config["dream.in.authtoken"].AsText; if(!string.IsNullOrEmpty(_dreamInParamAuthtoken)) { _log.Debug("Host is configured in dream.in param authorizing mode"); } // read ip-addresses var addresses = new List<string>(); foreach(XDoc ip in config["host|ip"]) { addresses.Add(ip.AsText); } if(addresses.Count == 0) { // if no addresses were supplied listen to all addresses.Add("*:" + httpPort); } // use default servername XUri publicUri = config["uri.public"].AsUri; if(publicUri == null) { // backwards compatibility publicUri = config["server-name"].AsUri; if(publicUri == null) { foreach(IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName())) { if(addr.AddressFamily == AddressFamily.InterNetwork) { XUri.TryParse("http://" + addr, out publicUri); } } if(publicUri == null) { // failed to get an address out of dns, fall back to localhost XUri.TryParse("http://localhost", out publicUri); } } publicUri = publicUri.AtPath(config["server-path"].AsText ?? config["path-prefix"].AsText ?? string.Empty); } // create environment and initialize it _env = new DreamHostService(container); try { // initialize environment string apikey = config["apikey"].AsText ?? StringUtil.CreateAlphaNumericKey(32); XDoc serviceConfig = new XDoc("config"); var storageType = config["storage/@type"].AsText ?? "local"; if("s3".EqualsInvariant(storageType)) { serviceConfig.Add(config["storage"]); } else { serviceConfig.Elem("storage-dir", config["storage-dir"].AsText ?? config["service-dir"].AsText ?? appDirectory); } serviceConfig.Elem("apikey", apikey); serviceConfig.Elem("uri.public", publicUri); serviceConfig.Elem("connect-limit", limit); serviceConfig.Elem("guid", config["guid"].AsText); serviceConfig.AddAll(config["components"]); var memorize = config["memorize-aliases"]; if(!memorize.IsEmpty) { serviceConfig.Elem("memorize-aliases", memorize.AsBool); } _env.Initialize(serviceConfig); // initialize host plug _host = _env.Self.With("apikey", apikey); // load assemblies in 'services' folder string servicesFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "services"); if(Directory.Exists(servicesFolder)) { // Note (arnec): Deprecated, but the suggested alternative really doesn't apply since we don't want to // load services into a separate appdomain. #pragma warning disable 618,612 AppDomain.CurrentDomain.AppendPrivatePath("services"); #pragma warning restore 618,612 foreach(string file in Directory.GetFiles(servicesFolder, "*.dll")) { // register assembly blueprints DreamMessage response = _host.At("load").With("name", Path.GetFileNameWithoutExtension(file)).Post(new Result<DreamMessage>(TimeSpan.MaxValue)).Wait(); if(!response.IsSuccessful) { _log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file); } } } // add acccess-points AddListener(new XUri(String.Format("http://{0}:{1}/", "localhost", httpPort)), authenticationScheme); // check if user prescribed a set of IP addresses to use if(addresses != null) { // listen to custom addresses (don't use the supplied port info, we expect that to be part of the address) foreach(string address in addresses) { if(!StringUtil.EqualsInvariantIgnoreCase(address, "localhost")) { AddListener(new XUri(String.Format("http://{0}/", address)), authenticationScheme); } } } else { // add listeners for all known IP addresses foreach(IPAddress address in Dns.GetHostAddresses(Dns.GetHostName())) { XUri uri = MakeUri(address, httpPort); if(uri != null) { AddListener(uri, authenticationScheme); try { foreach(string alias in Dns.GetHostEntry(address).Aliases) { AddListener(new XUri(String.Format("http://{0}:{1}/", alias, httpPort)), authenticationScheme); } } catch { } } } } } catch(Exception e) { if((e is HttpListenerException) && e.Message.EqualsInvariant("Access is denied")) { _log.ErrorExceptionMethodCall(e, "ctor", "insufficient privileges to create HttpListener, make sure the application runs with Administrator rights"); } else { _log.ErrorExceptionMethodCall(e, "ctor"); } try { _env.Deinitialize(); } catch { } throw; } }
private void AssertFeature(string pattern, Result<DreamMessage> result, XDoc expected) { var feature = _blueprint[string.Format("features/feature[pattern='{0}']", pattern)]; Assert.IsTrue(feature.Any(), string.Format("service doesn't have a feature for {0}", pattern)); var doc = new XDoc("response").Elem("method", feature["method"].AsText); if(expected != null) { doc.Add(expected); } var response = result.Wait(); Assert.IsTrue(response.IsSuccessful, response.GetErrorString()); Assert.AreEqual(doc.ToCompactString(), response.ToDocument().ToCompactString()); }
private void SaveUsersAndGroupsToXML() { XDoc doc = new XDoc(UsersAndGroupsXMLRootName); foreach (string confluenceUserName in _convertedUsers.Keys) { ACConverterUserInfo userInfo = _convertedUsers[confluenceUserName]; XDoc userDoc = new XDoc(UserXMLTagName); userDoc.Attr(ConfluenceUserNameXMLAttributeName, confluenceUserName); userDoc.Attr(DekiUserNameXMLAttributeName, userInfo.DekiUserName); doc.Add(userDoc); } foreach (string confluenceGroupName in _convertedGroups.Keys) { ACConverterGroupInfo groupInfo = _convertedGroups[confluenceGroupName]; XDoc groupDoc = new XDoc(GroupXMLTagName); groupDoc.Attr(ConfluenceGroupNameXMLAttributeName, confluenceGroupName); groupDoc.Attr(DekiGroupNameXMLAttributeName, groupInfo.DekiGroupName); doc.Add(groupDoc); } doc.Save(ConvertedUsersAndGroupsFileName); }
public Yield GetUsers(DreamContext context, DreamMessage request, Result<DreamMessage> response) { // TODO (steveb): add 'emailfilter' and use it to obsolete 'usernameemailfilter'; 'usernamefilter', 'fullnamefilter', and 'emailfilter' // should be OR'ed together when they are present. PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ); uint totalCount; uint queryCount; IList<UserBE> users = UserBL.GetUsersByQuery(context, null, out totalCount, out queryCount); XDoc result = new XDoc("users"); result.Attr("count", users.Count); result.Attr("querycount", queryCount); result.Attr("totalcount", totalCount); result.Attr("href", DekiContext.Current.ApiUri.At("users")); foreach (UserBE u in users) { result.Add(UserBL.GetUserXmlVerbose(u, null, Utils.ShowPrivateUserInfo(u))); } response.Return(DreamMessage.Ok(result)); yield break; }
private static DreamMessage Response(string methodName, XDoc body) { var doc = new XDoc("response").Elem("method", methodName); if(body != null) { doc.Add(body); } return DreamMessage.Ok(doc); }
public Yield GetSiteFunctions(DreamContext context, DreamMessage request, Result<DreamMessage> response) { PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.UPDATE); // build set of libraries List<XDoc> libraries = DekiContext.Current.Instance.RunningServices.ExtensionServices .Select(x => x.Extension.Manifest).ToList(); // add registered libraries libraries.Sort((left, right) => left["title"].Contents.CompareInvariantIgnoreCase(right["title"].Contents)); // add built-in functions XDoc builtinlib = new XDoc("extension"); builtinlib.Elem("title", "Built-in Functions"); builtinlib.Elem("label", "Built-in"); builtinlib.Elem("uri.help", "http://wiki.developer.mindtouch.com/MindTouch_Deki/DekiScript/Reference"); builtinlib.Elem("description", "The following functions and variables are part the DekiScript and MindTouch runtime environment."); foreach(var function in ScriptRuntime.Functions.Values) { if(function.Access == DreamAccess.Public) { builtinlib.Add(function.ToXml(null)); } } libraries.Insert(0, builtinlib); // create composite document bool hasUnsafeContentPermission = PermissionsBL.IsUserAllowed(DekiContext.Current.User, Permissions.UNSAFECONTENT); XDoc extensions = new XDoc("extensions").AddAll(libraries); foreach(XDoc extension in extensions["extension"]) { XUri serviceUri = extension["@uri"].AsUri; // check if extension is protected bool @protected; bool.TryParse(ExtensionBL.GetExtensionPreference(serviceUri, "protected"), out @protected); if(@protected) { if(!hasUnsafeContentPermission) { extension.Remove(); continue; } extension.Attr("protected", @protected); } // read overwriteable settings AddOrReplace(extension, "title", ExtensionBL.GetExtensionPreference(serviceUri, "title.custom")); AddOrReplace(extension, "uri.logo", ExtensionBL.GetExtensionPreference(serviceUri, "uri.logo.custom")); AddOrReplace(extension, "namespace", ExtensionBL.GetExtensionPreference(serviceUri, "namespace.custom")); extension.Elem("description.custom", ExtensionBL.GetExtensionPreference(serviceUri, "description.custom")); // check which functions to keep string[] allowedFunctions = (ExtensionBL.GetExtensionPreference(serviceUri, "functions") ?? string.Empty).Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); if(allowedFunctions.Length > 0) { foreach(XDoc function in extension["function"]) { // check if user specified a list of functions to show string name = function["name"].Contents; if(Array.FindIndex(allowedFunctions, current => current.EqualsInvariantIgnoreCase(name)) < 0) { function.Remove(); } } } // check if extension has any functions if(extension["function"].ListLength == 0) { extension.Remove(); } } // build response document string format = context.GetParam("format", "html"); if(StringUtil.EqualsInvariant(format, "xml")) { response.Return(DreamMessage.Ok(extensions)); } else { // prepare document string header = string.Format("{0} - Registered Extensions", DekiContext.Current.Instance.SiteName); XDoc result = new XDoc("html").Attr("xmlns", "http://www.w3.org/1999/xhtml") .Start("head") .Elem("title", header) .Start("meta").Attr("http-equiv", "content-type").Attr("content", "text/html;charset=utf-8").End() .End(); result.Start("body"); result.Elem("h1", header); // build table of contents result.Elem("strong", "Table of Contents"); result.Start("ol"); int count = 0; foreach(XDoc library in extensions["extension"]) { ++count; XUri serviceUri = library["@uri"].AsUri; result.Start("li").Start("a").Attr("href", "#section" + count).Value(ExtensionBL.GetExtensionPreference(serviceUri, "title.custom") ?? library["title"].AsText).End().End(); } result.End(); // enumerate libraries count = 0; foreach(XDoc library in extensions["extension"]) { ++count; // read overwriteable settings string title = library["title"].AsText; string logo = library["uri.logo"].AsText; string ns = library["namespace"].AsText; bool @protected = library["@protected"].AsBool ?? false; // show & link library name result.Start("h2").Attr("id", "section" + count); if(!string.IsNullOrEmpty(library["uri.help"].AsText)) { result.Start("a").Attr("href", library["uri.help"].AsText).Attr("target", "_blank").Attr("title", library["title"].AsText + " Documentation").Value(title).End(); } else { result.Value(title); } if(@protected) { result.Value(string.Format(" ({0})", DekiResources.PROTECTED)); } result.End(); // show optional logo if(!string.IsNullOrEmpty(logo)) { result.Start("img").Attr("src", logo).Attr("alt", title).End(); } // show descriptions if(library["uri.license"].AsText != null) { result.Start("a").Attr("href", library["uri.license"].AsText).Attr("target", "_blank").Value("Read Library License").End(); } if(!string.IsNullOrEmpty(library["description"].AsText)) { result.Elem("p", library["description"].AsText); } if(!string.IsNullOrEmpty(library["description.custom"].AsText)) { result.Elem("p", library["description.custom"].AsText); } // enumerate library functions XDoc functions = new XDoc("functions").AddAll(library["function"]); functions.Sort(delegate(XDoc left, XDoc right) { return StringUtil.CompareInvariantIgnoreCase(left["name"].Contents, right["name"].Contents); }); foreach(XDoc function in functions["function"]) { AddFunction(result, ns, function); } } result.End(); switch(format) { default: case "html": response.Return(DreamMessage.Ok(MimeType.HTML, result.ToString())); break; case "body": response.Return(DreamMessage.Ok(MimeType.TEXT_UTF8, result["body"].Contents)); break; } } yield break; }
private static XDoc GetServiceOverview(XDoc service) { // generate a document containing the overview information for a service XDoc overviewDoc = new XDoc("html"); overviewDoc.Start("h2").Value("Overview").End(); overviewDoc.Add(GetWarning()); overviewDoc.Start("strong").Value("Assembly: ").End().Value(service["assembly"].Contents); overviewDoc.Add(new XDoc("br")); overviewDoc.Start("strong").Value("Class: ").End().Value(service["class"].Contents); overviewDoc.Add(new XDoc("br")); overviewDoc.Start("strong").Value("SID: ").End().Value(service["sid"].Contents); overviewDoc.Start("h5").Value("Configuration").End(); overviewDoc.Add(GetTable(new string[] { "Name", "Type", "Description" }, service["configuration/entry"])); overviewDoc.Start("h5").Value("Features").End(); XDoc featuresDoc = new XDoc("features"); foreach(XDoc featureDoc in service["features/feature"]) { string name = featureDoc["pattern"].Contents; if(!IsExcludedFeature(name)) { featuresDoc.Start("feature").Start("name").Value(String.Format("[[./{0}|{1}]]", name.Replace("/", "//"), name)).End().Start("description").Value(featureDoc["description"].Contents).End().End(); } } overviewDoc.Add(GetTable(new string[] { "Name", "Description" }, featuresDoc["feature"])); return overviewDoc; }
public XDoc GetAttachmentRevisionListXml(IList<ResourceBE> fileList, XUri href) { XDoc attachmentListDoc = null; attachmentListDoc = new XDoc("files"); attachmentListDoc.Attr("count", fileList == null ? 0 : fileList.Count); if(href != null) attachmentListDoc.Attr("href", href); if(fileList != null) { List<ResourceBE> sortedFiles = new List<ResourceBE>(fileList); sortedFiles = SortFileListByNameAndRevision(sortedFiles); //HACK: Convenient place to ensure all images that haven't been identified are looked at IdentifyUnknownImages(sortedFiles); //Add attachment info to list wrapper xml foreach(ResourceBE att in sortedFiles) { attachmentListDoc.Add(GetFileXml(att, true, null, null)); } } return attachmentListDoc; }
public Yield GetGroupUsers(DreamContext context, DreamMessage request, Result<DreamMessage> response) { PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ); GroupBE group = GetGroupFromUrl(); DreamMessage responseMsg = null; uint totalCount; uint queryCount; var usersInGroup = UserBL.GetUsersByQuery(context, group.Id, out totalCount, out queryCount); XDoc ret = new XDoc("users"); ret.Attr("count", usersInGroup.Count()); ret.Attr("querycount", queryCount); ret.Attr("totalcount", totalCount); ret.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString(), "users")); foreach(UserBE member in usersInGroup) ret.Add(UserBL.GetUserXml(member, null, Utils.ShowPrivateUserInfo(member))); responseMsg = DreamMessage.Ok(ret); response.Return(responseMsg); yield break; }
public static XDoc GetPermissionsRevokedXml(UserBE user) { XDoc ret = new XDoc("permissions.revoked"); // banning ulong banRevokeMask = BanningBL.GetBanPermissionRevokeMaskForUser(user); if(banRevokeMask != ulong.MinValue) { ret.Add(GetPermissionXml(banRevokeMask, "banning")); } // License: invalid var license = DekiContext.Current.LicenseManager; ulong licenseInvalidRevokeMask = license.LicensePermissionRevokeMask(); if(licenseInvalidRevokeMask != ulong.MaxValue) { ret.Add(GetPermissionXml(licenseInvalidRevokeMask, "license.invalid")); } if(UserBL.IsAnonymous(user)) { // License: anonymous ret.Add(GetPermissionXml(~license.AnonymousUserMask(user), "license.anonymous")); } else if(!user.LicenseSeat && license.IsSeatLicensingEnabled()) { // License: no seat ret.Add(GetPermissionXml(~license.GetUnseatedUserMask(), "license.unseated")); } return ret; }
public static XDoc GetGrantListXml(IList<GrantBE> grants) { XDoc doc = new XDoc("grants"); if(grants != null) { foreach(GrantBE g in grants) { doc.Add(GetGrantXml(g)); } } return doc; }
public static XDoc GetGrantXml(GrantBE grant) { XDoc doc = new XDoc("grant"); //Permissions for the user from user role doc.Add(PermissionsBL.GetRoleXml(grant.Role, null)); if(grant.Type == GrantType.USER) { UserBE user = UserBL.GetUserById(grant.UserId); if(user != null) doc.Add(UserBL.GetUserXml(user, null, Utils.ShowPrivateUserInfo(user))); } else if(grant.Type == GrantType.GROUP) { GroupBE group = GroupBL.GetGroupById(grant.GroupId); if(group != null) doc.Add(GroupBL.GetGroupXml(group, null)); } if(grant.ExpirationDate != DateTime.MaxValue) doc.Start("date.expires").Value(grant.ExpirationDate).End(); doc.Start("date.modified").Value(grant.TimeStamp).End(); UserBE creatorUser = UserBL.GetUserById(grant.CreatorUserId); if(creatorUser != null) doc.Add(UserBL.GetUserXml(creatorUser, "modifiedby", Utils.ShowPrivateUserInfo(creatorUser))); return doc; }
/// <summary> /// Create a new mock service instance. /// </summary> /// <param name="hostInfo">Host info.</param> /// <param name="extraConfig">Additional service configuration.</param> /// <param name="privateStorage">Use private storage</param> /// <returns>New mock service info instance.</returns> public static MockServiceInfo CreateMockService(DreamHostInfo hostInfo, XDoc extraConfig, bool privateStorage) { var path = StringUtil.CreateAlphaNumericKey(8); var type = privateStorage ? typeof(MockServiceWithPrivateStorage) : typeof(MockService); var config = new XDoc("config") .Elem("class", type.FullName) .Elem("path", path); if(extraConfig != null) { foreach(var extra in extraConfig["*"]) { config.Add(extra); } } hostInfo.Host.Self.At("services").Post(config); _log.DebugFormat("path: {0}", path); return new MockServiceInfo(hostInfo, path, MockRegister[path]); }
protected Yield DiagnosticGetAllSubscriptionSets(DreamContext context, DreamMessage request, Result<DreamMessage> response) { var sets = new XDoc("subscription-sets"); foreach(var set in _dispatcher.GetAllSubscriptionSets()) { sets.Add(set.AsDocument()); } response.Return(DreamMessage.Ok(sets)); yield break; }
public Yield PostUsersAllowed(DreamContext context, DreamMessage request, Result<DreamMessage> response) { ulong permissionMask = context.GetParam<ulong>("mask", 0); string operationList = context.GetParam("operations", ""); UserBE u = GetUserFromUrlMustExist(); //Use comma separated permission list or permissionmask from request. Permissions p = Permissions.NONE; if (permissionMask != 0) { p = (Permissions) permissionMask; } //Convert operation list to mask combined with provided mask if (!string.IsNullOrEmpty(operationList)) { try { p |= (Permissions) PermissionsBL.MaskFromPermissionList(PermissionsBL.PermissionListFromString(operationList)); } catch { throw new DreamAbortException(DreamMessage.BadRequest(DekiResources.INVALID_OPERATION_LIST)); } } if (request.ToDocument().HasName("pages")) { //Parse provided page list into objects IList<PageBE> result = PageBL.ReadPagesXml(request.ToDocument()); if (p != Permissions.NONE) { result = PermissionsBL.FilterDisallowed(u, result, false, p); } XDoc responseDoc = new XDoc("pages"); if (result != null) { foreach (PageBE pg in result) { responseDoc.Add(PageBL.GetPageXml(pg, null)); } } response.Return(DreamMessage.Ok(responseDoc)); } else { throw new DreamAbortException(DreamMessage.BadRequest(DekiResources.EXPECTED_ROOT_NODE_PAGES)); } yield break; }
//--- Methods --- /// <summary> /// Create a new subscription set document. /// </summary> /// <returns>Set Xml document.</returns> public XDoc AsDocument() { XDoc doc = new XDoc("subscription-set") .Attr("max-failures", MaxFailures) .Elem("uri.owner", Owner); if(Version.HasValue) { doc.Attr("version", Version.Value); } foreach(PubSubSubscription subscription in Subscriptions) { doc.Add(subscription.AsDocument()); } return doc; }
private void AppendDiff(bool diffCacheEnabled, XDoc body, RecentChangeEntry change, RC type, Title title, IDictionary<string, XDoc> cache) { var resources = DekiContext.Current.Resources; ulong pageid = change.CurId; int? after = (change.Revision > 0) ? (int?)change.Revision : null; int? before = change.PreviousRevision; // append edit summary, if any body.Elem("p", change.Summary); // append comment(s) int count = (change.ExtraComments == null) ? (string.IsNullOrEmpty(change.Comment) ? 0 : 1) : change.ExtraComments.Count; switch(count) { case 0: // nothing to do break; case 1: body.Elem("p", (change.ExtraComments != null) ? change.ExtraComments[0].Item3 : change.Comment); break; default: body.Start("ol"); foreach(var comment in ((IEnumerable<Tuplet<string, string, string>>)change.ExtraComments).Reverse()) { string author = string.IsNullOrEmpty(comment.Item2) ? comment.Item1 : comment.Item2; body.Elem("li", string.IsNullOrEmpty(author) ? comment.Item3 : string.Format("{0} ({1})", comment.Item3, author)); } body.End(); break; } // check if page was modified if(after.HasValue && before.HasValue && (after != before)) { // check if we have a cached version of this page diff XDoc diffXml = null; Plug store = Storage.At("site_" + XUri.EncodeSegment(DekiContext.Current.Instance.Id), DreamContext.Current.Culture.Name, "feeds", string.Format("page_{0}", pageid), string.Format("diff_{0}-{1}.xml", before, after)); if(diffCacheEnabled) { var v = store.Get(new Result<DreamMessage>(TimeSpan.MaxValue)).Wait(); diffXml = (v.IsSuccessful && v.HasDocument) ? v.ToDocument() : null; if(diffXml != null) { // TODO (steveb): this problem only exists b/c we can't determine the actual revision number that we should use for diffing (see bug 7824) // check if either revision has been hidden since we computed the diff var session = DbUtils.CurrentSession; if(after.Value != change.CurrentRevision) { OldBE afterRevision = session.Old_GetOldByRevision(pageid, (ulong)after.Value); if((afterRevision == null) || afterRevision.IsHidden) { diffXml = null; } } if((diffXml != null) && (before.Value != change.CurrentRevision) && (before.Value > 0)) { OldBE beforeRevision = session.Old_GetOldByRevision(pageid, (ulong)before.Value); if((beforeRevision == null) || beforeRevision.IsHidden) { diffXml = null; } } } } if(diffXml == null) { diffXml = new XDoc("diff"); // retrieve page versions XDoc res = QueryPageVersions(pageid, after, before, cache); XDoc beforeDoc = res["before/body"]; XDoc afterDoc = res["after/body"]; // check if either both versions or only one version were retrieved XDoc diff = XDoc.Empty; XDoc invisibleDiff = XDoc.Empty; string summary = null; if(!beforeDoc.IsEmpty && !afterDoc.IsEmpty) { XDoc beforeChanges; XDoc afterChanges; DekiResource summaryResource = null; // compute differences between 'before' and 'after' versions diff = Utils.GetPageDiff(beforeDoc, afterDoc, true, DekiContext.Current.Instance.MaxDiffSize, out invisibleDiff, out summaryResource, out beforeChanges, out afterChanges); // TODO (arnec): why are we using ToLower here at all and without a culture? summary = resources.Localize(summaryResource).ToLower(); } else if(!afterDoc.IsEmpty) { // since we don't have a 'before' version, just show the entire 'after' version (can happen for new pages or hidden revisions) diff = afterDoc; } else if(!beforeDoc.IsEmpty) { // since we don't have a 'after' version, just show the entire 'before' version (can happen for hidden revisions) diff = beforeDoc; } // add change summary diffXml.Start("blockquote"); diffXml.Start("p").Elem("strong", summary).End(); // check if a diff was computed if(!diff.IsEmpty) { diffXml.Start("hr").Attr("width", "100%").Attr("size", "2").End(); diffXml.AddNodes(diff); diffXml.Start("hr").Attr("width", "100%").Attr("size", "2").End(); // check if there are invisible changes as well to show if(!invisibleDiff.IsEmpty) { diffXml.Start("p").Elem("strong", resources.Localize(DekiResources.PAGE_DIFF_OTHER_CHANGES())).End(); diffXml.Add(invisibleDiff); } } else if(!invisibleDiff.IsEmpty) { // only show invisible changes diffXml.Start("hr").Attr("width", "100%").Attr("size", "2").End(); diffXml.Start("p").Elem("strong", resources.Localize(DekiResources.PAGE_DIFF_OTHER_CHANGES())).End(); diffXml.Add(invisibleDiff); } else if(beforeDoc.IsEmpty && afterDoc.IsEmpty) { // show message that page contents were not available anymore diffXml.Elem("p", resources.Localize(DekiResources.PAGE_NOT_AVAILABLE())); } diffXml.End(); // store diff in cache if(diffCacheEnabled && !afterDoc.IsEmpty) { store.With("ttl", TimeSpan.FromDays(30).TotalSeconds).Put(diffXml, new Result<DreamMessage>(TimeSpan.MaxValue)).Block(); } } body.AddNodes(diffXml); } // check if we have a comment text if(Utils.IsPageComment(type)) { string text = change.CmntContent; if(!string.IsNullOrEmpty(text) && !change.CmntDeleted) { MimeType mime = new MimeType(change.CmntMimetype ?? MimeType.TEXT_UTF8.ToString()); if(mime.Match(MimeType.HTML)) { XDoc html = XDocFactory.From(string.Format("<html><body>{0}</body></html>", text), MimeType.HTML); body.Start("blockquote").AddNodes(html["body"]).End(); } else { // anything else should be consider to be text body.Start("blockquote").Elem("p", text).End(); } } else { // anything else should be consider to be text body.Start("blockquote").Elem("p", resources.Localize(DekiResources.COMMENT_NOT_AVAILABLE())).End(); } } // adds links body.Start("table").Attr("border", 0).Attr("padding", "5").Attr("width", "80%").Start("tr"); // add link for viewing the page if(change.PageExists) { Title view = new Title(title); body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(view, true)).Value(resources.Localize(DekiResources.VIEW_PAGE())).End().End(); } // check if we need to add link for editing the page if(after.HasValue && before.HasValue && (after != before)) { Title edit = new Title(title) { Query = "action=edit" }; body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(edit)).Value(resources.Localize(DekiResources.EDIT_PAGE())).End().End(); } // check if we need to add link for viewing the complete diff if(after.HasValue && before.HasValue && (after != before)) { Title show = new Title(title) { Query = string.Format("diff={0}&revision={1}", after.Value, before.Value) }; body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(show, true)).Value(resources.Localize(DekiResources.VIEW_PAGE_DIFF())).End().End(); } // check if we need to add link for seeing full page history if(after.HasValue && before.HasValue && (after != before)) { Title history = new Title(title) { Query = "action=history" }; body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(history)).Value(resources.Localize(DekiResources.VIEW_PAGE_HISTORY())).End().End(); } // check if we need to add link for banning the user List<KeyValuePair<string, string>> authors = change.SortedAuthors; if((authors == null) || (authors.Count == 0)) { authors = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(change.Username, change.Fullname) }; } for(int i = 0; i < authors.Count; ++i) { string username = authors[i].Key; string fullname = authors[i].Value; if(!string.IsNullOrEmpty(username)) { // don't put up ban link for admins. UserBE user = DbUtils.CurrentSession.Users_GetByName(username); if(!UserBL.IsAnonymous(user) && !PermissionsBL.IsUserAllowed(user, Permissions.ADMIN)) { Title ban = Title.FromUIUri(null, "Special:Userban"); ban.Query += string.Format("username={0}", username); body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(ban)).Value(resources.Localize(DekiResources.BAN_USER(string.IsNullOrEmpty(fullname) ? username : fullname))).End().End(); } } } // close HTML body.End().End(); }
public Yield GetExtensionLibrary(DreamContext contex, DreamMessage request, Result<DreamMessage> response) { // create manifest XDoc manifest = new XDoc("extension"); manifest.Elem("title", _title); manifest.Elem("label", _label); manifest.Elem("copyright", _copyright); manifest.Elem("description", _description); manifest.Elem("uri.help", _help); manifest.Elem("uri.logo", _logo); manifest.Elem("namespace", _namespace); // add functions foreach(var function in _functions) { if(function.Value.Access == DreamAccess.Public) { manifest.Add(function.Value.ToXml(function.Key)); } } response.Return(DreamMessage.Ok(manifest)); yield break; }