Beispiel #1
0
        private void RegisterFileResourceTypeImpl(string fileResType,
                                                  params string[] exts)
        {
            foreach (string ext in exts)
            {
                if (ext.Length > 0)
                {
                    string    lower_ext    = ext.ToLower();
                    IResource fileMapEntry = _store.FindUniqueResource("FileTypeMap", _propExtension, lower_ext);
                    if (fileMapEntry == null)
                    {
                        fileMapEntry = _store.BeginNewResource("FileTypeMap");
                    }
                    else
                    {
                        fileMapEntry.BeginUpdate();
                    }
                    try
                    {
                        fileMapEntry.SetProp(_propExtension, lower_ext);
                        fileMapEntry.SetProp(_propResType, fileResType);
                        lock ( _extension2ResTypeMap )
                        {
                            _extension2ResTypeMap[lower_ext] = fileResType;
                        }
                    }
                    finally
                    {
                        fileMapEntry.EndUpdate();
                    }
                }
            }

            RegisterFileTypeColumns(fileResType);
        }
Beispiel #2
0
        [Test] public void UnreadOnOff()
        {
            IResource email = _storage.NewResource("Email");

            email.SetProp(_propUnread, true);
            _folder.AddLink(_propFolder, email);

            email.BeginUpdate();
            email.SetProp(_propUnread, false);
            email.SetProp(_propUnread, true);
            email.EndUpdate();

            Assert.AreEqual(1, _unreadManager.GetUnreadCount(_folder));

            IResource email2 = _storage.NewResource("Email");

            _folder.AddLink(_propFolder, email2);

            email2.BeginUpdate();
            email2.SetProp(_propUnread, true);
            email2.SetProp(_propUnread, false);
            email2.EndUpdate();

            Assert.AreEqual(1, _unreadManager.GetUnreadCount(_folder));
        }
Beispiel #3
0
 private void SetGroupNumbers()
 {
     if (!Core.ResourceStore.IsOwnerThread())
     {
         Core.ResourceAP.QueueJob(
             _priority, "Updating newsgroup structure", new MethodInvoker(SetGroupNumbers));
     }
     else
     {
         IResource group = _group.Resource;
         if (!group.IsDeleted)
         {
             group.BeginUpdate();
             try
             {
                 _group.LastArticle  = _lastArticle;
                 _group.FirstArticle = _firstArticle;
                 if (_firstArticleCopy >= _group.FirstArticle)
                 {
                     group.SetProp(NntpPlugin._propNoMoreHeaders, true);
                 }
             }
             finally
             {
                 group.EndUpdate();
             }
         }
     }
 }
        private static void LinkResource(BinaryReader reader, IResource result, int linkId,
                                         BeforeDeserializationDelegate beforeCheck)
        {
            int       linkedResId = reader.ReadInt32();
            IResource linked      = Core.ResourceStore.TryLoadResource(linkedResId);

            if (linked != null)
            {
                linked.BeginUpdate();
                //  Caller may need to perform special actions, e.g. to
                //  keep the consistency of link restrictions
                if (beforeCheck != null)
                {
                    beforeCheck(result, linked, linkId);
                }

                if (Math.Abs(linkId) == Core.ContactManager.Props.LinkBaseContact)
                {
                    Trace.WriteLine("Deserializer -- adding link between " + result.DisplayName + "/" + result.Id + " and " + linked.DisplayName + "/" + linked.Id);
                }
                if (linkId < 0)
                {
                    linked.AddLink(-linkId, result);
                }
                else
                {
                    result.AddLink(linkId, linked);
                }
                linked.EndUpdate();
            }
        }
Beispiel #5
0
        [Test] public void UnreadAndLink()
        {
            IResource email = _storage.BeginNewResource("Email");

            email.SetProp(_propUnread, true);
            email.AddLink(_propFolder, _folder);
            email.EndUpdate();

            Assert.AreEqual(1, _unreadManager.GetUnreadCount(_folder));

            IResource email2 = _storage.BeginNewResource("Email");

            email2.AddLink(_propFolder, _folder);
            email2.SetProp(_propUnread, true);
            email2.EndUpdate();

            Assert.AreEqual(2, _unreadManager.GetUnreadCount(_folder));

            email.BeginUpdate();
            email.SetProp(_propUnread, false);
            email.DeleteLink(_propFolder, _folder);
            email.EndUpdate();
            Assert.AreEqual(1, _unreadManager.GetUnreadCount(_folder));

            email2.Delete();
            Assert.AreEqual(0, _unreadManager.GetUnreadCount(_folder));
        }
Beispiel #6
0
        private void CreateFolder(string path)
        {
            IResource folder = Core.ResourceStore.FindUniqueResource(
                FileProxy._folderResourceType, FileProxy._propDirectory, path);

            if (folder != null)
            {
                folder.BeginUpdate();
            }
            else
            {
                folder = Core.ResourceStore.BeginNewResource(FileProxy._folderResourceType);
            }
            try
            {
                Core.WorkspaceManager.AddToActiveWorkspaceRecursive(folder);
                folder.SetProp(Core.Props.Name, path);
                folder.SetProp(FileProxy._propDirectory, path);
                folder.SetProp(FileProxy._propParentFolder, FoldersCollection.Instance.FilesRoot);
                folder.SetProp(FileProxy._propStatus, _statusBox.SelectedIndex);
                folder.SetProp(FileProxy._propNew, true);
                folder.SetProp(FileProxy._propDeleted, false);
            }
            finally
            {
                folder.EndUpdate();
            }
        }
