Skip to content

Commit

Permalink
* Первая редация этого модуля в отдельном репозитории. до этого - был…
Browse files Browse the repository at this point in the history
… в ITG.WinAPI

Signed-off-by: Sergey S. Betke <[email protected]>
  • Loading branch information
sergey-s-betke committed Oct 8, 2012
0 parents commit c166979
Show file tree
Hide file tree
Showing 6 changed files with 197 additions and 0 deletions.
34 changes: 34 additions & 0 deletions ITG.PrepareModulesEnv.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<#
.Synopsis
Скрипт, вызываемый при загрузке модулей ITG. Выполняет подготовку для загрузки модулей ITG.
.Description
Скрипт, вызываемый при загрузке модулей ITG. Выполняет подготовку для загрузки модулей ITG.
На данном этапе:
- добавляет в $env:PSModulePath каталог загружаемого модуля, чтобы все зависимости могли быть
импортированы без указания полного пути (то есть - в том числе и из общего репозитория модулей
powerShell)
.Link
описание манифеста модуля: http://get-powershell.com/post/2011/04/04/How-to-Package-and-Distribute-PowerShell-Cmdlets-Functions-and-Scripts.aspx
#>
[CmdletBinding(
)]
param ()

Write-Verbose "Добавляем каталог $( ( [System.IO.FileInfo] ( $myinvocation.mycommand.path ) ).directory ) в `$Env:PSModulePath.";

$Env:PSModulePath = (
@( $env:psmodulepath -split ';' ) `
+ ( ( [System.IO.FileInfo] ( $myinvocation.mycommand.path ) ).directory ) `
| Select-Object -Unique `
) -join ';';

Write-Verbose @"
Изменённое значение `$Env:PSModulePath:
$(
(
@( $env:psmodulepath -split ';' ) `
| %{ "`t" + $_ } `
) -join "`n"
)
"@
;
45 changes: 45 additions & 0 deletions ITG.WinAPI.UrlMon.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace ITG.WinAPI.UrlMon {

[Flags]
public enum FMFD {
Default = 0x00000000, // No flags specified. Use default behavior for the function.
URLAsFileName = 0x00000001, // Treat the specified pwzUrl as a file name.
EnableMIMESniffing = 0x00000002, // Internet Explorer 6 for Windows XP SP2 and later. Use MIME-type detection even if FEATURE_MIME_SNIFFING is detected. Usually, this feature control key would disable MIME-type detection.
IgnoreMIMETextPlain = 0x00000004, // Internet Explorer 6 for Windows XP SP2 and later. Perform MIME-type detection if "text/plain" is proposed, even if data sniffing is otherwise disabled. Plain text may be converted to text/html if HTML tags are detected.
ServerMIME = 0x00000008, // Internet Explorer 8. Use the authoritative MIME type specified in pwzMimeProposed. Unless FMFD_IGNOREMIMETEXTPLAIN is specified, no data sniffing is performed.
RespectTextPlain = 0x00000010, // Internet Explorer 9. Do not perform detection if "text/plain" is specified in pwzMimeProposed.
RetrunUpdatedImgMIMEs = 0x00000020 // Internet Explorer 9. Returns image/png and image/jpeg instead of image/x-png and image/pjpeg.
};

public
class API {

// http://msdn.microsoft.com/en-us/library/ms775107(VS.85).aspx
// http://www.rsdn.ru/article/dotnet/netTocom.xml

[DllImport(
"urlmon.dll"
, CharSet=CharSet.Unicode
, SetLastError=false
)]
public
static
extern
System.UInt32
FindMimeFromData(
System.UInt32 pBC,
[In, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwzUrl,
[In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=3)] byte[] pBuffer,
[In, MarshalAs(UnmanagedType.U4)] System.UInt32 cbSize,
[In, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwzMimeProposed,
[In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwMimeFlags,
[Out, MarshalAs(UnmanagedType.LPWStr)] out String ppwzMimeOut,
[In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwReserverd
);

}
}
Binary file added ITG.WinAPI.UrlMon.psd1
Binary file not shown.
92 changes: 92 additions & 0 deletions ITG.WinAPI.UrlMon.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
'ITG.WinAPI.UrlMon.cs' `
| % {
Add-Type `
-Path (join-path `
-path $PSScriptRoot `
-childPath $_ `
) `
;
} `
;

function Get-MIME {
<#
.Synopsis
Функция определяет MIME тип файла по его содержимому и расширению имени файла.
.Description
Функция определяет MIME тип файла по его содержимому и расширению имени файла
(если файл недоступен).
Обёртка для API FindMimeFromData.
.Link
http://msdn.microsoft.com/en-us/library/ms775107(VS.85).aspx
http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/d79e76e3-b8c9-4fce-a97d-94ded18ea4dd
.Example
"logo.jpg" | Get-MIME
#>
[CmdletBinding(
)]

param (
# путь к файлу, MIME для которого необходимо определить
[Parameter(
Mandatory=$true,
Position=0,
ValueFromPipeline=$true
)]
[System.IO.FileInfo]$Path
)

process {
try {
$length = 0;
[Byte[]] $buffer = $null;
if ( [System.IO.File]::Exists( $Path ) ) {
Write-Verbose "Определяем MIME тип файла по его содержимому (файл $($Path.FullName) доступен).";
$fs = New-Object System.IO.FileStream (
$Path,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[system.IO.FileShare]::Read,
256
);
try {
if ( $fs.Length -ge 256) {
$length = 256;
} else {
$length = $fs.Length;
};
if ( $length ) {
$buffer = New-Object Byte[] (256);
$length = $fs.Read( $buffer, 0, $length );
};
} finally {
$fs.Dispose();
};
} else {
Write-Verbose "Определяем MIME тип файла по расширению его имени (файл $($Path.FullName) недоступен).";
};
[string]$mime = '';
$err = [ITG.WinAPI.UrlMon.API]::FindMimeFromData(
0,
$Path.FullName,
$buffer,
$length,
$null,
[ITG.WinAPI.UrlMon.FMFD]::URLAsFileName -bor [ITG.WinAPI.UrlMon.FMFD]::RetrunUpdatedImgMIMEs,
[ref]$mime,
0
);
[System.Runtime.InteropServices.Marshal]::ThrowExceptionForHR( $err );
$mime;
} catch [Exception] {
Write-Error `
-Exception $_.Exception `
-Message "Возникла ошибка при попытке определения MIME типа для файла $($Path.FullName)" `
;
};
}
}

Export-ModuleMember `
Get-MIME `
;
26 changes: 26 additions & 0 deletions test.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[CmdletBinding(
SupportsShouldProcess=$true,
ConfirmImpact="Medium"
)]
param ()

. `
(Join-Path `
-Path ( ( [System.IO.FileInfo] ( $MyInvocation.MyCommand.Path ) ).Directory ) `
-ChildPath 'ITG.PrepareModulesEnv.ps1' `
) `
;

Import-Module 'ITG.WinAPI.UrlMon' -Force;

'test\logo.jpg' `
, 'test\logo2.jpg' `
| % {
(join-path `
-path ( ( [System.IO.FileInfo] ( $myinvocation.mycommand.path ) ).directory ) `
-childPath $_ `
) `
} `
| Get-MIME -ErrorAction Continue `
;
#>
Binary file added test/logo.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit c166979

Please sign in to comment.