public void ChangeStatus(IMediaItem inItem, MediaStatus inStatus) { var item = (TvEpisode)inItem; item.Status = inStatus; Cabinet.SetAsync(item).Wait(); }
public async Task PostStatusAsync(string text, long? inReplyToStatusId, IMediaItem[] mediaItems) { if (mediaItems == null) throw new ArgumentNullException(nameof(mediaItems)); if (mediaItems.Length == 0) throw new ArgumentException("Err:Media not specified."); foreach (var item in mediaItems) { if (item == null) throw new ArgumentException("Err:Media not specified."); if (!item.Exists) throw new ArgumentException("Err:Media not found."); } var uploadTasks = from m in mediaItems select this.UploadMediaItem(m); var mediaIds = await Task.WhenAll(uploadTasks) .ConfigureAwait(false); await this.tw.PostStatus(text, inReplyToStatusId, mediaIds) .ConfigureAwait(false); }
public VideoTranscoder(IMediaItem item, uint quality, bool isDirect, uint? width, uint? height, bool maintainAspect, uint offsetSeconds, uint lengthSeconds) : base(item, quality, isDirect, offsetSeconds, lengthSeconds) { Width = width; Height = height; MaintainAspect = maintainAspect; OffsetSeconds = offsetSeconds; LengthSeconds = lengthSeconds; }
public AbstractTranscoder(IMediaItem item, uint quality, bool isDirect, uint offsetSeconds, uint lengthSeconds) { State = TranscodeState.None; Item = item; Quality = quality; IsDirect = isDirect; OffsetSeconds = offsetSeconds; LengthSeconds = lengthSeconds; }
private MediaItemViewModel BuildMediaItemsTimelineMediaItemViewModel(IMediaItem mediaItem, MediaItemsTimelineViewModel mediaItemsTimelineViewModel, TrackViewModel trackViewModel) { return new MediaItemViewModel { MediaItem = mediaItem, MediaItemsTimelineViewModel = mediaItemsTimelineViewModel, TrackViewModel = trackViewModel }; }
public override int Compare(IMediaItem x, IMediaItem y) { if (x == null) { throw new ArgumentNullException("x"); } if (y == null) { throw new ArgumentNullException("y"); } return comp.Compare(x.Title, y.Title); }
public override int Compare(IMediaItem x, IMediaItem y) { var xm = x as IMetaInfo; var ym = y as IMetaInfo; if (xm != null && ym != null) { var rv = xm.InfoDate.CompareTo(ym.InfoDate); if (rv != 0) { return rv; } } return base.Compare(x, y); }
public KFile( Kernel kernel, KDevice device, IMediaItem item ) { Kernel = kernel; Device = device; Item = item; FolderOffset = 0; IsOpen = true; CanWrite = !( ( item.Attributes & MediaItemAttributes.ReadOnly ) == MediaItemAttributes.ReadOnly ); CanSeek = false; IsValid = true; }
public override int Compare(IMediaItem x, IMediaItem y) { if (x == null) { throw new ArgumentNullException("x"); } if (y == null) { throw new ArgumentNullException("y"); } ITitleComparable tx = x as ITitleComparable, ty = y as ITitleComparable; return comp.Compare( tx != null ? tx.ToComparableTitle() : x.Title.StemCompareBase(), ty != null ? ty.ToComparableTitle() : y.Title.StemCompareBase() ); }
public override int Compare(IMediaItem x, IMediaItem y) { if (x == null && y == null) { return 0; throw new ArgumentNullException("x"); } if (x == null) { return 1; } if (y == null) { return -1; } return comparer.Compare(x.ToComparableTitle(), y.ToComparableTitle()); }
public KFile( Kernel kernel, KDevice device, IMediaItem item, Stream stream ) { Kernel = kernel; Device = device; Item = item; FolderOffset = 0; Stream = stream; IsOpen = true; CanWrite = stream.CanWrite; CanSeek = stream.CanSeek; IsValid = true; }
private void RegisterPath(IMediaItem item) { var path = item.Path; string id; if (!paths.ContainsKey(path)) { while (ids.ContainsKey(id = idGen.Next(1000, int.MaxValue).ToString("X8"))) { } paths[path] = id; } else { id = paths[path]; } ids[id] = new WeakReference(item); item.Id = id; }
public async Task PostStatusAsync(string text, long? inReplyToStatusId, IMediaItem[] mediaItems) { if (mediaItems == null) throw new ArgumentNullException(nameof(mediaItems)); if (mediaItems.Length == 0) throw new ArgumentException("Err:Media not specified."); foreach (var item in mediaItems) { if (item == null) throw new ArgumentException("Err:Media not specified."); if (!item.Exists) throw new ArgumentException("Err:Media not found."); } await Task.Run(() => this.tw.PostStatusWithMultipleMedia(text, inReplyToStatusId, mediaItems)) .ConfigureAwait(false); }
public bool TryParseItem(XElement element, out IMediaItem item) { item = null; if (element.Name != "video") { return false; } VideoItem videoItem = new VideoItem(); item = videoItem; XItemParserMediaItem.ReadItem(videoItem, element); var audioTracks = (from ats in element.Elements("audioTracks") from at in ats.Elements("audioTrack") select new AudioTrack { Title = (string)at.Attribute("title") }).ToArray(); for (int i = 0; i < audioTracks.Length; i++) { audioTracks[i].Index = i; } videoItem.AudioTracks = audioTracks; videoItem.ItemType = "Video"; return true; }
public MetadataFoundResult(IMediaItem mediaItem, MetadataResult <TEmbyItem> metadataResult) { EmbyMetadataResult = metadataResult; MediaItem = mediaItem; }
public void InsertMediaItem(int itemId, int index) { IMediaItem item = Injection.Kernel.Get <IMediaItemRepository>().MediaItemForId(itemId); InsertMediaItem(item, index); }
public bool Equals(IMediaItem other) { return(resource.Equals(other)); }
private bool CreateMediaFileSystem(IDiscRecorder2 discRecorder, object[] multisessionInterfaces, out IStream dataStream, IMediaItem mediaItem) { MsftFileSystemImage fileSystemImage = null; try { fileSystemImage = new MsftFileSystemImage(); fileSystemImage.ChooseImageDefaults(discRecorder); fileSystemImage.FileSystemsToCreate = FsiFileSystems.FsiFileSystemJoliet | FsiFileSystems.FsiFileSystemISO9660; fileSystemImage.VolumeName = "2019_10_22"; fileSystemImage.Update += fileSystemImage_Update; // // If multisessions, then import previous sessions // if (multisessionInterfaces != null) { fileSystemImage.MultisessionInterfaces = multisessionInterfaces; fileSystemImage.ImportFileSystem(); } // // Get the image root // IFsiDirectoryItem rootItem = fileSystemImage.Root; // // Add Files and Directories to File System Image // mediaItem.AddToFileSystem(rootItem); fileSystemImage.Update -= fileSystemImage_Update; // // did we cancel? // if (backgroundWorkerBurn.CancellationPending) { dataStream = null; return(false); } dataStream = fileSystemImage.CreateResultImage().ImageStream; } catch (COMException exception) { MessageBox.Show(exception.Message, "Create File System Error", MessageBoxButtons.OK, MessageBoxIcon.Error); dataStream = null; return(false); } finally { if (fileSystemImage != null) { Marshal.ReleaseComObject(fileSystemImage); } } return(true); }
internal void AddItemInternal(IMediaItem item) { _items.Add(item); _itemLookup.Add(item.Name.ToLowerInvariant(), item); _itemCache = null; }
public Task AddMediaItem(IMediaItem item) { this.State.Items.Add(item); return(Task.CompletedTask); }
// SDK location: /user/pspiofilemgr.h:344 // SDK declaration: int sceIoGetstat(const char *file, SceIoStat *stat); public int sceIoGetstat(int file, int stat) { string path = _kernel.ReadString(( uint )file); IMediaItem item = _kernel.FindPath(path); if (item == null) { Log.WriteLine(Verbosity.Normal, Feature.Bios, "sceIoGetstat: could not find path {0}", path); return(unchecked (( int )( uint )0x80010002)); //_memory.WriteWord( stat, 4, 0777 | 0x2000 ); //_memory.WriteWord( stat + 4, 4, 0x0020 ); //_memory.WriteWord( stat + 8, 4, 0 ); //_memory.WriteWord( stat + 12, 4, 0 ); //return 0; } int mode = 0; int attr = 0; if (item.IsSymbolicLink == true) { mode |= 0x4000; attr |= 0x0008; } //if( ( item.Attributes & MediaItemAttributes.Hidden ) == MediaItemAttributes.Hidden ) mode |= 0x0100 | 0x0020 | 0x004; // read user / group /others attr |= 0x0004; // read if ((item.Attributes & MediaItemAttributes.ReadOnly) == MediaItemAttributes.ReadOnly) { mode |= 0x0080 | 0x0010 | 0x0002; // write user / group / others attr |= 0x0002; // write } mode |= 0x0040 | 0x0008 | 0x0001; // exec user / group / others attr |= 0x0001; // execute uint size = 0; if (item is IMediaFile) { mode |= 0x2000; // file attr |= 0x0020; // file size = ( uint )(( IMediaFile )item).Length; } else if (item is IMediaFolder) { mode |= 0x1000; // dir attr |= 0x0010; // directory } int address = stat; _memory.WriteWord(address, 4, mode); address += 4; _memory.WriteWord(address, 4, attr); address += 4; // Is this the right order for 64 bit? _memory.WriteWord(address, 4, ( int )size); _memory.WriteWord(address + 4, 4, 0); address += 8; address += _kernel.WriteTime(( uint )address, item.CreationTime); address += _kernel.WriteTime(( uint )address, item.AccessTime); address += _kernel.WriteTime(( uint )address, item.ModificationTime); // + 6 words of garbage return(0); }
private async Task SetMedia(IMediaItem media, bool autoPlay = true) { if (media == null) { throw new ArgumentNullException(nameof(media), "Media is missing. Can't play"); } if (Playlist.ElementAt(CurrentMedia) != null) { Stop(); } if (media is VideoItem || media is TrackItem) { StorageFile currentFile; try { currentFile = media.File ?? await StorageFile.GetFileFromPathAsync(media.Path); } catch (Exception exception) { Playback_MediaFileNotFound?.Invoke(media); return; } } if (media is VideoItem) { var video = (VideoItem)media; await InitializePlayback(video, autoPlay); var roamFile = await ApplicationData.Current.RoamingFolder.TryGetItemAsync("roamVideo.txt"); if (roamFile != null) { var roamVideos = await FileIO.ReadLinesAsync(roamFile as StorageFile); if (roamVideos.Any()) { if (roamVideos[0] == media.Name) { int leftTime = 0; if (int.TryParse(roamVideos[1], out leftTime)) { video.TimeWatchedSeconds = leftTime; } } } } if (video.TimeWatched != TimeSpan.FromSeconds(0)) { SetTime((long)video.TimeWatched.TotalMilliseconds); } TileHelper.UpdateVideoTile(); } else if (media is TrackItem) { var track = (TrackItem)media; await InitializePlayback(track, autoPlay); int index = IsShuffled ? NonShuffledPlaylist.IndexOf(Playlist[CurrentMedia]): CurrentMedia; ApplicationSettingsHelper.SaveSettingsValue(nameof(CurrentMedia), index); } else if (media is StreamMedia) { await InitializePlayback(media, autoPlay); } }
private void AddCover(IRequest request, IMediaItem resource, XmlNode item) { var result = item.OwnerDocument; if (result == null) { return; } var cover = resource as IMediaCover; if (cover == null) { return; } try { var c = cover.Cover; var curl = $"http://{request.LocalEndPoint.Address}:{request.LocalEndPoint.Port}{Prefix}cover/{resource.Id}/i.jpg"; var icon = result.CreateElement("upnp", "albumArtURI", NS_UPNP); var profile = result.CreateAttribute("dlna", "profileID", NS_DLNA); profile.InnerText = "JPEG_TN"; icon.SetAttributeNode(profile); icon.InnerText = curl; item.AppendChild(icon); icon = result.CreateElement("upnp", "icon", NS_UPNP); profile = result.CreateAttribute("dlna", "profileID", NS_DLNA); profile.InnerText = "JPEG_TN"; icon.SetAttributeNode(profile); icon.InnerText = curl; item.AppendChild(icon); var res = result.CreateElement(string.Empty, "res", NS_DIDL); res.InnerText = curl; res.SetAttribute("protocolInfo", string.Format( "http-get:*:{1}:DLNA.ORG_PN={0};DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS={2}", c.PN, DlnaMaps.Mime[c.Type], DlnaMaps.DefaultStreaming )); var width = c.MetaWidth; var height = c.MetaHeight; if (width.HasValue && height.HasValue) { res.SetAttribute("resolution", $"{width.Value}x{height.Value}"); } else { res.SetAttribute("resolution", "200x200"); } res.SetAttribute("protocolInfo", $"http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_CI=1;DLNA.ORG_FLAGS={DlnaMaps.DefaultInteractive}"); item.AppendChild(res); } catch (Exception) { // ignored } }
public abstract int Compare(IMediaItem x, IMediaItem y);
public async Task <bool> SetPlaylist(IEnumerable <IMediaItem> mediaItems, bool reset, bool play, IMediaItem media) { if (reset) { await ResetCollection(); } if (mediaItems != null) { var count = (uint)Playlist.Count; var trackItems = mediaItems.OfType <TrackItem>(); var backgroundTrackItems = new List <BackgroundTrackItem>(); foreach (var track in trackItems) { backgroundTrackItems.Add(new BackgroundTrackItem() { TrackId = track.Id }); track.Index = count; count++; } Playlist.AddRange(mediaItems); await BackgroundTrackRepository.Add(backgroundTrackItems); IsRunning = true; } if (media != null && Playlist.Any()) { var mediaInPlaylist = Playlist.FirstOrDefault(x => x.Path == media.Path); if (mediaInPlaylist == null) { return(false); } var mediaIndex = Playlist.IndexOf(mediaInPlaylist); if (mediaIndex < 0) { return(false); } SetCurrentMediaPosition(mediaIndex); Playback_MediaSet.Invoke(mediaInPlaylist); await SetMedia(mediaInPlaylist, play); } return(true); }
public static MediaBrowserCompat.MediaItem ToMediaBrowserMediaItem(this IMediaItem item) { var media = new MediaBrowserCompat.MediaItem(ToMediaDescription(item), MediaBrowserCompat.MediaItem.FlagPlayable); return(media); }
public FFMpegMpegtsTranscoder(IMediaItem item, uint quality, bool isDirect, uint?width, uint?height, bool maintainAspect, uint offsetSeconds, uint lengthSeconds) : base(item, quality, isDirect, width, height, maintainAspect, offsetSeconds, lengthSeconds) { }
/// <summary> /// Return a readonly FileStream of this IMediaItem /// </summary> public static FileStream File(this IMediaItem mediaItem) { return(new FileStream(mediaItem.FilePath(), FileMode.Open, FileAccess.Read)); }
public virtual int CompareTo(IMediaItem other) { return(resource.CompareTo(other)); }
public int CompareTo(IMediaItem other) { throw new NotImplementedException(); }
public Task RemoveMediaItem(IMediaItem item) { this.State.Items.Remove(item); return(Task.CompletedTask); }
private IResponse ProcessHtmlRequest(IMediaItem aItem) { var item = aItem as IMediaFolder; if (item == null) { throw new HttpStatusException(HttpCode.NotFound); } var article = HtmlTools.CreateHtmlArticle( $"Folder: {item.Title}"); var document = article.OwnerDocument; if (document == null) { throw new HttpStatusException(HttpCode.InternalError); } XmlNode e; var folders = document.EL( "ul", new AttributeCollection {{"class", "folders"}} ); if (item.Parent != null) { folders.AppendChild(e = document.EL("li")); e.AppendChild(document.EL( "a", new AttributeCollection { {"href", $"{Prefix}index/{item.Parent.Id}"}, {"class", "parent"} }, "Parent" )); } foreach (var i in item.ChildFolders) { folders.AppendChild(e = document.EL("li")); e.AppendChild(document.EL( "a", new AttributeCollection { {"href", $"{Prefix}index/{i.Id}#{i.Path}"} }, $"{i.Title} ({i.FullChildCount})")); } article.AppendChild(folders); XmlNode items; article.AppendChild(items = document.EL( "ul", new AttributeCollection {{"class", "items"}})); foreach (var i in item.ChildItems) { items.AppendChild(e = document.EL("li")); var link = document.EL( "a", new AttributeCollection { { "href", $"{Prefix}file/{i.Id}/{i.Title}.{DlnaMaps.Dlna2Ext[i.Type][0]}" } } ); var details = document.EL("section"); link.AppendChild(details); e.AppendChild(link); details.AppendChild(document.EL( "h3", new AttributeCollection {{"title", i.Title}}, i.Title)); var props = i.Properties; if (props.ContainsKey("HasCover")) { details.AppendChild(document.EL( "img", new AttributeCollection { {"title", "Cover image"}, {"alt", "Cover image"}, { "src", $"{Prefix}cover/{i.Id}/{i.Title}.{DlnaMaps.Dlna2Ext[i.Type][0]}" } })); } var table = document.EL("table"); foreach (var p in htmlItemProperties) { string v; if (props.TryGetValue(p, out v)) { table.AppendChild(e = document.EL("tr")); e.AppendChild(document.EL("th", p)); e.AppendChild(document.EL("td", v)); } } if (table.ChildNodes.Count != 0) { details.AppendChild(table); } string description; if (props.TryGetValue("Description", out description)) { link.AppendChild(document.EL( "p", new AttributeCollection {{"class", "desc"}}, description)); } } return new StringResponse(HttpCode.Ok, document.OuterXml); }
// SDK location: /user/pspiofilemgr.h:280 // SDK declaration: int sceIoDread(SceUID fd, SceIoDirent *dir); public int sceIoDread(int fd, int dir) { KFile handle = _kernel.GetHandle <KFile>(fd); if (handle == null) { Log.WriteLine(Verbosity.Normal, Feature.Bios, "sceIoDread: kernel dir handle {0:X} not found", fd); return(-1); } int offset = handle.FolderOffset; handle.FolderOffset++; IMediaFolder folder = ( IMediaFolder )handle.Item; if (offset == folder.Items.Length) { return(0); } // (d_stat) // SceMode st_mode // unsigned int st_attr // SceOff st_size (64) // ScePspDateTime st_ctime // ScePspDateTime st_atime // ScePspDateTime st_mtime // unsigned int st_private [6] //char d_name [256] //void* d_private //int dummy if ((offset == -2) || (offset == -1)) { int address = dir; _memory.WriteWord(address, 4, 0777); address += 4; uint attributes = 0x0010; _memory.WriteWord(address, 4, ( int )attributes); address += 4; _memory.WriteWord(address, 4, 0); _memory.WriteWord(address + 4, 4, 0); address += 8; address += _kernel.WriteTime(( uint )address, DateTime.Now); address += _kernel.WriteTime(( uint )address, DateTime.Now); address += _kernel.WriteTime(( uint )address, DateTime.Now); address += 6 * 4; // no private stat data - blank here? String name = (offset == -2) ? "." : ".."; int nameLength = _kernel.WriteString(( uint )address, name); address += 256; // Maybe blank here? _memory.WriteWord(address, 4, 0); address += 4; // no private dir data _memory.WriteWord(address, 4, 0); address += 4; } else { IMediaItem child = folder.Items[offset]; IMediaFolder childFolder = null; IMediaFile childFile = null; if (child.GetType().GetInterface("IMediaFolder", false) != null) { childFolder = ( IMediaFolder )child; } else { childFile = ( IMediaFile )child; } int address = dir; int mode = 0777; // | ( ( childFolder != null ) ? 0x10 : 0x20 ); _memory.WriteWord(address, 4, mode); address += 4; uint attributes = 0; //if( ( child.Attributes & MediaItemAttributes.Hidden ) == MediaItemAttributes.Hidden ) // attributes |= 0; //if( ( child.Attributes & MediaItemAttributes.ReadOnly ) == MediaItemAttributes.ReadOnly ) // attributes |= 0; if (childFile != null) { attributes |= 0x0020; } if (childFolder != null) { attributes |= 0x0010; } if (child.IsSymbolicLink == true) { attributes |= 0x0008; } _memory.WriteWord(address, 4, ( int )attributes); address += 4; if (childFile != null) { _memory.WriteWord(address, 4, ( int )childFile.Length); } else { _memory.WriteWord(address, 4, 0); } _memory.WriteWord(address + 4, 4, 0); address += 8; address += _kernel.WriteTime(( uint )address, child.CreationTime); address += _kernel.WriteTime(( uint )address, child.AccessTime); address += _kernel.WriteTime(( uint )address, child.ModificationTime); // private[ 0 ] = start sector on disk if (childFile != null) { _memory.WriteWord(address, 4, ( int )( uint )childFile.LogicalBlockNumber); } else { _memory.WriteWord(address, 4, 0); } address += 5 * 4; // no private stat data - blank here? int nameLength = _kernel.WriteString(( uint )address, child.Name); address += 256; // Maybe blank here? _memory.WriteWord(address, 4, 0); address += 4; // no private dir data _memory.WriteWord(address, 4, 0); address += 4; } // 0 to stop, 1 to keep going return(1); }
/// <summary> /// 画像のアップロードを行います /// </summary> /// <exception cref="WebApiException"/> /// <exception cref="XmlException"/> public async Task<XDocument> UploadFileAsync(IMediaItem item) { // 参照: http://p.twipple.jp/wiki/API_Upload2/ja var param = new Dictionary<string, string> { {"upload_from", Application.ProductName}, }; var paramFiles = new List<KeyValuePair<string, IMediaItem>> { new KeyValuePair<string, IMediaItem>("media", item), }; var response = ""; var uploadTask = Task.Run(() => this.GetContent(HttpConnection.PostMethod, UploadEndpoint, param, paramFiles, ref response, null, null)); var ret = await uploadTask.ConfigureAwait(false); if (ret != HttpStatusCode.OK) throw new WebApiException("Err:" + ret, response); return XDocument.Parse(response); }
public void UpdateNotification(IMediaItem mediaItem) { throw new NotImplementedException("This is an Android only method"); }
public async Task PostStatusAsync(string text, long? inReplyToStatusId, IMediaItem[] mediaItems) { if (mediaItems == null) throw new ArgumentNullException(nameof(mediaItems)); if (mediaItems.Length != 1) throw new ArgumentOutOfRangeException(nameof(mediaItems)); var item = mediaItems[0]; if (item == null) throw new ArgumentException("Err:Media not specified."); if (!item.Exists) throw new ArgumentException("Err:Media not found."); XDocument xml; try { xml = await this.UploadFileAsync(item, text) .ConfigureAwait(false); } catch (HttpRequestException ex) { throw new WebApiException("Err:" + ex.Message, ex); } catch (OperationCanceledException ex) { throw new WebApiException("Err:Timeout", ex); } var imageElm = xml.Element("data"); if (imageElm.Attribute("success").Value != "1") throw new WebApiException("Err:" + imageElm.Attribute("status").Value); var imageUrl = imageElm.Element("link").Value; var textWithImageUrl = text + " " + imageUrl.Trim(); await Task.Run(() => this.twitter.PostStatus(textWithImageUrl, inReplyToStatusId)) .ConfigureAwait(false); }
private IResponse ProcessHtmlRequest(IMediaItem aItem) { var item = aItem as IMediaFolder; if (item == null) { throw new HttpStatusException(HttpCode.NotFound); } var article = HtmlTools.CreateHtmlArticle( string.Format("Folder: {0}", item.Title)); var document = article.OwnerDocument; XmlNode e; var folders = document.EL( "ul", new AttributeCollection() { { "class", "folders" } } ); if (item.Parent != null) { folders.AppendChild(e = document.EL("li")); e.AppendChild(document.EL( "a", new AttributeCollection() { { "href", String.Format("{0}index/{1}", prefix, item.Parent.Id) }, { "class", "parent" } }, "Parent" )); } foreach (var i in item.ChildFolders) { folders.AppendChild(e = document.EL("li")); e.AppendChild(document.EL( "a", new AttributeCollection() { { "href", String.Format("{0}index/{1}", prefix, i.Id) } }, string.Format("{0} ({1})", i.Title, i.FullChildCount) )); } article.AppendChild(folders); var items = (XmlNode)null; article.AppendChild(items = document.EL( "ul", new AttributeCollection() { { "class", "items" } })); foreach (var i in item.ChildItems) { items.AppendChild(e = document.EL("li")); var link = document.EL( "a", new AttributeCollection() { { "href", string.Format( "{0}file/{1}/{2}.{3}", prefix, i.Id, i.Title, DlnaMaps.Dlna2Ext[i.Type][0]) } } ); var details = document.EL("section"); link.AppendChild(details); e.AppendChild(link); details.AppendChild(document.EL( "h3", new AttributeCollection { { "title", i.Title } }, i.Title)); var props = i.Properties; if (props.ContainsKey("HasCover")) { details.AppendChild(document.EL( "img", new AttributeCollection { { "title", "Cover image" }, { "alt", "Cover image" }, { "src", String.Format( "{0}cover/{1}/{2}.{3}", prefix, i.Id, i.Title, DlnaMaps.Dlna2Ext[i.Type][0]) } })); } var table = document.EL("table"); foreach (var p in htmlItemProperties) { string v; if (props.TryGetValue(p, out v)) { table.AppendChild(e = document.EL("tr")); e.AppendChild(document.EL("th", text: p)); e.AppendChild(document.EL("td", text: v)); } } if (table.ChildNodes.Count != 0) { details.AppendChild(table); } string description; if (props.TryGetValue("Description", out description)) { link.AppendChild(document.EL( "p", new AttributeCollection() { { "class", "desc" } }, description)); } } return(new StringResponse(HttpCode.Ok, document.OuterXml)); }
public string PostStatusWithMultipleMedia(string postStr, long? reply_to, IMediaItem[] mediaItems) { if (MyCommon._endingFlag) return ""; if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return ""; if (Twitter.DMSendTextRegex.IsMatch(postStr)) { return SendDirectMessage(postStr); } var mediaIds = new List<long>(); foreach (var item in mediaItems) { long? mediaId = null; var err = UploadMedia(item, ref mediaId); if (!mediaId.HasValue || !string.IsNullOrEmpty(err)) return err; mediaIds.Add(mediaId.Value); } if (mediaIds.Count == 0) return "Err:Invalid Files!"; return PostStatus(postStr, reply_to, mediaIds); }
public void InsertMediaItem(IMediaItem item, int index) { // make sure the input is within bounds and is not null if (ReferenceEquals(item, null) || index > PlaylistCount || index < 0 || ReferenceEquals(PlaylistId, null)) { return; } ISQLiteConnection conn = null; try { int?id = Injection.Kernel.Get <IItemRepository>().GenerateItemId(ItemType.PlaylistItem); if (!ReferenceEquals(id, null)) { // to do - better way of knowing whether or not a query has been successfully completed. conn = Injection.Kernel.Get <IDatabase>().GetSqliteConnection(); conn.BeginTransaction(); for (int position = (int)PlaylistCount - 1; position >= index; position--) { logger.IfInfo("Updating position " + position + " to " + (position + 1)); conn.ExecuteLogged("UPDATE PlaylistItem SET ItemPosition = ItemPosition + 1 WHERE PlaylistId = ? AND ItemPosition = ?", PlaylistId, position); } // conditional rollback here // Insert the new item var playlistItem = new PlaylistItem(); playlistItem.PlaylistItemId = id; playlistItem.PlaylistId = PlaylistId; playlistItem.ItemType = item.ItemType; playlistItem.ItemId = item.ItemId; playlistItem.ItemPosition = index; int affected = conn.Insert(playlistItem); // conditional rollback here if (affected > 0) { PlaylistCount++; PlaylistDuration += (int)item.Duration; LastUpdateTime = DateTime.UtcNow.ToUnixTime(); Md5Hash = CalculateHash(); conn.ExecuteLogged("UPDATE Playlist SET PlaylistName = ?, PlaylistCount = ?, PlaylistDuration = ?, Md5Hash = ?, LastUpdateTime = ? " + "WHERE PlaylistId = ?", PlaylistName == null ? "" : PlaylistName, PlaylistCount, PlaylistDuration, Md5Hash, LastUpdateTime, PlaylistId); conn.Commit(); } else { conn.Rollback(); } } } catch (Exception e) { if (!ReferenceEquals(conn, null)) { conn.Rollback(); } logger.Error(e); } finally { Injection.Kernel.Get <IDatabase>().CloseSqliteConnection(conn); } }
public int CompareTo(IMediaItem other) { if (other == null) { throw new ArgumentNullException("other"); } return Title.CompareTo(other.Title); }
public void RemoveMediaItem(IMediaItem item) { RemoveMediaItemAtIndex(IndexOfMediaItem(item)); }
protected override void OnCurrentItemChanged(IMediaItem oldValue, IMediaItem newValue) { RefreshDisplayPictureSource(); base.OnCurrentItemChanged(oldValue, newValue); }
public int CompareTo(IMediaItem other) { throw new NotSupportedException(); }
/// <summary> /// Indicates vendor specific UPNP error code of 878. /// </summary> /// <param name="item">The item that cannot have a reference created to it.</param> public Error_PendingDeleteException(IMediaItem item) : base(878, "The item (@id=\"" + item.ID + "\") has been deleted or is about to be deleted.") { Item = item; }
private IResponse ProcessHtmlRequest(IMediaItem aItem) { var item = aItem as IMediaFolder; if (item == null) { throw new Http404Exception(); } var article = HtmlTools.CreateHtmlArticle(string.Format("Folder: {0}", item.Title)); var document = article.OwnerDocument; XmlNode e; var folders = document.EL("ul", new AttributeCollection() { { "class", "folders" } }); if (item.Parent != null) { folders.AppendChild(e = document.EL("li")); e.AppendChild(document.EL( "a", new AttributeCollection() { { "href", String.Format("{0}index/{1}", prefix, item.Parent.Id) }, { "class", "parent" } }, "Parent" )); } foreach (var i in item.ChildFolders) { folders.AppendChild(e = document.EL("li")); e.AppendChild(document.EL( "a", new AttributeCollection() { { "href", String.Format("{0}index/{1}", prefix, i.Id) } }, string.Format("{0} ({1})", i.Title, i.ChildCount) )); } article.AppendChild(folders); var items = (XmlNode)null; article.AppendChild(items = document.EL("ul", new AttributeCollection() { { "class", "items" } })); foreach (var i in item.ChildItems) { items.AppendChild(e = document.EL("li")); var link = document.EL( "a", new AttributeCollection() { { "href", string.Format("{0}file/{1}/{2}.{3}", prefix, i.Id, i.Title, DlnaMaps.Dlna2Ext[i.Type][0]) } } ); var details = document.EL("section"); link.AppendChild(details); e.AppendChild(link); details.AppendChild(document.EL("h3", new AttributeCollection { { "title", i.Title } }, i.Title)); var props = i.Properties; if (props.ContainsKey("HasCover")) { details.AppendChild(document.EL( "img", new AttributeCollection { { "title", "Cover image" }, { "alt", "Cover image" }, { "src", String.Format("{0}cover/{1}", prefix, i.Id) } } )); } var table = document.EL("table"); foreach (var p in htmlItemProperties) { string v; if (props.TryGetValue(p, out v)) { table.AppendChild(e = document.EL("tr")); e.AppendChild(document.EL("th", text: p)); e.AppendChild(document.EL("td", text: v)); } } if (table.ChildNodes.Count != 0) { details.AppendChild(table); } string description; if (props.TryGetValue("Description", out description)) { link.AppendChild(document.EL("p", new AttributeCollection() { { "class", "desc" } }, description)); } } return new StringResponse(HttpCodes.OK, document.OuterXml); }
public int CompareTo(IMediaItem other) => throw new NotImplementedException();
public bool Equals(IMediaItem other) { throw new NotImplementedException(); }
public bool Equals(IMediaItem other) => throw new NotImplementedException();
public async Task PostStatusAsync(string text, long? inReplyToStatusId, IMediaItem[] mediaItems) { if (mediaItems == null) throw new ArgumentNullException("mediaItems"); if (mediaItems.Length != 1) throw new ArgumentOutOfRangeException("mediaItems"); var item = mediaItems[0]; if (item == null) throw new ArgumentException("Err:Media not specified."); if (!item.Exists) throw new ArgumentException("Err:Media not found."); var xml = await this.twippleApi.UploadFileAsync(item) .ConfigureAwait(false); var imageUrlElm = xml.XPathSelectElement("/rsp/mediaurl"); if (imageUrlElm == null) throw new WebApiException("Invalid API response", xml.ToString()); var textWithImageUrl = text + " " + imageUrlElm.Value.Trim(); await Task.Run(() => this.twitter.PostStatus(textWithImageUrl, inReplyToStatusId)) .ConfigureAwait(false); }
public void Remove(IMediaItem media) { Playlist.Remove(media); }
public async Task<XDocument> UploadFileAsync(IMediaItem item, string title) { using (var content = new MultipartFormDataContent()) using (var mediaStream = item.OpenRead()) using (var mediaContent = new StreamContent(mediaStream)) using (var titleContent = new StringContent(title)) { content.Add(mediaContent, "image", item.Name); content.Add(titleContent, "title"); using (var request = new HttpRequestMessage(HttpMethod.Post, UploadEndpoint)) { request.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", ApplicationSettings.ImgurClientID); request.Content = content; using (var response = await Networking.Http.SendAsync(request).ConfigureAwait(false)) { response.EnsureSuccessStatusCode(); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { return XDocument.Load(stream); } } } } }
public FFMpegOGGTranscoder(IMediaItem item, uint quality, bool isDirect, uint offsetSeconds, uint lengthSeconds) : base(item, quality, isDirect, offsetSeconds, lengthSeconds) { }
public string PostStatusWithMedia(string postStr, long? reply_to, IMediaItem item) { if (MyCommon._endingFlag) return ""; if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return ""; HttpStatusCode res; var content = ""; try { res = twCon.UpdateStatusWithMedia(postStr, reply_to, item, ref content); } catch(Exception ex) { return "Err:" + ex.Message; } // 投稿に成功していても404が返ることがあるらしい: https://dev.twitter.com/discussions/1213 if (res == HttpStatusCode.NotFound) return ""; var err = this.CheckStatusCode(res, content); if (err != null) return err; TwitterStatus status; try { status = TwitterStatus.ParseJson(content); } catch(SerializationException ex) { MyCommon.TraceOut(ex.Message + Environment.NewLine + content); return "Err:Json Parse Error(DataContractJsonSerializer)"; } catch(Exception ex) { MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content); return "Err:Invalid Json!"; } _followersCount = status.User.FollowersCount; _friendsCount = status.User.FriendsCount; _statusesCount = status.User.StatusesCount; _location = status.User.Location; _bio = status.User.Description; if (IsPostRestricted(status)) { return "OK:Delaying?"; } return ""; }
/// <summary> /// Process handles the initialization of the file transcoding sequence /// <summary> public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // Get TranscodeService instance TranscodeService transcodeService = (TranscodeService)ServiceManager.GetInstance("transcode"); // Ensure transcode service is ready if ((object)transcodeService == null) { processor.WriteJson(new TranscodeResponse("TranscodeService is not running!")); return; } // Create transcoder ITranscoder transcoder = null; // Get seconds offset float seconds = 0f; if (uri.Parameters.ContainsKey("seconds")) { float.TryParse(uri.Parameters["seconds"], out seconds); } // Verify ID received if (uri.Id == null) { processor.WriteJson(new TranscodeResponse("Missing required parameter 'id'")); return; } try { // Set up default transcoding parameters ItemType itemType = Injection.Kernel.Get <IItemRepository>().ItemTypeForItemId((int)uri.Id); IMediaItem item = null; TranscodeType transType = TranscodeType.MP3; bool isDirect = false; Stream stream = null; int startOffset = 0; long? limitToSize = null; long length = 0; bool estimateContentLength = false; // Optionally estimate content length if (uri.Parameters.ContainsKey("estimateContentLength")) { estimateContentLength = uri.Parameters["estimateContentLength"].IsTrue(); } // Get the media item associated with this id if (itemType == ItemType.Song) { item = Injection.Kernel.Get <ISongRepository>().SongForId((int)uri.Id); logger.IfInfo("Preparing audio transcode: " + item.FileName); // Default to MP3 transcoding transType = TranscodeType.MP3; } else if (itemType == ItemType.Video) { item = Injection.Kernel.Get <IVideoRepository>().VideoForId((int)uri.Id); logger.IfInfo("Preparing video transcode: " + item.FileName); // Default to h.264 transcoding transType = TranscodeType.X264; } // Return an error if no item exists if ((item == null) || (!File.Exists(item.FilePath()))) { processor.WriteJson(new TranscodeResponse("No media item exists with ID: " + (int)uri.Id)); return; } // Optionally add isDirect parameter if (uri.Parameters.ContainsKey("isDirect")) { isDirect = uri.Parameters["isDirect"].IsTrue(); } if (seconds > 0) { // Guess the file position based on the seconds requested // this is wrong now, but will be improved to take into account the header size and transcode quality // or even better, we should be able to just pass the offset seconds to ffmpeg float percent = seconds / (float)item.Duration; if (percent < 1f) { startOffset = (int)(item.FileSize * percent); logger.IfInfo("seconds: " + seconds + " Resuming from " + startOffset); } } else if (processor.HttpHeaders.ContainsKey("Range")) { // Handle the Range header to start from later in the file string range = (string)processor.HttpHeaders["Range"]; var split = range.Split(new char[] { '-', '=' }); string start = split[1]; string end = split.Length > 2 ? split[2] : null; logger.IfInfo("Range header: " + range + " Resuming from " + start + " end: " + end); if (isDirect) { // TODO: Actually implement this lol // This is a direct transfer with no file buffer, so treat a Range request as if it // were start offset, unless an offsetSeconds was specified if (uri.Parameters.ContainsKey("offsetSeconds")) { } else { } } else { // This is a file request so use the range header to specify where in the file to return startOffset = Convert.ToInt32(start); if (!ReferenceEquals(end, null) && end.Length > 0) { limitToSize = (Convert.ToInt64(end) + 1) - startOffset; } } } // Get the transcoding type if specified if (uri.Parameters.ContainsKey("transType")) { // Parse transcoding type TranscodeType transTypeTemp; if (Enum.TryParse <TranscodeType>(uri.Parameters["transType"], true, out transTypeTemp)) { // Verify this is a valid transcode type for this item type if (transTypeTemp.IsValidForItemType(item.ItemType)) { // It is, so use it transType = transTypeTemp; } } } // Get the quality, default to medium uint quality = (uint)TranscodeQuality.Medium; if (uri.Parameters.ContainsKey("transQuality")) { string qualityString = uri.Parameters["transQuality"]; TranscodeQuality qualityEnum; uint qualityValue; // First try and parse a word enum value if (Enum.TryParse <TranscodeQuality>(qualityString, true, out qualityEnum)) { quality = (uint)qualityEnum; } // Otherwise look for a number to use as bitrate else if (UInt32.TryParse(qualityString, out qualityValue)) { quality = qualityValue; } } // Create the transcoder if (item.ItemType == ItemType.Song) { // Begin transcoding song transcoder = transcodeService.TranscodeSong(item, transType, (uint)quality, isDirect, 0, (uint)item.Duration); } else { // Video transcoding is just a bit more complicated. // Check to see if the width, height, and maintainAspect options were used uint?width = null; if (uri.Parameters.ContainsKey("width")) { uint widthTemp; width = UInt32.TryParse(uri.Parameters["width"], out widthTemp) ? (uint?)widthTemp : null; } uint?height = 0; if (uri.Parameters.ContainsKey("height")) { uint heightTemp; height = UInt32.TryParse(uri.Parameters["height"], out heightTemp) ? (uint?)heightTemp : null; } bool maintainAspect = true; if (uri.Parameters.ContainsKey("maintainAspect")) { if (!Boolean.TryParse(uri.Parameters["maintainAspect"], out maintainAspect)) { maintainAspect = true; } } // Check for offset seconds and length seconds parameters uint offsetSeconds = 0; if (uri.Parameters.ContainsKey("offsetSeconds")) { UInt32.TryParse(uri.Parameters["offsetSeconds"], out offsetSeconds); } uint lengthSeconds = 0; if (uri.Parameters.ContainsKey("lengthSeconds")) { UInt32.TryParse(uri.Parameters["lengthSeconds"], out lengthSeconds); } // Either stream the rest of the file, or the duration specified lengthSeconds = lengthSeconds == 0 ? (uint)item.Duration - offsetSeconds : lengthSeconds; // Begin video transcoding transcoder = transcodeService.TranscodeVideo(item, transType, quality, isDirect, width, height, maintainAspect, offsetSeconds, lengthSeconds); } // If a transcoder was generated... if ((object)transcoder != null) { length = (long)transcoder.EstimatedOutputSize; // Wait up 5 seconds for file or basestream to appear for (int i = 0; i < 20; i++) { if (transcoder.IsDirect) { logger.IfInfo("Checking if base stream exists"); if ((object)transcoder.TranscodeProcess != null && (object)transcoder.TranscodeProcess.StandardOutput.BaseStream != null) { // The base stream exists, so the transcoding process has started logger.IfInfo("Base stream exists, starting transfer"); stream = transcoder.TranscodeProcess.StandardOutput.BaseStream; break; } } else { logger.IfInfo("Checking if file exists (" + transcoder.OutputPath + ")"); if (File.Exists(transcoder.OutputPath)) { // The file exists, so the transcoding process has started stream = new FileStream(transcoder.OutputPath, FileMode.Open, FileAccess.Read); break; } } Thread.Sleep(250); } } // Send the file if either there is no transcoder and the original file exists OR // it's a direct transcoder and the base stream exists OR // it's a file transcoder and the transcoded file exists if ((object)transcoder == null && File.Exists(item.FilePath()) || (transcoder.IsDirect && (object)stream != null) || (!transcoder.IsDirect && File.Exists(transcoder.OutputPath))) { logger.IfInfo("Sending direct stream"); string mimeType = (object)transcoder == null?item.FileType.MimeType() : transcoder.MimeType; processor.Transcoder = transcoder; if (uri.Parameters.ContainsKey("offsetSeconds")) { logger.IfInfo("Writing file at offsetSeconds " + uri.Parameters["offsetSeconds"]); } DateTime lastModified = transcoder.IsDirect ? DateTime.UtcNow : new FileInfo(transcoder.OutputPath).LastWriteTimeUtc; // Direct write file processor.WriteFile(stream, startOffset, length, mimeType, null, estimateContentLength, lastModified, limitToSize); stream.Close(); logger.IfInfo("Successfully sent direct stream"); if (uri.Parameters.ContainsKey("offsetSeconds")) { logger.IfInfo("DONE writing file at offsetSeconds " + uri.Parameters["offsetSeconds"]); } } else { processor.WriteErrorHeader(); } // Spin off a thread to consume the transcoder in 30 seconds. Thread consume = new Thread(() => transcodeService.ConsumedTranscode(transcoder)); consume.Start(); } catch (Exception e) { logger.Error(e); } }
public string UploadMedia(IMediaItem item, ref long? mediaId) { if (MyCommon._endingFlag) return ""; if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return ""; HttpStatusCode res; var content = ""; try { res = twCon.UploadMedia(item, ref content); } catch (Exception ex) { return "Err:" + ex.Message; } var err = this.CheckStatusCode(res, content); if (err != null) return err; TwitterUploadMediaResult status; try { status = TwitterUploadMediaResult.ParseJson(content); } catch (SerializationException ex) { MyCommon.TraceOut(ex.Message + Environment.NewLine + content); return "Err:Json Parse Error(DataContractJsonSerializer)"; } catch (Exception ex) { MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content); return "Err:Invalid Json!"; } mediaId = status.MediaId; return ""; }
public MediaItemFailedEventArgs(IMediaItem Item, Exception Exception, string Message) : base(Item) { this.Exeption = Exception; this.Message = Message; }
public void SubmitTrackToLastFM(IMediaItem track, DateTime timeStarted) { try { AudioscrobblerRequest request = new AudioscrobblerRequest(); request.Username = "******"; request.Password = "******"; request.SubmitTrack(track, timeStarted); //if (StatusUpdated != null) //StatusUpdated(this, new UpdateStatusEventArgs("Track submitted to Last.fm", string.Format("{0} - {1} - {2}", track.Artist, track.Album, track.Name))); } catch (Exception) { //if (StatusUpdated != null) //StatusUpdated(this, new UpdateStatusEventArgs("Error submitting track to Last.fm", ex.Message)); } }
public abstract Task Play(IMediaItem mediaItem);
public FFMpegOpusTranscoder(IMediaItem item, uint quality, bool isDirect, uint offsetSeconds, uint lengthSeconds) : base(item, quality, isDirect, offsetSeconds, lengthSeconds) { }
public abstract Task SetSource(IMediaItem mediaItem);