Beispiel #7
0
        private static void MoveDirectory(string dest, IResource folder, IResource targetResource)
        {
            string source = folder.GetPropText(_propDirectory);

            Directory.Move(source, dest);
            folder.BeginUpdate();
            try
            {
                folder.SetProp(_propDirectory, dest);
                folder.SetProp(_propParentFolder, targetResource);
            }
            finally
            {
                folder.EndUpdate();
            }
            foreach (IResource file in folder.GetLinksTo(null, _propParentFolder).ValidResources)
            {
                if (file.Type != _folderResourceType)
                {
                    file.SetProp(_propDirectory, dest);
                }
                else
                {
                    string name = file.GetPropText(_propDirectory).Replace(source, null).Trim('/', '\\');
                    file.SetProp(_propDirectory, IOTools.Combine(dest, name));
                }
            }
        }
Beispiel #8
0
 public override MDState BeginUpdate(ref IResource resMail)
 {
     if (resMail != null)
     {
         resMail.BeginUpdate();
     }
     return(this);
 }
Beispiel #9
0
        private void NewWeblink()
        {
            bool newWeblink = false;

            if (_favorite == null)
            {
                _favorite  = Core.ResourceStore.BeginNewResource("Weblink");
                newWeblink = true;
            }
            else
            {
                _favorite.BeginUpdate();
            }
            try
            {
                string url = _URLBox.Text;
                _favorite.SetProp(Core.Props.Name, _nameBox.Text);
                _favorite.SetProp(FavoritesPlugin._propURL, url);
                int updateFreq = 0;
                if (_updateCheckBox.Checked)
                {
                    updateFreq = (int)_hoursBox.Value * 60 * 60;
                    int unitIndex = _unitBox.SelectedIndex;
                    if (unitIndex > 0)  // days or weeks
                    {
                        updateFreq *= 24;
                        if (unitIndex > 1)  // weeks
                        {
                            updateFreq *= 7;
                        }
                    }
                }
                _favorite.SetProp(FavoritesPlugin._propUpdateFreq, updateFreq);
                if (_parent != null)
                {
                    _favorite.AddLink(FavoritesPlugin._propParent, _parent);
                }
                Core.WorkspaceManager.AddToActiveWorkspace(_favorite);
            }
            finally
            {
                _favorite.EndUpdate();
            }
            if (newWeblink)
            {
                IBookmarkProfile profile = _bookmarkService.GetOwnerProfile(_favorite);
                string           error   = null;
                if (profile != null && profile.CanCreate(_favorite, out error))
                {
                    profile.Create(_favorite);
                }
                else
                {
                    Core.UserInterfaceAP.QueueJob(new LineDelegate(DisplayError), error);
                }
                BookmarkService.ImmediateQueueWeblink(_favorite, _URLBox.Text);
            }
        }
Beispiel #10
0
 public void BeginUpdate()
 {
     _updateCount++;
     if (_updateCount == 1)
     {
         _oldBody = ContactBody;
         _resource.BeginUpdate();
     }
 }
Beispiel #11
0
        public static IResource FindOrCreate(FolderDescriptor folderDescriptor, IResource parentFolder)
        {
            Guard.NullArgument(folderDescriptor, "folderDescriptor");
            IResource MAPIStore = FindOrCreateMAPIStore(folderDescriptor.FolderIDs.StoreId);
            IResource resFolder =
                Core.ResourceStore.FindUniqueResource(STR.MAPIFolder, PROP.EntryID, folderDescriptor.FolderIDs.EntryId);

            if (resFolder != null)
            {
                resFolder.BeginUpdate();
            }
            else
            {
                resFolder = Core.ResourceStore.BeginNewResource(STR.MAPIFolder);
                Core.WorkspaceManager.AddToActiveWorkspaceRecursive(resFolder);
                resFolder.SetProp("EntryID", folderDescriptor.FolderIDs.EntryId);
                resFolder.SetProp("OwnerStore", MAPIStore);
                if (OutlookSession.IsDeletedItemsFolder(folderDescriptor.FolderIDs.EntryId))
                {
                    resFolder.SetProp(Core.Props.ShowDeletedItems, true);
                    resFolder.SetProp(PROP.DeletedItemsFolder, true);
                    resFolder.SetProp(PROP.DefaultDeletedItems, true);
                }
                if (parentFolder != null)
                {
                    SetIgnored(resFolder, IsIgnored(parentFolder));
                }
            }
            SetName(resFolder, folderDescriptor.Name);
            string containerClass = folderDescriptor.ContainerClass;

            resFolder.SetProp(PROP.PR_STORE_SUPPORT_MASK, folderDescriptor.StoreSupportMask);
            resFolder.SetProp(PROP.PR_CONTENT_COUNT, folderDescriptor.ContentCount);
            if (containerClass.Length > 0)
            {
                resFolder.SetProp(PROP.ContainerClass, containerClass);
            }
            containerClass = resFolder.GetPropText(PROP.ContainerClass);
            bool visible =
                (containerClass.Length == 0 || containerClass == FolderType.Mail ||
                 containerClass == FolderType.Post || containerClass == FolderType.IMAP || containerClass == FolderType.Dav);

            resFolder.SetProp(PROP.MAPIVisible, visible);

            if (parentFolder != null)
            {
                SetParent(resFolder, parentFolder);
            }
            else
            {
                Folder.SetAsRoot(resFolder);
            }
            resFolder.EndUpdate();
            _resourceTreeManager.SetResourceNodeSort(resFolder, STR.Name);
            return(resFolder);
        }
Beispiel #12
0
        private void ProcessFile()
        {
            if (_webLink.IsDeleted)  // if favorite resource was deleted then do nothing
            {
                return;
            }
            FileInfo fileInfo   = _reader.fileInfo;
            Stream   readStream = _reader.ReadStream;

            using ( readStream )
            {
                DateTime lastWriteTime = IOTools.GetLastWriteTime(fileInfo);
                if (!_webLink.HasProp("LastModified") || lastWriteTime > LastModified() ||
                    _webLink.HasProp(Core.Props.LastError))
                {
                    bool      isShowed   = BookmarkService.BookmarkSynchronizationFrequency(_webLink) > 0;
                    IResource formatFile = _webLink.GetLinkProp("Source");
                    _webLink.BeginUpdate();
                    if (formatFile != null)
                    {
                        formatFile.BeginUpdate();
                    }
                    else
                    {
                        string resourceType = Core.FileResourceManager.GetResourceTypeByExtension(fileInfo.Extension);
                        if (resourceType == null)
                        {
                            resourceType = "UnknownFile";
                        }
                        formatFile = Core.ResourceStore.BeginNewResource(resourceType);
                        _webLink.AddLink("Source", formatFile);
                    }
                    if (_webLink.HasProp(Core.Props.LastError))
                    {
                        SetLastError(null);
                    }
                    _webLink.SetProp("LastModified", lastWriteTime);
                    formatFile.SetProp(Core.Props.Size, (int)readStream.Length);
                    formatFile.SetProp(FavoritesPlugin._propContent, readStream);
                    if (isShowed)
                    {
                        formatFile.SetProp(Core.Props.Date, lastWriteTime);
                        formatFile.SetProp(FavoritesPlugin._propIsUnread, true);
                        Core.FilterEngine.ExecRules(StandardEvents.ResourceReceived, _webLink);
                    }
                    if (formatFile.Type != "UnknownFile")
                    {
                        Core.TextIndexManager.QueryIndexing(formatFile.Id);
                    }
                    _webLink.EndUpdate();
                    formatFile.EndUpdate();
                }
            }
        }
Beispiel #13
0
        protected override void Execute()
        {
            if (_resource != null && _resource.IsDeleted)
            {
                return;
            }
            if (_deletedItemsId == null && _entryId == null)
            {
                return;
            }

            if (_resource == null && _deletedItemsId != null)
            {
                _resource = Core.ResourceStore.FindUniqueResource(STR.MAPIInfoStore,
                                                                  PROP.DeletedItemsEntryID, _deletedItemsId);
            }

            if (_resource == null)
            {
                _resource = Core.ResourceStore.BeginNewResource(STR.MAPIInfoStore);
            }
            else
            {
                _resource.BeginUpdate();
            }

            IStringList propList = _resource.GetStringListProp(PROP.DefaultFolderEntryIDs);

            propList.Clear();
            foreach (string entryId in _defaultFolderEntryIDs)
            {
                propList.Add(entryId);
            }
            _resource.SetProp(PROP.EntryID, _entryId);
            _resource.SetProp(PROP.DeletedItemsEntryID, _deletedItemsId);
            _resource.SetProp(PROP.JunkEmailEntryID, _junkEmailId);

            _resource.SetProp(PROP.PR_STORE_SUPPORT_MASK, _supportMask);
            _resource.SetProp(PROP.StoreSupported, _supported);
            if (!_supported)
            {
                _resource.SetProp(PROP.IgnoredFolder, 1);
                _name += " (Not supported)";
            }
            else if ((_supportMask & STORE_SUPPORT_MASK.STORE_PUBLIC_FOLDERS) != 0)
            {
                _resource.SetProp(PROP.IgnoredFolder, 1);
            }
            _resource.SetProp(Core.Props.Name, _name);
            _resource.SetProp(PROP.StoreTypeChecked, _storeTypeChecked);
            _resource.EndUpdate();
        }
Beispiel #14
0
        private static void  AddSpecificParams(IResource rule, string name, Icon icon)
        {
            rule.BeginUpdate();
            rule.SetProp("IsTrayIconFilter", true);
            rule.SetProp("DeepName", name);
            rule.SetProp("IsLiveMode", true);
            JetMemoryStream mstrm = new JetMemoryStream(2048);

            icon.Save(mstrm);
            rule.SetProp("IconBlob", mstrm);
            rule.DeleteProp(Core.Props.LastError);
            rule.EndUpdate();
        }
Beispiel #15
0
 public virtual MDState BeginUpdate(ref IResource resMail)
 {
     if (resMail == null)
     {
         resMail = Core.ResourceStore.BeginNewResource(STR.Email);
         if (Settings.UseOutlookListeners)
         {
             Tracer._Trace("Created email resource ID=" + resMail.Id);
         }
         return(this);
     }
     resMail.BeginUpdate();
     return(MailDescriptor.UpdateState);
 }
Beispiel #16
0
 private void Dismiss(IResource task)
 {
     if (!task.IsDeleted)
     {
         task.BeginUpdate();
         try
         {
             task.DeleteProp(TasksPlugin._propRemindDate);
             task.DeleteLinks(TasksPlugin._propRemindWorkspace);
         }
         finally
         {
             task.EndUpdate();
         }
     }
 }
Beispiel #17
0
 private void Snooze(IResource task)
 {
     if (!task.IsDeleted)
     {
         task.BeginUpdate();
         try
         {
             DateTime rd = DateTime.Now.Add(_snoozePeriods[_snoozePeriodList.SelectedIndex]);
             task.SetProp(TasksPlugin._propRemindDate, rd);
         }
         finally
         {
             task.EndUpdate();
         }
     }
 }
Beispiel #18
0
 private static void MoveFile(string source, string dest, string directory, IResource file, IResource targetResource)
 {
     File.Move(source, dest);
     if (!file.IsTransient)
     {
         file.BeginUpdate();
         try
         {
             file.SetProp(_propDirectory, directory);
             file.SetProp(_propParentFolder, targetResource);
         }
         finally
         {
             file.EndUpdate();
         }
     }
 }
Beispiel #19
0
        [Test] public void OneEventTest()
        {
            IResourceList  list     = Core.ResourceStore.GetAllResourcesLive("Setting");
            ChangeListener listener = new ChangeListener();

            list.ResourceChanged += new ResourcePropIndexEventHandler(listener.list_ResourceChanged);
            IResource setting = Core.ResourceStore.BeginNewResource("Setting");

            setting.EndUpdate();
            setting.BeginUpdate();
            IntResourceSetting setting1 = new IntResourceSetting(setting, _SIZE, 30);
            IntResourceSetting setting2 = new IntResourceSetting(setting, _NUM, 5);

            setting1.Save(12);
            setting2.Save(13);
            setting.EndUpdate();
            Assert.AreEqual(1, listener.Count);
        }
Beispiel #20
0
        /// <summary>
        /// Processes drop of something on the task. May either link-as-attachment or link-as-supertask.
        /// Must be called on the Resource thread.
        /// </summary>
        internal static void AddDescendants(IResource task, IResourceList descendants, int linkId)
        {
            ArrayList parentTasks = new ArrayList();

            task.BeginUpdate();
            try
            {
                foreach (IResource res in descendants)
                {
                    //  Attached resources may be linked to many tasks, while
                    //  tasks may have only one supertask.
                    if (res.Type != "Task")
                    {
                        res.AddLink(linkId, task);
                    }
                    else
                    {
                        //  Collect current parents of the tasks in order to
                        //  recalculate their stati on completeness and dates
                        IResource parent = res.GetLinkProp(linkId);
                        if (parent != null && parent.Id != TasksPlugin.RootTask.Id)
                        {
                            parentTasks.Add(parent);
                        }

                        res.SetProp(linkId, task);
                    }
                }
            }
            finally
            {
                task.EndUpdate();
            }

            if (task.Id != TasksPlugin.RootTask.Id)
            {
                parentTasks.Add(task);
            }

            TasksPlugin.RecalculateSupertaskParameters(parentTasks);
        }
Beispiel #21
0
 /**
  * performs renaming of a directory updating all its sub-directories
  */
 public void RenameDirectory(IResource folder, string name, string fullname)
 {
     if (!Core.ResourceStore.IsOwnerThread())
     {
         _resourceAP.RunUniqueJob("Renaming directory",
                                  new RenameDirectoryDelegate(RenameDirectory), folder, name, fullname);
     }
     else
     {
         folder.BeginUpdate();
         try
         {
             folder.SetProp(Core.Props.Name, name);
             folder.SetProp(FileProxy._propDirectory, fullname);
         }
         finally
         {
             folder.EndUpdate();
         }
         foreach (IResource res in folder.GetLinksTo(null, FileProxy._propParentFolder))
         {
             if (res.Type != FileProxy._folderResourceType)
             {
                 res.SetProp(FileProxy._propDirectory, fullname);
             }
             else
             {
                 string folderName     = res.GetPropText(Core.Props.Name);
                 string folderFullName = IOTools.Combine(fullname, folderName);
                 if (folderFullName.Length > 0)
                 {
                     RenameDirectory(res, folderName, folderFullName);
                 }
             }
         }
     }
 }
Beispiel #22
0
 private void SubmitChanges()
 {
     if (!_weblink.IsTransient)
     {
         _weblink.BeginUpdate();
     }
     try
     {
         string annotation = _edtAnnotation.Text;
         if (annotation.Length == 0)
         {
             _weblink.DeleteProp("Annotation");
         }
         else
         {
             _weblink.SetProp("Annotation", annotation);
         }
         string name = _nameBox.Text;
         if (name != _weblink.GetPropText(Core.Props.Name))
         {
             _weblink.SetProp(Core.Props.Name, name);
             IBookmarkService service =
                 (IBookmarkService)Core.PluginLoader.GetPluginService(typeof(IBookmarkService));
             IBookmarkProfile profile = service.GetOwnerProfile(_weblink);
             string           error;
             if (profile != null && profile.CanCreate(_weblink, out error))
             {
                 profile.Create(_weblink);
             }
         }
     }
     finally
     {
         _weblink.EndUpdate();
     }
 }
Beispiel #23
0
 private void DoSave()
 {
     lock (this)
     {
         if (_resource == null)
         {
             _resource = Core.ResourceStore.BeginNewResource(_newResourceType);
             BusinessObjectCache.Put(this);
         }
         else
         {
             _resource.BeginUpdate();
         }
         if (_props != null)
         {
             foreach (var prop in _props)
             {
                 _resource.SetProp(prop.Key, prop.Value);
             }
             _props = null;
         }
         _resource.EndUpdate();
     }
 }
Beispiel #24
0
        private void RSSParseDelegate()
        {
            if (_feed.IsDeleted)
            {
                OnParseDone(RSSWorkStatus.FeedDeleted);
                return;
            }

            Stream feedStream = _httpReader.ReadStream;

            _feed.BeginUpdate();
            try
            {
                if (HttpStatus == HttpStatusCode.Moved && _httpReader.RedirectUrl != null)
                {
                    _feed.SetProp(Props.URL, _httpReader.RedirectUrl);
                }

                byte[] streamStartBytes = new byte[256];
                int    cBytes           = feedStream.Read(streamStartBytes, 0, 256);
                string streamStart      = Encoding.Default.GetString(streamStartBytes, 0, cBytes);
                feedStream.Position = 0;

                Encoding encoding = null;
                string   charset  = _httpReader.CharacterSet;
                if (charset != null)
                {
                    try
                    {
                        encoding = Encoding.GetEncoding(charset);
                    }
                    catch (Exception)
                    {
                        Trace.WriteLine("Unknown encoding in HTTP for RSS feed: " + charset);
                        encoding = null;
                    }
                }

                TraceUrlsUnderSpy(_feed, feedStream, encoding);

                RSSParser parser = new RSSParser(_feed);
                try
                {
                    parser.Parse(feedStream, encoding, _parseItems);
                }
                catch (XmlException e)
                {
                    feedStream.Position = 0;
                    if (_acceptHtmlIfXmlError &&
                        ((_httpReader.WebResponse != null && _httpReader.WebResponse.ContentType.StartsWith("text/html")) ||
                         HtmlTools.IsHTML(streamStart)))
                    {
                        OnParseDone(RSSWorkStatus.FoundHTML);
                    }
                    else
                    {
                        _lastException = e;
                        OnParseDone(RSSWorkStatus.XMLError);
                    }
                    return;
                }

                if (parser.FoundChannel)
                {
                    if (_parseItems && _httpReader.ETag != null && _httpReader.ETag.Length > 0)
                    {
                        _feed.SetProp(Props.ETag, _httpReader.ETag);
                    }
                    else
                    {
                        _feed.DeleteProp(Props.ETag);
                    }
                    OnParseDone(RSSWorkStatus.Success);
                }
                else if (HtmlTools.IsHTML(streamStart))
                {
                    OnParseDone(RSSWorkStatus.FoundHTML);
                }
                else
                {
                    OnParseDone(RSSWorkStatus.FoundXML);
                }
            }
            finally
            {
                _feed.EndUpdate();
                if (RSSParser._nextItem != null)
                {
                    RSSParser._nextItem.ClearProperties();
                }
            }
            Core.NetworkAP.QueueJob(_cleanJob);
        }
Beispiel #25
0
        /**
         * IResource article can be null, in that case the new article is created
         */
        public static IResource PlaceArticle(IResource article, IResource folder, IResourceList groups,
                                             string from, string subject, string text, string charset, string references,
                                             string nntpText, IResourceList attachments)
        {
            IResourceStore store = Core.ResourceStore;

            if (!store.IsOwnerThread())
            {
                IAsyncProcessor resourceProcessor = Core.ResourceAP;
                article = (IResource)resourceProcessor.RunUniqueJob(
                    new PlaceArticleDelegate(PlaceArticle), article, folder, groups, from,
                    subject, text, charset, references, nntpText, attachments);
            }
            else
            {
                if (article == null || article.IsDeleted)
                {
                    article = store.BeginNewResource(NntpPlugin._newsLocalArticle);
                }
                else
                {
                    article.BeginUpdate();
                    article.DeleteProp(NntpPlugin._propArticleId);
                }
                try
                {
                    article.SetProp(Core.Props.Subject, subject);
                    article.SetProp(Core.Props.Date, DateTime.Now);
                    IContact sender;
                    NewsArticleParser.ParseFrom(article, from, out sender);
                    NewsArticleParser.ParseReferences(article, references);
                    article.SetProp(Core.Props.LongBody, text);
                    article.SetProp(Core.FileResourceManager.PropCharset, charset);
                    article.SetProp(NntpPlugin._propNntpText, nntpText);
                    if (!folder.IsDeleted)
                    {
                        article.SetProp(NntpPlugin._propTo, folder);
                    }
                    if (groups != null)
                    {
                        foreach (IResource group in groups)
                        {
                            if (!group.IsDeleted)
                            {
                                article.AddLink(NntpPlugin._propTo, group);
                            }
                        }
                    }
                    if (attachments != null)
                    {
                        foreach (IResource attachment in attachments)
                        {
                            if (!attachment.IsDeleted)
                            {
                                attachment.AddLink(NntpPlugin._propAttachment, article);
                                string actualResourceType =
                                    Core.FileResourceManager.GetResourceTypeByExtension(
                                        IOTools.GetExtension(attachment.GetPropText(Core.Props.Name)));
                                if (actualResourceType != null && attachment.Type != actualResourceType)
                                {
                                    attachment.ChangeType(actualResourceType);
                                }
                                if (attachment.IsTransient)
                                {
                                    attachment.EndUpdate();
                                }
                            }
                        }
                    }
                    Core.WorkspaceManager.AddToActiveWorkspace(article);
                }
                finally
                {
                    article.EndUpdate();
                    Core.TextIndexManager.QueryIndexing(article.Id);
                }
            }
            return(article);
        }
Beispiel #26
0
        /**
         * finds or creates resource for a file
         * for the UnknowFile type creates transient resources
         */
        public IResource FindOrCreateFile(FileInfo fileInfo, bool createTransient)
        {
            string   resourceType;
            bool     indexIt       = false;
            DateTime lastWriteTime = IOTools.GetLastWriteTime(fileInfo);
            string   extension     = IOTools.GetExtension(fileInfo);
            int      size          = (int)IOTools.GetLength(fileInfo);
            string   name          = IOTools.GetName(fileInfo);

            IResource file = FindFile(fileInfo);

            if (file != null)
            {
                if (!Core.ResourceStore.IsOwnerThread())
                {
                    return((IResource)_resourceAP.RunUniqueJob(_cUpdatingFileJob, _findOrCreateFileDelegate, fileInfo, createTransient));
                }
                file.BeginUpdate();
                if (file.Type == FileProxy._unknownFileResourceType &&
                    (resourceType = _ftm.GetResourceTypeByExtension(extension)) != null)
                {
                    file.ChangeType(resourceType);
                    indexIt = true;
                }
                if (name != file.GetPropText(Core.Props.Name))
                {
                    file.SetProp(Core.Props.Name, name);
                    indexIt = true;
                }
                if (lastWriteTime != file.GetDateProp(Core.Props.Date))
                {
                    file.SetProp(Core.Props.Date, lastWriteTime);
                    indexIt = true;
                }
                indexIt = indexIt || (!file.IsTransient && !file.HasProp("InTextIndex"));
                file.SetProp(FileProxy._propSize, size);
                string filetype = FileSystemTypes.GetFileType(extension);
                file.SetProp(FileProxy._propFileType, filetype ?? "Unknown");
            }
            else
            {
                string    directoryName = IOTools.GetDirectoryName(fileInfo);
                IResource folder        = FindOrCreateDirectory(directoryName);
                if (folder == null)
                {
                    return(null);
                }
                resourceType = _ftm.GetResourceTypeByExtension(extension);

                /**
                 * look through pending file deletions
                 */
                IResourceList deletedFiles = Core.ResourceStore.FindResourcesWithProp(resourceType, FileProxy._propDeletedFile);
                deletedFiles = deletedFiles.Intersect(
                    Core.ResourceStore.FindResources(null, FileProxy._propSize, size), true);
                deletedFiles = deletedFiles.Intersect(
                    Core.ResourceStore.FindResources(null, Core.Props.Name, name), true);
                if (deletedFiles.Count > 0)
                {
                    file = deletedFiles[0];
                    if (!file.IsTransient)
                    {
                        if (!Core.ResourceStore.IsOwnerThread())
                        {
                            return((IResource)_resourceAP.RunUniqueJob(
                                       _cUpdatingFileJob, _findOrCreateFileDelegate, fileInfo, createTransient));
                        }
                        file.BeginUpdate();
                    }
                }
                if (file == null)
                {
                    if (resourceType != null && !createTransient)
                    {
                        if (!Core.ResourceStore.IsOwnerThread())
                        {
                            return((IResource)_resourceAP.RunUniqueJob(
                                       _cUpdatingFileJob, _findOrCreateFileDelegate, fileInfo, createTransient));
                        }
                        file    = Core.ResourceStore.BeginNewResource(resourceType);
                        indexIt = true;
                    }
                    else
                    {
                        if (!createTransient)
                        {
                            return(null);
                        }
                        if (resourceType == null)
                        {
                            resourceType = FileProxy._unknownFileResourceType;
                        }
                        file = Core.ResourceStore.NewResourceTransient(resourceType);
                    }
                }
                file.SetProp(FileProxy._propParentFolder, folder);
                file.SetProp(FileProxy._propDirectory, directoryName);
                file.SetProp(Core.Props.Name, name);
                file.SetProp(Core.Props.Date, lastWriteTime);
                file.SetProp(FileProxy._propSize, size);
                string filetype = FileSystemTypes.GetFileType(extension);
                file.SetProp(FileProxy._propFileType, filetype ?? "Unknown");
            }
            file.SetProp(FileProxy._propDeletedFile, false);
            if (!file.IsTransient)
            {
                file.EndUpdate();
                if (indexIt)
                {
                    Core.TextIndexManager.QueryIndexing(file.Id);
                }
            }
            return(file);
        }
Beispiel #27
0
        private void ProcessWebLink()
        {
            Stream readStream = _reader.ReadStream;

            if (readStream == null || _webLink.IsDeleted)  // if favorite resource was deleted then do nothing
            {
                return;
            }
            int             propContent = FavoritesPlugin._propContent;
            HttpWebResponse response    = _reader.WebResponse;
            // check whether http stream differs from earlier saved one
            bool differs = true;

            ///////////////////////////////////////////////////////////////////////////////
            /// the following if statement is a workaround over invalid processing by
            /// HttpReader the Not-Modified-Since header. .NET 1.1 was throwing the
            /// exception if content not modified, .NET 1.1 SP1 just returns empty stream
            ///////////////////////////////////////////////////////////////////////////////
            if (readStream.Length == 0 && !_webLink.HasProp(Core.Props.LastError))
            {
                return;
            }

            IResource formatFile = _webLink.GetLinkProp("Source");

            if (formatFile != null && formatFile.HasProp(propContent))
            {
                Stream savedStream = formatFile.GetBlobProp(propContent);
                using ( savedStream )
                {
                    if (savedStream.Length == readStream.Length)
                    {
                        differs = false;
                        for (int i = 0; i < readStream.Length; ++i)
                        {
                            if (( byte )savedStream.ReadByte() != ( byte )readStream.ReadByte())
                            {
                                readStream.Position = 0;
                                differs             = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (differs)
            {
                DateTime lastModified = GetLastModified(response);
                bool     isShowed     = BookmarkService.BookmarkSynchronizationFrequency(_webLink) > 0;
                // content changed, so set properties and proceed with indexing

                string resourceType = "UnknownFile";
                if (!String.IsNullOrEmpty(response.ContentType))
                {
                    resourceType = (Core.FileResourceManager as FileResourceManager).GetResourceTypeByContentType(response.ContentType);
                    if (resourceType == null)
                    {
                        resourceType = "UnknownFile";
                    }
                }
                _webLink.BeginUpdate();
                if (formatFile != null)
                {
                    formatFile.BeginUpdate();
                    if (resourceType != "UnknownFile" && formatFile.Type != resourceType)
                    {
                        formatFile.ChangeType(resourceType);
                    }
                }
                else
                {
                    formatFile = Core.ResourceStore.BeginNewResource(resourceType);
                    _webLink.AddLink("Source", formatFile);
                }
                if (_webLink.HasProp(Core.Props.LastError))
                {
                    SetLastError(null);
                }
                _webLink.SetProp("LastModified", lastModified);
                string redirectedUrl = _reader.RedirectUrl;
                if (redirectedUrl != null && redirectedUrl.Length > 0)
                {
                    _webLink.SetProp(FavoritesPlugin._propURL, redirectedUrl);
                }
                if (_reader.ETag.Length > 0)
                {
                    _webLink.SetProp(FavoritesPlugin._propETag, _reader.ETag);
                }
                // try to get charset from content-type or from content itself
                string charset = _reader.CharacterSet;
                if (charset != null)
                {
                    _webLink.SetProp(Core.FileResourceManager.PropCharset, charset);
                }
                formatFile.SetProp(Core.Props.Size, (int)readStream.Length);
                formatFile.SetProp(propContent, readStream);
                if (isShowed)
                {
                    formatFile.SetProp(Core.Props.Date, lastModified);
                    formatFile.SetProp(FavoritesPlugin._propIsUnread, true);
                    Core.FilterEngine.ExecRules(StandardEvents.ResourceReceived, _webLink);
                }
                if (formatFile.Type != "UnknownFile")
                {
                    Core.TextIndexManager.QueryIndexing(formatFile.Id);
                }
                _webLink.EndUpdate();
                formatFile.EndUpdate();
            }
        }
Beispiel #28
0
        private void RepairLinkRestriction(IResource lr, IResource resource)
        {
            IResourceStore store          = MyPalStorage.Storage;
            string         toResourceType = lr.GetStringProp("toResourceType");
            string         resName        = !String.IsNullOrEmpty(resource.DisplayName) ? resource.DisplayName : "<empty>";
            int            linkType       = lr.GetIntProp("LinkType");
            int            minCount       = lr.GetIntProp("MinCount");
            int            maxCount       = lr.GetIntProp("MaxCount");
            string         linkTypeName   = (string)_propTypeMap [linkType];

            IResourceList links;
            int           linkTypeReverse;

            if (store.PropTypes [linkType].HasFlag(PropTypeFlags.DirectedLink))
            {
                links           = resource.GetLinksFrom(null, linkType);
                linkTypeReverse = -linkType;
            }
            else
            {
                links           = resource.GetLinksOfType(null, linkType);
                linkTypeReverse = linkType;
            }

            /**
             * check destination resource types
             */
            if (toResourceType != null)
            {
                foreach (IResource link in links)
                {
                    if (link.Type != toResourceType)
                    {
                        ReportError("Restricted link found: resource ID=" + resource.Id +
                                    " [" + resName + "] link [" + linkTypeName + "] destination resource type=[" + link.Type + "]");
                        if (_fixErrors)
                        {
                            if (store.GetMinLinkCountRestriction(resource.Type, linkType) > resource.GetLinkCount(linkType) &&
                                store.GetMinLinkCountRestriction(link.Type, linkTypeReverse) > link.GetLinkCount(linkTypeReverse))
                            {
                                resource.DeleteLink(linkType, link);
                                ShowProgress("Link deleted");
                                ++_fixCount;
                            }
                            else
                            {
                                ShowProgress("Can not delete link due to min/max restrictions: {0}/{1} in store vs {2}/{3} in resource",
                                             store.GetMinLinkCountRestriction(resource.Type, linkType).ToString(),
                                             store.GetMinLinkCountRestriction(link.Type, linkTypeReverse).ToString(),
                                             resource.GetLinkCount(linkType).ToString(),
                                             link.GetLinkCount(linkTypeReverse).ToString());
                                //  NB: rough hack. To be deleted after the problem is identified
                                //      in the source code.
                                if (resource.Type == "ContactName")
                                {
                                    resource.Delete();
                                }
                            }
                        }
                    }
                }
            }

            /**
             * check counts
             */

            if (links.Count < minCount)
            {
                ReportError(String.Format("Not enough links of type {3} for resource '{2}' {0} minimum, {1} found",
                                          minCount, links.Count, resource, linkTypeName));
                if (_fixErrors && IsSafeToDeleteResource(resource))
                {
                    resource.Delete();
                    ++_fixCount;
                }
            }

            if (maxCount >= 0 && links.Count > maxCount)
            {
                ReportError(String.Format("Too many links of type {3} for resource '{2}': {0} maximum, {1} found",
                                          maxCount, links.Count, resource, linkTypeName));
                if (_fixErrors)
                {
                    int linkCount = links.Count;
                    resource.BeginUpdate();
                    for (int i = links.Count - 1; i >= 0 && linkCount > maxCount; i--)
                    {
                        IResource target = links [i];
                        // make sure we don't corrupt the DB by deleting the link
                        if (target.GetLinksOfType(null, linkTypeReverse).Count > store.GetMinLinkCountRestriction(target.Type, linkTypeReverse))
                        {
                            ShowProgress("Deleting link to resource " + links [i]);
                            resource.DeleteLink(linkType, links[i]);
                            linkCount--;
                        }
                    }
                    resource.EndUpdate();
                    ++_fixCount;
                }
            }
        }
Beispiel #29
0
        private void ImportGroup(XmlElement root, IResource rootGroup, ImportUtils.FeedUpdateData defaultUpdatePeriod, bool addToWorkspace)
        {
            // Import all groups
            XmlNodeList l = root.SelectNodes("RssFeedsCategory");

            if (l != null)
            {
                foreach (XmlElement group in l)
                {
                    string name = group.GetAttribute("name");
                    if (name == null)
                    {
                        name = "Unknown group";
                    }
                    IResource iGroup = _plugin.FindOrCreateGroup(name, rootGroup);
                    ImportGroup(group, iGroup, defaultUpdatePeriod, addToWorkspace);
                }
            }
            // Import all elements
            IResource feedRes = null;

            l = root.SelectNodes("RssFeed");
            if (l != null)
            {
                foreach (XmlElement feed in l)
                {
                    string s = feed.GetAttribute("url");

                    if (s == null)
                    {
                        continue;
                    }
                    // May be, we are already subscribed?
                    if (Core.ResourceStore.FindUniqueResource("RSSFeed", "URL", s) != null)
                    {
                        continue;
                    }

                    FeedInfo info = new FeedInfo();
                    info.url = s;

                    // Ok, now we should create feed
                    feedRes = Core.ResourceStore.NewResource("RSSFeed");
                    feedRes.BeginUpdate();

                    feedRes.SetProp("URL", s);

                    ImportUtils.Attrib2Prop(feed, "name", feedRes, Core.Props.Name, Props.OriginalName);
                    ImportUtils.Attrib2Prop(feed, "etag", feedRes, Props.ETag);
                    ImportUtils.Attrib2Prop(feed, "authUserName", feedRes, Props.HttpUserName);
                    s = feed.GetAttribute("authPassword");
                    if (s != null)
                    {
                        string sharpReaderPassword         = "******";
                        MD5CryptoServiceProvider       MD5 = new MD5CryptoServiceProvider();
                        TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
                        DES.Key  = MD5.ComputeHash(Encoding.ASCII.GetBytes(sharpReaderPassword));
                        DES.Mode = CipherMode.ECB;

                        byte[] DESed   = Convert.FromBase64String(s);
                        byte[] DeDESed = DES.CreateDecryptor().TransformFinalBlock(DESed, 0, DESed.Length);
                        // Huuray!
                        feedRes.SetProp(Props.HttpPassword, Encoding.Unicode.GetString(DeDESed));
                    }

                    s = feed.GetAttribute("lastRefresh");
                    if (s != null)
                    {
                        DateTime dt = DateTime.Parse(s);
                        feedRes.SetProp(Props.LastUpdateTime, dt);
                    }

                    // Peridoically
                    ImportUtils.FeedUpdateData upd;
                    s = feed.GetAttribute("refreshMinutes");
                    if (s != null)
                    {
                        upd = ImportUtils.ConvertUpdatePeriod(s, 1);
                    }
                    else
                    {
                        upd = defaultUpdatePeriod;
                    }
                    feedRes.SetProp(Props.UpdatePeriod, upd.period);
                    feedRes.SetProp(Props.UpdateFrequency, upd.freq);

                    // Cached?
                    info.cacheFile = GetCacheNameByURL(info.url);

                    // Feed is ready
                    feedRes.AddLink(Core.Props.Parent, rootGroup);
                    feedRes.EndUpdate();

                    info.feed = feedRes;
                    _importedFeeds.Add(info);
                    if (addToWorkspace)
                    {
                        Core.WorkspaceManager.AddToActiveWorkspace(feedRes);
                    }
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Import subscription
        /// </summary>
        public void DoImport(IResource importRoot, bool addToWorkspace)
        {
            IResource feedRes = null;

            importRoot = _plugin.FindOrCreateGroup("RssBandit subscriptions", importRoot);

            // We will add info about imported feeds here
            _importedFeeds = new ArrayList();

            ImportUtils.UpdateProgress(0, _progressMessage);
            // Start to import feeds structure
            XmlDocument feedlist = new XmlDocument();

            try
            {
                feedlist.Load(_subscriptionPath);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("RssBandit subscrption load failed: '" + ex.Message + "'");
                RemoveFeedsAndGroupsAction.DeleteFeedGroup(importRoot);
                ImportUtils.ReportError("RSS Bandit Subscription Import", "Import of RSS Bandit subscription failed:\n" + ex.Message);
                return;
            }

            ImportUtils.FeedUpdateData defaultUpdatePeriod;
            XmlAttribute period = feedlist.SelectSingleNode("/feeds/@refresh-rate") as XmlAttribute;

            if (period != null)
            {
                defaultUpdatePeriod = ImportUtils.ConvertUpdatePeriod(period.Value, 60000);
            }
            else
            {
                defaultUpdatePeriod = ImportUtils.ConvertUpdatePeriod("", 60000);
            }

            XmlNodeList feeds = feedlist.GetElementsByTagName("feed");

            int totalFeeds     = Math.Max(feeds.Count, 1);
            int processedFeeds = 0;

            ImportUtils.UpdateProgress(processedFeeds / totalFeeds, _progressMessage);
            foreach (XmlElement feed in feeds)
            {
                string s = ImportUtils.GetUniqueChildText(feed, "link");

                if (s == null)
                {
                    continue;
                }
                // May be, we are already subscribed?
                if (Core.ResourceStore.FindUniqueResource("RSSFeed", "URL", s) != null)
                {
                    continue;
                }

                FeedInfo info = new FeedInfo();
                info.url = s;

                IResource group = AddCategory(importRoot, feed.GetAttribute("category"));
                // Ok, now we should create feed
                feedRes = Core.ResourceStore.NewResource("RSSFeed");
                feedRes.BeginUpdate();
                feedRes.SetProp("URL", s);

                s = ImportUtils.GetUniqueChildText(feed, "title");
                ImportUtils.Child2Prop(feed, "title", feedRes, Core.Props.Name, Props.OriginalName);

                ImportUtils.Child2Prop(feed, "etag", feedRes, Props.ETag);

                s = ImportUtils.GetUniqueChildText(feed, "last-retrieved");
                if (s != null)
                {
                    DateTime dt = DateTime.Parse(s);
                    feedRes.SetProp("LastUpdateTime", dt);
                }

                // Peridoically
                ImportUtils.FeedUpdateData upd;
                s = ImportUtils.GetUniqueChildText(feed, "refresh-rate");
                if (s != null)
                {
                    upd = ImportUtils.ConvertUpdatePeriod(s, 60000);
                }
                else
                {
                    upd = defaultUpdatePeriod;
                }
                feedRes.SetProp("UpdatePeriod", upd.period);
                feedRes.SetProp("UpdateFrequency", upd.freq);

                // Cached?
                s = ImportUtils.GetUniqueChildText(feed, "cacheurl");
                if (s != null)
                {
                    info.cacheFile = s;
                }
                else
                {
                    info.cacheFile = null;
                }

                // Login & Password
                ImportUtils.Child2Prop(feed, "auth-user", feedRes, Props.HttpUserName);
                s = ImportUtils.GetUniqueChildText(feed, "auth-password");
                if (s != null)
                {
                    feedRes.SetProp(Props.HttpPassword, DecryptPassword(s));
                }

                // Enclosures
                ImportUtils.Child2Prop(feed, "enclosure-folder", feedRes, Props.EnclosurePath);

                // Try to load "read" list
                XmlElement read = ImportUtils.GetUniqueChild(feed, "stories-recently-viewed");
                if (read != null)
                {
                    ArrayList list = new ArrayList();
                    foreach (XmlElement story in read.GetElementsByTagName("story"))
                    {
                        list.Add(story.InnerText);
                    }
                    if (list.Count > 0)
                    {
                        info.readItems = list;
                    }
                    else
                    {
                        info.readItems = null;
                    }
                }
                // Feed is ready
                feedRes.AddLink(Core.Props.Parent, group);
                feedRes.EndUpdate();
                info.feed = feedRes;
                _importedFeeds.Add(info);
                if (addToWorkspace)
                {
                    Core.WorkspaceManager.AddToActiveWorkspace(feedRes);
                }

                processedFeeds += 100;
                ImportUtils.UpdateProgress(processedFeeds / totalFeeds, _progressMessage);
            }
            return;
        }